<commit_before>"use strict";

if (!jxcore.utils.OSInfo().isMobile) {
  return;
}

var net = require('net');
var randomstring = require('randomstring');
var ThaliEmitter = require('thali/thaliemitter');
var tape = require('../lib/thali-tape');

function newPeerIdentifier() {
  return (+ new Date()).toString() + "." + process.pid;
}

var  emitterToShutDown = null;

var test = tape({
  setup: function(t) {
    t.end();
  },
  teardown: function(t) {
    if(emitterToShutDown != null){
      console.log("calling stopBroadcasting");
      emitterToShutDown.stopBroadcasting(function (err4) {
        console.log("stopBroadcasting returned " + err4);
      });
      emitterToShutDown = null;
    }
    t.end();
  }
});

test('ThaliEmitter can call repeatedly startBroadcasting and stopBroadcasting without error', function (t) {
  var e = new ThaliEmitter();

  function repeatCalls(count) {
    if (count == 0) {
      t.end();
      return;
    }

    e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
      t.notOk(err1, 'Should be able to call startBroadcasting without error');
      e.stopBroadcasting(function (err2) {
        t.notOk(err2, 'Should be able to call stopBroadcasting without error');
        repeatCalls(count - 1);
      });
    });
  }

  repeatCalls(10);
});

test('ThaliEmitter calls startBroadcasting twice with error', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.startBroadcasting(newPeerIdentifier(), 5001, function (err2) {

      t.assert(!!err2, 'Cannot call startBroadcasting twice');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

test('ThaliEmitter throws on connection to bad peer', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.connect('foobar', function (err2, port) {
      t.assert(!!err2, 'Should not connect to a bad peer');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

test('ThaliEmitter throws on disconnect to bad peer', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.disconnect('foobar', function (err2, port) {
      t.assert(!!err2, 'Disconnect should fail to a non-existant peer ');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

function connectWithRetryTestAndDisconnect(t, testFunction) {
  var e = new ThaliEmitter();

  var _done = false;

  e.on(ThaliEmitter.events.PEER_AVAILABILITY_CHANGED, function (peers) {

    peers.forEach(function (peer) {

      if (peer.peerAvailable) {
        var connectToPeer = function(attempts) {

          if (!_done) {
            if (attempts === 0) {
              t.fail('Connecting failed');
              return t.end();
            }

            e.connect(peer.peerIdentifier, function (err2, port) {

              if (err2) {
                if (err2.message.indexOf("unreachable") != -1) {
                  // Peer has become unreachable no point retrying
                  return;
                } else {
                  // Retry
                  return setTimeout(function () { connectToPeer(attempts - 1); }, 1000);
                }
              }

              t.notOk(err2, 'Should be able to connect without error');
              t.ok(port > 0 && port <= 65536, 'Port should be within range');

              testFunction(t, e, peer, port, function() {
                console.log("setting stopBroadcasting callback and ending test.");
                emitterToShutDown = e;
                _done = true;
                t.end();
              });
            });
          };
        }

        connectToPeer(10);
      }
    });
  });

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');
  });
}

test('ThaliEmitter can discover and connect to peers', function (t) {
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    e.disconnect(peer.peerIdentifier, function (err3) {
      t.notOk(err3, 'Should be able to disconnect without error');
      cb();
    });
  });
});

test('ThaliEmitter can discover and connect to peers and then fail on double connect', function (t) {
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    e.connect(peer.peerIdentifier, function(err3, port) {
      t.ok(err3, 'Should fail on double connect');
      e.disconnect(peer.peerIdentifier, function (err3) {
        t.notOk(err3, 'Should be able to disconnect without error');
        cb();
      });
    });
  });
});

test('ThaliEmitter can discover and connect to peers and then fail on double disconnect', function (t) {
  connectWithRetryTestAndDisconnect(t, function (t, e, peer, port, cb) {
    e.disconnect(peer.peerIdentifier, function (err3) {
      t.notOk(err3, 'Should be able to disconnect without error');

      e.disconnect(peer.peerIdentifier, function (err4) {
        t.ok(err4, 'Disconnect should fail ');
        cb();
      });
    });
  });
});

test('ThaliEmitter can connect and send data', function (t) {
  var len = 1025;
  var testMessage = randomstring.generate(len);
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    var clientSocket = net.createConnection( { port: port }, function () {
      clientSocket.write(testMessage);
    });

    clientSocket.setTimeout(120000);
    clientSocket.setKeepAlive(true);

    var testData = '';

    clientSocket.on('data', function (data) {
      testData += data;

      if (testData.length === len) {
        t.equal(testData, testMessage, 'the test messages should be equal');

        e.disconnect(peer.peerIdentifier, function (err3) {
          t.notOk(err3, 'Should be able to disconnect without error');
          cb();
        });
      }
    });
  });
});
<commit_msg>Adapt tests to new test environment<commit_after>"use strict";

if (!jxcore.utils.OSInfo().isMobile) {
  return;
}

var net = require('net');
var randomstring = require('randomstring');
var ThaliEmitter = require('thali/thaliemitter');
var tape = require('../lib/thali-tape');

function newPeerIdentifier() {
  return (+ new Date()).toString() + "." + process.pid;
}

var  emitterToShutDown = null;

var test = tape({
  setup: function(t) {
    t.end();
  },
  teardown: function(t) {
    if(emitterToShutDown != null){
      console.log("calling stopBroadcasting");
      emitterToShutDown.stopBroadcasting(function (err4) {
        console.log("stopBroadcasting returned " + err4);
      });
      emitterToShutDown = null;
    }
    t.end();
  }
});

test('ThaliEmitter can call repeatedly startBroadcasting and stopBroadcasting without error', function (t) {
  var e = new ThaliEmitter();

  function repeatCalls(count) {
    if (count == 0) {
      t.end();
      return;
    }

    e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
      t.notOk(err1, 'Should be able to call startBroadcasting without error');
      e.stopBroadcasting(function (err2) {
        t.notOk(err2, 'Should be able to call stopBroadcasting without error');
        repeatCalls(count - 1);
      });
    });
  }

  repeatCalls(10);
});

test('ThaliEmitter calls startBroadcasting twice with error', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.startBroadcasting(newPeerIdentifier(), 5001, function (err2) {

      t.assert(!!err2, 'Cannot call startBroadcasting twice');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

test('ThaliEmitter throws on connection to bad peer', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.connect('foobar', function (err2, port) {
      t.assert(!!err2, 'Should not connect to a bad peer');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

test('ThaliEmitter throws on disconnect to bad peer', function (t) {
  var e = new ThaliEmitter();

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');

    e.disconnect('foobar', function (err2, port) {
      t.assert(!!err2, 'Disconnect should fail to a non-existant peer ');

      e.stopBroadcasting(function (err3) {
        t.notOk(err3, 'Should be able to call stopBroadcasting without error');
        t.end();
      });
    });
  });
});

function connectWithRetryTestAndDisconnect(t, testFunction) {
  var e = new ThaliEmitter();

  var _done = false;

  e.on(ThaliEmitter.events.PEER_AVAILABILITY_CHANGED, function (peers) {

    peers.forEach(function (peer) {

      if (peer.peerAvailable) {
        var connectToPeer = function(attempts) {

          if (!_done) {
            if (attempts === 0) {
              t.fail('Connecting failed');
              return t.end();
            }

            e.connect(peer.peerIdentifier, function (err2, port) {

              if (err2) {
                if (err2.message.indexOf("unreachable") != -1) {
                  // Peer has become unreachable no point retrying
                  return;
                } else {
                  // Retry
                  return setTimeout(function () { connectToPeer(attempts - 1); }, 1000);
                }
              }

              t.notOk(err2, 'Should be able to connect without error');
              t.ok(port > 0 && port <= 65536, 'Port should be within range');

              testFunction(t, e, peer, port, function() {
                console.log("setting stopBroadcasting callback and ending test.");
                emitterToShutDown = e;
                _done = true;
                t.end();
              });
            });
          };
        }

        connectToPeer(10);
      }
    });
  });

  e.startBroadcasting(newPeerIdentifier(), 5001, function (err1) {
    t.notOk(err1, 'Should be able to call startBroadcasting without error');
  });
}

test('ThaliEmitter can discover and connect to peers', function (t) {
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    e.disconnect(peer.peerIdentifier, function (err3) {
      t.notOk(err3, 'Should be able to disconnect without error');
      cb();
    });
  });
});

test('ThaliEmitter can discover and connect to peers and then fail on double connect', function (t) {
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    e.connect(peer.peerIdentifier, function(err3, port) {
      t.ok(err3, 'Should fail on double connect');
      e.disconnect(peer.peerIdentifier, function (err3) {
        t.notOk(err3, 'Should be able to disconnect without error');
        cb();
      });
    });
  });
});

test('ThaliEmitter can discover and connect to peers and then fail on double disconnect', function (t) {
  connectWithRetryTestAndDisconnect(t, function (t, e, peer, port, cb) {
    e.disconnect(peer.peerIdentifier, function (err3) {
      t.notOk(err3, 'Should be able to disconnect without error');

      e.disconnect(peer.peerIdentifier, function (err4) {
        t.ok(err4, 'Disconnect should fail ');
        cb();
      });
    });
  });
});

test('ThaliEmitter can connect and send data', function (t) {

  var server = net.createServer(function(s) {
    s.pipe(s);
  });

  server.listen(5001, function() {
    console.log("echo server started");
  });

  var len = 1025;
  var testMessage = randomstring.generate(len);
  connectWithRetryTestAndDisconnect(t, function(t, e, peer, port, cb) {
    var clientSocket = net.createConnection( { port: port }, function () {
      clientSocket.write(testMessage);
    });

    clientSocket.setTimeout(120000);
    clientSocket.setKeepAlive(true);

    var testData = '';

    clientSocket.on('data', function (data) {
      testData += data;

      if (testData.length === len) {
        t.equal(testData, testMessage, 'the test messages should be equal');

        e.disconnect(peer.peerIdentifier, function (err3) {
          t.notOk(err3, 'Should be able to disconnect without error');
          cb();
        });
      }
    });
  });
});
<|endoftext|>


<commit_before>/*
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'tabletop',
  name: 'PlayerController',
  extends: 'tabletop.EntityController',
  requires: [
    'tabletop.BulletController',
    'tabletop.Entity',
  ],
  constants: {
    SHOT_COOL_DOWN: 0.15
  },
  properties: [
    [ 'coolDown', 1 ],
    {
      name: 'target',
      factory: function() { return { x: 800, y: 450 }; }
    },

  ],

  methods: [
    /** Applies movement and physics calculations required for a frame. */
    function move() {
      // Doesn't move, no super

      this.coolDown -= this.frameTime;
      if ( this.coolDown < 0 ) {
        this.coolDown = this.SHOT_COOL_DOWN;
        this.shoot();
      }
    },
  ],

  listeners: [
    {
      name: 'shoot',
      code: function() {
        var e = this.owner;
        var b = this.Entity.create({
          x: e.x,
          y: e.y,
          br: 10,
          bplane: 1,
          collisionPlane: 0,
          rotation: e.rotation,
          manager: e,
          controller: this.BulletController.create(),
        });
        b.damage.damaging = true;
        b.damage.hurt = 1;
        b.damage.killed.sub(e.manager.killedSomething);

        // TODO: clean up sprite init
        b.sprite.x = e.x;
        b.sprite.y = e.y;
        b.sprite.rotation = e.rotation;
        b.sprite.imageIndex = 'bullet';
        b.sprite.scaleX = 0.1;
        b.sprite.scaleY = 0.1;

        this.aimTowards({ x: this.target.x, y: this.target.y }, b, 1000, Math.random() * 0.2 - 0.1);
        e.rotation = b.rotation;
        b.install();
        e.audioManager.play("impact", e);
      }
    }
  ]
});

foam.CLASS({
  package: 'tabletop',
  name: 'PlayerManager',
  extends: 'tabletop.EntityManager',
  requires: [
    'tabletop.Entity',
    'tabletop.ImageSprite',
    'tabletop.TextSprite',
    'tabletop.Hull',
    'tabletop.PlayerController'
  ],
  imports: [
    'worldDAO',
    'worldWidth',
    'worldHeight',
  ],
  properties: [
    {
      name: 'main',
      factory: function() {
        var h = this.Hull.create({
          basehp: 10,
          currhp: 10
        });

        var s = this.ImageSprite.create({
          x: this.x,
          y: this.y,
          scaleX: 0.5,
          scaleY: 0.5,
          rotation: this.rotation,
          imageIndex: 'claw',
        });
        var t = this.TextSprite.create({
          y: -55,
          color: 'red'
        });
        t.text$.follow(h.currhp$);
        s.addChild(t);

        var ptsT = this.TextSprite.create({
          y: -30,
          color: 'lightgreen'
        });
        ptsT.text$.follow(this.points$);
        s.addChild(ptsT);

        return this.Entity.create({
          id: 'player' + this.$UID,
          bplane: 3,
          vx: 1,
          br: 40,
          sprite: s,
          hull: h,
          controller: this.PlayerController.create(),
          manager: this
        });
      },
    },
    {
      name: 'points',
      value: 0
    },
    {
      name: 'corner',
      factory: function() { return [0,0]; },
      postSet: function(old,nu) {
        var r;
        if ( nu[0] ) {
          r = nu[1] ? Math.PI * 5/4 : Math.PI * 3/4;
        } else {
          r = nu[1] ? Math.PI * 7/4 : Math.PI * 1/4;
        }

        Math.PI * ( nu[0] ? 1 : -1 ) * ( nu[1] ? 1/4 : 3/4 );

        if ( this.main ) {
          this.main.x = nu[0] ? 1600 - 20 : 20;
          this.main.y = nu[1] ? 900 - 20 : 20;
          this.main.rotation = r;
        }
        this.restartButton.x = nu[0] ? 1600 - 20 : 20;
        this.restartButton.y = nu[1] ? 900 - 20 : 20;
        this.restartButton.rotation = r;
      }
    },
    {
      name: 'restartButton',
      factory: function() {
        var s = this.ImageSprite.create({
          imageIndex: 'greenPlate',
        });
        var t = this.TextSprite.create({
          y: -55,
          text: 'Start',
          color: 'lightgreen'
        });
        s.addChild(t);

        return s;
      },
    }
  ],
  methods: [
    function init() {
      this.main.install();
      this.corner = this.corner;
      this.main.onDestroy(this.clearEntity);
      this.healMe();
    },
    /** Click/tap from user, in world coordinates */
    function clickEvent(x,y) {
      console.log('player click', this.corner, x, y);

      if ( this.main ) {
        this.main.controller.target = { x: x, y: y };
      } else {
        this.reset();
      }
    },

    function reset() {
      this.restartButton.uninstall();
      this.points = 0;
      this.main = undefined;
      this.main.install();
      this.corner = this.corner;
      this.main.onDestroy(this.clearEntity);
    }
  ],
  listeners: [
    {
      name: 'clearEntity',
      code: function() {
        this.main = null;
        this.restartButton.install();
      }
    },
    {
      name: 'healMe',
      code: function() {
        if ( this.main ) {
          this.main.hull.heal(1);
          setTimeout(this.healMe, 5000);
        }
      }
    },
    {
      name: 'killedSomething',
      code: function(_, _, target) {
        //console.log('killed', target);
        this.points += target.hull.basehp;
      }
    }
  ]
});
<commit_msg>Bullet size<commit_after>/*
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'tabletop',
  name: 'PlayerController',
  extends: 'tabletop.EntityController',
  requires: [
    'tabletop.BulletController',
    'tabletop.Entity',
  ],
  constants: {
    SHOT_COOL_DOWN: 0.15
  },
  properties: [
    [ 'coolDown', 1 ],
    {
      name: 'target',
      factory: function() { return { x: 800, y: 450 }; }
    },

  ],

  methods: [
    /** Applies movement and physics calculations required for a frame. */
    function move() {
      // Doesn't move, no super

      this.coolDown -= this.frameTime;
      if ( this.coolDown < 0 ) {
        this.coolDown = this.SHOT_COOL_DOWN;
        this.shoot();
      }
    },
  ],

  listeners: [
    {
      name: 'shoot',
      code: function() {
        var e = this.owner;
        var b = this.Entity.create({
          x: e.x,
          y: e.y,
          br: 10,
          bplane: 1,
          collisionPlane: 0,
          rotation: e.rotation,
          manager: e,
          controller: this.BulletController.create(),
        });
        b.damage.damaging = true;
        b.damage.hurt = 1;
        b.damage.killed.sub(e.manager.killedSomething);

        // TODO: clean up sprite init
        b.sprite.x = e.x;
        b.sprite.y = e.y;
        b.sprite.rotation = e.rotation;
        b.sprite.imageIndex = 'bullet';
        b.sprite.scaleX = 0.2;
        b.sprite.scaleY = 0.2;

        this.aimTowards({ x: this.target.x, y: this.target.y }, b, 1000, Math.random() * 0.2 - 0.1);
        e.rotation = b.rotation;
        b.install();
        e.audioManager.play("impact", e);
      }
    }
  ]
});

foam.CLASS({
  package: 'tabletop',
  name: 'PlayerManager',
  extends: 'tabletop.EntityManager',
  requires: [
    'tabletop.Entity',
    'tabletop.ImageSprite',
    'tabletop.TextSprite',
    'tabletop.Hull',
    'tabletop.PlayerController'
  ],
  imports: [
    'worldDAO',
    'worldWidth',
    'worldHeight',
  ],
  properties: [
    {
      name: 'main',
      factory: function() {
        var h = this.Hull.create({
          basehp: 10,
          currhp: 10
        });

        var s = this.ImageSprite.create({
          x: this.x,
          y: this.y,
          scaleX: 0.5,
          scaleY: 0.5,
          rotation: this.rotation,
          imageIndex: 'claw',
        });
        var t = this.TextSprite.create({
          y: -55,
          color: 'red'
        });
        t.text$.follow(h.currhp$);
        s.addChild(t);

        var ptsT = this.TextSprite.create({
          y: -30,
          color: 'lightgreen'
        });
        ptsT.text$.follow(this.points$);
        s.addChild(ptsT);

        return this.Entity.create({
          id: 'player' + this.$UID,
          bplane: 3,
          vx: 1,
          br: 40,
          sprite: s,
          hull: h,
          controller: this.PlayerController.create(),
          manager: this
        });
      },
    },
    {
      name: 'points',
      value: 0
    },
    {
      name: 'corner',
      factory: function() { return [0,0]; },
      postSet: function(old,nu) {
        var r;
        if ( nu[0] ) {
          r = nu[1] ? Math.PI * 5/4 : Math.PI * 3/4;
        } else {
          r = nu[1] ? Math.PI * 7/4 : Math.PI * 1/4;
        }

        Math.PI * ( nu[0] ? 1 : -1 ) * ( nu[1] ? 1/4 : 3/4 );

        if ( this.main ) {
          this.main.x = nu[0] ? 1600 - 20 : 20;
          this.main.y = nu[1] ? 900 - 20 : 20;
          this.main.rotation = r;
        }
        this.restartButton.x = nu[0] ? 1600 - 20 : 20;
        this.restartButton.y = nu[1] ? 900 - 20 : 20;
        this.restartButton.rotation = r;
      }
    },
    {
      name: 'restartButton',
      factory: function() {
        var s = this.ImageSprite.create({
          imageIndex: 'greenPlate',
        });
        var t = this.TextSprite.create({
          y: -55,
          text: 'Start',
          color: 'lightgreen'
        });
        s.addChild(t);

        return s;
      },
    }
  ],
  methods: [
    function init() {
      this.main.install();
      this.corner = this.corner;
      this.main.onDestroy(this.clearEntity);
      this.healMe();
    },
    /** Click/tap from user, in world coordinates */
    function clickEvent(x,y) {
      console.log('player click', this.corner, x, y);

      if ( this.main ) {
        this.main.controller.target = { x: x, y: y };
      } else {
        this.reset();
      }
    },

    function reset() {
      this.restartButton.uninstall();
      this.points = 0;
      this.main = undefined;
      this.main.install();
      this.corner = this.corner;
      this.main.onDestroy(this.clearEntity);
    }
  ],
  listeners: [
    {
      name: 'clearEntity',
      code: function() {
        this.main = null;
        this.restartButton.install();
      }
    },
    {
      name: 'healMe',
      code: function() {
        if ( this.main ) {
          this.main.hull.heal(1);
          setTimeout(this.healMe, 5000);
        }
      }
    },
    {
      name: 'killedSomething',
      code: function(_, _, target) {
        //console.log('killed', target);
        this.points += target.hull.basehp;
      }
    }
  ]
});
<|endoftext|>


<commit_before>/*!
  Copyright (C) 2016 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe('GGRC.Components.personItem', function () {
  'use strict';

  var Component;  // the component under test

  beforeAll(function () {
    Component = GGRC.Components.get('personItem');
  });

  describe('defining default scope values', function () {
    var scope;

    beforeAll(function () {
      scope = Component.prototype.scope;
    });

    it('sets the personObj to null', function () {
      expect(scope.personObj).toBeNull();
    });
  });

  describe('init() method', function () {
    var dfdFindOne;
    var template;  // the DOM element passed to the component instance
    var origPersonCache;
    var component;
    var frag;

    beforeEach(function () {
      dfdFindOne = new can.Deferred();
      spyOn(CMS.Models.Person, 'findOne').and.returnValue(dfdFindOne);

      origPersonCache = CMS.Models.Person.cache;
      CMS.Models.Person.cache = {};
    });

    afterEach(function () {
      CMS.Models.Person.cache = origPersonCache;
    });

    it('sets the personObj in scope to the cached Person object ' +
      'if found there',
      function () {
        var person42 = new can.Map({
          id: 42, name: 'John', email: 'john@doe.com'
        });
        CMS.Models.Person.cache[42] = person42;

        template = can.view
          .mustache('<person-info person-id="42"></person-info>');
        frag = template();
        frag = $(frag);
        component = frag.find('person-info').control();

        expect(component.scope.attr('personObj')).toBe(person42);
      }
    );

    it('sets the personObj in scope to the fetched Person object ' +
      'if not found in cache',
      function () {
        var person123 = new can.Map({
          id: 123, name: 'Mike', email: 'mike@mike.com'
        });

        template = can.view
          .mustache('<person-info person-id="123"></person-info>');
        frag = template();

        frag = $(frag);
        component = frag.find('person-info').control();

        delete CMS.Models.Person.cache[123];

        dfdFindOne.resolve(person123);

        expect(CMS.Models.Person.findOne).toHaveBeenCalledWith({id: 123});
        expect(component.scope.attr('personObj')).toBe(person123);
      }
    );

    it('sets the personObj in scope to the fetched Person object ' +
      'for partially loaded objects in cache',
      function () {
        var person123 = new can.Map({id: 123, name: '', email: ''});
        var fetchedPerson = new can.Map({
          id: 123, name: 'John', email: 'john@doe.com'
        });

        template = can.view
          .mustache('<person-info person-id="123"></person-info>');
        frag = template();

        CMS.Models.Person.cache[123] = person123;

        frag = $(frag);
        component = frag.find('person-info').control();

        dfdFindOne.resolve(fetchedPerson);

        expect(CMS.Models.Person.findOne).toHaveBeenCalledWith({id: 123});
        expect(component.scope.attr('personObj')).toBe(fetchedPerson);
      }
    );
  });

  describe('unmap person click event handler', function () {
    var handler;  // the event handler under test
    var componentInst;  // fake component instance

    beforeAll(function () {
      handler = Component.prototype.events['a.unmap click'];
    });

    beforeEach(function () {
      componentInst = {
        element: {
          triggerHandler: jasmine.createSpy()
        },
        scope: new can.Map()
      };

      handler = handler.bind(componentInst);
    });

    it('triggers the person-remove event with the person object as the ' +
      'event argument',
      function () {
        var call;
        componentInst.scope.attr('personObj', {id: 123, name: 'John'});

        handler();

        expect(componentInst.element.triggerHandler).toHaveBeenCalled();
        call = componentInst.element.triggerHandler.calls.mostRecent();
        expect(call.args[0].type).toEqual(
          Component.prototype._EV_REMOVE_CLICK);
        expect(call.args[0].person.attr()).toEqual({id: 123, name: 'John'});
      }
    );
  });
});
<commit_msg>Add test for no person id nor person object<commit_after>/*!
  Copyright (C) 2016 Google Inc.
  Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/

describe('GGRC.Components.personItem', function () {
  'use strict';

  var Component;  // the component under test

  beforeAll(function () {
    Component = GGRC.Components.get('personItem');
  });

  describe('defining default scope values', function () {
    var scope;

    beforeAll(function () {
      scope = Component.prototype.scope;
    });

    it('sets the personObj to null', function () {
      expect(scope.personObj).toBeNull();
    });
  });

  describe('init() method', function () {
    var dfdFindOne;
    var template;  // the DOM element passed to the component instance
    var origPersonCache;
    var component;
    var frag;

    beforeEach(function () {
      dfdFindOne = new can.Deferred();
      spyOn(CMS.Models.Person, 'findOne').and.returnValue(dfdFindOne);

      origPersonCache = CMS.Models.Person.cache;
      CMS.Models.Person.cache = {};
    });

    afterEach(function () {
      CMS.Models.Person.cache = origPersonCache;
    });

    it('sets the personObj in scope to the cached Person object ' +
      'if found there',
      function () {
        var person42 = new can.Map({
          id: 42, name: 'John', email: 'john@doe.com'
        });
        CMS.Models.Person.cache[42] = person42;

        template = can.view
          .mustache('<person-info person-id="42"></person-info>');
        frag = template();
        frag = $(frag);
        component = frag.find('person-info').control();

        expect(component.scope.attr('personObj')).toBe(person42);
      }
    );

    it('sets the personObj in scope to the fetched Person object ' +
      'if not found in cache',
      function () {
        var person123 = new can.Map({
          id: 123, name: 'Mike', email: 'mike@mike.com'
        });

        template = can.view
          .mustache('<person-info person-id="123"></person-info>');
        frag = template();

        frag = $(frag);
        component = frag.find('person-info').control();

        delete CMS.Models.Person.cache[123];

        dfdFindOne.resolve(person123);

        expect(CMS.Models.Person.findOne).toHaveBeenCalledWith({id: 123});
        expect(component.scope.attr('personObj')).toBe(person123);
      }
    );

    it('sets the personObj in scope to the fetched Person object ' +
      'for partially loaded objects in cache',
      function () {
        var person123 = new can.Map({id: 123, name: '', email: ''});
        var fetchedPerson = new can.Map({
          id: 123, name: 'John', email: 'john@doe.com'
        });

        template = can.view
          .mustache('<person-info person-id="123"></person-info>');
        frag = template();

        CMS.Models.Person.cache[123] = person123;

        frag = $(frag);
        component = frag.find('person-info').control();

        dfdFindOne.resolve(fetchedPerson);

        expect(CMS.Models.Person.findOne).toHaveBeenCalledWith({id: 123});
        expect(component.scope.attr('personObj')).toBe(fetchedPerson);
      }
    );
    it('does not make a get request when person-id is undefined',
      function () {
        spyOn(console, 'warn');
        template = can.view
          .mustache('<person-info person-id=""></person-info>');
        frag = template();

        frag = $(frag);
        component = frag.find('person-info').control();

        expect(CMS.Models.Person.findOne).not.toHaveBeenCalled();
        expect(console.warn).toHaveBeenCalled();
      }
    );
  });

  describe('unmap person click event handler', function () {
    var handler;  // the event handler under test
    var componentInst;  // fake component instance

    beforeAll(function () {
      handler = Component.prototype.events['a.unmap click'];
    });

    beforeEach(function () {
      componentInst = {
        element: {
          triggerHandler: jasmine.createSpy()
        },
        scope: new can.Map()
      };

      handler = handler.bind(componentInst);
    });

    it('triggers the person-remove event with the person object as the ' +
      'event argument',
      function () {
        var call;
        componentInst.scope.attr('personObj', {id: 123, name: 'John'});

        handler();

        expect(componentInst.element.triggerHandler).toHaveBeenCalled();
        call = componentInst.element.triggerHandler.calls.mostRecent();
        expect(call.args[0].type).toEqual(
          Component.prototype._EV_REMOVE_CLICK);
        expect(call.args[0].person.attr()).toEqual({id: 123, name: 'John'});
      }
    );
  });
});
<|endoftext|>


<commit_before>!function($, wysi) {
	"use strict"

	var templates = {
		"font-styles": "
" +
							"" +
								" Normal text " +
							"" +
						    "
" +
						      	"
Normal text
" +
					            "
Heading 1
" +
					            "
Heading 2
" +
						    "
" +
						"
",
		"emphasis":     "
" +
							"
" +
							    "Bold" +
							    "Italic" +
							"
" +
						"
",
		"lists": 		"
" +
							"
" +
						    	"" +
							    "" +
							"
" +
						"
"
	};

	var defaultOptions = {
		"font-styles": true,
		"emphasis": true,
		"lists": true
	};

	var Wysihtml5 = function(el, options) {
		this.el = el;
		this.toolbar = this.createToolbar(el, options || defaultOptions);
		this.editor =  new wysi.Editor(this.el.attr('id'), {
    		toolbar: this.toolbar.attr('id')
  		});

  		$('iframe.wysihtml5-sandbox').each(function(i, el){
			$(el.contentWindow).off('focus.wysihtml5').on({
			  'focus.wysihtml5' : function(){
			     $('li.dropdown').removeClass('open');
			   }
			});
		});
	};

	Wysihtml5.prototype = {
		constructor: Wysihtml5,

		createToolbar: function(el, options) {
			var toolbar = $("
", {
					id : el.attr('id') + "-wysihtml5-toolbar",
					class : "wysihtml5-toolbar",
					style: "display:none"
				}).button();

			for(var key in defaultOptions) {
				var value;

				if(options[key] != undefined) {
					if(options[key] == true) {
						value = true;
					}
				} else {
					value = defaultOptions[key];
				}

				if(value == true) {
					toolbar.append(templates[key]);
				}
			}

			var self = this;

			toolbar.find("a[data-wysihtml5-command='formatBlock']").click(function(e) {
				var el = $(e.srcElement);
				self.toolbar.find('.current-font').text(el.html())
			});

			this.el.before(toolbar);

			return toolbar;
		}
	};

	$.fn.wysihtml5 = function (options) {
		return this.each(function () {
			var $this = $(this);
	      	$this.data('wysihtml5', new Wysihtml5($this, options));
	    })
  	};

  	$.fn.wysihtml5.Constructor = Wysihtml5;

}(window.jQuery, window.wysihtml5);<commit_msg>Don't make the toolbar a jQuery UI button<commit_after>!function($, wysi) {
	"use strict"

	var templates = {
		"font-styles": "
" +
							"" +
								" Normal text " +
							"" +
						    "
" +
						      	"
Normal text
" +
					            "
Heading 1
" +
					            "
Heading 2
" +
						    "
" +
						"
",
		"emphasis":     "
" +
							"
" +
							    "Bold" +
							    "Italic" +
							"
" +
						"
",
		"lists": 		"
" +
							"
" +
						    	"" +
							    "" +
							"
" +
						"
"
	};

	var defaultOptions = {
		"font-styles": true,
		"emphasis": true,
		"lists": true
	};

	var Wysihtml5 = function(el, options) {
		this.el = el;
		this.toolbar = this.createToolbar(el, options || defaultOptions);
		this.editor =  new wysi.Editor(this.el.attr('id'), {
    		toolbar: this.toolbar.attr('id')
  		});

  		$('iframe.wysihtml5-sandbox').each(function(i, el){
			$(el.contentWindow).off('focus.wysihtml5').on({
			  'focus.wysihtml5' : function(){
			     $('li.dropdown').removeClass('open');
			   }
			});
		});
	};

	Wysihtml5.prototype = {
		constructor: Wysihtml5,

		createToolbar: function(el, options) {
			var toolbar = $("
", {
					id : el.attr('id') + "-wysihtml5-toolbar",
					class : "wysihtml5-toolbar",
					style: "display:none"
				});

			for(var key in defaultOptions) {
				var value;

				if(options[key] != undefined) {
					if(options[key] == true) {
						value = true;
					}
				} else {
					value = defaultOptions[key];
				}

				if(value == true) {
					toolbar.append(templates[key]);
				}
			}

			var self = this;

			toolbar.find("a[data-wysihtml5-command='formatBlock']").click(function(e) {
				var el = $(e.srcElement);
				self.toolbar.find('.current-font').text(el.html())
			});

			this.el.before(toolbar);

			return toolbar;
		}
	};

	$.fn.wysihtml5 = function (options) {
		return this.each(function () {
			var $this = $(this);
	      	$this.data('wysihtml5', new Wysihtml5($this, options));
	    })
  	};

  	$.fn.wysihtml5.Constructor = Wysihtml5;

}(window.jQuery, window.wysihtml5);<|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(["widgets/js/manager",
        "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._buffered_state_diff = {};
            this.pending_msgs = 0;
            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);
                    this.trigger('displayed');
                    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 {
                    WidgetModel.__super__.set.apply(that, [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.get('msg_throttle') || 3) === 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;
        },

        set: function(key, val, options) {
            // Set a value.
            var return_value = WidgetModel.__super__.set.apply(this, arguments);

            // Backbone only remembers the diff of the most recent set()
            // operation.  Calling set multiple times in a row results in a
            // loss of diff information.  Here we keep our own running diff.
            this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
            return return_value;
        },

        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.
            attrs = this._pack_models(attrs);
            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.get('msg_throttle') || 3)) {
                    // 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.
            this._buffered_state_diff = {};
        },

        save_changes: function(callbacks) {
            // Push this model's state to the back-end
            //
            // This invokes a Backbone.Sync.
            this.save(this._buffered_state_diff, {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_model_views = {};
            this.child_views = {};
            this.model.views.push(this);
            this.id = this.id || IPython.utils.uuid();
        },

        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);
            child_view.id = child_view.id || IPython.utils.uuid();

            // Associate the view id with the model id.
            if (this.child_model_views[child_model.id] === undefined) {
                this.child_model_views[child_model.id] = [];
            }
            this.child_model_views[child_model.id].push(child_view.id);

            // Remember the view by id.
            this.child_views[child_view.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_ids = this.child_model_views[child_model.id];
            if (view_ids !== undefined) {

                // Only delete the first view in the list.
                var view_id = view_ids[0];
                var view = this.child_views[view_id];
                delete this.child_views[view_id];
                view_ids.splice(0,1);
                child_model.views.pop(view);

                // Remove the view list specific to this model if it is empty.
                if (view_ids.length === 0) {
                    delete this.child_model_views[child_model.id];
                }
                return view;
            }
            return null;
        },

        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.

            // Walk the lists until an unequal entry is found.
            var i;
            for (i = 0; i < new_list.length; i++) {
                if (i < old_list.length || new_list[i] !== old_list[i]) {
                    break;
                }
            }

            // Remove the non-matching items from the old list.
            for (var j = i; j < old_list.length; j++) {
                removed_callback(old_list[j]);
            }

            // Add the rest of the new list items.
            for (i; i < new_list.length; i++) {
                added_callback(new_list[i]);
            }
        },

        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>Reverted strange change that I don't remember making to update method.<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(["widgets/js/manager",
        "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._buffered_state_diff = {};
            this.pending_msgs = 0;
            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);
                    this.trigger('displayed');
                    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 {
                    WidgetModel.__super__.set.apply(that, [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.get('msg_throttle') || 3) === 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;
        },

        set: function(key, val, options) {
            // Set a value.
            var return_value = WidgetModel.__super__.set.apply(this, arguments);

            // Backbone only remembers the diff of the most recent set()
            // operation.  Calling set multiple times in a row results in a
            // loss of diff information.  Here we keep our own running diff.
            this._buffered_state_diff = $.extend(this._buffered_state_diff, this.changedAttributes() || {});
            return return_value;
        },

        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.
            attrs = this._pack_models(attrs);
            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.get('msg_throttle') || 3)) {
                    // 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.
            this._buffered_state_diff = {};
        },

        save_changes: function(callbacks) {
            // Push this model's state to the back-end
            //
            // This invokes a Backbone.Sync.
            this.save(this._buffered_state_diff, {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_model_views = {};
            this.child_views = {};
            this.model.views.push(this);
            this.id = this.id || IPython.utils.uuid();
        },

        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);
            child_view.id = child_view.id || IPython.utils.uuid();

            // Associate the view id with the model id.
            if (this.child_model_views[child_model.id] === undefined) {
                this.child_model_views[child_model.id] = [];
            }
            this.child_model_views[child_model.id].push(child_view.id);

            // Remember the view by id.
            this.child_views[child_view.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_ids = this.child_model_views[child_model.id];
            if (view_ids !== undefined) {

                // Only delete the first view in the list.
                var view_id = view_ids[0];
                var view = this.child_views[view_id];
                delete this.child_views[view_id];
                view_ids.splice(0,1);
                child_model.views.pop(view);

                // Remove the view list specific to this model if it is empty.
                if (view_ids.length === 0) {
                    delete this.child_model_views[child_model.id];
                }
                return view;
            }
            return null;
        },

        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.

            // Walk the lists until an unequal entry is found.
            var i;
            for (i = 0; i < new_list.length; i++) {
                if (i < old_list.length || new_list[i] !== old_list[i]) {
                    break;
                }
            }

            // Remove the non-matching items from the old list.
            for (var j = i; j < old_list.length; j++) {
                removed_callback(old_list[j]);
            }

            // Add the rest of the new list items.
            for (i; i < new_list.length; i++) {
                added_callback(new_list[i]);
            }
        },

        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;}
            for (var i = 0; i < css.length; i++) {
                // Apply the css traits to all elements that match the selector.
                var selector = css[i][0];
                var elements = this._get_selector_element(selector);
                if (elements.length > 0) {
                    var trait_key = css[i][1];
                    var trait_value = css[i][2];
                    elements.css(trait_key ,trait_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|>