<commit_before>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(){ 'use strict'
  var _shell = new ActiveXObject("WScript.Shell"),
      _network = new ActiveXObject("WScript.Network"),
      _fso = new ActiveXObject("Scripting.FileSystemObject"),
      _drivers = _network.EnumNetworkDrives(),
      _printers = _network.EnumPrinterConnections(),
      _consts = {
        ENVTYPE_PROCESS: 'PROCESS',
        ENVTYPE_USER: 'USER',
        ENVTYPE_SYSTEM: 'SYSTEM'
      },
      _host = {
        name: WScript.Name,
        version: WScript.Version,
        build: WScript.BuildVersion,
        execPath: WScript.FullName,
        execDirectory: WScript.Path
      },
      _script = {
        name: WScript.ScriptName,
        file: WScript.ScriptFullName,
        currentDirectory: _shell.CurrentDirectory
      },
      _net = {
        domain: _network.UserDomain,
        user: _network.UserName,
        computer: _network.ComputerName,
        drives: (function(){
          var _result = [];
          for(i = 0; i < _drivers.length; i += 2) {
            _result.push({drive: _drivers.Item(i), path: _drivers.Item(i+1)});
          }
          return _result;
        })(),
        printers: (function(){
          var _result = [];
          for(i = 0; i < _printers.length; i += 2) {
            _result.push({id: _printers.Item(i), name: _printers.Item(i+1)});
          }
          return _result;
        })()
      },
      // Minimalist copy of <fsutils.js>.
      // You are here not to cause circular reference, because <fsutils.js>
      // refers to <sysutils.js>.
      fs = _fsUtilsLite = {
        absolutePath: function(path){
          return _fso.GetAbsolutePathName(path);
        },
        createTextFile: function(path, overwrite, unicode){
          overwrite = overwrite || false;
          unicode = unicode || false;
          return _fso.CreateTextFile(this.absolutePath(path), overwrite, unicode);
        },
        fileExists: function(path){
          var _path = this.absolutePath(path);
          return _fso.FileExists(_path);
        },
        getArrayFileContent: function(path){
          var _file = _fso.OpenTextFile(this.absolutePath(path), 1),
              _content = [];
          while(!_file.AtEndOfStream)
            _content.push(_file.ReadLine());
          _file.Close();
          return _content;
        }
      };

  /**
   * Get a maker for environment variables of process data
   *
   * @return function
   */
  function _getterProcessEnv(){
    return _shell.Environment(_consts.ENVTYPE_PROCESS);
  }

  /**
   * Get a maker for environment variables of user data
   *
   * @return function
   */
  function _getterUserEnvironment(){
    return _shell.Environment(_consts.ENVTYPE_USER);
  }

  /**
   * Get a maker for environment variables of system data
   *
   * @return function
   */
  function _getterSystemEnvironment(){
    return _shell.Environment(_consts.ENVTYPE_SYSTEM);
  }

  /**
   * Awaits X miliseconds
   *
   * @param {int} miliseconds Number of miliseconds to wait
   */
  function _sleep(miliseconds){
    WScript.Sleep(miliseconds);
  }

  /**
   * Build a string, expandding a environment variable names.
   *
   * @param {string} envString  String to expand
   *
   * @return New string with environment variable expandded.
   */
  function _buildEnvirementString(envString){
    return _shell.ExpandEnvironmentStrings(envString);
  }

  /**
   * Get a environment variable value.
   *
   * @param {string}  varName   Name of environment variable
   * @param {ENVTYPE} envType   Type of environment
   *
   * @return Value os variable or empty string if not found.
   */
  function _getEnvironment(varName, envType){
    var _getEnv,
        envType = envType || _consts.ENVTYPE_PROCESS;
    if(envType == _consts.ENVTYPE_SYSTEM){
      _getEnv = _getterSystemEnvironment();
    }else if(envType == _consts.ENVTYPE_USER){
      _getEnv = _getterUserEnvironment();
    }else{
      _getEnv = _getterProcessEnv();
    }
    return _getEnv(varName);
  }

  /**
   * Set a environment variable value.
   *
   * @param {string}  varName   Name of environment variable
   * @param {string}  varValue  Value os environment variable
   * @param {ENVTYPE} envType   Type of environment
   *
   * @return Value os variable or empty string if not found.
   */
  function _setEnvironment(varName, varValue, envType){
    var _getEnv,
        envType = envType || _consts.ENVTYPE_PROCESS;
    if(envType == _consts.ENVTYPE_SYSTEM){
      _getEnv = _getterSystemEnvironment();
    }else if(envType == _consts.ENVTYPE_USER){
      _getEnv = _getterUserEnvironment();
    }else if(envType == _consts.ENVTYPE_PROCESS){
      _getEnv = _getterProcessEnv();
    }else{
      throw new Error('<sysutils._setEnvironment> #ArgumentException: Invalid @envType.');
    }
    _getEnv(varName) = varValue;
    // Creating a POSTFILE to update environment on parent process
    if(envType == _consts.ENVTYPE_PROCESS){
      sys.log('#WARNING: Creating a POSTFILE to update environment on parent process');
      sys.log('#TODO: Implements PowerShell version');

      var _postFilePathCmd = sys.product.meta.hotEnvVarsFileName.replace('{type}', 'cmd'),
          _postFileContentCmd = [];

      if(fs.fileExists(_postFilePathCmd)){
        var _fileContent = fs.getArrayFileContent(_postFilePathCmd);
        for(var l in _fileContent){
          var _line = _fileContent[l];
          if(_line.indexOf('set {k}='.replace('{k}', varName)) == 0) continue;
          _postFileContentCmd.push(_line);
        }
      }

      _postFileContentCmd.push('set {k}={v}'.replace('{k}', varName).replace('{v}', varValue));

      var _postFileCmd = fs.createTextFile(_postFilePathCmd, true);
      for(var l in _postFileContentCmd){
        _postFileCmd.WriteLine(_postFileContentCmd[l]);
      }
      _postFileCmd.Close();
    }
    return _getEnv(varName);
  }

  /**
   * Checks if @v is a valid Array object
   */
  function _isArray(v){
    return (v.length && typeof v != 'string');
  }

  /**
   * Checks if @a contains @v
   */
  function _inArray(a,v){
    for(var i in a){
      if(a[i] == v) return true;
    }
    return false;
  }

  /**
   * Create a command actions runner descriptor.
   *
   * @param {array} options   List of options arguments
   *
   * Ex1:    ['value|version|v','value|path|p']
   *
   * Usage: e5r <cmd> -v 1.0       | e5r <cmd> --version 1.0
   *        e5r <cmd> -p "path/to" | e5r <cmd> --path "path/to"
   *
   *        {version:'1.0', path:null}
   *        {version:null, path:'path/to'}
   *
   * Ex2:   ['switch|test|t,T']
   *
   * Usage: e5r <cmd> --test --other "value param"
   *        e5r <cmd> --other "value param"
   *        e5r <cmd> --T
   *
   *        {test: true, other:'value param'}
   *        {test: false, other:'value param'}
   *        {test: true, other:null}
   *
   * @param {array} actions   List of actions to execute
   *
   * @return Command Action Descriptor object
   */
  function _createCmdActionsDescriptor(options, actions){
    if(!_isArray(options)){
      throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @options must be an Array.');
    }
    if(!_isArray(actions)){
      throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @actions must be an Array.');
    }
    for(var a in actions){
      if(!_isArray(actions[a])){
        throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @actions['+a+'] must be an Array.');
      }
    }

    return {
      __options: options,
      __actions: actions,

      __getAction: function(act){
        for(var _act in this.__actions){
          var _actObj = this.__actions[_act],
              _actName = _actObj.length > 1 ? (_actObj[0]||null) : '',
              _actCbck = _actObj.length > 1 ? (_actObj[1]||null) : (_actObj[0]||null);
          if(typeof _actName != 'string' || typeof _actCbck != 'function')
            throw new Error('<sysutils._createCmdActionsDescriptor.__getAction>: Invalid action signature.');
          if(_actName === act)
            return _actCbck;
        }
        return null;
      },

      __describe: function(n){
        for(var o in this.__options){
          var oArray = this.__options[o].split('|'),
              oType = (oArray[0]||null),
              oName = (oArray[1]||null),
              oAliases = (oArray[2]||'').split(','),
              _n = '',
              _isNamed = false;
          if(oType == null || oName == null){
            throw new Error('<sysutils._createCmdActionsDescriptor.__describe>: Invalid option syntax.');
          }
          for(var c = 0; c < n.length; c++){
            if(c < 2 && n.charAt(c)=='-') continue;
            _n += n.charAt(c);
          }
          _isNamed = (n.length == 2 && n.charAt(0) == '-' && n.charAt(1) != '-') ||
                     (n.length > 2 && n.charAt(0) == '-' && n.charAt(1) == '-');
          if(!_isNamed) continue;
          if(oName == _n || _inArray(oAliases,_n)){
            return {
              type: oType.toLowerCase(),
              name: oName
            }
          }
        }
        return null;
      },

      run:function(args){
        var _opts = {},
            _args = [],
            _pIdx = 0;
        // Options informed in params
        while(_pIdx < args.length){
          var param = args[_pIdx],
              nextParam = (args[_pIdx+1]||null),
              descriptor = this.__describe(param);
          if(!descriptor){
            _args.push(param);
            _pIdx++;
            continue;
          }
          if(descriptor.type == 'switch'){
            _opts[descriptor.name] = true;
          }
          if(descriptor.type == 'value'){
            if(nextParam != null && nextParam.charAt(0) != '-'){
              _opts[descriptor.name] = nextParam;
              _pIdx++;
            }else{
              _opts[descriptor.name] = null;
            }
          }
          _pIdx++;
        }
        // Not informed options
        for(var _iO in this.__options){
          var _optObj = this.__options[_iO].split('|'),
              _optType = _optObj[0]||null,
              _optName = _optObj[1]||null;
          if(!(_optName in _opts))
            _opts[_optName] = _optType == 'switch' ? false : null;
        }
        // Detect action name and others parameters
        var _actionName = _args[0]||'',
            _actionCallback = this.__getAction(_actionName),
            _newArgs = [];
        if(_actionName) for(var a = 1; a < _args.length;a++)
          _newArgs.push(_args[a]);

        if(typeof _actionCallback == 'function')
          _actionCallback(_opts, _newArgs);
      }
    }
  }

  module.exports = {
    CONST: _consts,
    stdErr: WScript.StdErr,
    stdIn: WScript.StdIn,
    stdOut: WScript.StdOut,

    host: _host,
    script: _script,
    net: _net,

    sleep: _sleep,
    buildEnvString: _buildEnvirementString,
    getEnvironment: _getEnvironment,
    setEnvironment: _setEnvironment,
    cmdActions: _createCmdActionsDescriptor
  }
})();
<commit_msg>Implemented HotEnvVars file to PowerShell<commit_after>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(){ 'use strict'
  var _shell = new ActiveXObject("WScript.Shell"),
      _network = new ActiveXObject("WScript.Network"),
      _fso = new ActiveXObject("Scripting.FileSystemObject"),
      _drivers = _network.EnumNetworkDrives(),
      _printers = _network.EnumPrinterConnections(),
      _consts = {
        ENVTYPE_PROCESS: 'PROCESS',
        ENVTYPE_USER: 'USER',
        ENVTYPE_SYSTEM: 'SYSTEM'
      },
      _host = {
        name: WScript.Name,
        version: WScript.Version,
        build: WScript.BuildVersion,
        execPath: WScript.FullName,
        execDirectory: WScript.Path
      },
      _script = {
        name: WScript.ScriptName,
        file: WScript.ScriptFullName,
        currentDirectory: _shell.CurrentDirectory
      },
      _net = {
        domain: _network.UserDomain,
        user: _network.UserName,
        computer: _network.ComputerName,
        drives: (function(){
          var _result = [];
          for(i = 0; i < _drivers.length; i += 2) {
            _result.push({drive: _drivers.Item(i), path: _drivers.Item(i+1)});
          }
          return _result;
        })(),
        printers: (function(){
          var _result = [];
          for(i = 0; i < _printers.length; i += 2) {
            _result.push({id: _printers.Item(i), name: _printers.Item(i+1)});
          }
          return _result;
        })()
      },
      // Minimalist copy of <fsutils.js>.
      // You are here not to cause circular reference, because <fsutils.js>
      // refers to <sysutils.js>.
      fs = _fsUtilsLite = {
        absolutePath: function(path){
          return _fso.GetAbsolutePathName(path);
        },
        createTextFile: function(path, overwrite, unicode){
          overwrite = overwrite || false;
          unicode = unicode || false;
          return _fso.CreateTextFile(this.absolutePath(path), overwrite, unicode);
        },
        fileExists: function(path){
          var _path = this.absolutePath(path);
          return _fso.FileExists(_path);
        },
        getArrayFileContent: function(path){
          var _file = _fso.OpenTextFile(this.absolutePath(path), 1),
              _content = [];
          while(!_file.AtEndOfStream)
            _content.push(_file.ReadLine());
          _file.Close();
          return _content;
        }
      };

  /**
   * Get a maker for environment variables of process data
   *
   * @return function
   */
  function _getterProcessEnv(){
    return _shell.Environment(_consts.ENVTYPE_PROCESS);
  }

  /**
   * Get a maker for environment variables of user data
   *
   * @return function
   */
  function _getterUserEnvironment(){
    return _shell.Environment(_consts.ENVTYPE_USER);
  }

  /**
   * Get a maker for environment variables of system data
   *
   * @return function
   */
  function _getterSystemEnvironment(){
    return _shell.Environment(_consts.ENVTYPE_SYSTEM);
  }

  /**
   * Awaits X miliseconds
   *
   * @param {int} miliseconds Number of miliseconds to wait
   */
  function _sleep(miliseconds){
    WScript.Sleep(miliseconds);
  }

  /**
   * Build a string, expandding a environment variable names.
   *
   * @param {string} envString  String to expand
   *
   * @return New string with environment variable expandded.
   */
  function _buildEnvirementString(envString){
    return _shell.ExpandEnvironmentStrings(envString);
  }

  /**
   * Get a environment variable value.
   *
   * @param {string}  varName   Name of environment variable
   * @param {ENVTYPE} envType   Type of environment
   *
   * @return Value os variable or empty string if not found.
   */
  function _getEnvironment(varName, envType){
    var _getEnv,
        envType = envType || _consts.ENVTYPE_PROCESS;
    if(envType == _consts.ENVTYPE_SYSTEM){
      _getEnv = _getterSystemEnvironment();
    }else if(envType == _consts.ENVTYPE_USER){
      _getEnv = _getterUserEnvironment();
    }else{
      _getEnv = _getterProcessEnv();
    }
    return _getEnv(varName);
  }

  /**
   * Set a environment variable value.
   *
   * @param {string}  varName   Name of environment variable
   * @param {string}  varValue  Value os environment variable
   * @param {ENVTYPE} envType   Type of environment
   *
   * @return Value os variable or empty string if not found.
   */
  function _setEnvironment(varName, varValue, envType){
    var _getEnv,
        envType = envType || _consts.ENVTYPE_PROCESS;
    if(envType == _consts.ENVTYPE_SYSTEM){
      _getEnv = _getterSystemEnvironment();
    }else if(envType == _consts.ENVTYPE_USER){
      _getEnv = _getterUserEnvironment();
    }else if(envType == _consts.ENVTYPE_PROCESS){
      _getEnv = _getterProcessEnv();
    }else{
      throw new Error('<sysutils._setEnvironment> #ArgumentException: Invalid @envType.');
    }
    _getEnv(varName) = varValue;

    // Creating a POSTFILE to update environment on parent process
    if(envType == _consts.ENVTYPE_PROCESS){
      function __(fileType, tmplSearch, tmplReplace, key, value){
        var _path = sys.product.meta.hotEnvVarsFileName.replace('{type}', fileType),
            _fileContent = [],
            _tmpContent,
            _file;
        if(fs.fileExists(_path)){
          _tmpContent = fs.getArrayFileContent(_path);
          for(var l in _tmpContent){
            var _line = _tmpContent[l];
            if(_line.indexOf(tmplSearch.replace('{k}', key)) == 0) continue;
            _fileContent.push(_line);
          }
        }
        _fileContent.push(tmplReplace.replace('{k}', key).replace('{v}', value));
        _file = fs.createTextFile(_path, true);
        for(var l in _fileContent){
          _file.WriteLine(_fileContent[l]);
        }
        _file.Close();
      }
      __('cmd', 'set {k}=', 'set {k}={v}', varName, varValue);
      __('ps1', '$env:{k}=', '$env:{k}="{v}"', varName, varValue.replace(/"/g, '`"'));
    }
    return _getEnv(varName);
  }

  /**
   * Checks if @v is a valid Array object
   */
  function _isArray(v){
    return (v.length && typeof v != 'string');
  }

  /**
   * Checks if @a contains @v
   */
  function _inArray(a,v){
    for(var i in a){
      if(a[i] == v) return true;
    }
    return false;
  }

  /**
   * Create a command actions runner descriptor.
   *
   * @param {array} options   List of options arguments
   *
   * Ex1:    ['value|version|v','value|path|p']
   *
   * Usage: e5r <cmd> -v 1.0       | e5r <cmd> --version 1.0
   *        e5r <cmd> -p "path/to" | e5r <cmd> --path "path/to"
   *
   *        {version:'1.0', path:null}
   *        {version:null, path:'path/to'}
   *
   * Ex2:   ['switch|test|t,T']
   *
   * Usage: e5r <cmd> --test --other "value param"
   *        e5r <cmd> --other "value param"
   *        e5r <cmd> --T
   *
   *        {test: true, other:'value param'}
   *        {test: false, other:'value param'}
   *        {test: true, other:null}
   *
   * @param {array} actions   List of actions to execute
   *
   * @return Command Action Descriptor object
   */
  function _createCmdActionsDescriptor(options, actions){
    if(!_isArray(options)){
      throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @options must be an Array.');
    }
    if(!_isArray(actions)){
      throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @actions must be an Array.');
    }
    for(var a in actions){
      if(!_isArray(actions[a])){
        throw new Error('<sysutils._createCmdActionsDescriptor> #ArgumentException: @actions['+a+'] must be an Array.');
      }
    }

    return {
      __options: options,
      __actions: actions,

      __getAction: function(act){
        for(var _act in this.__actions){
          var _actObj = this.__actions[_act],
              _actName = _actObj.length > 1 ? (_actObj[0]||null) : '',
              _actCbck = _actObj.length > 1 ? (_actObj[1]||null) : (_actObj[0]||null);
          if(typeof _actName != 'string' || typeof _actCbck != 'function')
            throw new Error('<sysutils._createCmdActionsDescriptor.__getAction>: Invalid action signature.');
          if(_actName === act)
            return _actCbck;
        }
        return null;
      },

      __describe: function(n){
        for(var o in this.__options){
          var oArray = this.__options[o].split('|'),
              oType = (oArray[0]||null),
              oName = (oArray[1]||null),
              oAliases = (oArray[2]||'').split(','),
              _n = '',
              _isNamed = false;
          if(oType == null || oName == null){
            throw new Error('<sysutils._createCmdActionsDescriptor.__describe>: Invalid option syntax.');
          }
          for(var c = 0; c < n.length; c++){
            if(c < 2 && n.charAt(c)=='-') continue;
            _n += n.charAt(c);
          }
          _isNamed = (n.length == 2 && n.charAt(0) == '-' && n.charAt(1) != '-') ||
                     (n.length > 2 && n.charAt(0) == '-' && n.charAt(1) == '-');
          if(!_isNamed) continue;
          if(oName == _n || _inArray(oAliases,_n)){
            return {
              type: oType.toLowerCase(),
              name: oName
            }
          }
        }
        return null;
      },

      run:function(args){
        var _opts = {},
            _args = [],
            _pIdx = 0;
        // Options informed in params
        while(_pIdx < args.length){
          var param = args[_pIdx],
              nextParam = (args[_pIdx+1]||null),
              descriptor = this.__describe(param);
          if(!descriptor){
            _args.push(param);
            _pIdx++;
            continue;
          }
          if(descriptor.type == 'switch'){
            _opts[descriptor.name] = true;
          }
          if(descriptor.type == 'value'){
            if(nextParam != null && nextParam.charAt(0) != '-'){
              _opts[descriptor.name] = nextParam;
              _pIdx++;
            }else{
              _opts[descriptor.name] = null;
            }
          }
          _pIdx++;
        }
        // Not informed options
        for(var _iO in this.__options){
          var _optObj = this.__options[_iO].split('|'),
              _optType = _optObj[0]||null,
              _optName = _optObj[1]||null;
          if(!(_optName in _opts))
            _opts[_optName] = _optType == 'switch' ? false : null;
        }
        // Detect action name and others parameters
        var _actionName = _args[0]||'',
            _actionCallback = this.__getAction(_actionName),
            _newArgs = [];
        if(_actionName) for(var a = 1; a < _args.length;a++)
          _newArgs.push(_args[a]);

        if(typeof _actionCallback == 'function')
          _actionCallback(_opts, _newArgs);
      }
    }
  }

  module.exports = {
    CONST: _consts,
    stdErr: WScript.StdErr,
    stdIn: WScript.StdIn,
    stdOut: WScript.StdOut,

    host: _host,
    script: _script,
    net: _net,

    sleep: _sleep,
    buildEnvString: _buildEnvirementString,
    getEnvironment: _getEnvironment,
    setEnvironment: _setEnvironment,
    cmdActions: _createCmdActionsDescriptor
  }
})();
<|endoftext|>


<commit_before>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
], function(IPython, $, utils) {
    "use strict";

    var KernelSelector = function(selector, notebook) {
        var that = this;
        this.selector = selector;
        this.notebook = notebook;
        this.notebook.set_kernelselector(this);
        this.events = notebook.events;
        this.current_selection = null;
        this.kernelspecs = {};
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.request_kernelspecs();
        }
        this.bind_events();
        // Make the object globally available for user convenience & inspection
        IPython.kernelselector = this;
        this._finish_load = null;
        this.loaded = new Promise(function(resolve, reject) {
            that._finish_load = resolve;
        });

        Object.seal(this);
    };

    KernelSelector.prototype.request_kernelspecs = function() {
        var url = utils.url_join_encode(this.notebook.base_url, 'api/kernelspecs');
        utils.promising_ajax(url).then($.proxy(this._got_kernelspecs, this));
    };

    KernelSelector.prototype._got_kernelspecs = function(data) {
        this.kernelspecs = data.kernelspecs;
        var change_kernel_submenu = $("#menu-change-kernel-submenu");
        var new_notebook_submenu = $("#menu-new-notebook-submenu");

        var keys = Object.keys(data.kernelspecs).sort(function (a, b) {
            // sort by display_name
            var da = data.kernelspecs[a].spec.display_name;
            var db = data.kernelspecs[b].spec.display_name;
            if (da === db) {
                return 0;
            } else if (da > db) {
                return 1;
            } else {
                return -1;
            }
        });

        var i, ks, ks_submenu_entry;
        // Create the Kernel > Change kernel submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "kernel-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click($.proxy(this.set_kernel, this, ks.name))
                .text(ks.spec.display_name));
            change_kernel_submenu.append(ks_submenu_entry);
        }

        // Create the File > New Notebook submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "new-notebook-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click($.proxy(this.new_notebook, this, ks.name))
                .text(ks.spec.display_name));
            new_notebook_submenu.append(ks_submenu_entry);
        }
        // trigger loaded promise
        this._finish_load();
    };

    KernelSelector.prototype._spec_changed = function (event, ks) {
        /** event handler for spec_changed */

        // update selection
        this.current_selection = ks.name;

        // put the current kernel at the top of File > New Notebook
        var cur_kernel_entry = $("#new-notebook-submenu-" + ks.name);
        if (cur_kernel_entry.length) {
            cur_kernel_entry.parent().prepend($("<li>").attr("class","divider"))
                                     .prepend(cur_kernel_entry);
        }

        // load logo
        var logo_img = this.element.find("img.current_kernel_logo");
        $("#kernel_indicator").find('.kernel_indicator_name').text(ks.spec.display_name);
        if (ks.resources['logo-64x64']) {
            logo_img.attr("src", ks.resources['logo-64x64']);
            logo_img.show();
        } else {
            logo_img.hide();
        }

        // load kernel css
        var css_url = ks.resources['kernel.css'];
        if (css_url) {
            $('#kernel-css').attr('href', css_url);
        } else {
            $('#kernel-css').attr('href', '');
        }

        // load kernel js
        if (ks.resources['kernel.js']) {
            require([ks.resources['kernel.js']],
                function (kernel_mod) {
                    if (kernel_mod && kernel_mod.onload) {
                        kernel_mod.onload();
                    } else {
                        console.warn("Kernel " + ks.name + " has a kernel.js file that does not contain "+
                                     "any asynchronous module definition. This is undefined behavior "+
                                     "and not recommended.");
                    }
                }, function (err) {
                    console.warn("Failed to load kernel.js from ", ks.resources['kernel.js'], err);
                }
            );
        }
    };

    KernelSelector.prototype.set_kernel = function (kernel_name) {
        /** set the kernel by name, ensuring kernelspecs have been loaded, first */
        var that = this;
        return this.loaded.then(function () {
            that._set_kernel(kernel_name);
        });
    };

    KernelSelector.prototype._set_kernel = function (kernel_name) {
        /** Actually set the kernel (kernelspecs have been loaded) */
        if (kernel_name === this.current_selection) {
            // only trigger event if value changed
            return;
        }
        var ks = this.kernelspecs[kernel_name];
        if (this.notebook._session_starting) {
            console.error("Cannot change kernel while waiting for pending session start.");
            return;
        }
        this.current_selection = kernel_name;
        this.events.trigger('spec_changed.Kernel', ks);
    };

    KernelSelector.prototype.new_notebook = function (kernel_name) {

        var w = window.open();
        // Create a new notebook in the same path as the current
        // notebook's path.
        var that = this;
        var parent = utils.url_path_split(that.notebook.notebook_path)[0];
        that.notebook.contents.new_untitled(parent, {type: "notebook"}).then(
            function (data) {
                var url = utils.url_join_encode(
                    that.notebook.base_url, 'notebooks', data.path
                );
                url += "?kernel_name=" + kernel_name;
                w.location = url;
            },
            function(error) {
                w.close();
                dialog.modal({
                    title : 'Creating Notebook Failed',
                    body : "The error was: " + error.message,
                    buttons : {'OK' : {'class' : 'btn-primary'}}
                });
            }
        );
    };

    KernelSelector.prototype.lock_switch = function() {
        // should set a flag and display warning+reload if user want to
        // re-change kernel. As UI discussion never finish
        // making that a separate PR.
        console.warn('switching kernel is not guaranteed to work !');
    };

    KernelSelector.prototype.bind_events = function() {
        var that = this;
        this.events.on('spec_changed.Kernel', $.proxy(this._spec_changed, this));

        this.events.on('kernel_created.Session', function (event, data) {
            that.set_kernel(data.kernel.name);
        });

        var logo_img = this.element.find("img.current_kernel_logo");
        logo_img.on("load", function() {
            logo_img.show();
        });
        logo_img.on("error", function() {
            logo_img.hide();
        });
    };

    return {'KernelSelector': KernelSelector};
});
<commit_msg>fix kernel change breaking new notebook list<commit_after>// Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.

define([
    'base/js/namespace',
    'jquery',
    'base/js/utils',
], function(IPython, $, utils) {
    "use strict";

    var KernelSelector = function(selector, notebook) {
        var that = this;
        this.selector = selector;
        this.notebook = notebook;
        this.notebook.set_kernelselector(this);
        this.events = notebook.events;
        this.current_selection = null;
        this.kernelspecs = {};
        if (this.selector !== undefined) {
            this.element = $(selector);
            this.request_kernelspecs();
        }
        this.bind_events();
        // Make the object globally available for user convenience & inspection
        IPython.kernelselector = this;
        this._finish_load = null;
        this.loaded = new Promise(function(resolve, reject) {
            that._finish_load = resolve;
        });

        Object.seal(this);
    };

    KernelSelector.prototype.request_kernelspecs = function() {
        var url = utils.url_join_encode(this.notebook.base_url, 'api/kernelspecs');
        utils.promising_ajax(url).then($.proxy(this._got_kernelspecs, this));
    };

    KernelSelector.prototype._got_kernelspecs = function(data) {
        this.kernelspecs = data.kernelspecs;
        var change_kernel_submenu = $("#menu-change-kernel-submenu");
        var new_notebook_submenu = $("#menu-new-notebook-submenu");

        var keys = Object.keys(data.kernelspecs).sort(function (a, b) {
            // sort by display_name
            var da = data.kernelspecs[a].spec.display_name;
            var db = data.kernelspecs[b].spec.display_name;
            if (da === db) {
                return 0;
            } else if (da > db) {
                return 1;
            } else {
                return -1;
            }
        });

        var i, ks, ks_submenu_entry;
        // Create the Kernel > Change kernel submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "kernel-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click($.proxy(this.set_kernel, this, ks.name))
                .text(ks.spec.display_name));
            change_kernel_submenu.append(ks_submenu_entry);
        }

        // Create the File > New Notebook submenu
        for (i = 0; i < keys.length; i++) {
            ks = this.kernelspecs[keys[i]];
            ks_submenu_entry = $("<li>").attr("id", "new-notebook-submenu-"+ks.name).append($('<a>')
                .attr('href', '#')
                .click($.proxy(this.new_notebook, this, ks.name))
                .text(ks.spec.display_name));
            new_notebook_submenu.append(ks_submenu_entry);
        }
        // trigger loaded promise
        this._finish_load();
    };

    KernelSelector.prototype._spec_changed = function (event, ks) {
        /** event handler for spec_changed */

        // update selection
        this.current_selection = ks.name;

        // put the current kernel at the top of File > New Notebook
        var cur_kernel_entry = $("#new-notebook-submenu-" + ks.name);
        var parent = cur_kernel_entry.parent();
        // do something only if there is more than one kernel
        if (parent.children().length > 1) {
            // first, sort back the submenu
            parent.append(
                parent.children("li[class!='divider']").sort(
                    function (a,b) {
                        var da = $("a",a).text();
                        var db = $("a",b).text();
                        if (da === db) {
                            return 0;
                        } else if (da > db) {
                            return 1;
                        } else {
                            return -1;
                        }}));
            // then, if there is no divider yet, add one
            if (!parent.children("li[class='divider']").length) {
                parent.prepend($("<li>").attr("class","divider"));
            }
            // finally, put the current kernel at the top
            parent.prepend(cur_kernel_entry);
        }

        // load logo
        var logo_img = this.element.find("img.current_kernel_logo");
        $("#kernel_indicator").find('.kernel_indicator_name').text(ks.spec.display_name);
        if (ks.resources['logo-64x64']) {
            logo_img.attr("src", ks.resources['logo-64x64']);
            logo_img.show();
        } else {
            logo_img.hide();
        }

        // load kernel css
        var css_url = ks.resources['kernel.css'];
        if (css_url) {
            $('#kernel-css').attr('href', css_url);
        } else {
            $('#kernel-css').attr('href', '');
        }

        // load kernel js
        if (ks.resources['kernel.js']) {
            require([ks.resources['kernel.js']],
                function (kernel_mod) {
                    if (kernel_mod && kernel_mod.onload) {
                        kernel_mod.onload();
                    } else {
                        console.warn("Kernel " + ks.name + " has a kernel.js file that does not contain "+
                                     "any asynchronous module definition. This is undefined behavior "+
                                     "and not recommended.");
                    }
                }, function (err) {
                    console.warn("Failed to load kernel.js from ", ks.resources['kernel.js'], err);
                }
            );
        }
    };

    KernelSelector.prototype.set_kernel = function (kernel_name) {
        /** set the kernel by name, ensuring kernelspecs have been loaded, first */
        var that = this;
        return this.loaded.then(function () {
            that._set_kernel(kernel_name);
        });
    };

    KernelSelector.prototype._set_kernel = function (kernel_name) {
        /** Actually set the kernel (kernelspecs have been loaded) */
        if (kernel_name === this.current_selection) {
            // only trigger event if value changed
            return;
        }
        var ks = this.kernelspecs[kernel_name];
        if (this.notebook._session_starting) {
            console.error("Cannot change kernel while waiting for pending session start.");
            return;
        }
        this.current_selection = kernel_name;
        this.events.trigger('spec_changed.Kernel', ks);
    };

    KernelSelector.prototype.new_notebook = function (kernel_name) {

        var w = window.open();
        // Create a new notebook in the same path as the current
        // notebook's path.
        var that = this;
        var parent = utils.url_path_split(that.notebook.notebook_path)[0];
        that.notebook.contents.new_untitled(parent, {type: "notebook"}).then(
            function (data) {
                var url = utils.url_join_encode(
                    that.notebook.base_url, 'notebooks', data.path
                );
                url += "?kernel_name=" + kernel_name;
                w.location = url;
            },
            function(error) {
                w.close();
                dialog.modal({
                    title : 'Creating Notebook Failed',
                    body : "The error was: " + error.message,
                    buttons : {'OK' : {'class' : 'btn-primary'}}
                });
            }
        );
    };

    KernelSelector.prototype.lock_switch = function() {
        // should set a flag and display warning+reload if user want to
        // re-change kernel. As UI discussion never finish
        // making that a separate PR.
        console.warn('switching kernel is not guaranteed to work !');
    };

    KernelSelector.prototype.bind_events = function() {
        var that = this;
        this.events.on('spec_changed.Kernel', $.proxy(this._spec_changed, this));

        this.events.on('kernel_created.Session', function (event, data) {
            that.set_kernel(data.kernel.name);
        });

        var logo_img = this.element.find("img.current_kernel_logo");
        logo_img.on("load", function() {
            logo_img.show();
        });
        logo_img.on("error", function() {
            logo_img.hide();
        });
    };

    return {'KernelSelector': KernelSelector};
});
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2013 The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Base Widget Model and View classes
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 **/

define(["notebook/js/widgetmanager",
        "underscore",
        "backbone"],
function(widget_manager, underscore, backbone){

    //--------------------------------------------------------------------
    // WidgetModel class
    //--------------------------------------------------------------------
    var WidgetModel = Backbone.Model.extend({
        constructor: function (widget_manager, model_id, comm) {
            this.widget_manager = widget_manager;
            this.pending_msgs = 0;
            this.msg_throttle = 3;
            this.msg_buffer = null;
            this.id = model_id;
            this.views = [];

            if (comm !== undefined) {
                // Remember comm associated with the model.
                this.comm = comm;
                comm.model = this;

                // Hook comm messages up to model.
                comm.on_close($.proxy(this._handle_comm_closed, this));
                comm.on_msg($.proxy(this._handle_comm_msg, this));
            }
            return Backbone.Model.apply(this);
        },

        send: function (content, callbacks) {
            if (this.comm !== undefined) {
                var data = {method: 'custom', custom_content: content};
                this.comm.send(data, callbacks);
            }
        },

        // Handle when a widget is closed.
        _handle_comm_closed: function (msg) {
            this.trigger('comm:close');
            delete this.comm.model; // Delete ref so GC will collect widget model.
            delete this.comm;
            delete this.model_id; // Delete id from model so widget manager cleans up.
            // TODO: Handle deletion, like this.destroy(), and delete views, etc.
        },

        // Handle incoming comm msg.
        _handle_comm_msg: function (msg) {
            var method = msg.content.data.method;
            switch (method) {
                case 'update':
                    this.apply_update(msg.content.data.state);
                    break;
                case 'custom':
                    this.trigger('msg:custom', msg.content.data.custom_content);
                    break;
                case 'display':
                    this.widget_manager.display_view(msg.parent_header.msg_id, this);
                    break;
            }
        },

        // Handle when a widget is updated via the python side.
        apply_update: function (state) {
            this.updating = true;
            try {
                for (var key in state) {
                    if (state.hasOwnProperty(key)) {
                            this.set(key, state[key]);
                    }
                }
                //TODO: are there callbacks that make sense in this case?  If so, attach them here as an option
                this.save();
            } finally {
                this.updating = false;
            }
        },

        _handle_status: function (msg, callbacks) {
            //execution_state : ('busy', 'idle', 'starting')
            if (this.comm !== undefined && msg.content.execution_state ==='idle') {
                // Send buffer if this message caused another message to be
                // throttled.
                if (this.msg_buffer !== null &&
                    this.msg_throttle === this.pending_msgs) {
                    var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
                    this.comm.send(data, callbacks);
                    this.msg_buffer = null;
                } else {
                    // Only decrease the pending message count if the buffer
                    // doesn't get flushed (sent).
                    --this.pending_msgs;
                }
            }
        },

        // Custom syncronization logic.
        _handle_sync: function (method, options) {
            var model_json = this.toJSON();
            var attr;

            // Only send updated state if the state hasn't been changed
            // during an update.
            if (this.comm !== undefined) {
                if (!this.updating) {
                    if (this.pending_msgs >= this.msg_throttle) {
                        // The throttle has been exceeded, buffer the current msg so
                        // it can be sent once the kernel has finished processing
                        // some of the existing messages.
                        if (method=='patch') {
                            if (this.msg_buffer === null) {
                                this.msg_buffer = $.extend({}, model_json); // Copy
                            }
                            for (attr in options.attrs) {
                                this.msg_buffer[attr] = options.attrs[attr];
                            }
                        } else {
                            this.msg_buffer = $.extend({}, model_json); // Copy
                        }

                    } else {
                        // We haven't exceeded the throttle, send the message like
                        // normal.  If this is a patch operation, just send the
                        // changes.
                        var send_json = model_json;
                        if (method =='patch') {
                            send_json = {};
                            for (attr in options.attrs) {
                                send_json[attr] = options.attrs[attr];
                            }
                        }

                        var data = {method: 'backbone', sync_data: send_json};
                        this.comm.send(data, options.callbacks);
                        this.pending_msgs++;
                    }
                }
            }

            // Since the comm is a one-way communication, assume the message
            // arrived.
            return model_json;
        },

    });

    //--------------------------------------------------------------------
    // WidgetView class
    //--------------------------------------------------------------------
    var BaseWidgetView = Backbone.View.extend({
        initialize: function(options) {
            this.model.on('change',this.update,this);
            this.widget_manager = options.widget_manager;
            this.comm_manager = options.widget_manager.comm_manager;
            this.options = options.options;
            this.child_views = [];
            this.model.views.push(this);
        },

        update: function(){
            // update view to be consistent with this.model
            // triggered on model change
        },

        child_view: function(model_id, view_name, options) {
            // create and return a child view, given a model id for a model and (optionally) a view name
            // if the view name is not given, it defaults to the model's default view attribute
            var child_model = this.widget_manager.get_model(model_id);
            var child_view = this.widget_manager.create_view(child_model, view_name, options);
            this.child_views[model_id] = child_view;
            return child_view;
        },

        update_child_views: function(old_list, new_list) {
            // this function takes an old list and new list of model ids
            // views in child_views that correspond to deleted ids are deleted
            // views corresponding to added ids are added child_views

            // delete old views
            _.each(_.difference(old_list, new_list), function(element, index, list) {
                var view = this.child_views[element];
                delete this.child_views[element];
                view.remove();
            }, this);

            // add new views
            _.each(_.difference(new_list, old_list), function(element, index, list) {
                // this function adds the view to the child_views dictionary
                this.child_view(element);
            }, this);
        },

        callbacks: function(){
            return this.widget_manager.callbacks(this);
        }

        render: function(){
            // render the view.  By default, this is only called the first time the view is created
        },
        send: function (content) {
            this.model.send(content, this.callbacks());
        },

        touch: function () {
            this.model.save(this.model.changedAttributes(), {patch: true, callbacks: this.callbacks()});
        },

    });

    var WidgetView = BaseWidgetView.extend({
        initialize: function (options) {
            // TODO: make changes more granular (e.g., trigger on visible:change)
            this.model.on('change', this.update, this);
            this.model.on('msg:custom', this.on_msg, this);
            BaseWidgetView.prototype.initialize.apply(this, arguments);
        },

        on_msg: function(msg) {
            switch(msg.msg_type) {
                case 'add_class':
                    this.add_class(msg.selector, msg.class_list);
                    break;
                case 'remove_class':
                    this.remove_class(msg.selector, msg.class_list);
                    break;
            }
        },

        add_class: function (selector, class_list) {
            var elements = this._get_selector_element(selector);
            if (elements.length > 0) {
                elements.addClass(class_list);
            }
        },

        remove_class: function (selector, class_list) {
            var elements = this._get_selector_element(selector);
            if (elements.length > 0) {
                elements.removeClass(class_list);
            }
        },

        update: function () {
            // the very first update seems to happen before the element is finished rendering
            // so we use setTimeout to give the element time to render
            var e = this.$el;
            var visible = this.model.get('visible');
            setTimeout(function() {e.toggle(visible)},0);

            var css = this.model.get('_css');
            if (css === undefined) {return;}
            for (var selector in css) {
                if (css.hasOwnProperty(selector)) {
                    // Apply the css traits to all elements that match the selector.
                    var elements = this._get_selector_element(selector);
                    if (elements.length > 0) {
                        var css_traits = css[selector];
                        for (var css_key in css_traits) {
                            if (css_traits.hasOwnProperty(css_key)) {
                                elements.css(css_key, css_traits[css_key]);
                            }
                        }
                    }
                }
            }
        },

        _get_selector_element: function (selector) {
            // Get the elements via the css selector.  If the selector is
            // blank, apply the style to the $el_to_style element.  If
            // the $el_to_style element is not defined, use apply the
            // style to the view's element.
            var elements;
            if (selector === undefined || selector === null || selector === '') {
                if (this.$el_to_style === undefined) {
                    elements = this.$el;
                } else {
                    elements = this.$el_to_style;
                }
            } else {
                elements = this.$el.find(selector);
            }
            return elements;
        },
    });

    IPython.WidgetModel = WidgetModel;
    IPython.WidgetView = WidgetView;
    IPython.BaseWidgetView = BaseWidgetView;

    return widget_manager;
});
<commit_msg>Added missing comma<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2013 The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Base Widget Model and View classes
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 **/

define(["notebook/js/widgetmanager",
        "underscore",
        "backbone"],
function(widget_manager, underscore, backbone){

    //--------------------------------------------------------------------
    // WidgetModel class
    //--------------------------------------------------------------------
    var WidgetModel = Backbone.Model.extend({
        constructor: function (widget_manager, model_id, comm) {
            this.widget_manager = widget_manager;
            this.pending_msgs = 0;
            this.msg_throttle = 3;
            this.msg_buffer = null;
            this.id = model_id;
            this.views = [];

            if (comm !== undefined) {
                // Remember comm associated with the model.
                this.comm = comm;
                comm.model = this;

                // Hook comm messages up to model.
                comm.on_close($.proxy(this._handle_comm_closed, this));
                comm.on_msg($.proxy(this._handle_comm_msg, this));
            }
            return Backbone.Model.apply(this);
        },

        send: function (content, callbacks) {
            if (this.comm !== undefined) {
                var data = {method: 'custom', custom_content: content};
                this.comm.send(data, callbacks);
            }
        },

        // Handle when a widget is closed.
        _handle_comm_closed: function (msg) {
            this.trigger('comm:close');
            delete this.comm.model; // Delete ref so GC will collect widget model.
            delete this.comm;
            delete this.model_id; // Delete id from model so widget manager cleans up.
            // TODO: Handle deletion, like this.destroy(), and delete views, etc.
        },

        // Handle incoming comm msg.
        _handle_comm_msg: function (msg) {
            var method = msg.content.data.method;
            switch (method) {
                case 'update':
                    this.apply_update(msg.content.data.state);
                    break;
                case 'custom':
                    this.trigger('msg:custom', msg.content.data.custom_content);
                    break;
                case 'display':
                    this.widget_manager.display_view(msg.parent_header.msg_id, this);
                    break;
            }
        },

        // Handle when a widget is updated via the python side.
        apply_update: function (state) {
            this.updating = true;
            try {
                for (var key in state) {
                    if (state.hasOwnProperty(key)) {
                            this.set(key, state[key]);
                    }
                }
                //TODO: are there callbacks that make sense in this case?  If so, attach them here as an option
                this.save();
            } finally {
                this.updating = false;
            }
        },

        _handle_status: function (msg, callbacks) {
            //execution_state : ('busy', 'idle', 'starting')
            if (this.comm !== undefined && msg.content.execution_state ==='idle') {
                // Send buffer if this message caused another message to be
                // throttled.
                if (this.msg_buffer !== null &&
                    this.msg_throttle === this.pending_msgs) {
                    var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
                    this.comm.send(data, callbacks);
                    this.msg_buffer = null;
                } else {
                    // Only decrease the pending message count if the buffer
                    // doesn't get flushed (sent).
                    --this.pending_msgs;
                }
            }
        },

        // Custom syncronization logic.
        _handle_sync: function (method, options) {
            var model_json = this.toJSON();
            var attr;

            // Only send updated state if the state hasn't been changed
            // during an update.
            if (this.comm !== undefined) {
                if (!this.updating) {
                    if (this.pending_msgs >= this.msg_throttle) {
                        // The throttle has been exceeded, buffer the current msg so
                        // it can be sent once the kernel has finished processing
                        // some of the existing messages.
                        if (method=='patch') {
                            if (this.msg_buffer === null) {
                                this.msg_buffer = $.extend({}, model_json); // Copy
                            }
                            for (attr in options.attrs) {
                                this.msg_buffer[attr] = options.attrs[attr];
                            }
                        } else {
                            this.msg_buffer = $.extend({}, model_json); // Copy
                        }

                    } else {
                        // We haven't exceeded the throttle, send the message like
                        // normal.  If this is a patch operation, just send the
                        // changes.
                        var send_json = model_json;
                        if (method =='patch') {
                            send_json = {};
                            for (attr in options.attrs) {
                                send_json[attr] = options.attrs[attr];
                            }
                        }

                        var data = {method: 'backbone', sync_data: send_json};
                        this.comm.send(data, options.callbacks);
                        this.pending_msgs++;
                    }
                }
            }

            // Since the comm is a one-way communication, assume the message
            // arrived.
            return model_json;
        },

    });

    //--------------------------------------------------------------------
    // WidgetView class
    //--------------------------------------------------------------------
    var BaseWidgetView = Backbone.View.extend({
        initialize: function(options) {
            this.model.on('change',this.update,this);
            this.widget_manager = options.widget_manager;
            this.comm_manager = options.widget_manager.comm_manager;
            this.options = options.options;
            this.child_views = [];
            this.model.views.push(this);
        },

        update: function(){
            // update view to be consistent with this.model
            // triggered on model change
        },

        child_view: function(model_id, view_name, options) {
            // create and return a child view, given a model id for a model and (optionally) a view name
            // if the view name is not given, it defaults to the model's default view attribute
            var child_model = this.widget_manager.get_model(model_id);
            var child_view = this.widget_manager.create_view(child_model, view_name, options);
            this.child_views[model_id] = child_view;
            return child_view;
        },

        update_child_views: function(old_list, new_list) {
            // this function takes an old list and new list of model ids
            // views in child_views that correspond to deleted ids are deleted
            // views corresponding to added ids are added child_views

            // delete old views
            _.each(_.difference(old_list, new_list), function(element, index, list) {
                var view = this.child_views[element];
                delete this.child_views[element];
                view.remove();
            }, this);

            // add new views
            _.each(_.difference(new_list, old_list), function(element, index, list) {
                // this function adds the view to the child_views dictionary
                this.child_view(element);
            }, this);
        },

        callbacks: function(){
            return this.widget_manager.callbacks(this);
        },

        render: function(){
            // render the view.  By default, this is only called the first time the view is created
        },
        send: function (content) {
            this.model.send(content, this.callbacks());
        },

        touch: function () {
            this.model.save(this.model.changedAttributes(), {patch: true, callbacks: this.callbacks()});
        },

    });

    var WidgetView = BaseWidgetView.extend({
        initialize: function (options) {
            // TODO: make changes more granular (e.g., trigger on visible:change)
            this.model.on('change', this.update, this);
            this.model.on('msg:custom', this.on_msg, this);
            BaseWidgetView.prototype.initialize.apply(this, arguments);
        },

        on_msg: function(msg) {
            switch(msg.msg_type) {
                case 'add_class':
                    this.add_class(msg.selector, msg.class_list);
                    break;
                case 'remove_class':
                    this.remove_class(msg.selector, msg.class_list);
                    break;
            }
        },

        add_class: function (selector, class_list) {
            var elements = this._get_selector_element(selector);
            if (elements.length > 0) {
                elements.addClass(class_list);
            }
        },

        remove_class: function (selector, class_list) {
            var elements = this._get_selector_element(selector);
            if (elements.length > 0) {
                elements.removeClass(class_list);
            }
        },

        update: function () {
            // the very first update seems to happen before the element is finished rendering
            // so we use setTimeout to give the element time to render
            var e = this.$el;
            var visible = this.model.get('visible');
            setTimeout(function() {e.toggle(visible)},0);

            var css = this.model.get('_css');
            if (css === undefined) {return;}
            for (var selector in css) {
                if (css.hasOwnProperty(selector)) {
                    // Apply the css traits to all elements that match the selector.
                    var elements = this._get_selector_element(selector);
                    if (elements.length > 0) {
                        var css_traits = css[selector];
                        for (var css_key in css_traits) {
                            if (css_traits.hasOwnProperty(css_key)) {
                                elements.css(css_key, css_traits[css_key]);
                            }
                        }
                    }
                }
            }
        },

        _get_selector_element: function (selector) {
            // Get the elements via the css selector.  If the selector is
            // blank, apply the style to the $el_to_style element.  If
            // the $el_to_style element is not defined, use apply the
            // style to the view's element.
            var elements;
            if (selector === undefined || selector === null || selector === '') {
                if (this.$el_to_style === undefined) {
                    elements = this.$el;
                } else {
                    elements = this.$el_to_style;
                }
            } else {
                elements = this.$el.find(selector);
            }
            return elements;
        },
    });

    IPython.WidgetModel = WidgetModel;
    IPython.WidgetView = WidgetView;
    IPython.BaseWidgetView = BaseWidgetView;

    return widget_manager;
});
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2013 The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Base Widget Model and View classes
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 **/

define(["notebook/js/widgetmanager",
        "underscore",
        "backbone"],
function(WidgetManager, _, Backbone){

    var WidgetModel = Backbone.Model.extend({
        constructor: function (widget_manager, model_id, comm) {
            // Constructor
            //
            // Creates a WidgetModel instance.
            //
            // Parameters
            // ----------
            // widget_manager : WidgetManager instance
            // model_id : string
            //      An ID unique to this model.
            // comm : Comm instance (optional)
            this.widget_manager = widget_manager;
            this.pending_msgs = 0;
            this.msg_throttle = 3;
            this.msg_buffer = null;
            this.key_value_lock = null;
            this.id = model_id;
            this.views = [];

            if (comm !== undefined) {
                // Remember comm associated with the model.
                this.comm = comm;
                comm.model = this;

                // Hook comm messages up to model.
                comm.on_close($.proxy(this._handle_comm_closed, this));
                comm.on_msg($.proxy(this._handle_comm_msg, this));
            }
            return Backbone.Model.apply(this);
        },

        send: function (content, callbacks) {
            // Send a custom msg over the comm.
            if (this.comm !== undefined) {
                var data = {method: 'custom', content: content};
                this.comm.send(data, callbacks);
                this.pending_msgs++;
            }
        },

        _handle_comm_closed: function (msg) {
            // Handle when a widget is closed.
            this.trigger('comm:close');
            delete this.comm.model; // Delete ref so GC will collect widget model.
            delete this.comm;
            delete this.model_id; // Delete id from model so widget manager cleans up.
            _.each(this.views, function(view, i) {
                view.remove();
            });
        },

        _handle_comm_msg: function (msg) {
            // Handle incoming comm msg.
            var method = msg.content.data.method;
            switch (method) {
                case 'update':
                    this.apply_update(msg.content.data.state);
                    break;
                case 'custom':
                    this.trigger('msg:custom', msg.content.data.content);
                    break;
                case 'display':
                    this.widget_manager.display_view(msg, this);
                    break;
            }
        },

        apply_update: function (state) {
            // Handle when a widget is updated via the python side.
            var that = this;
            _.each(state, function(value, key) {
                that.key_value_lock = [key, value];
                try {
                    that.set(key, that._unpack_models(value));
                } finally {
                    that.key_value_lock = null;
                }
            });
        },

        _handle_status: function (msg, callbacks) {
            // Handle status msgs.

            // execution_state : ('busy', 'idle', 'starting')
            if (this.comm !== undefined) {
                if (msg.content.execution_state ==='idle') {
                    // Send buffer if this message caused another message to be
                    // throttled.
                    if (this.msg_buffer !== null &&
                        this.msg_throttle === this.pending_msgs) {
                        var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
                        this.comm.send(data, callbacks);
                        this.msg_buffer = null;
                    } else {
                        --this.pending_msgs;
                    }
                }
            }
        },

        callbacks: function(view) {
            // Create msg callbacks for a comm msg.
            var callbacks = this.widget_manager.callbacks(view);

            if (callbacks.iopub === undefined) {
                callbacks.iopub = {};
            }

            var that = this;
            callbacks.iopub.status = function (msg) {
                that._handle_status(msg, callbacks);
            };
            return callbacks;
        },

        sync: function (method, model, options) {
            // Handle sync to the back-end.  Called when a model.save() is called.

            // Make sure a comm exists.
            var error = options.error || function() {
                console.error('Backbone sync error:', arguments);
            };
            if (this.comm === undefined) {
                error();
                return false;
            }

            // Delete any key value pairs that the back-end already knows about.
            var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
            if (this.key_value_lock !== null) {
                var key = this.key_value_lock[0];
                var value = this.key_value_lock[1];
                if (attrs[key] === value) {
                    delete attrs[key];
                }
            }

            // Only sync if there are attributes to send to the back-end.
            if (_.size(attrs) > 0) {

                // If this message was sent via backbone itself, it will not
                // have any callbacks.  It's important that we create callbacks
                // so we can listen for status messages, etc...
                var callbacks = options.callbacks || this.callbacks();

                // Check throttle.
                if (this.pending_msgs >= this.msg_throttle) {
                    // The throttle has been exceeded, buffer the current msg so
                    // it can be sent once the kernel has finished processing
                    // some of the existing messages.

                    // Combine updates if it is a 'patch' sync, otherwise replace updates
                    switch (method) {
                        case 'patch':
                            this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
                            break;
                        case 'update':
                        case 'create':
                            this.msg_buffer = attrs;
                            break;
                        default:
                            error();
                            return false;
                    }
                    this.msg_buffer_callbacks = callbacks;

                } else {
                    // We haven't exceeded the throttle, send the message like
                    // normal.
                    var data = {method: 'backbone', sync_data: attrs};
                    this.comm.send(data, callbacks);
                    this.pending_msgs++;
                }
            }
            // Since the comm is a one-way communication, assume the message
            // arrived.  Don't call success since we don't have a model back from the server
            // this means we miss out on the 'sync' event.
        },

        save_changes: function(callbacks) {
            // Push this model's state to the back-end
            //
            // This invokes a Backbone.Sync.
            this.save({patch: true, callbacks: callbacks});
        },

        _pack_models: function(value) {
            // Replace models with model ids recursively.
            if (value instanceof Backbone.Model) {
                return value.id;

            } else if ($.isArray(value)) {
                var packed = [];
                var that = this;
                _.each(value, function(sub_value, key) {
                    packed.push(that._pack_models(sub_value));
                });
                return packed;

            } else if (value instanceof Object) {
                var packed = {};
                var that = this;
                _.each(value, function(sub_value, key) {
                    packed[key] = that._pack_models(sub_value);
                });
                return packed;

            } else {
                return value;
            }
        },

        _unpack_models: function(value) {
            // Replace model ids with models recursively.
            if ($.isArray(value)) {
                var unpacked = [];
                var that = this;
                _.each(value, function(sub_value, key) {
                    unpacked.push(that._unpack_models(sub_value));
                });
                return unpacked;

            } else if (value instanceof Object) {
                var unpacked = {};
                var that = this;
                _.each(value, function(sub_value, key) {
                    unpacked[key] = that._unpack_models(sub_value);
                });
                return unpacked;

            } else {
                var model = this.widget_manager.get_model(value);
                if (model) {
                    return model;
                } else {
                    return value;
                }
            }
        },

    });
    WidgetManager.register_widget_model('WidgetModel', WidgetModel);

    var WidgetView = Backbone.View.extend({
        initialize: function(parameters) {
            // Public constructor.
            this.model.on('change',this.update,this);
            this.options = parameters.options;
            this.child_views = [];
            this.model.views.push(this);
        },

        update: function(){
            // Triggered on model change.
            //
            // Update view to be consistent with this.model
        },

        create_child_view: function(child_model, options) {
            // Create and return a child view.
            //
            // -given a model and (optionally) a view name if the view name is
            // not given, it defaults to the model's default view attribute.

            // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
            // it would be great to have the widget manager add the cell metadata
            // to the subview without having to add it here.
            var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
            this.child_views[child_model.id] = child_view;
            return child_view;
        },

        delete_child_view: function(child_model, options) {
            // Delete a child view that was previously created using create_child_view.
            var view = this.child_views[child_model.id];
            if (view !== undefined) {
                delete this.child_views[child_model.id];
                view.remove();
            }
        },

        do_diff: function(old_list, new_list, removed_callback, added_callback) {
            // Difference a changed list and call remove and add callbacks for
            // each removed and added item in the new list.
            //
            // Parameters
            // ----------
            // old_list : array
            // new_list : array
            // removed_callback : Callback(item)
            //      Callback that is called for each item removed.
            // added_callback : Callback(item)
            //      Callback that is called for each item added.

            // removed items
            _.each(_.difference(old_list, new_list), function(item, index, list) {
                removed_callback(item);
            }, this);

            // added items
            _.each(_.difference(new_list, old_list), function(item, index, list) {
                added_callback(item);
            }, this);
        },

        callbacks: function(){
            // Create msg callbacks for a comm msg.
            return this.model.callbacks(this);
        },

        render: function(){
            // Render the view.
            //
            // By default, this is only called the first time the view is created
        },

        send: function (content) {
            // Send a custom msg associated with this view.
            this.model.send(content, this.callbacks());
        },

        touch: function () {
            this.model.save_changes(this.callbacks());
        },
    });

    var DOMWidgetView = WidgetView.extend({
        initialize: function (options) {
            // Public constructor

            // In the future we may want to make changes more granular
            // (e.g., trigger on visible:change).
            this.model.on('change', this.update, this);
            this.model.on('msg:custom', this.on_msg, this);
            DOMWidgetView.__super__.initialize.apply(this, arguments);
        },

        on_msg: function(msg) {
            // Handle DOM specific msgs.
            switch(msg.msg_type) {
                case 'add_class':
                    this.add_class(msg.selector, msg.class_list);
                    break;
                case 'remove_class':
                    this.remove_class(msg.selector, msg.class_list);
                    break;
            }
        },

        add_class: function (selector, class_list) {
            // Add a DOM class to an element.
            this._get_selector_element(selector).addClass(class_list);
        },

        remove_class: function (selector, class_list) {
            // Remove a DOM class from an element.
            this._get_selector_element(selector).removeClass(class_list);
        },

        update: function () {
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            //      The very first update seems to happen before the element is
            // finished rendering so we use setTimeout to give the element time
            // to render
            var e = this.$el;
            var visible = this.model.get('visible');
            setTimeout(function() {e.toggle(visible);},0);

            var css = this.model.get('_css');
            if (css === undefined) {return;}
            var that = this;
            _.each(css, function(css_traits, selector){
                // Apply the css traits to all elements that match the selector.
                var elements = that._get_selector_element(selector);
                if (elements.length > 0) {
                    _.each(css_traits, function(css_value, css_key){
                        elements.css(css_key, css_value);
                    });
                }
            });
        },

        _get_selector_element: function (selector) {
            // Get the elements via the css selector.

            // If the selector is blank, apply the style to the $el_to_style
            // element.  If the $el_to_style element is not defined, use apply
            // the style to the view's element.
            var elements;
            if (!selector) {
                if (this.$el_to_style === undefined) {
                    elements = this.$el;
                } else {
                    elements = this.$el_to_style;
                }
            } else {
                elements = this.$el.find(selector);
            }
            return elements;
        },
    });

    IPython.WidgetModel = WidgetModel;
    IPython.WidgetView = WidgetView;
    IPython.DOMWidgetView = DOMWidgetView;

    // Pass through WidgetManager namespace.
    return WidgetManager;
});
<commit_msg>Revert "Let backbone get changed attrs"<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2013 The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// Base Widget Model and View classes
//============================================================================

/**
 * @module IPython
 * @namespace IPython
 **/

define(["notebook/js/widgetmanager",
        "underscore",
        "backbone"],
function(WidgetManager, _, Backbone){

    var WidgetModel = Backbone.Model.extend({
        constructor: function (widget_manager, model_id, comm) {
            // Constructor
            //
            // Creates a WidgetModel instance.
            //
            // Parameters
            // ----------
            // widget_manager : WidgetManager instance
            // model_id : string
            //      An ID unique to this model.
            // comm : Comm instance (optional)
            this.widget_manager = widget_manager;
            this.pending_msgs = 0;
            this.msg_throttle = 3;
            this.msg_buffer = null;
            this.key_value_lock = null;
            this.id = model_id;
            this.views = [];

            if (comm !== undefined) {
                // Remember comm associated with the model.
                this.comm = comm;
                comm.model = this;

                // Hook comm messages up to model.
                comm.on_close($.proxy(this._handle_comm_closed, this));
                comm.on_msg($.proxy(this._handle_comm_msg, this));
            }
            return Backbone.Model.apply(this);
        },

        send: function (content, callbacks) {
            // Send a custom msg over the comm.
            if (this.comm !== undefined) {
                var data = {method: 'custom', content: content};
                this.comm.send(data, callbacks);
                this.pending_msgs++;
            }
        },

        _handle_comm_closed: function (msg) {
            // Handle when a widget is closed.
            this.trigger('comm:close');
            delete this.comm.model; // Delete ref so GC will collect widget model.
            delete this.comm;
            delete this.model_id; // Delete id from model so widget manager cleans up.
            _.each(this.views, function(view, i) {
                view.remove();
            });
        },

        _handle_comm_msg: function (msg) {
            // Handle incoming comm msg.
            var method = msg.content.data.method;
            switch (method) {
                case 'update':
                    this.apply_update(msg.content.data.state);
                    break;
                case 'custom':
                    this.trigger('msg:custom', msg.content.data.content);
                    break;
                case 'display':
                    this.widget_manager.display_view(msg, this);
                    break;
            }
        },

        apply_update: function (state) {
            // Handle when a widget is updated via the python side.
            var that = this;
            _.each(state, function(value, key) {
                that.key_value_lock = [key, value];
                try {
                    that.set(key, that._unpack_models(value));
                } finally {
                    that.key_value_lock = null;
                }
            });
        },

        _handle_status: function (msg, callbacks) {
            // Handle status msgs.

            // execution_state : ('busy', 'idle', 'starting')
            if (this.comm !== undefined) {
                if (msg.content.execution_state ==='idle') {
                    // Send buffer if this message caused another message to be
                    // throttled.
                    if (this.msg_buffer !== null &&
                        this.msg_throttle === this.pending_msgs) {
                        var data = {method: 'backbone', sync_method: 'update', sync_data: this.msg_buffer};
                        this.comm.send(data, callbacks);
                        this.msg_buffer = null;
                    } else {
                        --this.pending_msgs;
                    }
                }
            }
        },

        callbacks: function(view) {
            // Create msg callbacks for a comm msg.
            var callbacks = this.widget_manager.callbacks(view);

            if (callbacks.iopub === undefined) {
                callbacks.iopub = {};
            }

            var that = this;
            callbacks.iopub.status = function (msg) {
                that._handle_status(msg, callbacks);
            };
            return callbacks;
        },

        sync: function (method, model, options) {
            // Handle sync to the back-end.  Called when a model.save() is called.

            // Make sure a comm exists.
            var error = options.error || function() {
                console.error('Backbone sync error:', arguments);
            };
            if (this.comm === undefined) {
                error();
                return false;
            }

            // Delete any key value pairs that the back-end already knows about.
            var attrs = (method === 'patch') ? options.attrs : model.toJSON(options);
            if (this.key_value_lock !== null) {
                var key = this.key_value_lock[0];
                var value = this.key_value_lock[1];
                if (attrs[key] === value) {
                    delete attrs[key];
                }
            }

            // Only sync if there are attributes to send to the back-end.
            if (_.size(attrs) > 0) {

                // If this message was sent via backbone itself, it will not
                // have any callbacks.  It's important that we create callbacks
                // so we can listen for status messages, etc...
                var callbacks = options.callbacks || this.callbacks();

                // Check throttle.
                if (this.pending_msgs >= this.msg_throttle) {
                    // The throttle has been exceeded, buffer the current msg so
                    // it can be sent once the kernel has finished processing
                    // some of the existing messages.

                    // Combine updates if it is a 'patch' sync, otherwise replace updates
                    switch (method) {
                        case 'patch':
                            this.msg_buffer = $.extend(this.msg_buffer || {}, attrs);
                            break;
                        case 'update':
                        case 'create':
                            this.msg_buffer = attrs;
                            break;
                        default:
                            error();
                            return false;
                    }
                    this.msg_buffer_callbacks = callbacks;

                } else {
                    // We haven't exceeded the throttle, send the message like
                    // normal.
                    var data = {method: 'backbone', sync_data: attrs};
                    this.comm.send(data, callbacks);
                    this.pending_msgs++;
                }
            }
            // Since the comm is a one-way communication, assume the message
            // arrived.  Don't call success since we don't have a model back from the server
            // this means we miss out on the 'sync' event.
        },

        save_changes: function(callbacks) {
            // Push this model's state to the back-end
            //
            // This invokes a Backbone.Sync.
            this.save(this.changedAttributes(), {patch: true, callbacks: callbacks});
        },

        _pack_models: function(value) {
            // Replace models with model ids recursively.
            if (value instanceof Backbone.Model) {
                return value.id;

            } else if ($.isArray(value)) {
                var packed = [];
                var that = this;
                _.each(value, function(sub_value, key) {
                    packed.push(that._pack_models(sub_value));
                });
                return packed;

            } else if (value instanceof Object) {
                var packed = {};
                var that = this;
                _.each(value, function(sub_value, key) {
                    packed[key] = that._pack_models(sub_value);
                });
                return packed;

            } else {
                return value;
            }
        },

        _unpack_models: function(value) {
            // Replace model ids with models recursively.
            if ($.isArray(value)) {
                var unpacked = [];
                var that = this;
                _.each(value, function(sub_value, key) {
                    unpacked.push(that._unpack_models(sub_value));
                });
                return unpacked;

            } else if (value instanceof Object) {
                var unpacked = {};
                var that = this;
                _.each(value, function(sub_value, key) {
                    unpacked[key] = that._unpack_models(sub_value);
                });
                return unpacked;

            } else {
                var model = this.widget_manager.get_model(value);
                if (model) {
                    return model;
                } else {
                    return value;
                }
            }
        },

    });
    WidgetManager.register_widget_model('WidgetModel', WidgetModel);

    var WidgetView = Backbone.View.extend({
        initialize: function(parameters) {
            // Public constructor.
            this.model.on('change',this.update,this);
            this.options = parameters.options;
            this.child_views = [];
            this.model.views.push(this);
        },

        update: function(){
            // Triggered on model change.
            //
            // Update view to be consistent with this.model
        },

        create_child_view: function(child_model, options) {
            // Create and return a child view.
            //
            // -given a model and (optionally) a view name if the view name is
            // not given, it defaults to the model's default view attribute.

            // TODO: this is hacky, and makes the view depend on this cell attribute and widget manager behavior
            // it would be great to have the widget manager add the cell metadata
            // to the subview without having to add it here.
            var child_view = this.model.widget_manager.create_view(child_model, options || {}, this);
            this.child_views[child_model.id] = child_view;
            return child_view;
        },

        delete_child_view: function(child_model, options) {
            // Delete a child view that was previously created using create_child_view.
            var view = this.child_views[child_model.id];
            if (view !== undefined) {
                delete this.child_views[child_model.id];
                view.remove();
            }
        },

        do_diff: function(old_list, new_list, removed_callback, added_callback) {
            // Difference a changed list and call remove and add callbacks for
            // each removed and added item in the new list.
            //
            // Parameters
            // ----------
            // old_list : array
            // new_list : array
            // removed_callback : Callback(item)
            //      Callback that is called for each item removed.
            // added_callback : Callback(item)
            //      Callback that is called for each item added.

            // removed items
            _.each(_.difference(old_list, new_list), function(item, index, list) {
                removed_callback(item);
            }, this);

            // added items
            _.each(_.difference(new_list, old_list), function(item, index, list) {
                added_callback(item);
            }, this);
        },

        callbacks: function(){
            // Create msg callbacks for a comm msg.
            return this.model.callbacks(this);
        },

        render: function(){
            // Render the view.
            //
            // By default, this is only called the first time the view is created
        },

        send: function (content) {
            // Send a custom msg associated with this view.
            this.model.send(content, this.callbacks());
        },

        touch: function () {
            this.model.save_changes(this.callbacks());
        },
    });

    var DOMWidgetView = WidgetView.extend({
        initialize: function (options) {
            // Public constructor

            // In the future we may want to make changes more granular
            // (e.g., trigger on visible:change).
            this.model.on('change', this.update, this);
            this.model.on('msg:custom', this.on_msg, this);
            DOMWidgetView.__super__.initialize.apply(this, arguments);
        },

        on_msg: function(msg) {
            // Handle DOM specific msgs.
            switch(msg.msg_type) {
                case 'add_class':
                    this.add_class(msg.selector, msg.class_list);
                    break;
                case 'remove_class':
                    this.remove_class(msg.selector, msg.class_list);
                    break;
            }
        },

        add_class: function (selector, class_list) {
            // Add a DOM class to an element.
            this._get_selector_element(selector).addClass(class_list);
        },

        remove_class: function (selector, class_list) {
            // Remove a DOM class from an element.
            this._get_selector_element(selector).removeClass(class_list);
        },

        update: function () {
            // Update the contents of this view
            //
            // Called when the model is changed.  The model may have been
            // changed by another view or by a state update from the back-end.
            //      The very first update seems to happen before the element is
            // finished rendering so we use setTimeout to give the element time
            // to render
            var e = this.$el;
            var visible = this.model.get('visible');
            setTimeout(function() {e.toggle(visible);},0);

            var css = this.model.get('_css');
            if (css === undefined) {return;}
            var that = this;
            _.each(css, function(css_traits, selector){
                // Apply the css traits to all elements that match the selector.
                var elements = that._get_selector_element(selector);
                if (elements.length > 0) {
                    _.each(css_traits, function(css_value, css_key){
                        elements.css(css_key, css_value);
                    });
                }
            });
        },

        _get_selector_element: function (selector) {
            // Get the elements via the css selector.

            // If the selector is blank, apply the style to the $el_to_style
            // element.  If the $el_to_style element is not defined, use apply
            // the style to the view's element.
            var elements;
            if (!selector) {
                if (this.$el_to_style === undefined) {
                    elements = this.$el;
                } else {
                    elements = this.$el_to_style;
                }
            } else {
                elements = this.$el.find(selector);
            }
            return elements;
        },
    });

    IPython.WidgetModel = WidgetModel;
    IPython.WidgetView = WidgetView;
    IPython.DOMWidgetView = DOMWidgetView;

    // Pass through WidgetManager namespace.
    return WidgetManager;
});
<|endoftext|>