<commit_before>'use strict';

/*
 * Copyright (c) 2013-2015 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */

var bl              = require('bl')
  , util            = require('util')
  , events          = require('events')
  , dgram           = require('dgram')
  , parse           = require('coap-packet').parse
  , generate        = require('coap-packet').generate
  , URL             = require('url')
  , IncomingMessage = require('./incoming_message')
  , OutgoingMessage = require('./outgoing_message')
  , ObserveStream   = require('./observe_read_stream')
  , optionsConv     = require('./option_converter')
  , RetrySend       = require('./retry_send')
  , parseBlock2     = require('./helpers').parseBlock2
  , createBlock2    = require('./helpers').createBlock2
  , getOption       = require('./helpers').getOption
  , maxToken        = Math.pow(2, 32)
  , maxMessageId    = Math.pow(2, 16)
  , pf              = require('./polyfill')
  , hasDNSbug       = true

;(function () {
  var major = parseInt(process.version.match(/^v([^.]+).*$/)[1])

  if (major >= 4) {
    hasDNSbug = false
  }
})()

function Agent(opts) {
  if (!(this instanceof Agent))
    return new Agent(opts)

  if (!opts)
    opts = {}

  if (!opts.type)
    opts.type = 'udp4'

  if (opts.socket) {
    opts.type = opts.socket.type
    delete opts.port
  }

  this._opts = opts

  this._init(opts.socket)
}

util.inherits(Agent, events.EventEmitter)

Agent.prototype._init = function initSock(socket) {
  if (this._sock) {
    return
  }

  var that = this
  this._sock = socket || dgram.createSocket(this._opts.type)
  this._sock.on('message', function(msg, rsinfo) {
    var packet
      , message
      , outSocket

    try {
      packet = parse(msg)
    } catch(err) {
      return
    }

    if (packet.code[0] === '0' && packet.code !== '0.00') {
      // ignore this packet since it's not a response.
      return
    }

    outSocket = that._sock.address();
    that._handle(msg, rsinfo, outSocket)
  })

  if(this._opts.port){
    this._sock.bind( this._opts.port );
  };

  this._sock.on('error', function(err) {
    // we are skipping DNS errors
    if(!hasDNSbug || err.code !== 'ENOTFOUND')
      that.emit('error', err)
  })

  this._msgIdToReq = {}
  this._tkToReq = {}

  this._lastToken = Math.floor(Math.random() * (maxToken - 1))
  this._lastMessageId = Math.floor(Math.random() * (maxMessageId - 1))

  this._closing = false
  this._msgInFlight = 0
  this._requests = 0
}

Agent.prototype._cleanUp = function cleanUp() {
  if (--this._requests !== 0)
    return

  if (!this._opts.socket)
    this._closing = true

  if (this._msgInFlight !== 0)
    return

  this._doClose()
}

Agent.prototype._doClose = function() {
  for (var k in this._msgIdToReq)
    this._msgIdToReq[k].sender.reset()

  if (this._opts.socket)
    return

  this._sock.close()
  this._sock = null
}

Agent.prototype._handle = function handle(msg, rsinfo, outSocket) {
  var packet = parse(msg)
    , buf
    , response
    , that = this
    , req = this._msgIdToReq[packet.messageId]
    , ackSent = function(err) {
        if (err && req)
          req.emit('error', err)

        that._msgInFlight--
        if (that._closing && that._msgInFlight === 0) {
          that._doClose()
        }
      }

  if (!req) {
    if (packet.token.length == 4) {
      req = this._tkToReq[packet.token.readUInt32BE(0)]
    }

    if ((packet.ack || packet.reset) && !req) {
      // Nothing to do on unknown or duplicate ACK/RST packet
      return
    }

    if (!req) {
      buf = generate({
          code: '0.00'
        , reset: true
        , messageId: packet.messageId
      })

      this._msgInFlight++
      this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
      return
    }
  }

  if (packet.confirmable) {
    buf = generate({
        code: '0.00'
      , ack: true
      , messageId: packet.messageId
    })

    this._msgInFlight++
    this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
  }

  if (packet.code != '0.00' && (req._packet.token.length != packet.token.length || pf.compareBuffers(req._packet.token, packet.token) != 0)) {
    // The tokens don't match, ignore the message since it is a malformed response
    return
  }

  if (!packet.confirmable && !req.multicast) {
    delete this._msgIdToReq[packet.messageId]
  }

  req.sender.reset()

  // Drop empty messages (ACKs), but process RST
  if (packet.code == '0.00' && !packet.reset)
    return

  var block2Buff = getOption(packet.options, 'Block2')
  var block2
  // if we got blockwise (2) response
  if (block2Buff) {
    block2 = parseBlock2(block2Buff)
    // check for error
    if (!block2) {
      req.sender.reset()
      return req.emit('error', new Error('failed to parse block2'))
    }
  }
  if (block2) {
    // accumulate payload
    req._totalPayload = Buffer.concat([req._totalPayload, packet.payload])

    if (block2.moreBlock2) {
      // increase message id for next request
      delete this._msgIdToReq[req._packet.messageId]
      req._packet.messageId = that._nextMessageId()
      this._msgIdToReq[req._packet.messageId] = req

      // next block2 request
      var block2Val = createBlock2({
        moreBlock2: false,
        num: block2.num+1,
        size: block2.size
      })
      if (!block2Val) {
        req.sender.reset()
        return req.emit('error', new Error('failed to create block2'))
      }
      req.setOption('Block2', block2Val)
      req.sender.send(generate(req._packet))

      return
    }
    else {
      // get full payload
      packet.payload = req._totalPayload
      // clear the payload incase of block2
      req._totalPayload = Buffer.alloc(0)
    }
  }

  if (req.response) {
    if (req.response.append) {
      // it is an observe request
      // and we are already streaming
      return req.response.append(packet)
    } else {
      // TODO There is a previous response but is not an ObserveStream !
      return
    }

  }
  else if (block2) {
    delete that._tkToReq[req._packet.token.readUInt32BE(0)]
  }
  else if (!req.url.observe && packet.token.length > 0 && !req.multicast) {
    // it is not, so delete the token
    delete that._tkToReq[packet.token.readUInt32BE(0)]
  }

  if (req.url.observe && packet.code !== '4.04') {
    response = new ObserveStream(packet, rsinfo, outSocket)
    response.on('close', function() {
      delete that._tkToReq[packet.token.readUInt32BE(0)]
      that._cleanUp()
    })
  } else {
    response = new IncomingMessage(packet, rsinfo, outSocket)
  }

  if (!req.multicast) {
    req.response = response
  }

  req.emit('response', response)
}

Agent.prototype._nextToken = function nextToken() {
  var buf = Buffer.alloc(4)

  if (++this._lastToken === maxToken)
    this._lastToken = 0

  buf.writeUInt32BE(this._lastToken, 0)

  return buf;
}

Agent.prototype._nextMessageId = function nextToken() {
  if (++this._lastMessageId === maxMessageId)
    this._lastMessageId = 1

  return this._lastMessageId
}

Agent.prototype.request = function request(url) {
  this._init()

  var req
    , response
    , options = url.options || url.headers
    , option
    , that = this
    , multicastTimeout = url.multicastTimeout !== undefined ? parseInt(url.multicastTimeout) : 20000

  req = new OutgoingMessage({}, function(req, packet) {
    var buf

    if (url.confirmable !== false) {
      packet.confirmable = true
    }

    // multicast message should be forced non-confirmable
    if (url.multicast === true) {
      req.multicast = true
      packet.confirmable = false
    }

    if (!(packet.ack || packet.reset)) {
      packet.messageId = that._nextMessageId()
      packet.token = that._nextToken()
    }

    try {
      buf = generate(packet)
    } catch(err) {
      req.sender.reset()
      return req.emit('error', err)
    }

    that._msgIdToReq[packet.messageId] = req
    that._tkToReq[that._lastToken] = req

    req.sender.send(buf, !packet.confirmable)
  })

  req.sender = new RetrySend(this._sock, url.port, url.hostname || url.host, url.retrySend)

  req.url = url

  req.statusCode = url.method || 'GET'

  urlPropertyToPacketOption(url, req, 'pathname', 'Uri-Path', '/')
  urlPropertyToPacketOption(url, req, 'query', 'Uri-Query', '&')

  if (options) {
    for (option in options) {
      if (options.hasOwnProperty(option)) {
        req.setOption(option, options[option])
      }
    }
  }

  if (url.proxyUri) {
    req.setOption('Proxy-Uri', url.proxyUri)
  }

  req.sender.on('error', req.emit.bind(req, 'error'))

  req.sender.on('sending', function() {
    that._msgInFlight++
  })

  req.sender.on('timeout', function (err) {
    req.emit('timeout', err)
    that.abort(req)
  })

  req.sender.on('sent', function() {
    if (req.multicast) return;

    that._msgInFlight--
    if (that._closing && that._msgInFlight === 0) {
      that._doClose()
    }
  })

  // Start multicast monitoring timer in case of multicast request
  if (url.multicast === true) {
    req.multicastTimer = setTimeout(function() {
      if (req._packet.token) {
        delete that._tkToReq[req._packet.token.readUInt32BE(0)]
      }
      that._msgInFlight--
      if (that._msgInFlight === 0) {
        that._doClose()
      }
    }, multicastTimeout)
  }

  if (url.observe)
    req.setOption('Observe', null)
  else
    req.on('response', this._cleanUp.bind(this))

  this._requests++

  req._totalPayload = Buffer.alloc(0)

  return req
}

Agent.prototype.abort = function (req) {
  req.sender.removeAllListeners()
  req.sender.reset()
  this._cleanUp()
  delete this._msgIdToReq[req._packet.messageId]
  delete this._tkToReq[req._packet.token.readUInt32BE(0)]
}

function urlPropertyToPacketOption(url, req, property, option, separator) {
  if (url[property])
    req.setOption(option, url[property].normalize('NFC').split(separator)
      .filter(function(part) { return part !== '' })
      .map(function(part) {
        var buf = Buffer.alloc(Buffer.byteLength(part))
        buf.write(part)
        return buf
      }))
}

module.exports = Agent
<commit_msg>fix(agent): remove useless variables<commit_after>'use strict';

/*
 * Copyright (c) 2013-2015 node-coap contributors.
 *
 * node-coap is licensed under an MIT +no-false-attribs license.
 * All rights not explicitly granted in the MIT license are reserved.
 * See the included LICENSE file for more details.
 */

var util            = require('util')
  , events          = require('events')
  , dgram           = require('dgram')
  , parse           = require('coap-packet').parse
  , generate        = require('coap-packet').generate
  , IncomingMessage = require('./incoming_message')
  , OutgoingMessage = require('./outgoing_message')
  , ObserveStream   = require('./observe_read_stream')
  , RetrySend       = require('./retry_send')
  , parseBlock2     = require('./helpers').parseBlock2
  , createBlock2    = require('./helpers').createBlock2
  , getOption       = require('./helpers').getOption
  , maxToken        = Math.pow(2, 32)
  , maxMessageId    = Math.pow(2, 16)
  , pf              = require('./polyfill')
  , hasDNSbug       = true

;(function () {
  var major = parseInt(process.version.match(/^v([^.]+).*$/)[1])

  if (major >= 4) {
    hasDNSbug = false
  }
})()

function Agent(opts) {
  if (!(this instanceof Agent))
    return new Agent(opts)

  if (!opts)
    opts = {}

  if (!opts.type)
    opts.type = 'udp4'

  if (opts.socket) {
    opts.type = opts.socket.type
    delete opts.port
  }

  this._opts = opts

  this._init(opts.socket)
}

util.inherits(Agent, events.EventEmitter)

Agent.prototype._init = function initSock(socket) {
  if (this._sock) {
    return
  }

  var that = this
  this._sock = socket || dgram.createSocket(this._opts.type)
  this._sock.on('message', function(msg, rsinfo) {
    var packet
      , message
      , outSocket

    try {
      packet = parse(msg)
    } catch(err) {
      return
    }

    if (packet.code[0] === '0' && packet.code !== '0.00') {
      // ignore this packet since it's not a response.
      return
    }

    outSocket = that._sock.address();
    that._handle(msg, rsinfo, outSocket)
  })

  if(this._opts.port){
    this._sock.bind( this._opts.port );
  };

  this._sock.on('error', function(err) {
    // we are skipping DNS errors
    if(!hasDNSbug || err.code !== 'ENOTFOUND')
      that.emit('error', err)
  })

  this._msgIdToReq = {}
  this._tkToReq = {}

  this._lastToken = Math.floor(Math.random() * (maxToken - 1))
  this._lastMessageId = Math.floor(Math.random() * (maxMessageId - 1))

  this._closing = false
  this._msgInFlight = 0
  this._requests = 0
}

Agent.prototype._cleanUp = function cleanUp() {
  if (--this._requests !== 0)
    return

  if (!this._opts.socket)
    this._closing = true

  if (this._msgInFlight !== 0)
    return

  this._doClose()
}

Agent.prototype._doClose = function() {
  for (var k in this._msgIdToReq)
    this._msgIdToReq[k].sender.reset()

  if (this._opts.socket)
    return

  this._sock.close()
  this._sock = null
}

Agent.prototype._handle = function handle(msg, rsinfo, outSocket) {
  var packet = parse(msg)
    , buf
    , response
    , that = this
    , req = this._msgIdToReq[packet.messageId]
    , ackSent = function(err) {
        if (err && req)
          req.emit('error', err)

        that._msgInFlight--
        if (that._closing && that._msgInFlight === 0) {
          that._doClose()
        }
      }

  if (!req) {
    if (packet.token.length == 4) {
      req = this._tkToReq[packet.token.readUInt32BE(0)]
    }

    if ((packet.ack || packet.reset) && !req) {
      // Nothing to do on unknown or duplicate ACK/RST packet
      return
    }

    if (!req) {
      buf = generate({
          code: '0.00'
        , reset: true
        , messageId: packet.messageId
      })

      this._msgInFlight++
      this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
      return
    }
  }

  if (packet.confirmable) {
    buf = generate({
        code: '0.00'
      , ack: true
      , messageId: packet.messageId
    })

    this._msgInFlight++
    this._sock.send(buf, 0, buf.length, rsinfo.port, rsinfo.address, ackSent)
  }

  if (packet.code != '0.00' && (req._packet.token.length != packet.token.length || pf.compareBuffers(req._packet.token, packet.token) != 0)) {
    // The tokens don't match, ignore the message since it is a malformed response
    return
  }

  if (!packet.confirmable && !req.multicast) {
    delete this._msgIdToReq[packet.messageId]
  }

  req.sender.reset()

  // Drop empty messages (ACKs), but process RST
  if (packet.code == '0.00' && !packet.reset)
    return

  var block2Buff = getOption(packet.options, 'Block2')
  var block2
  // if we got blockwise (2) response
  if (block2Buff) {
    block2 = parseBlock2(block2Buff)
    // check for error
    if (!block2) {
      req.sender.reset()
      return req.emit('error', new Error('failed to parse block2'))
    }
  }
  if (block2) {
    // accumulate payload
    req._totalPayload = Buffer.concat([req._totalPayload, packet.payload])

    if (block2.moreBlock2) {
      // increase message id for next request
      delete this._msgIdToReq[req._packet.messageId]
      req._packet.messageId = that._nextMessageId()
      this._msgIdToReq[req._packet.messageId] = req

      // next block2 request
      var block2Val = createBlock2({
        moreBlock2: false,
        num: block2.num+1,
        size: block2.size
      })
      if (!block2Val) {
        req.sender.reset()
        return req.emit('error', new Error('failed to create block2'))
      }
      req.setOption('Block2', block2Val)
      req.sender.send(generate(req._packet))

      return
    }
    else {
      // get full payload
      packet.payload = req._totalPayload
      // clear the payload incase of block2
      req._totalPayload = Buffer.alloc(0)
    }
  }

  if (req.response) {
    if (req.response.append) {
      // it is an observe request
      // and we are already streaming
      return req.response.append(packet)
    } else {
      // TODO There is a previous response but is not an ObserveStream !
      return
    }

  }
  else if (block2) {
    delete that._tkToReq[req._packet.token.readUInt32BE(0)]
  }
  else if (!req.url.observe && packet.token.length > 0 && !req.multicast) {
    // it is not, so delete the token
    delete that._tkToReq[packet.token.readUInt32BE(0)]
  }

  if (req.url.observe && packet.code !== '4.04') {
    response = new ObserveStream(packet, rsinfo, outSocket)
    response.on('close', function() {
      delete that._tkToReq[packet.token.readUInt32BE(0)]
      that._cleanUp()
    })
  } else {
    response = new IncomingMessage(packet, rsinfo, outSocket)
  }

  if (!req.multicast) {
    req.response = response
  }

  req.emit('response', response)
}

Agent.prototype._nextToken = function nextToken() {
  var buf = Buffer.alloc(4)

  if (++this._lastToken === maxToken)
    this._lastToken = 0

  buf.writeUInt32BE(this._lastToken, 0)

  return buf;
}

Agent.prototype._nextMessageId = function nextToken() {
  if (++this._lastMessageId === maxMessageId)
    this._lastMessageId = 1

  return this._lastMessageId
}

Agent.prototype.request = function request(url) {
  this._init()

  var req
    , response
    , options = url.options || url.headers
    , option
    , that = this
    , multicastTimeout = url.multicastTimeout !== undefined ? parseInt(url.multicastTimeout) : 20000

  req = new OutgoingMessage({}, function(req, packet) {
    var buf

    if (url.confirmable !== false) {
      packet.confirmable = true
    }

    // multicast message should be forced non-confirmable
    if (url.multicast === true) {
      req.multicast = true
      packet.confirmable = false
    }

    if (!(packet.ack || packet.reset)) {
      packet.messageId = that._nextMessageId()
      packet.token = that._nextToken()
    }

    try {
      buf = generate(packet)
    } catch(err) {
      req.sender.reset()
      return req.emit('error', err)
    }

    that._msgIdToReq[packet.messageId] = req
    that._tkToReq[that._lastToken] = req

    req.sender.send(buf, !packet.confirmable)
  })

  req.sender = new RetrySend(this._sock, url.port, url.hostname || url.host, url.retrySend)

  req.url = url

  req.statusCode = url.method || 'GET'

  urlPropertyToPacketOption(url, req, 'pathname', 'Uri-Path', '/')
  urlPropertyToPacketOption(url, req, 'query', 'Uri-Query', '&')

  if (options) {
    for (option in options) {
      if (options.hasOwnProperty(option)) {
        req.setOption(option, options[option])
      }
    }
  }

  if (url.proxyUri) {
    req.setOption('Proxy-Uri', url.proxyUri)
  }

  req.sender.on('error', req.emit.bind(req, 'error'))

  req.sender.on('sending', function() {
    that._msgInFlight++
  })

  req.sender.on('timeout', function (err) {
    req.emit('timeout', err)
    that.abort(req)
  })

  req.sender.on('sent', function() {
    if (req.multicast) return;

    that._msgInFlight--
    if (that._closing && that._msgInFlight === 0) {
      that._doClose()
    }
  })

  // Start multicast monitoring timer in case of multicast request
  if (url.multicast === true) {
    req.multicastTimer = setTimeout(function() {
      if (req._packet.token) {
        delete that._tkToReq[req._packet.token.readUInt32BE(0)]
      }
      that._msgInFlight--
      if (that._msgInFlight === 0) {
        that._doClose()
      }
    }, multicastTimeout)
  }

  if (url.observe)
    req.setOption('Observe', null)
  else
    req.on('response', this._cleanUp.bind(this))

  this._requests++

  req._totalPayload = Buffer.alloc(0)

  return req
}

Agent.prototype.abort = function (req) {
  req.sender.removeAllListeners()
  req.sender.reset()
  this._cleanUp()
  delete this._msgIdToReq[req._packet.messageId]
  delete this._tkToReq[req._packet.token.readUInt32BE(0)]
}

function urlPropertyToPacketOption(url, req, property, option, separator) {
  if (url[property])
    req.setOption(option, url[property].normalize('NFC').split(separator)
      .filter(function(part) { return part !== '' })
      .map(function(part) {
        var buf = Buffer.alloc(Buffer.byteLength(part))
        buf.write(part)
        return buf
      }))
}

module.exports = Agent
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
  nsp({package: path.resolve('package.json')}, cb);
});

gulp.task('pre-test', function () {
  return gulp.src('generators/**/*.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

//gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test']);
<commit_msg>Removing nsp zone until it's fixed. jfigueruela will report it<commit_after>'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');

gulp.task('static', function () {
  return gulp.src('**/*.js')
    .pipe(excludeGitignore())
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

//gulp.task('nsp', function (cb) {
//  nsp({package: path.resolve('package.json')}, cb);
//});

gulp.task('pre-test', function () {
  return gulp.src('generators/**/*.js')
    .pipe(excludeGitignore())
    .pipe(istanbul({
      includeUntested: true
    }))
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
  var mochaErr;

  gulp.src('test/**/*.js')
    .pipe(plumber())
    .pipe(mocha({reporter: 'spec'}))
    .on('error', function (err) {
      mochaErr = err;
    })
    .pipe(istanbul.writeReports())
    .on('end', function () {
      cb(mochaErr);
    });
});

gulp.task('watch', function () {
  gulp.watch(['generators/**/*.js', 'test/**'], ['test']);
});

//gulp.task('prepublish', ['nsp']);
gulp.task('prepublish', []);
gulp.task('default', ['static', 'test']);
<|endoftext|>


<commit_before>/*
 * Disk
 */

function dsk_total_data(data) {
  for (idata in data) {
    ldata = data[idata];
    /* Byte to MB */
    data[idata].y = Math.round((data[idata].y / (1024 * 1024) ));
  }

  return data;
}

function dsk_total_options() {
  return { area: true };
}

function dsk_total_graph(graph) {
  graph.yAxis.axisLabel('Trafic (MB)').tickFormat(function(d) { return d3.format('.2f')(d); });
}

/*
 * CPU
 */

function total_cpu_usage_graph(graph) {
  graph.yAxis.axisLabel('%');
  graph.color(function (d) {
      if (d.key == 'idl') return 'white'; if (d.key == 'usr') return '#aec7e8'; if (d.key == 'sys') return '#ff7f7f';
      if (d.key == 'stl') return '#7b94b5'; return '#ffd384';
  })
}

function total_cpu_usage_options() {
  return { type: 'stacked' };
}

function total_cpu_usage_data(data) {
  return data;
}

/*
 * Network
 */

function net_total_data(data) {
  for (idata in data) {
    ldata = data[idata];
    /* Byte to MB */
    data[idata].y = Math.round((data[idata].y / (1024 * 1024)));
  }

  return data;
}

function net_total_graph(graph) {
  graph.yAxis.axisLabel('Trafic (MB)').tickFormat(function(d) { return d3.format('.2f')(d); });
}

function net_total_options() {
  return { area: true };
}

/*
 * MongoDB
 */

function mongodb_stats_graph(graph) {
  graph.yAxis.axisLabel('Size (MB)').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_con_graph(graph) {
  graph.yAxis.axisLabel('Connection').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_mem_graph(graph) {
  graph.yAxis.axisLabel('Size (MB)').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_mem_options() {
  return { area: true };
}
<commit_msg>Added memory plugin support<commit_after>/*
 * Disk
 */

function dsk_total_data(data) {
  for (idata in data) {
    ldata = data[idata];
    /* Byte to MB */
    data[idata].y = Math.round((data[idata].y / (1024 * 1024) ));
  }

  return data;
}

function dsk_total_options() {
  return { area: true };
}

function dsk_total_graph(graph) {
  graph.yAxis.axisLabel('Trafic (MB)').tickFormat(function(d) { return d3.format('.2f')(d); });
}

/*
 * CPU
 */

function total_cpu_usage_graph(graph) {
  graph.yAxis.axisLabel('%');
  graph.color(function (d) {
      if (d.key == 'idl') return 'white'; if (d.key == 'usr') return '#aec7e8'; if (d.key == 'sys') return '#ff7f7f';
      if (d.key == 'stl') return '#7b94b5'; return '#ffd384';
  })
}

function total_cpu_usage_options() {
  return { type: 'stacked' };
}

function total_cpu_usage_data(data) {
  return data;
}

/*
 * Network
 */

function net_total_data(data) {
  for (idata in data) {
    ldata = data[idata];
    /* Byte to MB */
    data[idata].y = Math.round((data[idata].y / (1024 * 1024)));
  }

  return data;
}

function net_total_graph(graph) {
  graph.yAxis.axisLabel('Trafic (MB)').tickFormat(function(d) { return d3.format('.2f')(d); });
}

function net_total_options() {
  return { area: true };
}

/*
 * mem
 */

function memory_usage_data(data) {
  for (idata in data) {
    ldata = data[idata];
    /* Byte to MB */
    data[idata].y = Math.round((data[idata].y / (1024 * 1024) ));
  }

  return data;
}

function memory_usage_graph(graph) {
  graph.yAxis.axisLabel('Memory (MB)').tickFormat(function(d) { return d3.format('.2f')(d); });
}

function memory_usage_options() {
  return { area: true };
}

/*
 * MongoDB
 */

function mongodb_stats_graph(graph) {
  graph.yAxis.axisLabel('Size (MB)').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_con_graph(graph) {
  graph.yAxis.axisLabel('Connection').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_mem_graph(graph) {
  graph.yAxis.axisLabel('Size (MB)').tickFormat(function(d) { return d3.format('d.0')(d); });
}

function mongodb_mem_options() {
  return { area: true };
}
<|endoftext|>


<commit_before>jQuery(function ($) {
  function setDeifinitionLink(script) {
    script = script.replace(/sub_process:\s+(\d+)\s*\n/, function(match, jobId) {
      return '' + match + '';
    });

    script = script.replace(/^wait:\s*(.+)\s*$/gm, function(match, option) {
      return 'wait: ' + option.replace(/(\d+)\/\w+/g, function(match, jobId){
	return '' + match + '';
      });
    });

    return script
  }

  $('pre.kuroko-script').each(function(){
    var script = $(this).html();
    $(this).html(setDeifinitionLink(script));
  });
});
<commit_msg>Fix sub_process task linker<commit_after>jQuery(function ($) {
  function setDeifinitionLink(script) {
    script = script.replace(/sub_process:\s+(\d+)\s*$/gm, function(match, jobId) {
      return '' + match + '';
    });

    script = script.replace(/^wait:\s*(.+)\s*$/gm, function(match, option) {
      return 'wait: ' + option.replace(/(\d+)\/\w+/g, function(match, jobId){
	return '' + match + '';
      });
    });

    return script
  }

  $('pre.kuroko-script').each(function(){
    var script = $(this).html();
    $(this).html(setDeifinitionLink(script));
  });
});
<|endoftext|>


<commit_before>// @flow

/**
 * Enter messages here.
 *
 * Please keep keys valid JavaScript identifiers.
 * Please don't add flow type annotation
 *
 * @type {Object.<string, (string | {message: string, description: string})>}
 */
export const messages = {
  run: 'Run',
  reboot: {
    message: 'Reboot',
    description: 'Toolbar button to reboot a VM',
  },
  virtualMachines: 'Virtual Machines',
  addNewVm: 'Add new VM',
  failedToStartVm: 'Failed to start the VM',
  failedToRestartVm: 'Failed to restart the VM',
  failedToShutdownVm: 'Failed to shutdown the VM',
  failedToGetVmConsole: 'Failed to get the VM console',
  failedToSuspendVm: 'Failed to suspend the VM',
  failedToRemoveVm: 'Failed to remove the VM',
  failedToRetrieveVmIcon: 'Failed to retrieve VM icon',
  failedToRetrieveVmConsoleDetails: 'Failed to retrieve VM console details',
  failedToRetrieveListOfVmConsoles: 'Failed to retrieve list of VM consoles',
  failedToRetrieveDiskDetails: 'Failed to retrieve disk details',
  failedToRetrieveVmDisks: 'Failed to retrieve VM disks',
  failedToRetrieveIsoStorages: 'Failed to retrieve ISO storages',
  failedToRetrieveFilesFromStorage: 'Failed to retrieve files from storage',
  failedToRetrieveVmDetails: 'Failed to retrieve VM details',
  failedToChangeVmIcon: 'Failed to change VM icon',
  failedToChangeVmIconToDefault: 'Failed to change VM icon to default',
  actionFailed: '{action} failed',
  pleaseLogIn: 'Please log in',
  pleaseLogInTripleDot: 'Please log in ...',
  vmPortal: 'VM Portal',
  unknown: {
    message: 'unknown',
    description: 'followed by "version" to create "unknown version"',
  },
  unknownDatacenter: {
    message: 'unknown',
    description: 'unknown datacenter',
  },
  htmlUnsupportedOvirtVersionFoundButVersionAtLeastRequired: 'Unsupported {version} {productName} version, found but version at least {requiredVersion} is required.',
  authorizationExpired: 'Authorization expired. The page is going to be reloaded to re-login.',
  useCtrlAltEnd: 'Use Ctrl+Alt+End',
  mapCtrlAltDelKeyboardShortcutToCtrlAltEnd: 'Map Ctrl + Alt + Del keyboard shortcut to Ctrl + Alt + End',
  noVmAvailable: 'No VM available.',
  noVmAvailableForLoggedUser: 'No VM is available for the logged user.',
  consoleInUseContinue: 'Console in use, continue?',
  yes: 'Yes',
  cancel: 'Cancel',
  newNic: {
    message: 'New',
    description: 'New NIC',
  },
  save: 'Save',
  preserveDisks: 'Preserve disks',
  removeVmQustion: 'Remove the VM?',
  removeVm: 'Remove the VM',
  remove: 'Remove',
  force: 'force',
  openProtocolConsole: 'Open {protocol} Console',
  options: 'Options',
  startVm: 'Start the VM',
  suspendVm: 'Suspend the VM',
  suspend: 'Suspend',
  suspendVmQuestion: 'Suspend the VM?',
  shutdown: 'Shutdown',
  shutdownVm: 'Shutdown the VM',
  shutdownVmQuestion: 'Shutdown the VM?',
  smartcardEnabled: 'Smartcard enabled:',
  rebootVm: 'Reboot the VM',
  rebootVmQuestion: 'Restart the VM?',
  console: 'Console',
  edit: 'Edit',
  editVm: 'Edit the VM',
  noError: 'No error',
  vmHasPendingConfigurationChanges: 'The virtual machine has pending configuration changes. To take effect, please reboot the virtual machine.',
  pendingChanges: 'Pending Changes',
  vmType_desktop: 'Desktop',
  vmType_server: 'Server',
  vmType_highPerformance: 'High Performance',
  ifVmIsRunningClickToAccessItsGraphicsConsole: 'If the virtual machine is running, click the protocol name to access its Graphical Console.',
  noDisks: 'no disks',
  htmlPleaseReferToDocumentationForMoreInformation: 'Please refer to documentation for more information.',
  actualStateVmIsIn: 'The actual state the virtual machine is in.',
  state: 'State',
  optionalUserDescriptionOfVm: 'Optional user description of the virtual machine.',
  description: 'Description',
  groupOfHostsVmCanBeRunningOn: 'Group of hosts the virtual machine can be running on.',
  cluster: 'Cluster',
  containsConfigurationAndDisksWhichWillBeUsedToCreateThisVm: 'Contains the configuration and disks which will be used to create this virtual machine. Please customize as needed.',
  template: 'Template',
  operatingSystemInstalledOnVm: 'Operating system installed on the virtual machine.',
  operatingSystem: 'Operating System',
  typeOfWorkloadVmConfigurationIsOptimizedFor: 'Type of workload the virtual machine configuration is optimized for.',
  optimizedFor: 'Optimized for',
  definedMemory: 'Defined Memory',
  totalMemoryVmWillBeEquippedWith: 'Total memory the virtual machine will be equipped with.',
  lowOVirtVersion: 'SSH keys can not be managed with recent oVirt {apiVersion} version. Please upgrade oVirt to 4.2 or higher.',
  publicSSHKey: 'Your public SSH key.',
  SSHKey: 'SSH Key',
  cpus: 'CPUs',
  totalCountOfVirtualProcessorsVmWillBeEquippedWith: 'Total count of virtual processors the virtual machine will be equipped with.',
  fullyQualifiedDomainName: 'Fully Qualified Domain Name (FQDN) of the virtual machine. Please note, guest agent must be installed within the virtual machine to retrieve this value.',
  address: 'Address',
  currentlyInsertedIsoInCdDrive: 'Currently inserted ISO in CD drive',
  cd: 'CD',
  storageConnectedToVm: 'Storage connected to the virtual machine.',
  disks: 'Disks',
  close: 'Close',
  clearMessages: 'Clear Messages',
  messages: 'Messages',
  empty: 'Empty',
  refresh: {
    message: 'Refresh',
    description: 'Reload data from server',
  },
  about: {
    message: 'About',
    description: 'About application',
  },
  logOut: 'Log out',
  noMessages: 'No messages',
  enum_VmStatus_up: {
    message: 'Up',
    description: 'VM is running. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_down: {
    message: 'Down',
    description: 'VM is turned off. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_powering_up: {
    message: 'Powering up',
    description: 'VM is starting. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_paused: {
    message: 'Paused',
    description: 'VM is paused. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_migrating: {
    message: 'Migrating',
    description: 'VM is migrating from one host machine to another host machine. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_unknown: {
    message: 'Unknown',
    description: 'VM is in unknown state. Connection hot hypervisor is probably broken. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_wait_for_launch: {
    message: 'Waiting for launch',
    description: 'VM is down but planned to started. be One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_reboot_in_progress: {
    message: 'Reboot in progress',
    description: 'One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_saving_state: {
    message: 'Saving state',
    description: 'Being hibernated. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_restoring_state: {
    message: 'Restoring state',
    description: 'Waking up from hibernation. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_suspended: {
    message: 'Suspended',
    description: 'Hibernated. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_image_locked: {
    message: 'Image locked',
    description: 'Disk image is locked. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_powering_down: {
    message: 'Powering down',
    description: 'VM is being turned off. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_unassigned: {
    message: 'Unassigned',
    description: 'Error when obtaining virtual machine status. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  clickForHelp: 'Click for help',
  hostConsole: {
    message: 'Host Console',
    description: 'Label of link to the Cockpit app',
  },
  connectAutomatically: 'Connect automatically',
  fullScreen: 'Fullscreen',
  createANewVm: 'Create A New Virtual Machine',
  name: {
    message: 'Name',
    description: 'Virtual machine name',
  },
  uniqueNameOfTheVirtualMachine: 'Unique name of the virtual machine.',
  enterVmName: 'Enter VM Name',
  enterVmDescription: 'Enter VM Description (optional)',
  vmMemory: 'VM Memory',
  changeCd: 'Change CD.',
  updateVm: 'Update VM',
  createVm: 'Create VM',
  on: 'On',
  off: 'Off',
  bootMenu: 'Boot Menu',
  bootMenuTooltip: 'Boot menu allows to select bootable device. It is accessible from a console.',
  cloudInit: {
    message: 'Cloud-Init',
    description: 'Name of technology allowing to initialize operating system installation. Most likely not translatable.',
  },
  cloudInitTooltip: 'Early initialization of Linux operating systems.',
  hostName: 'Hostname',
  hostNameTooltip: 'Virtual Machine hostname.',
  sshAuthorizedKeys: 'SSH Authorized Keys',
  sshAuthorizedKeysTooltip: 'New line separated public SSH keys allowing for passwordless remote login.',
  loadingTripleDot: {
    message: 'Loading ...',
    description: 'Pending request to the server indicator label.',
  },
  thisOperationCantBeUndone: 'This operation cannot be undone.',
  areYouSureYouWantToDeleteDisk: 'Are you sure you want to delete disk {diskName}?',
  delete: 'Delete',
  confirmDelete: 'Confirm delete',
  diskCapacity: 'Disk Capacity',
  more: {
    message: 'more',
    description: 'more/less pair used to control collapsable long listing',
  },
  less: {
    message: 'less',
    description: 'more/less pair used to control collapsable long listing',
  },
  new: {
    message: 'New',
    description: 'New disk',
  },
  ok: 'OK',
  createNewDisk: 'Create New Disk',
  diskSizeHasToBeAPositiveInteger: 'Disk size has to be a positive integer.',
  noActiveStorageDomainInDataCenter: 'There is no active data storage domain in data center "{dataCenterName}"',
  alias: {
    message: 'Alias',
    description: 'In sense of "human friendly name"',
  },
  storageDomain: {
    message: 'Storage domain',
    description: 'An entity in the system where disks of virtual machines are stored. Abstraction of external file/block storages.',
  },
  size: {
    message: 'Size',
    description: '... of disk of virtual machine',
  },
  errorWhileCreatingNewDisk: 'Error while creating new disk:',
  notEditableForPoolsOrPoolVms: 'Not editable for Pools or pool VMs.',
  nic: 'Network interfaces',
  noNics: 'no NICs',
  addNewNic: 'Add new NIC',
  vnicProfile: 'VNIC Profile',
  areYouSureYouWantToDeleteNic: 'Are you sure you want to delete NIC {nicName}?',
  nicsTooltip: 'Connected VM network interfaces.',
  network: 'Network',
}

export type MessageIdType = $Keys<typeof messages>
<commit_msg>Change tooltip message to more specific one. Fixes: https://github.com/oVirt/ovirt-web-ui/issues/506<commit_after>// @flow

/**
 * Enter messages here.
 *
 * Please keep keys valid JavaScript identifiers.
 * Please don't add flow type annotation
 *
 * @type {Object.<string, (string | {message: string, description: string})>}
 */
export const messages = {
  run: 'Run',
  reboot: {
    message: 'Reboot',
    description: 'Toolbar button to reboot a VM',
  },
  virtualMachines: 'Virtual Machines',
  addNewVm: 'Add new VM',
  failedToStartVm: 'Failed to start the VM',
  failedToRestartVm: 'Failed to restart the VM',
  failedToShutdownVm: 'Failed to shutdown the VM',
  failedToGetVmConsole: 'Failed to get the VM console',
  failedToSuspendVm: 'Failed to suspend the VM',
  failedToRemoveVm: 'Failed to remove the VM',
  failedToRetrieveVmIcon: 'Failed to retrieve VM icon',
  failedToRetrieveVmConsoleDetails: 'Failed to retrieve VM console details',
  failedToRetrieveListOfVmConsoles: 'Failed to retrieve list of VM consoles',
  failedToRetrieveDiskDetails: 'Failed to retrieve disk details',
  failedToRetrieveVmDisks: 'Failed to retrieve VM disks',
  failedToRetrieveIsoStorages: 'Failed to retrieve ISO storages',
  failedToRetrieveFilesFromStorage: 'Failed to retrieve files from storage',
  failedToRetrieveVmDetails: 'Failed to retrieve VM details',
  failedToChangeVmIcon: 'Failed to change VM icon',
  failedToChangeVmIconToDefault: 'Failed to change VM icon to default',
  actionFailed: '{action} failed',
  pleaseLogIn: 'Please log in',
  pleaseLogInTripleDot: 'Please log in ...',
  vmPortal: 'VM Portal',
  unknown: {
    message: 'unknown',
    description: 'followed by "version" to create "unknown version"',
  },
  unknownDatacenter: {
    message: 'unknown',
    description: 'unknown datacenter',
  },
  htmlUnsupportedOvirtVersionFoundButVersionAtLeastRequired: 'Unsupported {version} {productName} version, found but version at least {requiredVersion} is required.',
  authorizationExpired: 'Authorization expired. The page is going to be reloaded to re-login.',
  useCtrlAltEnd: 'Use Ctrl+Alt+End',
  mapCtrlAltDelKeyboardShortcutToCtrlAltEnd: 'Map Ctrl + Alt + Del keyboard shortcut to Ctrl + Alt + End',
  noVmAvailable: 'No VM available.',
  noVmAvailableForLoggedUser: 'No VM is available for the logged user.',
  consoleInUseContinue: 'Console in use, continue?',
  yes: 'Yes',
  cancel: 'Cancel',
  newNic: {
    message: 'New',
    description: 'New NIC',
  },
  save: 'Save',
  preserveDisks: 'Preserve disks',
  removeVmQustion: 'Remove the VM?',
  removeVm: 'Remove the VM',
  remove: 'Remove',
  force: 'force',
  openProtocolConsole: 'Open {protocol} Console',
  options: 'Options',
  startVm: 'Start the VM',
  suspendVm: 'Suspend the VM',
  suspend: 'Suspend',
  suspendVmQuestion: 'Suspend the VM?',
  shutdown: 'Shutdown',
  shutdownVm: 'Shutdown the VM',
  shutdownVmQuestion: 'Shutdown the VM?',
  smartcardEnabled: 'Smartcard enabled:',
  rebootVm: 'Reboot the VM',
  rebootVmQuestion: 'Restart the VM?',
  console: 'Console',
  edit: 'Edit',
  editVm: 'Edit the VM',
  noError: 'No error',
  vmHasPendingConfigurationChanges: 'The virtual machine has pending configuration changes. To take effect, please reboot the virtual machine.',
  pendingChanges: 'Pending Changes',
  vmType_desktop: 'Desktop',
  vmType_server: 'Server',
  vmType_highPerformance: 'High Performance',
  ifVmIsRunningClickToAccessItsGraphicsConsole: 'If the virtual machine is running, click the protocol name to access its Graphical Console.',
  noDisks: 'no disks',
  htmlPleaseReferToDocumentationForMoreInformation: 'Please refer to documentation for more information.',
  actualStateVmIsIn: 'The actual state the virtual machine is in.',
  state: 'State',
  optionalUserDescriptionOfVm: 'Optional user description of the virtual machine.',
  description: 'Description',
  groupOfHostsVmCanBeRunningOn: 'Group of hosts the virtual machine can be running on.',
  cluster: 'Cluster',
  containsConfigurationAndDisksWhichWillBeUsedToCreateThisVm: 'Contains the configuration and disks which will be used to create this virtual machine. Please customize as needed.',
  template: 'Template',
  operatingSystemInstalledOnVm: 'Operating system installed on the virtual machine.',
  operatingSystem: 'Operating System',
  typeOfWorkloadVmConfigurationIsOptimizedFor: 'Type of workload the virtual machine configuration is optimized for.',
  optimizedFor: 'Optimized for',
  definedMemory: 'Defined Memory',
  totalMemoryVmWillBeEquippedWith: 'Total memory the virtual machine will be equipped with.',
  lowOVirtVersion: 'SSH keys can not be managed with recent oVirt {apiVersion} version. Please upgrade oVirt to 4.2 or higher.',
  publicSSHKey: 'Specify public key for access to guest serial console via SSH authentication.',
  SSHKey: 'SSH Key',
  cpus: 'CPUs',
  totalCountOfVirtualProcessorsVmWillBeEquippedWith: 'Total count of virtual processors the virtual machine will be equipped with.',
  fullyQualifiedDomainName: 'Fully Qualified Domain Name (FQDN) of the virtual machine. Please note, guest agent must be installed within the virtual machine to retrieve this value.',
  address: 'Address',
  currentlyInsertedIsoInCdDrive: 'Currently inserted ISO in CD drive',
  cd: 'CD',
  storageConnectedToVm: 'Storage connected to the virtual machine.',
  disks: 'Disks',
  close: 'Close',
  clearMessages: 'Clear Messages',
  messages: 'Messages',
  empty: 'Empty',
  refresh: {
    message: 'Refresh',
    description: 'Reload data from server',
  },
  about: {
    message: 'About',
    description: 'About application',
  },
  logOut: 'Log out',
  noMessages: 'No messages',
  enum_VmStatus_up: {
    message: 'Up',
    description: 'VM is running. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_down: {
    message: 'Down',
    description: 'VM is turned off. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_powering_up: {
    message: 'Powering up',
    description: 'VM is starting. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_paused: {
    message: 'Paused',
    description: 'VM is paused. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_migrating: {
    message: 'Migrating',
    description: 'VM is migrating from one host machine to another host machine. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_unknown: {
    message: 'Unknown',
    description: 'VM is in unknown state. Connection hot hypervisor is probably broken. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_wait_for_launch: {
    message: 'Waiting for launch',
    description: 'VM is down but planned to started. be One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_reboot_in_progress: {
    message: 'Reboot in progress',
    description: 'One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_saving_state: {
    message: 'Saving state',
    description: 'Being hibernated. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_restoring_state: {
    message: 'Restoring state',
    description: 'Waking up from hibernation. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_suspended: {
    message: 'Suspended',
    description: 'Hibernated. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_image_locked: {
    message: 'Image locked',
    description: 'Disk image is locked. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_powering_down: {
    message: 'Powering down',
    description: 'VM is being turned off. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  enum_VmStatus_unassigned: {
    message: 'Unassigned',
    description: 'Error when obtaining virtual machine status. One of states of a virtual machine. Other are e.g. Up, Down, Powering-Up',
  },
  clickForHelp: 'Click for help',
  hostConsole: {
    message: 'Host Console',
    description: 'Label of link to the Cockpit app',
  },
  connectAutomatically: 'Connect automatically',
  fullScreen: 'Fullscreen',
  createANewVm: 'Create A New Virtual Machine',
  name: {
    message: 'Name',
    description: 'Virtual machine name',
  },
  uniqueNameOfTheVirtualMachine: 'Unique name of the virtual machine.',
  enterVmName: 'Enter VM Name',
  enterVmDescription: 'Enter VM Description (optional)',
  vmMemory: 'VM Memory',
  changeCd: 'Change CD.',
  updateVm: 'Update VM',
  createVm: 'Create VM',
  on: 'On',
  off: 'Off',
  bootMenu: 'Boot Menu',
  bootMenuTooltip: 'Boot menu allows to select bootable device. It is accessible from a console.',
  cloudInit: {
    message: 'Cloud-Init',
    description: 'Name of technology allowing to initialize operating system installation. Most likely not translatable.',
  },
  cloudInitTooltip: 'Early initialization of Linux operating systems.',
  hostName: 'Hostname',
  hostNameTooltip: 'Virtual Machine hostname.',
  sshAuthorizedKeys: 'SSH Authorized Keys',
  sshAuthorizedKeysTooltip: 'New line separated public SSH keys allowing for passwordless remote login.',
  loadingTripleDot: {
    message: 'Loading ...',
    description: 'Pending request to the server indicator label.',
  },
  thisOperationCantBeUndone: 'This operation cannot be undone.',
  areYouSureYouWantToDeleteDisk: 'Are you sure you want to delete disk {diskName}?',
  delete: 'Delete',
  confirmDelete: 'Confirm delete',
  diskCapacity: 'Disk Capacity',
  more: {
    message: 'more',
    description: 'more/less pair used to control collapsable long listing',
  },
  less: {
    message: 'less',
    description: 'more/less pair used to control collapsable long listing',
  },
  new: {
    message: 'New',
    description: 'New disk',
  },
  ok: 'OK',
  createNewDisk: 'Create New Disk',
  diskSizeHasToBeAPositiveInteger: 'Disk size has to be a positive integer.',
  noActiveStorageDomainInDataCenter: 'There is no active data storage domain in data center "{dataCenterName}"',
  alias: {
    message: 'Alias',
    description: 'In sense of "human friendly name"',
  },
  storageDomain: {
    message: 'Storage domain',
    description: 'An entity in the system where disks of virtual machines are stored. Abstraction of external file/block storages.',
  },
  size: {
    message: 'Size',
    description: '... of disk of virtual machine',
  },
  errorWhileCreatingNewDisk: 'Error while creating new disk:',
  notEditableForPoolsOrPoolVms: 'Not editable for Pools or pool VMs.',
  nic: 'Network interfaces',
  noNics: 'no NICs',
  addNewNic: 'Add new NIC',
  vnicProfile: 'VNIC Profile',
  areYouSureYouWantToDeleteNic: 'Are you sure you want to delete NIC {nicName}?',
  nicsTooltip: 'Connected VM network interfaces.',
  network: 'Network',
}

export type MessageIdType = $Keys<typeof messages>
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
    '../Core/_Global',
    '../Core/_Base',
    '../Core/_BaseUtils',
    '../Core/_Events',
    '../Core/_Resources',
    '../Utilities/_Control',
    '../Utilities/_ElementUtilities',
    'require-style!less/controls'
    ],
    function toggleInit(_Global, _Base, _BaseUtils, _Events, _Resources, _Control, _ElementUtilities) {
        "use strict";

        _Base.Namespace.define("WinJS.UI", {
            /// <field>
            ///
            /// A control that lets the user switch an option on or off.
            ///
            /// </field>
            /// <icon src="ui_winjs.ui.toggleswitch.12x12.png" width="12" height="12" />
            /// <icon src="ui_winjs.ui.toggleswitch.16x16.png" width="16" height="16" />
            /// <htmlSnippet><![CDATA[

]]></htmlSnippet>
            /// <event name="change" bubbles="true" locid="WinJS.UI.ToggleSwitch_e:change">Raised when the switch is flipped to on (checked is set to true) or off (checked is set to false). </event>
            /// <part name="toggle" class="win-toggleswitch" locid="WinJS.UI.ToggleSwitch_part:toggle">The entire ToggleSwitch control.</part>
            /// <part name="track" class="win-toggleswitch-track" locid="WinJS.UI.ToggleSwitch_part:track">The slider portion of the toggle.</part>
            /// <part name="thumb" class="win-toggleswitch-thumb" locid="WinJS.UI.ToggleSwitch_part:thumb">The thumb of the slider.</part>
            /// <part name="title" class="win-toggleswitch-header" locid="WinJS.UI.ToggleSwitch_part:title">The main text for the ToggleSwitch control.</part>
            /// <part name="label-on" class="win-toggleswitch-value" locid="WinJS.UI.ToggleSwitch_part:label-on">The text for when the switch is on.</part>
            /// <part name="label-off" class="win-toggleswitch-value" locid="WinJS.UI.ToggleSwitch_part:label-off:">The text for when the switch is off.</part>
            /// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/base.js" shared="true" />
            /// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/ui.js" shared="true" />
            /// <resource type="css" src="//$(TARGET_DESTINATION)/css/ui-dark.css" shared="true" />
            ToggleSwitch: _Base.Namespace._lazy(function () {

                // Store some class names
                var classContainer = 'win-toggleswitch';
                var classHeader = 'win-toggleswitch-header';
                var classClick = 'win-toggleswitch-clickregion';
                var classTrack = 'win-toggleswitch-track';
                var classThumb = 'win-toggleswitch-thumb';
                var classValues = 'win-toggleswitch-values';
                var classValue = 'win-toggleswitch-value';
                var classValueOn = 'win-toggleswitch-value-on';
                var classValueOff = 'win-toggleswitch-value-off';
                var classDescription = 'win-toggleswitch-description';
                var classOn = 'win-toggleswitch-on';
                var classOff = 'win-toggleswitch-off';
                var classDisabled = 'win-toggleswitch-disabled';
                var classEnabled = 'win-toggleswitch-enabled';
                var classDragging = 'win-toggleswitch-dragging';
                var classPressed = 'win-toggleswitch-pressed';

                // Localized  strings
                var strings = {
                    get on() {
                        return _Resources._getWinJSString("ui/on").value;
                    },
                    get off() {
                        return _Resources._getWinJSString("ui/off").value;
                    },
                };

                // Define the ToggleSwitch class
                var Toggle = _Base.Class.define(function ToggleSwitch_ctor(element, options) {
                    /// <signature helpKeyword="WinJS.UI.ToggleSwitch.ToggleSwitch">
                    ///
                    /// Creates a new ToggleSwitch.
                    ///
                    /// <param name="element" domElement="true" locid="WinJS.UI.ToggleSwitch.constructor_p:element">
                    /// The DOM element that hosts the ToggleSwitch.
                    /// </param>
                    /// <param name="options" type="Object" locid="WinJS.UI.ToggleSwitch.constructor_p:options">
                    /// An object that contains one or more property/value pairs to apply to the new control.
                    /// Each property of the options object corresponds to one of the control's properties or events.
                    /// Event names must begin with "on". For example, to provide a handler for the change event,
                    /// add a property named "onchange" to the options object and set its value to the event handler.
                    /// This parameter is optional.
                    /// </param>
                    /// <returns type="WinJS.UI.ToggleSwitch" locid="WinJS.UI.ToggleSwitch.constructor_returnValue">
                    /// The new ToggleSwitch.
                    /// </returns>
                    /// </signature>

                    // Main container
                    element = element || _Global.document.createElement('div');
                    this._domElement = element;
                    _ElementUtilities.addClass(this._domElement, classContainer);

                    // Set up DOM elements
                    this._domElement.innerHTML = [
                        '

',
                        '
',
                        '
',
                        '

',
                        '
',
                        '
',
                        '
',
                        '

',
                        '

',
                        '
',
                        '

'
                    ].join('\n');

                    // Get references to elements
                    this._headerElement = this._domElement.firstElementChild;
                    this._clickElement = this._headerElement.nextElementSibling;
                    this._trackElement = this._clickElement.firstElementChild;
                    this._thumbElement = this._trackElement.firstElementChild;
                    this._labelsElement = this._clickElement.nextElementSibling;
                    this._labelOnElement = this._labelsElement.firstElementChild;
                    this._labelOffElement = this._labelOnElement.nextElementSibling;
                    this._descriptionElement = this._labelsElement.nextElementSibling;

                    // Set aria label info
                    this._headerElement.setAttribute('aria-hidden', true);
                    this._labelsElement.setAttribute('aria-hidden', true);
                    this._headerElement.setAttribute('id', _ElementUtilities._uniqueID(this._headerElement));
                    this._domElement.setAttribute('aria-labelledby', this._headerElement.id);
                    this._domElement.setAttribute('role', 'checkbox');

                    // Some initialization of main element
                    this._domElement.winControl = this;
                    _ElementUtilities.addClass(this._domElement, 'win-disposable');

                    // Add listeners
                    this._domElement.addEventListener('keydown', this._keyDownHandler.bind(this));
                    _ElementUtilities._addEventListener(this._clickElement, 'pointerdown', this._pointerDownHandler.bind(this));
                    _ElementUtilities._globalListener.addEventListener(this._domElement, 'pointermove', this._pointerMoveHandler.bind(this));
                    _ElementUtilities._globalListener.addEventListener(this._domElement, 'pointerup', this._pointerUpHandler.bind(this));

                    // Need mutation observer to listen for aria checked change
                    this._mutationObserver = new _ElementUtilities._MutationObserver(this._ariaChangedHandler.bind(this));
                    this._mutationObserver.observe(this._domElement, {attributes: true, attributeFilter: ['aria-checked']});

                    // Current x coord while being dragged
                    this._dragX = 0;
                    this._dragging = false;

                    // Default state
                    this.checked = false;
                    this.disabled = false;
                    this.labelOn = strings.on;
                    this.labelOff = strings.off;

                    // Apply options
                    _Control.setOptions(this, options);
                }, {
                    // Properties

                    /// <field type='HTMLElement' domElement='true' hidden='true' locid="WinJS.UI.ToggleSwitch.element" helpKeyword="WinJS.UI.ToggleSwitch.element">
                    /// The DOM element that hosts the ToggleSwitch control.
                    /// </field>
                    element: {
                        get: function () {
                            return this._domElement;
                        }
                    },
                    /// <field type="Boolean" locid="WinJS.UI.ToggleSwitch.checked" helpKeyword="WinJS.UI.ToggleSwitch.checked">
                    /// Gets or sets whether the control is on (checked is set to true) or off (checked is set to false).
                    /// </field>
                    checked: {
                        get: function () {
                            return this._checked;
                        },
                        set: function (value) {
                            value = !!value;
                            if (value === this.checked) {
                                return;
                            }

                            this._checked = value;
                            this._domElement.setAttribute('aria-checked', value);
                            if (value) {
                                _ElementUtilities.addClass(this._domElement, classOn);
                                _ElementUtilities.removeClass(this._domElement, classOff);
                            } else {
                                _ElementUtilities.addClass(this._domElement, classOff);
                                _ElementUtilities.removeClass(this._domElement, classOn);
                            }
                            this.dispatchEvent("change");
                        }
                    },
                    /// <field type="Boolean" locid="WinJS.UI.ToggleSwitch.disabled" helpKeyword="WinJS.UI.ToggleSwitch.disabled">
                    /// Gets or sets a value that specifies whether the control is disabled.
                    /// </field>
                    disabled: {
                        get: function () {
                            return this._disabled;
                        },
                        set: function (value) {
                            value = !!value;
                            if (value === this._disabled) {
                                return;
                            }

                            if (value) {
                                _ElementUtilities.addClass(this._domElement, classDisabled);
                                _ElementUtilities.removeClass(this._domElement, classEnabled);
                            } else {
                                _ElementUtilities.removeClass(this._domElement, classDisabled);
                                _ElementUtilities.addClass(this._domElement, classEnabled);
                            }

                            this._disabled = value;
                            this._domElement.setAttribute('aria-disabled', value);
                            this._domElement.setAttribute('tabIndex', value ? -1 : 0);
                        }
                    },
                    /// <field type="String" locid="WinJS.UI.ToggleSwitch.labelOn" helpKeyword="WinJS.UI.ToggleSwitch.labelOn">
                    /// Gets or sets the text that displays when the control is on (checked is set to true). The default value is "On".
                    /// </field>
                    labelOn: {
                        get: function () {
                            return this._labelOnElement.innerHTML;
                        },
                        set: function (value) {
                            this._labelOnElement.innerHTML = value;
                        }
                    },
                    /// <field type="String" locid="WinJS.UI.ToggleSwitch.labelOff" helpKeyword="WinJS.UI.ToggleSwitch.labelOff">
                    /// Gets or sets the text that displays when the control is off (checked is set to false). The default value is "Off".
                    /// </field>
                    labelOff: {
                        get: function () {
                            return this._labelOffElement.innerHTML;
                        },
                        set: function (value) {
                            this._labelOffElement.innerHTML = value;
                        }
                    },
                    /// <field type='String' locid="WinJS.UI.ToggleSwitch.title" helpKeyword="WinJS.UI.ToggleSwitch.title">
                    /// Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether
                    /// the control is switched on or off.
                    /// </field>
                    title: {
                        get: function () {
                            return this._headerElement.innerHTML;
                        },
                        set: function (value) {
                            this._headerElement.innerHTML = value;
                        }
                    },

                    // Events

                    /// <field type="Function" locid="WinJS.UI.ToggleSwitch.onchange" helpKeyword="WinJS.UI.ToggleSwitch.onchange">
                    /// Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false).
                    /// </field>
                    onchange: _Events._createEventProperty('change'),

                    // Public methods
                    dispose: function ToggleSwitch_dispose() {
                        if (this._disposed) {
                            return;
                        }

                        this._disposed = true;
                    },

                    // Private event handlers
                    _ariaChangedHandler: function ToggleSwitch_ariaChanged() {
                        var value = this._domElement.getAttribute('aria-checked');
                        value = (value === 'true') ? true : false;
                        this.checked = value;
                    },
                    _keyDownHandler: function ToggleSwitch_keyDown(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Toggle checked on spacebar
                        if (e.keyCode === _ElementUtilities.Key.space) {
                            this.checked = !this.checked;
                        }

                        // Arrow keys set value
                        if (e.keyCode === _ElementUtilities.Key.rightArrow ||
                            e.keyCode === _ElementUtilities.Key.upArrow) {
                            this.checked = true;
                        }
                        if (e.keyCode === _ElementUtilities.Key.leftArrow ||
                            e.keyCode === _ElementUtilities.Key.downArrow) {
                            this.checked = false;
                        }

                    },
                    _pointerDownHandler: function ToggleSwitch_pointerDown(e) {
                        if (this.disabled) {
                            return;
                        }

                        e.preventDefault();

                        this._mousedown = true;
                        this._dragXStart = e.pageX - this._trackElement.offsetLeft - this._thumbElement.offsetWidth / 2;
                        this._dragX = this._dragXStart;
                        this._dragging = false;
                        _ElementUtilities.addClass(this._domElement, classPressed);
                    },
                    _pointerUpHandler: function ToggleSwitch_pointerUp(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Since up is a global event we should only take action
                        // if a mousedown was registered on us initially
                        if (!this._mousedown) {
                            return;
                        }

                        e = e.detail.originalEvent;
                        e.preventDefault();

                        // If the thumb is being dragged, pick a new value based on what the thumb
                        // was closest to
                        var isRTL = _Global.getComputedStyle(this._domElement).direction === 'rtl';
                        if (this._dragging) {
                            var maxX = this._trackElement.offsetWidth - this._thumbElement.offsetWidth;
                            this.checked = isRTL ? this._dragX < maxX / 2 : this._dragX >= maxX / 2;
                            this._dragging = false;
                            _ElementUtilities.removeClass(this._domElement, classDragging);
                        } else {
                            // Otherwise, just toggle the value as the up constitutes a
                            // click event
                            this.checked = !this.checked;
                        }

                        // Reset tracking variables and intermediate styles
                        this._mousedown = false;
                        this._thumbElement.style.left = '';
                        _ElementUtilities.removeClass(this._domElement, classPressed);
                    },
                    _pointerMoveHandler: function ToggleSwitch_pointerMove(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Not dragging if mouse isn't down
                        if (!this._mousedown) {
                            return;
                        }

                        e = e.detail.originalEvent;
                        e.preventDefault();

                        // Get pointer x coord relative to control
                        var localMouseX = e.pageX - this._trackElement.offsetLeft - this._thumbElement.offsetWidth / 2;

                        // Calculate a position for the thumb
                        var maxX = this._trackElement.offsetWidth - this._thumbElement.offsetWidth - 6;
                        this._dragX = Math.min(maxX, localMouseX);
                        this._dragX = Math.max(2, this._dragX);

                        // Calculate if this pointermove constitutes switching to drag mode
                        if (!this._dragging && Math.abs(this._dragX - this._dragXStart) > 3) {
                            this._dragging = true;
                            _ElementUtilities.addClass(this._domElement, classDragging);
                        }

                        this._thumbElement.style.left = this._dragX + 'px';
                    }
                });

                // addEventListener, removeEventListener, dispatchEvent
                _Base.Class.mix(Toggle, _Control.DOMEventMixin);

                return Toggle;
            })
        });
    }
);<commit_msg>Fix toggle switch label to be clickable<commit_after>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
    '../Core/_Global',
    '../Core/_Base',
    '../Core/_BaseUtils',
    '../Core/_Events',
    '../Core/_Resources',
    '../Utilities/_Control',
    '../Utilities/_ElementUtilities',
    'require-style!less/controls'
    ],
    function toggleInit(_Global, _Base, _BaseUtils, _Events, _Resources, _Control, _ElementUtilities) {
        "use strict";

        _Base.Namespace.define("WinJS.UI", {
            /// <field>
            ///
            /// A control that lets the user switch an option on or off.
            ///
            /// </field>
            /// <icon src="ui_winjs.ui.toggleswitch.12x12.png" width="12" height="12" />
            /// <icon src="ui_winjs.ui.toggleswitch.16x16.png" width="16" height="16" />
            /// <htmlSnippet><![CDATA[

]]></htmlSnippet>
            /// <event name="change" bubbles="true" locid="WinJS.UI.ToggleSwitch_e:change">Raised when the switch is flipped to on (checked is set to true) or off (checked is set to false). </event>
            /// <part name="toggle" class="win-toggleswitch" locid="WinJS.UI.ToggleSwitch_part:toggle">The entire ToggleSwitch control.</part>
            /// <part name="track" class="win-toggleswitch-track" locid="WinJS.UI.ToggleSwitch_part:track">The slider portion of the toggle.</part>
            /// <part name="thumb" class="win-toggleswitch-thumb" locid="WinJS.UI.ToggleSwitch_part:thumb">The thumb of the slider.</part>
            /// <part name="title" class="win-toggleswitch-header" locid="WinJS.UI.ToggleSwitch_part:title">The main text for the ToggleSwitch control.</part>
            /// <part name="label-on" class="win-toggleswitch-value" locid="WinJS.UI.ToggleSwitch_part:label-on">The text for when the switch is on.</part>
            /// <part name="label-off" class="win-toggleswitch-value" locid="WinJS.UI.ToggleSwitch_part:label-off:">The text for when the switch is off.</part>
            /// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/base.js" shared="true" />
            /// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/ui.js" shared="true" />
            /// <resource type="css" src="//$(TARGET_DESTINATION)/css/ui-dark.css" shared="true" />
            ToggleSwitch: _Base.Namespace._lazy(function () {

                // Store some class names
                var classContainer = 'win-toggleswitch';
                var classHeader = 'win-toggleswitch-header';
                var classClick = 'win-toggleswitch-clickregion';
                var classTrack = 'win-toggleswitch-track';
                var classThumb = 'win-toggleswitch-thumb';
                var classValues = 'win-toggleswitch-values';
                var classValue = 'win-toggleswitch-value';
                var classValueOn = 'win-toggleswitch-value-on';
                var classValueOff = 'win-toggleswitch-value-off';
                var classDescription = 'win-toggleswitch-description';
                var classOn = 'win-toggleswitch-on';
                var classOff = 'win-toggleswitch-off';
                var classDisabled = 'win-toggleswitch-disabled';
                var classEnabled = 'win-toggleswitch-enabled';
                var classDragging = 'win-toggleswitch-dragging';
                var classPressed = 'win-toggleswitch-pressed';

                // Localized  strings
                var strings = {
                    get on() {
                        return _Resources._getWinJSString("ui/on").value;
                    },
                    get off() {
                        return _Resources._getWinJSString("ui/off").value;
                    },
                };

                // Define the ToggleSwitch class
                var Toggle = _Base.Class.define(function ToggleSwitch_ctor(element, options) {
                    /// <signature helpKeyword="WinJS.UI.ToggleSwitch.ToggleSwitch">
                    ///
                    /// Creates a new ToggleSwitch.
                    ///
                    /// <param name="element" domElement="true" locid="WinJS.UI.ToggleSwitch.constructor_p:element">
                    /// The DOM element that hosts the ToggleSwitch.
                    /// </param>
                    /// <param name="options" type="Object" locid="WinJS.UI.ToggleSwitch.constructor_p:options">
                    /// An object that contains one or more property/value pairs to apply to the new control.
                    /// Each property of the options object corresponds to one of the control's properties or events.
                    /// Event names must begin with "on". For example, to provide a handler for the change event,
                    /// add a property named "onchange" to the options object and set its value to the event handler.
                    /// This parameter is optional.
                    /// </param>
                    /// <returns type="WinJS.UI.ToggleSwitch" locid="WinJS.UI.ToggleSwitch.constructor_returnValue">
                    /// The new ToggleSwitch.
                    /// </returns>
                    /// </signature>

                    // Main container
                    element = element || _Global.document.createElement('div');
                    this._domElement = element;
                    _ElementUtilities.addClass(this._domElement, classContainer);

                    // Set up DOM elements
                    this._domElement.innerHTML = [
                        '

',
                        '
',
                        '
',
                        '

',
                        '
',
                        '
',
                        '

',
                        '

',
                        '
',
                        '
',
                        '

'
                    ].join('\n');

                    // Get references to elements
                    this._headerElement = this._domElement.firstElementChild;
                    this._clickElement = this._headerElement.nextElementSibling;
                    this._trackElement = this._clickElement.firstElementChild;
                    this._thumbElement = this._trackElement.firstElementChild;
                    this._labelsElement = this._trackElement.nextElementSibling;
                    this._labelOnElement = this._labelsElement.firstElementChild;
                    this._labelOffElement = this._labelOnElement.nextElementSibling;
                    this._descriptionElement = this._clickElement.nextElementSibling;

                    // Set aria label info
                    this._headerElement.setAttribute('aria-hidden', true);
                    this._labelsElement.setAttribute('aria-hidden', true);
                    this._headerElement.setAttribute('id', _ElementUtilities._uniqueID(this._headerElement));
                    this._domElement.setAttribute('aria-labelledby', this._headerElement.id);
                    this._domElement.setAttribute('role', 'checkbox');

                    // Some initialization of main element
                    this._domElement.winControl = this;
                    _ElementUtilities.addClass(this._domElement, 'win-disposable');

                    // Add listeners
                    this._domElement.addEventListener('keydown', this._keyDownHandler.bind(this));
                    _ElementUtilities._addEventListener(this._clickElement, 'pointerdown', this._pointerDownHandler.bind(this));
                    _ElementUtilities._globalListener.addEventListener(this._domElement, 'pointermove', this._pointerMoveHandler.bind(this));
                    _ElementUtilities._globalListener.addEventListener(this._domElement, 'pointerup', this._pointerUpHandler.bind(this));

                    // Need mutation observer to listen for aria checked change
                    this._mutationObserver = new _ElementUtilities._MutationObserver(this._ariaChangedHandler.bind(this));
                    this._mutationObserver.observe(this._domElement, {attributes: true, attributeFilter: ['aria-checked']});

                    // Current x coord while being dragged
                    this._dragX = 0;
                    this._dragging = false;

                    // Default state
                    this.checked = false;
                    this.disabled = false;
                    this.labelOn = strings.on;
                    this.labelOff = strings.off;

                    // Apply options
                    _Control.setOptions(this, options);
                }, {
                    // Properties

                    /// <field type='HTMLElement' domElement='true' hidden='true' locid="WinJS.UI.ToggleSwitch.element" helpKeyword="WinJS.UI.ToggleSwitch.element">
                    /// The DOM element that hosts the ToggleSwitch control.
                    /// </field>
                    element: {
                        get: function () {
                            return this._domElement;
                        }
                    },
                    /// <field type="Boolean" locid="WinJS.UI.ToggleSwitch.checked" helpKeyword="WinJS.UI.ToggleSwitch.checked">
                    /// Gets or sets whether the control is on (checked is set to true) or off (checked is set to false).
                    /// </field>
                    checked: {
                        get: function () {
                            return this._checked;
                        },
                        set: function (value) {
                            value = !!value;
                            if (value === this.checked) {
                                return;
                            }

                            this._checked = value;
                            this._domElement.setAttribute('aria-checked', value);
                            if (value) {
                                _ElementUtilities.addClass(this._domElement, classOn);
                                _ElementUtilities.removeClass(this._domElement, classOff);
                            } else {
                                _ElementUtilities.addClass(this._domElement, classOff);
                                _ElementUtilities.removeClass(this._domElement, classOn);
                            }
                            this.dispatchEvent("change");
                        }
                    },
                    /// <field type="Boolean" locid="WinJS.UI.ToggleSwitch.disabled" helpKeyword="WinJS.UI.ToggleSwitch.disabled">
                    /// Gets or sets a value that specifies whether the control is disabled.
                    /// </field>
                    disabled: {
                        get: function () {
                            return this._disabled;
                        },
                        set: function (value) {
                            value = !!value;
                            if (value === this._disabled) {
                                return;
                            }

                            if (value) {
                                _ElementUtilities.addClass(this._domElement, classDisabled);
                                _ElementUtilities.removeClass(this._domElement, classEnabled);
                            } else {
                                _ElementUtilities.removeClass(this._domElement, classDisabled);
                                _ElementUtilities.addClass(this._domElement, classEnabled);
                            }

                            this._disabled = value;
                            this._domElement.setAttribute('aria-disabled', value);
                            this._domElement.setAttribute('tabIndex', value ? -1 : 0);
                        }
                    },
                    /// <field type="String" locid="WinJS.UI.ToggleSwitch.labelOn" helpKeyword="WinJS.UI.ToggleSwitch.labelOn">
                    /// Gets or sets the text that displays when the control is on (checked is set to true). The default value is "On".
                    /// </field>
                    labelOn: {
                        get: function () {
                            return this._labelOnElement.innerHTML;
                        },
                        set: function (value) {
                            this._labelOnElement.innerHTML = value;
                        }
                    },
                    /// <field type="String" locid="WinJS.UI.ToggleSwitch.labelOff" helpKeyword="WinJS.UI.ToggleSwitch.labelOff">
                    /// Gets or sets the text that displays when the control is off (checked is set to false). The default value is "Off".
                    /// </field>
                    labelOff: {
                        get: function () {
                            return this._labelOffElement.innerHTML;
                        },
                        set: function (value) {
                            this._labelOffElement.innerHTML = value;
                        }
                    },
                    /// <field type='String' locid="WinJS.UI.ToggleSwitch.title" helpKeyword="WinJS.UI.ToggleSwitch.title">
                    /// Gets or sets the main text for the ToggleSwitch control. This text is always displayed, regardless of whether
                    /// the control is switched on or off.
                    /// </field>
                    title: {
                        get: function () {
                            return this._headerElement.innerHTML;
                        },
                        set: function (value) {
                            this._headerElement.innerHTML = value;
                        }
                    },

                    // Events

                    /// <field type="Function" locid="WinJS.UI.ToggleSwitch.onchange" helpKeyword="WinJS.UI.ToggleSwitch.onchange">
                    /// Occurs when the ToggleSwitch control is flipped to on (checked == true) or off (checked == false).
                    /// </field>
                    onchange: _Events._createEventProperty('change'),

                    // Public methods
                    dispose: function ToggleSwitch_dispose() {
                        if (this._disposed) {
                            return;
                        }

                        this._disposed = true;
                    },

                    // Private event handlers
                    _ariaChangedHandler: function ToggleSwitch_ariaChanged() {
                        var value = this._domElement.getAttribute('aria-checked');
                        value = (value === 'true') ? true : false;
                        this.checked = value;
                    },
                    _keyDownHandler: function ToggleSwitch_keyDown(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Toggle checked on spacebar
                        if (e.keyCode === _ElementUtilities.Key.space) {
                            this.checked = !this.checked;
                        }

                        // Arrow keys set value
                        if (e.keyCode === _ElementUtilities.Key.rightArrow ||
                            e.keyCode === _ElementUtilities.Key.upArrow) {
                            this.checked = true;
                        }
                        if (e.keyCode === _ElementUtilities.Key.leftArrow ||
                            e.keyCode === _ElementUtilities.Key.downArrow) {
                            this.checked = false;
                        }

                    },
                    _pointerDownHandler: function ToggleSwitch_pointerDown(e) {
                        if (this.disabled) {
                            return;
                        }

                        e.preventDefault();

                        this._mousedown = true;
                        this._dragXStart = e.pageX - this._trackElement.offsetLeft;
                        this._dragX = this._dragXStart;
                        this._dragging = false;
                        _ElementUtilities.addClass(this._domElement, classPressed);
                    },
                    _pointerUpHandler: function ToggleSwitch_pointerUp(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Since up is a global event we should only take action
                        // if a mousedown was registered on us initially
                        if (!this._mousedown) {
                            return;
                        }

                        e = e.detail.originalEvent;
                        e.preventDefault();

                        // If the thumb is being dragged, pick a new value based on what the thumb
                        // was closest to
                        var isRTL = _Global.getComputedStyle(this._domElement).direction === 'rtl';
                        if (this._dragging) {
                            var maxX = this._trackElement.offsetWidth - this._thumbElement.offsetWidth;
                            this.checked = isRTL ? this._dragX < maxX / 2 : this._dragX >= maxX / 2;
                            this._dragging = false;
                            _ElementUtilities.removeClass(this._domElement, classDragging);
                        } else {
                            // Otherwise, just toggle the value as the up constitutes a
                            // click event
                            this.checked = !this.checked;
                        }

                        // Reset tracking variables and intermediate styles
                        this._mousedown = false;
                        this._thumbElement.style.left = '';
                        _ElementUtilities.removeClass(this._domElement, classPressed);
                    },
                    _pointerMoveHandler: function ToggleSwitch_pointerMove(e) {
                        if (this.disabled) {
                            return;
                        }

                        // Not dragging if mouse isn't down
                        if (!this._mousedown) {
                            return;
                        }

                        e = e.detail.originalEvent;
                        e.preventDefault();

                        // Get pointer x coord relative to control
                        var localMouseX = e.pageX - this._trackElement.offsetLeft;

                        // Not dragging if mouse is outside track
                        if (localMouseX > this._trackElement.offsetWidth) {
                            return;
                        }

                        // Calculate a position for the thumb
                        var maxX = this._trackElement.offsetWidth - this._thumbElement.offsetWidth - 6;
                        this._dragX = Math.min(maxX, localMouseX - this._thumbElement.offsetWidth / 2);
                        this._dragX = Math.max(2, this._dragX);

                        // Calculate if this pointermove constitutes switching to drag mode
                        if (!this._dragging && Math.abs(this._dragX - this._dragXStart) > 3) {
                            this._dragging = true;
                            _ElementUtilities.addClass(this._domElement, classDragging);
                        }

                        this._thumbElement.style.left = this._dragX + 'px';
                    }
                });

                // addEventListener, removeEventListener, dispatchEvent
                _Base.Class.mix(Toggle, _Control.DOMEventMixin);

                return Toggle;
            })
        });
    }
);<|endoftext|>