<commit_before>
jQuery(document).ready(function(){

  var stage = new Kinetic.Stage({
    container: 'game',
    width: window.innerWidth,
    height: window.innerHeight
  });

  var SIZE = 10;

  var layers = {'bg':new Kinetic.Layer(), 'loading':new Kinetic.Layer({x: (stage.getWidth()/2)-(320/2),
    y: (stage.getHeight()/2)-(285/2),
    width: 320,
    height: 285}), 'game':new Kinetic.Layer({x:0,y:0,width:SIZE*2*50, height:SIZE*2*30})};

  //Haces un rectangulo sobre lo que quieras centrar y luego calculas:
  // x: (stage.getWidth()/2)-(rect.getWidth()/2)
  // y: (stage.getHeight()/2)-(rect.getHeight()/2)

  var rect = new Kinetic.Rect({

    'width': stage.attrs.width,
    'height': stage.attrs.height,
    'fillLinearGradientStartPoint':{x:0,y:0},
    'fillLinearGradientEndPoint':{x:stage.attrs.width,y:stage.attrs.height},
    'fillLinearGradientColorStops':[0, '#D7D7E2', 1, '#B7CBCF']
  });

  // add the shape to the layer
  layers['bg'].add(rect);

  var circlesList = new CircleList();

  circlesList.circles = [
      // x, y, radius, color
      new Circle(150, 160, 90, "rgba(197, 171, 224,.9)"),
      new Circle(67, 136, 34,  "rgba(177, 190, 229,.9)"),
      new Circle(106, 74, 22,  "rgba(137, 150, 224,.8)"),
      new Circle(114, 52, 10,  "rgba(177, 125, 221,.75)"),
      new Circle(220, 82, 56,  "rgba(177, 165, 224,.6)"),
      new Circle(250, 138, 43, "rgba(157, 170, 223,.9)"),
      new Circle(232, 232, 25, "rgba(157, 181, 224,.9)"),
      new Circle(256, 222, 10, "rgba(107, 212, 225,.7)"),
      new Circle(128, 244, 36, "rgba(107, 190, 225,.9)"),
      new Circle(64, 188, 10,  "rgba(107, 205, 226,.9)")
  ];

  for(var i=0;i<circlesList['circles'].length;i++)
  {
    layers['loading'].add(circlesList['circles'][i].kcircle);
  }

  var ebury_logo = new Image();

  // variables accessible from within function(frame)
  var frameCount = 0;
  var currentSecond = 0;
  var frameRate = 0;

  ebury_logo.onload = function() {

    var image = new Kinetic.Image({
      x: 100,
      y: 145,
      image: ebury_logo,
      width: 113,
      height: 40,
      opacity: 1
    });

    layers['loading'].add(image);
    layers['loading'].draw();

    function updateFrameRate(time) {
          var second = Math.floor(time / 1000); // ms to integer seconds
          console.log(second, currentSecond)
          if (second != currentSecond) {
             frameRate = frameCount;
             frameCount = 0;
             currentSecond = second;
          }
          frameCount ++;
      }

    var anim = new Kinetic.Animation(function(frame) {

      // within function(frame), called with current time on each new frame

      //updateFrameRate(frame.time);

      wait(10, frame.time, function(){
          layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
          circlesList.update();
      });
      //console.log(frameRate);

      // layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
      // circlesList.update();

    }, layers['loading']);

    anim.start();

    stage.on('click.start touchstart.start', function(e){

        stage.off('click.start touchstart.start');
        anim.stop();

        var tween = new Kinetic.Tween({
            node: layers['loading'],
            opacity: 0,
            duration: 1,
            onFinish: function(){
                console.log('done!');
                tween.destroy();
                layers['loading'].destroy();
                //Startgame
                startGame();
            }
        }).play();
    });

  };

  ebury_logo.src = './snake/images/ebury_logo.png';

  stage.add(layers['bg']);
  stage.add(layers['loading']);
  // for(var layer in layers)
  // {
  //   stage.add(layers[layer]);
  // }

  function wait(seconds, time, callback) {
      seconds = seconds || 1000;
      var second = Math.floor(time / seconds);
      if (second != currentSecond)
      {
         callback();
         currentSecond = second;
      }
  }

  function startGame()
  {

    var snake = new Player();

    // var border = new Kinetic.Rect({
    // width: layers['game'].getWidth(),
    // height: layers['game'].getHeight(),
    // stroke: 'black',
    // strokeWidth: 1, //Border Size in Pixels
    // fill: 'transparent' //Background Color
    // });
    // layers['game'].add(border);
    var scaleX = window.innerWidth/layers['game'].getWidth();
    var scaleY = window.innerHeight/layers['game'].getHeight();
    layers['game'].scale({x:scaleX, y:scaleY});
    console.log(1+scaleX, scaleY);

    layers['game'].add(snake.head);

    stage.add(layers['game']);

    // stage.on('mousemove.game', function(data){

    //     snake.targetPos.x = data.evt.clientX;
    //     snake.targetPos.y = data.evt.clientY;
    // });

    var canvas = layers['game'].getCanvas()._canvas;

    $(canvas).attr('tabindex', 1);

    canvas.focus();

    $(canvas).keydown(function (data) {

      var key = data.keyCode;

        //Going left
        if(key == 37 && snake.direction != 'right')
        {
          snake.direction = 'left';
        }
        //Going up
        else if(key == 38 && snake.direction != 'down')
        {
          snake.direction = 'up';
        }
        //Going right
        else if(key == 39 && snake.direction != 'left')
        {
          snake.direction = 'right';
        }
        //Going down
        else if(key == 40 && snake.direction != 'up')
        {
          snake.direction = 'down';
        }
    });

    var anim = new Kinetic.Animation(function(frame) {

       wait(60, frame.time, function(){

          snake.update();
      });

    }, layers['game']);

    anim.start();
  }

  function Player()
  {
    this.head = new Kinetic.Circle({x:SIZE, y:SIZE, radius: SIZE, fill:'black', stroke: 'rgb(191, 191, 191)', strokeWidth: 1})
    this.actor = [];

    this.direction = 'right';
    this.sprint = SIZE*2;

    this.update = function()
    {

      //Collipsion
      var x = x2 = this.head.x();
      var y = y2 = this.head.y();

      //Collision
      if(x>= window.innerWidth || x <= 0)
      {
        console.log(x,y);
        return;
      }

      if(y >= window.innerHeight || y <= 0)
      {
        console.log(x,y);
        return;
      }

      if(this.direction == 'right')
      {

        x2 += (this.sprint);
        x = x2-(this.sprint);
      }
      else if(this.direction == 'left')
      {

        x2 -= (this.sprint);
        x = x2+(this.sprint);
      }
      else if(this.direction == 'up')
      {

        y2 -= (this.sprint);
        y = y2+(this.sprint);
      }
      else if(this.direction == 'down')
      {

        y2 += (this.sprint);
        y = y2-(this.sprint);
      }

      //Remove last element and return it
      if (this.actor.length)
      {
        var tail = this.actor.pop();
        tail.x(x);
        tail.y(y);

        //Add to the begining
        this.actor.unshift(tail);
      }

      this.head.x(x2);
      this.head.y(y2);

      // for(var i=0; i<this.actor.length; i++)
      // {

      //   var x = this.actor[i].x();
      //   var y = this.actor[i].y();

      //   if(this.direction == 'right')
      //   {
      //     this.actor[i].x(x+this.sprint);
      //   }
      //   else if(this.direction == 'left')
      //   {
      //     this.actor[i].x(x-this.sprint);
      //   }
      //   else if(this.direction == 'up')
      //   {
      //     this.actor[i].y(y-this.sprint);
      //   }
      //   else if(this.direction == 'down')
      //   {
      //     this.actor[i].y(y+this.sprint);
      //   }

      //   // var ty = this.targetPos.y - i*15;
      //   // var tx = this.targetPos.x - i*15;
      //   // var y = this.actor[i].y() + (ty - this.actor[i].y())*this.sprint;
      //   // var x = this.actor[i].x() + (tx - this.actor[i].x())*this.sprint;

      //   // this.actor[i].x(x);
      //   // this.actor[i].y(y);
      // }

      //Eat something
      if(Math.random() > 0.89)
      {

        var new_actor = new Kinetic.Circle({x: x, y: y, radius: SIZE, fill:'red', stroke: 'rgb(191, 191, 191)', strokeWidth: 1});

        this.actor.push(new_actor);

        layers['game'].add(new_actor);
      }

    }
  };

  // data structures
  function CircleList()
  {
      this.circles = [];

      this.update = function()
      {
         // special case for first blob - which is the main magenta disc
         var circle = this.circles[0];
         if (Math.random() > 0.69)
         {
            circle.velocity.z += (Math.random()*0.10 - 0.05);
            circle.spring = 0.0125;
         }
         circle.update();

         // all the other blobs can animate based on mouse interaction
         for (var i = 1,dx,dy,d; i < this.circles.length; i++)
         {
            circle = this.circles[i];

            // else based on a random chance, pulse the blob
            if (Math.random() > 0.995)
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.velocity[2] += (Math.random()*0.30 - 0.15);
               circle.spring = 0.0125;
            }
            // else just animate towards the original position
            else
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.spring = 0.05;
            }

            circle.update();
         }
      };
   };

   function Circle(x, y, radius, colour)
   {
      this.kcircle = new Kinetic.Circle({x:x, y:y, radius: radius, fill:colour, stroke: 'rgb(191, 191, 191)', strokeWidth: 1});
      this.origin = [x,y, 0];
      this.position = [x,y, 0];
      this.targetPos = [x,y, 0];
      this.originradius = radius;
      this.radius = radius;
      this.velocity = [0,0, 0];
      this.friction = 0.75;
      this.spring = 0.05;

      this.update = function()
      {
         this.velocity[0] += (this.targetPos[0] - this.kcircle.x()) * this.spring;
         this.velocity[0] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[0]);

         this.velocity[1] += (this.targetPos[1] - this.kcircle.y()) * this.spring;
         this.velocity[1] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[1]);

         var dox = this.origin[0] - this.kcircle.x(),
             doy = this.origin[1] - this.kcircle.y(),
             d = Math.sqrt(dox * dox + doy * doy);

         this.targetPos[2] = d/150 + 1;
         this.velocity[2] += (this.targetPos[2] - this.position[2]) * this.spring;
         this.velocity[2] *= this.friction;
         this.position[2] += this.velocity[2];

         this.kcircle.radius(this.originradius * this.position[2]);
         if (this.kcircle.radius() < 1) this.kcircle.radius(1);
      };
   };

});

<commit_msg>control time<commit_after>
jQuery(document).ready(function(){

  var stage = new Kinetic.Stage({
    container: 'game',
    width: window.innerWidth,
    height: window.innerHeight
  });

  var SIZE = 10;
  var time_update_game = 60;

  var layers = {'bg':new Kinetic.Layer(), 'loading':new Kinetic.Layer({x: (stage.getWidth()/2)-(320/2),
    y: (stage.getHeight()/2)-(285/2),
    width: 320,
    height: 285}), 'game':new Kinetic.Layer({x:0,y:0,width:SIZE*2*50, height:SIZE*2*30})};

  var scaleX = window.innerWidth/layers['game'].getWidth();
  var scaleY = window.innerHeight/layers['game'].getHeight();

  //Haces un rectangulo sobre lo que quieras centrar y luego calculas:
  // x: (stage.getWidth()/2)-(rect.getWidth()/2)
  // y: (stage.getHeight()/2)-(rect.getHeight()/2)

  var bg_rect = new Kinetic.Rect({

    'width': stage.attrs.width,
    'height': stage.attrs.height,
    'fillLinearGradientStartPoint':{x:0,y:0},
    'fillLinearGradientEndPoint':{x:stage.attrs.width,y:stage.attrs.height},
    'fillLinearGradientColorStops':[0, '#D7D7E2', 1, '#B7CBCF']
  });

  // add the shape to the layer
  layers['bg'].add(bg_rect);

  var circlesList = new CircleList();

  circlesList.circles = [
      // x, y, radius, color
      new Circle(150, 160, 90, "rgba(197, 171, 224,.9)"),
      new Circle(67, 136, 34,  "rgba(177, 190, 229,.9)"),
      new Circle(106, 74, 22,  "rgba(137, 150, 224,.8)"),
      new Circle(114, 52, 10,  "rgba(177, 125, 221,.75)"),
      new Circle(220, 82, 56,  "rgba(177, 165, 224,.6)"),
      new Circle(250, 138, 43, "rgba(157, 170, 223,.9)"),
      new Circle(232, 232, 25, "rgba(157, 181, 224,.9)"),
      new Circle(256, 222, 10, "rgba(107, 212, 225,.7)"),
      new Circle(128, 244, 36, "rgba(107, 190, 225,.9)"),
      new Circle(64, 188, 10,  "rgba(107, 205, 226,.9)")
  ];

  for(var i=0;i<circlesList['circles'].length;i++)
  {
    layers['loading'].add(circlesList['circles'][i].kcircle);
  }

  var ebury_logo = new Image();

  // variables accessible from within function(frame)
  var frameCount = 0;
  var currentSecond = 0;
  var frameRate = 0;

  ebury_logo.onload = function() {

    var image = new Kinetic.Image({
      x: 100,
      y: 145,
      image: ebury_logo,
      width: 113,
      height: 40,
      opacity: 1
    });

    layers['loading'].add(image);
    layers['loading'].draw();

    function updateFrameRate(time) {
          var second = Math.floor(time / 1000); // ms to integer seconds
          console.log(second, currentSecond)
          if (second != currentSecond) {
             frameRate = frameCount;
             frameCount = 0;
             currentSecond = second;
          }
          frameCount ++;
      }

    var anim = new Kinetic.Animation(function(frame) {

      // within function(frame), called with current time on each new frame

      //updateFrameRate(frame.time);

      wait(10, frame.time, function(){
          layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
          circlesList.update();
      });
      //console.log(frameRate);

      // layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
      // circlesList.update();

    }, layers['loading']);

    anim.start();

    stage.on('click.start touchstart.start', function(e){

        stage.off('click.start touchstart.start');
        anim.stop();

        var tween = new Kinetic.Tween({
            node: layers['loading'],
            opacity: 0,
            duration: 1,
            onFinish: function(){
                console.log('done!');
                tween.destroy();
                layers['loading'].destroy();
                //Startgame
                startGame();
            }
        }).play();
    });

  };

  ebury_logo.src = './snake/images/ebury_logo.png';

  stage.add(layers['bg']);
  stage.add(layers['loading']);
  // for(var layer in layers)
  // {
  //   stage.add(layers[layer]);
  // }

  function wait(seconds, time, callback) {
      seconds = seconds || 1000;
      var second = Math.floor(time / seconds);
      if (second != currentSecond)
      {
         callback();
         currentSecond = second;
      }
  }

  function startGame()
  {

    var snake = new Player();

    // var border = new Kinetic.Rect({
    // width: layers['game'].getWidth(),
    // height: layers['game'].getHeight(),
    // stroke: 'black',
    // strokeWidth: 1, //Border Size in Pixels
    // fill: 'transparent' //Background Color
    // });
    // layers['game'].add(border);

    layers['game'].scale({x:scaleX, y:scaleY});
    console.log(1+scaleX, scaleY);

    layers['game'].add(snake.head);

    stage.add(layers['game']);

    // stage.on('mousemove.game', function(data){

    //     snake.targetPos.x = data.evt.clientX;
    //     snake.targetPos.y = data.evt.clientY;
    // });

    var canvas = layers['game'].getCanvas()._canvas;

    $(canvas).attr('tabindex', 1);

    canvas.focus();

    $(canvas).keydown(function (data) {

      var key = data.keyCode;

        //Going left
        if(key == 37 && snake.direction != 'right')
        {
          snake.direction = 'left';
        }
        //Going up
        else if(key == 38 && snake.direction != 'down')
        {
          snake.direction = 'up';
        }
        //Going right
        else if(key == 39 && snake.direction != 'left')
        {
          snake.direction = 'right';
        }
        //Going down
        else if(key == 40 && snake.direction != 'up')
        {
          snake.direction = 'down';
        }
    });

    var anim = new Kinetic.Animation(function(frame) {

       wait(time_update_game, frame.time, function(){

          snake.update();
      });

    }, layers['game']);

    anim.start();
  }

  function Player()
  {
    this.head = new Kinetic.Circle({x:SIZE, y:SIZE, radius: SIZE, fill:'black', stroke: 'rgb(191, 191, 191)', strokeWidth: 1})
    this.actor = [];

    this.direction = 'right';
    this.sprint = SIZE*2;

    this.update = function()
    {

      //Collipsion
      var x = x2 = this.head.x();
      var y = y2 = this.head.y();

      if(this.direction == 'right')
      {

        x2 += (this.sprint);
        x = x2-(this.sprint);
      }
      else if(this.direction == 'left')
      {

        x2 -= (this.sprint);
        x = x2+(this.sprint);
      }
      else if(this.direction == 'up')
      {

        y2 -= (this.sprint);
        y = y2+(this.sprint);
      }
      else if(this.direction == 'down')
      {

        y2 += (this.sprint);
        y = y2-(this.sprint);
      }

      //Collision
      if(x2 < 0 || x2*scaleX>window.innerWidth)
      {
        return;
      }

      if(y2 < 0 || y2*scaleY>window.innerHeight)
      {
        return;
      }

      //Remove last element and return it
      if (this.actor.length)
      {
        var tail = this.actor.pop();
        tail.x(x);
        tail.y(y);

        //Add to the begining
        this.actor.unshift(tail);
      }

      this.head.x(x2);
      this.head.y(y2);

      // for(var i=0; i<this.actor.length; i++)
      // {

      //   var x = this.actor[i].x();
      //   var y = this.actor[i].y();

      //   if(this.direction == 'right')
      //   {
      //     this.actor[i].x(x+this.sprint);
      //   }
      //   else if(this.direction == 'left')
      //   {
      //     this.actor[i].x(x-this.sprint);
      //   }
      //   else if(this.direction == 'up')
      //   {
      //     this.actor[i].y(y-this.sprint);
      //   }
      //   else if(this.direction == 'down')
      //   {
      //     this.actor[i].y(y+this.sprint);
      //   }

      //   // var ty = this.targetPos.y - i*15;
      //   // var tx = this.targetPos.x - i*15;
      //   // var y = this.actor[i].y() + (ty - this.actor[i].y())*this.sprint;
      //   // var x = this.actor[i].x() + (tx - this.actor[i].x())*this.sprint;

      //   // this.actor[i].x(x);
      //   // this.actor[i].y(y);
      // }

      //Eat something
      if(Math.random() > 0.89)
      {

        var new_actor = new Kinetic.Circle({x: x, y: y, radius: SIZE, fill:'red', stroke: 'rgb(191, 191, 191)', strokeWidth: 1});

        this.actor.push(new_actor);

        layers['game'].add(new_actor);

        if(time_update_game>10)
          time_update_game -= 1
      }

    }

    $(window).resize(function(e){

        scaleX = window.innerWidth/layers['game'].getWidth();
        scaleY = window.innerHeight/layers['game'].getHeight();
        layers['game'].scale({x:scaleX, y:scaleY});
        layers['game'].draw();

        stage.setWidth(window.innerWidth);
        stage.setHeight(window.innerHeight);

        bg_rect.size({width:window.innerWidth, height:window.innerHeight});
        bg_rect.fillLinearGradientEndPoint({x:window.innerWidth,y:window.innerHeight});
        layers['bg'].draw();

    });
  };

  // data structures
  function CircleList()
  {
      this.circles = [];

      this.update = function()
      {
         // special case for first blob - which is the main magenta disc
         var circle = this.circles[0];
         if (Math.random() > 0.69)
         {
            circle.velocity.z += (Math.random()*0.10 - 0.05);
            circle.spring = 0.0125;
         }
         circle.update();

         // all the other blobs can animate based on mouse interaction
         for (var i = 1,dx,dy,d; i < this.circles.length; i++)
         {
            circle = this.circles[i];

            // else based on a random chance, pulse the blob
            if (Math.random() > 0.995)
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.velocity[2] += (Math.random()*0.30 - 0.15);
               circle.spring = 0.0125;
            }
            // else just animate towards the original position
            else
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.spring = 0.05;
            }

            circle.update();
         }
      };
   };

   function Circle(x, y, radius, colour)
   {
      this.kcircle = new Kinetic.Circle({x:x, y:y, radius: radius, fill:colour, stroke: 'rgb(191, 191, 191)', strokeWidth: 1});
      this.origin = [x,y, 0];
      this.position = [x,y, 0];
      this.targetPos = [x,y, 0];
      this.originradius = radius;
      this.radius = radius;
      this.velocity = [0,0, 0];
      this.friction = 0.75;
      this.spring = 0.05;

      this.update = function()
      {
         this.velocity[0] += (this.targetPos[0] - this.kcircle.x()) * this.spring;
         this.velocity[0] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[0]);

         this.velocity[1] += (this.targetPos[1] - this.kcircle.y()) * this.spring;
         this.velocity[1] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[1]);

         var dox = this.origin[0] - this.kcircle.x(),
             doy = this.origin[1] - this.kcircle.y(),
             d = Math.sqrt(dox * dox + doy * doy);

         this.targetPos[2] = d/150 + 1;
         this.velocity[2] += (this.targetPos[2] - this.position[2]) * this.spring;
         this.velocity[2] *= this.friction;
         this.position[2] += this.velocity[2];

         this.kcircle.radius(this.originradius * this.position[2]);
         if (this.kcircle.radius() < 1) this.kcircle.radius(1);
      };
   };

});

<|endoftext|>


<commit_before><commit_msg>driver skeleton<commit_after>
function mongo_driver() {
}

exports = module.exports = function() {
    var driver = new mongo_driver();
    return driver;
};
<|endoftext|>


<commit_before>/* eslint-env jest */
/* global element, by */

describe('Edit Home tests to reorganize the home screen.', () => {
	it('should show home screen after tap to exit edit-home screen', async () => {
		await element(by.id('button-open-edit-home')).tap()
		await element(by.id('header-back')).tap()
		await expect(element(by.id('screen-homescreen'))).toBeVisible()
	})
})
<commit_msg>remove the open-edit-screen test<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Map of all currently open app window. The key is an app id.
 */
var appWindows = {};

/**
 * @return {Array.<DOMWindow>} Array of content windows for all currently open
 *   app windows.
 */
function getContentWindows() {
  var views = [];
  for (var key in appWindows) {
    if (appWindows.hasOwnProperty(key))
      views.push(appWindows[key].contentWindow);
  }
  return views;
}

/**
 * Wrapper for an app window.
 *
 * Expects the following from the app scripts:
 * 1. The page load handler should initialize the app using |window.appState|
 *    and call |util.platform.saveAppState|.
 * 2. Every time the app state changes the app should update |window.appState|
 *    and call |util.platform.saveAppState| .
 * 3. The app may have |unload| function to persist the app state that does not
 *    fit into |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {string} id App window id.
 * @param {Object|function} options Options object or a function to create it.
 * @constructor
 */
function AppWindowWrapper(url, id, options) {
  this.url_ = url;
  this.id_ = id;
  this.options_ = options;

  this.window_ = null;
  this.creating_ = false;
}

/**
 * @return {boolean} True if the window is currently open.
 */
AppWindowWrapper.prototype.isOpen = function() {
  return this.window_ && !this.window_.contentWindow.closed;
};

/**
 * Open the window.
 * @param {Object} appState App state.
 */
AppWindowWrapper.prototype.launch = function(appState) {
  console.assert(!this.isOpen(), 'The window is already open');
  console.assert(!this.creating_, 'The window is already opening');

  this.creating_ = true;
  this.appState_ = appState;

  var options = this.options_;
  if (typeof options == 'function')
    options = options();
  options.id = this.id_;

  chrome.app.window.create(this.url_, options, function(appWindow) {
    this.creating_ = false;
    this.window_ = appWindow;
    appWindows[this.id_] = appWindow;
    var contentWindow = appWindow.contentWindow;
    contentWindow.appID = this.id_;
    contentWindow.appState = this.appState_;
    appWindow.onClosed.addListener(function() {
      if (contentWindow.unload)
        contentWindow.unload();
      if (contentWindow.saveOnExit) {
        contentWindow.saveOnExit.forEach(function(entry) {
          util.AppCache.update(entry.key, entry.value);
        });
      }
      delete appWindows[this.id_];
      chrome.storage.local.remove(this.id_);  // Forget the persisted state.
      this.window_ = null;
      maybeCloseBackgroundPage();
    }.bind(this));
  }.bind(this));
};

/**
 * Wrapper for a singleton app window.
 *
 * In addition to the AppWindowWrapper requirements the app scripts should
 * have |reload| method that re-initializes the app based on a changed
 * |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {Object|function} options Options object or a function to return it.
 * @constructor
 */
function SingletonAppWindowWrapper(url, options) {
  AppWindowWrapper.call(this, url, url, options);
}

/**
 * Inherits from AppWindowWrapper.
 */
SingletonAppWindowWrapper.prototype = { __proto__: AppWindowWrapper.prototype };

/**
 * Open the window.
 *
 * Activates an existing window or creates a new one.
 *
 * @param {Object} appState App state.
 */
SingletonAppWindowWrapper.prototype.launch = function(appState) {
  if (this.isOpen()) {
    this.window_.contentWindow.appState = appState;
    this.window_.contentWindow.reload();
    this.window_.focus();
    return;
  }

  if (this.creating_) {
    this.appState_ = appState;
    return;
  }

  AppWindowWrapper.prototype.launch.call(this, appState);
};

/**
 * Reopen a window if its state is saved in the local storage.
 */
SingletonAppWindowWrapper.prototype.reopen = function() {
  chrome.storage.local.get(this.id_, function(items) {
    var value = items[this.id_];
    if (!value)
      return;  // No app state persisted.

    try {
      var appState = JSON.parse(value);
      this.launch(appState);
    } catch (e) {
      console.error('Corrupt launch data for ' + this.id_, value);
    }
  }.bind(this));
};

/**
 * Prefix for the file manager window ID.
 */
var FILES_ID_PREFIX = 'files#';

/**
 * Regexp matching a file manager window ID.
 */
var FILES_ID_PATTERN = new RegExp('^' + FILES_ID_PREFIX + '(\\d*)$');

/**
 * Value of the next file manager window ID.
 */
var nextFileManagerWindowID = 0;

/**
 * @return {Object} File manager window create options.
 */
function createFileManagerOptions() {
  return {
    defaultWidth: Math.round(window.screen.availWidth * 0.8),
    defaultHeight: Math.round(window.screen.availHeight * 0.8)
  };
}

/**
 * @param {Object=} opt_appState App state.
 * @param {number=} opt_id Window id.
 */
function launchFileManager(opt_appState, opt_id) {
  var id = opt_id || nextFileManagerWindowID;
  nextFileManagerWindowID = Math.max(nextFileManagerWindowID, id + 1);

  var appWindow = new AppWindowWrapper(
        'main.html', FILES_ID_PREFIX + id, createFileManagerOptions);
  appWindow.launch(opt_appState || {});
}

/**
 * Relaunch file manager windows based on the persisted state.
 */
function reopenFileManagers() {
  chrome.storage.local.get(function(items) {
    for (var key in items) {
      if (items.hasOwnProperty(key)) {
        var match = key.match(FILES_ID_PATTERN);
        if (match) {
          var id = Number(match[1]);
          try {
            var appState = JSON.parse(items[key]);
            launchFileManager(appState, id);
          } catch (e) {
            console.error('Corrupt launch data for ' + id, value);
          }
        }
      }
    }
  });
}

/**
 * @param {string} action Task id.
 * @param {Object} details Details object.
 */
function executeFileBrowserTask(action, details) {
  var urls = details.entries.map(function(e) { return e.toURL() });
  switch (action) {
    case 'play':
      launchAudioPlayer({items: urls, position: 0});
      break;

    case 'watch':
      launchVideoPlayer(urls[0]);
      break;

    default:
      // Every other action opens a Files app window.
      launchFileManager({
        params: {
          action: action
        },
        defaultPath: details.entries[0].fullPath
      });
      break;
  }
}

/**
 * @return {Object} Audio player window create options.
 */
function createAudioPlayerOptions() {
  var WIDTH = 280;
  var MIN_HEIGHT = 35 + 58;
  var MAX_HEIGHT = 35 + 58 * 3;
  var BOTTOM = 80;
  var RIGHT = 20;

  return {
    defaultLeft: (window.screen.availWidth - WIDTH - RIGHT),
    defaultTop: (window.screen.availHeight - MIN_HEIGHT - BOTTOM),
    minHeight: MIN_HEIGHT,
    maxHeight: MAX_HEIGHT,
    height: MIN_HEIGHT,
    minWidth: WIDTH,
    maxWidth: WIDTH,
    width: WIDTH
  };
}

var audioPlayer =
    new SingletonAppWindowWrapper('mediaplayer.html', createAudioPlayerOptions);

/**
 * Launch the audio player.
 * @param {Object} playlist Playlist.
 */
function launchAudioPlayer(playlist) {
  audioPlayer.launch(playlist);
}

var videoPlayer =
    new SingletonAppWindowWrapper('video_player.html', { hidden: true });

/**
 * Launch the video player.
 * @param {string} url Video url.
 */
function launchVideoPlayer(url) {
  videoPlayer.launch({url: url});
}

/**
 * Launch the app.
 */
function launch() {
  if (nextFileManagerWindowID == 0) {
    // The app just launched. Remove window state records that are not needed
    // any more.
    chrome.storage.local.get(function(items) {
      for (var key in items) {
        if (items.hasOwnProperty(key)) {
          if (key.match(FILES_ID_PATTERN))
            chrome.storage.local.remove(key);
        }
      }
    });
  }

  launchFileManager();
}

/**
 * Restarted the app, restore windows.
 */
function restart() {
  reopenFileManagers();
  audioPlayer.reopen();
  videoPlayer.reopen();
}

/**
 * Closes the background page, if it is not needed.
 */
function maybeCloseBackgroundPage() {
  if (Object.keys(appWindows).length === 0 &&
      !FileCopyManager.getInstance().hasQueuedTasks())
    close();
}

chrome.app.runtime.onLaunched.addListener(launch);
chrome.app.runtime.onRestarted.addListener(restart);

function addExecuteHandler() {
  if (!chrome.fileBrowserHandler) {
    console.log('Running outside Chrome OS, loading mock API implementations.');
    util.loadScripts(['js/mock_chrome.js'], addExecuteHandler);
    return;
  }
  chrome.fileBrowserHandler.onExecute.addListener(executeFileBrowserTask);
}

addExecuteHandler();
<commit_msg>Remember window geometries in Files.app v2.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Map of all currently open app window. The key is an app id.
 */
var appWindows = {};

/**
 * @return {Array.<DOMWindow>} Array of content windows for all currently open
 *   app windows.
 */
function getContentWindows() {
  var views = [];
  for (var key in appWindows) {
    if (appWindows.hasOwnProperty(key))
      views.push(appWindows[key].contentWindow);
  }
  return views;
}

/**
 * Wrapper for an app window.
 *
 * Expects the following from the app scripts:
 * 1. The page load handler should initialize the app using |window.appState|
 *    and call |util.platform.saveAppState|.
 * 2. Every time the app state changes the app should update |window.appState|
 *    and call |util.platform.saveAppState| .
 * 3. The app may have |unload| function to persist the app state that does not
 *    fit into |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {string} id App window id.
 * @param {Object|function} options Options object or a function to create it.
 * @constructor
 */
function AppWindowWrapper(url, id, options) {
  this.url_ = url;
  this.id_ = id;
  this.options_ = options;

  this.window_ = null;
  this.creating_ = false;
}

/**
 * Shift distance to avoid overlapping windows.
 * @type {number}
 * @const
 */
AppWindowWrapper.SHIFT_DISTANCE = 40;

/**
 * @return {boolean} True if the window is currently open.
 */
AppWindowWrapper.prototype.isOpen = function() {
  return this.window_ && !this.window_.contentWindow.closed;
};

/**
 * Gets similar windows, it means with the same initial url.
 * @return {Array.<AppWindow>} List of similar windows.
 * @private
 */
AppWindowWrapper.prototype.getSimilarWindows_ = function() {
  var result = [];
  for (var appID in appWindows) {
    if (appWindows[appID].contentWindow.appInitialURL == this.url_)
      result.push(appWindows[appID]);
  }
  return result;
};

/**
 * Open the window.
 * @param {Object} appState App state.
 */
AppWindowWrapper.prototype.launch = function(appState) {
  console.assert(!this.isOpen(), 'The window is already open');
  console.assert(!this.creating_, 'The window is already opening');

  this.creating_ = true;
  this.appState_ = appState;

  var options = this.options_;
  if (typeof options == 'function')
    options = options();
  options.id = this.url_;  // This is to make Chrome reuse window geometries.
  options.singleton = false;
  options.hidden = true;

  // Get similar windows, it means with the same initial url, eg. different
  // main windows of Files.app.
  var similarWindows = this.getSimilarWindows_();

  // Closure creating the window, once all preprocessing tasks are finished.
  var createWindow = function() {
    chrome.app.window.onRestored.removeListener(createWindow);
    chrome.app.window.create(this.url_, options, function(appWindow) {
      this.creating_ = false;
      this.window_ = appWindow;

      // If we have already another window of the same kind, then shift this
      // window to avoid overlapping with the previous one.
      if (similarWindows.length) {
        var bounds = appWindow.getBounds();
        appWindow.moveTo(bounds.left + AppWindowWrapper.SHIFT_DISTANCE,
                         bounds.top + AppWindowWrapper.SHIFT_DISTANCE);
      }

      // Show after changing bounds is done.
      appWindow.show();

      appWindows[this.id_] = appWindow;
      var contentWindow = appWindow.contentWindow;
      contentWindow.appID = this.id_;
      contentWindow.appState = this.appState_;
      contentWindow.appInitialURL = this.url_;
      appWindow.onClosed.addListener(function() {
        if (contentWindow.unload)
          contentWindow.unload();
        if (contentWindow.saveOnExit) {
          contentWindow.saveOnExit.forEach(function(entry) {
            util.AppCache.update(entry.key, entry.value);
          });
        }
        delete appWindows[this.id_];
        chrome.storage.local.remove(this.id_);  // Forget the persisted state.
        this.window_ = null;
        maybeCloseBackgroundPage();
      }.bind(this));
    }.bind(this));
  }.bind(this);

  // Restore maximized windows, to avoid hiding them to tray, which can be
  // confusing for users.
  for (var index = 0; index < similarWindows.length; index++) {
    if (similarWindows[index].isMaximized()) {
      var createWindowAndRemoveListener = function() {
        createWindow();
        similarWindows[index].onRestored.removeListener(
            createWindowAndRemoveListener);
      };
      similarWindows[index].onRestored.addListener(
          createWindowAndRemoveListener);
      similarWindows[index].restore();
      return;
    }
  }

  // If no maximized windows, then create the window immediately.
  createWindow();
};

/**
 * Wrapper for a singleton app window.
 *
 * In addition to the AppWindowWrapper requirements the app scripts should
 * have |reload| method that re-initializes the app based on a changed
 * |window.appState|.
 *
 * @param {string} url App window content url.
 * @param {Object|function} options Options object or a function to return it.
 * @constructor
 */
function SingletonAppWindowWrapper(url, options) {
  AppWindowWrapper.call(this, url, url, options);
}

/**
 * Inherits from AppWindowWrapper.
 */
SingletonAppWindowWrapper.prototype = { __proto__: AppWindowWrapper.prototype };

/**
 * Open the window.
 *
 * Activates an existing window or creates a new one.
 *
 * @param {Object} appState App state.
 */
SingletonAppWindowWrapper.prototype.launch = function(appState) {
  if (this.isOpen()) {
    this.window_.contentWindow.appState = appState;
    this.window_.contentWindow.reload();
    this.window_.focus();
    return;
  }

  if (this.creating_) {
    this.appState_ = appState;
    return;
  }

  AppWindowWrapper.prototype.launch.call(this, appState);
};

/**
 * Reopen a window if its state is saved in the local storage.
 */
SingletonAppWindowWrapper.prototype.reopen = function() {
  chrome.storage.local.get(this.id_, function(items) {
    var value = items[this.id_];
    if (!value)
      return;  // No app state persisted.

    try {
      var appState = JSON.parse(value);
      this.launch(appState);
    } catch (e) {
      console.error('Corrupt launch data for ' + this.id_, value);
    }
  }.bind(this));
};

/**
 * Prefix for the file manager window ID.
 */
var FILES_ID_PREFIX = 'files#';

/**
 * Regexp matching a file manager window ID.
 */
var FILES_ID_PATTERN = new RegExp('^' + FILES_ID_PREFIX + '(\\d*)$');

/**
 * Value of the next file manager window ID.
 */
var nextFileManagerWindowID = 0;

/**
 * @return {Object} File manager window create options.
 */
function createFileManagerOptions() {
  return {
    defaultLeft: Math.round(window.screen.availWidth * 0.1),
    defaultTop: Math.round(window.screen.availHeight * 0.1),
    defaultWidth: Math.round(window.screen.availWidth * 0.8),
    defaultHeight: Math.round(window.screen.availHeight * 0.8),
    minWidth: 320,
    minHeight: 240
  };
}

/**
 * @param {Object=} opt_appState App state.
 * @param {number=} opt_id Window id.
 */
function launchFileManager(opt_appState, opt_id) {
  var id = opt_id || nextFileManagerWindowID;
  nextFileManagerWindowID = Math.max(nextFileManagerWindowID, id + 1);

  var appWindow = new AppWindowWrapper(
        'main.html', FILES_ID_PREFIX + id, createFileManagerOptions);
  appWindow.launch(opt_appState || {});
}

/**
 * Relaunch file manager windows based on the persisted state.
 */
function reopenFileManagers() {
  chrome.storage.local.get(function(items) {
    for (var key in items) {
      if (items.hasOwnProperty(key)) {
        var match = key.match(FILES_ID_PATTERN);
        if (match) {
          var id = Number(match[1]);
          try {
            var appState = JSON.parse(items[key]);
            launchFileManager(appState, id);
          } catch (e) {
            console.error('Corrupt launch data for ' + id, value);
          }
        }
      }
    }
  });
}

/**
 * @param {string} action Task id.
 * @param {Object} details Details object.
 */
function executeFileBrowserTask(action, details) {
  var urls = details.entries.map(function(e) { return e.toURL() });
  switch (action) {
    case 'play':
      launchAudioPlayer({items: urls, position: 0});
      break;

    case 'watch':
      launchVideoPlayer(urls[0]);
      break;

    default:
      // Every other action opens a Files app window.
      launchFileManager({
        params: {
          action: action
        },
        defaultPath: details.entries[0].fullPath
      });
      break;
  }
}

/**
 * @return {Object} Audio player window create options.
 */
function createAudioPlayerOptions() {
  var WIDTH = 280;
  var MIN_HEIGHT = 35 + 58;
  var MAX_HEIGHT = 35 + 58 * 3;
  var BOTTOM = 80;
  var RIGHT = 20;

  return {
    defaultLeft: (window.screen.availWidth - WIDTH - RIGHT),
    defaultTop: (window.screen.availHeight - MIN_HEIGHT - BOTTOM),
    minHeight: MIN_HEIGHT,
    maxHeight: MAX_HEIGHT,
    height: MIN_HEIGHT,
    minWidth: WIDTH,
    maxWidth: WIDTH,
    width: WIDTH
  };
}

var audioPlayer =
    new SingletonAppWindowWrapper('mediaplayer.html', createAudioPlayerOptions);

/**
 * Launch the audio player.
 * @param {Object} playlist Playlist.
 */
function launchAudioPlayer(playlist) {
  audioPlayer.launch(playlist);
}

var videoPlayer =
    new SingletonAppWindowWrapper('video_player.html', { hidden: true });

/**
 * Launch the video player.
 * @param {string} url Video url.
 */
function launchVideoPlayer(url) {
  videoPlayer.launch({url: url});
}

/**
 * Launch the app.
 */
function launch() {
  if (nextFileManagerWindowID == 0) {
    // The app just launched. Remove window state records that are not needed
    // any more.
    chrome.storage.local.get(function(items) {
      for (var key in items) {
        if (items.hasOwnProperty(key)) {
          if (key.match(FILES_ID_PATTERN))
            chrome.storage.local.remove(key);
        }
      }
    });
  }

  launchFileManager();
}

/**
 * Restarted the app, restore windows.
 */
function restart() {
  reopenFileManagers();
  audioPlayer.reopen();
  videoPlayer.reopen();
}

/**
 * Closes the background page, if it is not needed.
 */
function maybeCloseBackgroundPage() {
  if (Object.keys(appWindows).length === 0 &&
      !FileCopyManager.getInstance().hasQueuedTasks())
    close();
}

chrome.app.runtime.onLaunched.addListener(launch);
chrome.app.runtime.onRestarted.addListener(restart);

function addExecuteHandler() {
  if (!chrome.fileBrowserHandler) {
    console.log('Running outside Chrome OS, loading mock API implementations.');
    util.loadScripts(['js/mock_chrome.js'], addExecuteHandler);
    return;
  }
  chrome.fileBrowserHandler.onExecute.addListener(executeFileBrowserTask);
}

addExecuteHandler();
<|endoftext|>


<commit_before>import add from './support/task';
import createDocument from './system/createDocument';
import {createInput} from './common/cElement';
import {getElementById} from './common/getElement';
import getMembrList from './ajax/getMembrList';
import getValue from './system/getValue';
import insertElement from './common/insertElement';
import insertHtmlAfterBegin from './common/insertHtmlAfterBegin';
import insertHtmlBeforeEnd from './common/insertHtmlBeforeEnd';
import jQueryNotPresent from './common/jQueryNotPresent';
import moreToDo from './common/moreToDo';
import {pCC} from './support/layout';
import playerName from './common/playerName';
import retryAjax from './ajax/retryAjax';

var ranks;
var myRank;
var theRows;
var rankCount;
var characterRow;

var privLookup = {
  'Bank Withdraw': 5,
  'Build/Upgrade/Demolish Structures': 5,
  'Can Un-Tag Items': 5,
  'Build/Upgrade Structures': 4,
  'Can Kick Members': 4,
  'Can Mass Messages': 0.5,
  'Take Items': 0.2,
  'Can Recall Tagged Items': 0.2,
  'Store Items': 0.1,
  'Can View Advisor': 0.1
};

function parseRankData(linkElement, responseText) {
  // Makes a weighted calculation of available permissions and gets tax rate
  var doc = createDocument(responseText);
  var checkBoxes = doc.querySelectorAll(
    '#pCC input[type="checkbox"]:checked');
  var count = 0;
  Array.prototype.forEach.call(checkBoxes, function(checkbox) {
    var privName = checkbox.nextElementSibling.textContent.trim();
    if (privName in privLookup) {
      count += privLookup[privName];
    } else {count += 1;}
  });
  var taxRate = doc.querySelector('#pCC input[name="rank_tax"]').value;
  insertHtmlAfterBegin(linkElement, '(' +
    Math.round(10 * count) / 10 + ') Tax:(' + taxRate + '%) ');
}

function fetchRankData() { // jQuery.min
  var calcButton = getElementById('getrankweightings');
  calcButton.classList.add('fshHide');
  var allItems = document.querySelectorAll('#pCC input[value="Edit"]');
  Array.prototype.forEach.call(allItems, function(anItem) {
    var targetNode = anItem.parentNode.parentNode.previousElementSibling;
    var href = /window\.location='(.*)';/.exec(anItem
      .getAttribute('onclick'))[1];
    retryAjax(href).done(parseRankData.bind(null, targetNode));
  });
}

function notValidRow(thisRankRowNum, targetRowNum, parentTable) {
  return characterRow >= Math.min(thisRankRowNum, targetRowNum) ||
    targetRowNum < 1 ||
    targetRowNum > parentTable.rows.length;
}

function getTargetRowNumber(val) {
  if (val === 'Up') {return -1;}
  return 2;
}

function getPxScroll(val) {
  if (val === 'Up') {return -22;}
  return 22;
}

function overrideUpDown(evt, val) {
  var onclickHREF = /window.location='(.*)';/
    .exec(evt.target.getAttribute('onclick'))[1];
  var thisRankRow = evt.target.parentNode.parentNode.parentNode;
  var thisRankRowNum = thisRankRow.rowIndex;
  var targetRowNum = thisRankRowNum + getTargetRowNumber(val);
  var parentTable = thisRankRow.parentNode;
  if (notValidRow(thisRankRowNum, targetRowNum, parentTable)) {return;}
  retryAjax(onclickHREF);
  var injectRow = parentTable.rows[targetRowNum];
  parentTable.insertBefore(thisRankRow, injectRow);
  var pxScroll = getPxScroll(val);
  window.scrollBy(0, pxScroll);
  evt.stopPropagation();
}

function ajaxifyRankControls(evt) {
  var val = evt.target.getAttribute('value');
  if (val === 'Up' || val === 'Down') {overrideUpDown(evt, val);}
}

function doButtons() {
  // gather rank info button
  var founder = getElementById('show-guild-founder-rank-name');
  if (founder) {
    var weightButton = createInput({
      id: 'getrankweightings',
      className: 'custombutton',
      type: 'button',
      value: 'Get Rank Weightings'
    });
    weightButton.addEventListener('click', fetchRankData);
    var theTd = founder.parentNode;
    insertHtmlBeforeEnd(theTd, ' ');
    insertElement(theTd, weightButton);
  }
  // var theTd = getElementById('show-guild-founder-rank-name') // TODO why wouldn't you be able to see this?
  //   .parentNode;

  if (getValue('ajaxifyRankControls')) {
    pCC.addEventListener('click',
      ajaxifyRankControls, true);
  }
}

function writeMembers(el) {
  var rankCell = el.firstElementChild;
  var rankName = rankCell.textContent;
  if (ranks[rankName]) { // has members
    if (rankName === myRank) {
      characterRow = rankCount; // limit for ajaxify later
    }
    insertHtmlBeforeEnd(rankCell, ' - ' +
      ranks[rankName].join(', ') + '');
  }
}

function paintRanks() {
  var limit = performance.now() + 10;
  while (moreToDo(limit, rankCount, theRows)) {
    var el = theRows[rankCount];

    writeMembers(el);

    rankCount += 1;
  }
  if (rankCount < theRows.length) {
    add(3, paintRanks);
  }
}

function findTheRows() {
  var outerTable = pCC.lastElementChild.previousElementSibling;
  if (outerTable.rows && outerTable.rows.length > 13) {
    return outerTable.rows[13].firstElementChild.firstElementChild.rows;
  }
}

function getRanks(membrList) {
  ranks = Object.keys(membrList).reduce(function(prev, curr) {
    if (curr !== 'lastUpdate') {
      var rankName = membrList[curr].rank_name;
      prev[rankName] = prev[rankName] || [];
      prev[rankName].push(curr);
    }
    return prev;
  }, {});
  myRank = membrList[playerName()].rank_name;
  theRows = findTheRows();
  if (theRows) {
    rankCount = 1;
    add(3, paintRanks);
  }
}

export default function injectGuildRanks() { // jQuery.min
  if (jQueryNotPresent()) {return;}
  getMembrList(true).done(function(membrList) {
    add(3, getRanks, [membrList]);
  });
  add(3, doButtons);
}
<commit_msg>partial fix for rank page<commit_after>import add from './support/task';
import createDocument from './system/createDocument';
import {createInput} from './common/cElement';
import {getElementById} from './common/getElement';
import getMembrList from './ajax/getMembrList';
import getValue from './system/getValue';
import insertElement from './common/insertElement';
import insertHtmlAfterBegin from './common/insertHtmlAfterBegin';
import insertHtmlBeforeEnd from './common/insertHtmlBeforeEnd';
import jQueryNotPresent from './common/jQueryNotPresent';
import moreToDo from './common/moreToDo';
import {pCC} from './support/layout';
import playerName from './common/playerName';
import retryAjax from './ajax/retryAjax';

var ranks;
var myRank;
var theRows;
var rankCount;
var characterRow;

var privLookup = {
  'Bank Withdraw': 5,
  'Build/Upgrade/Demolish Structures': 5,
  'Can Un-Tag Items': 5,
  'Build/Upgrade Structures': 4,
  'Can Kick Members': 4,
  'Can Mass Messages': 0.5,
  'Take Items': 0.2,
  'Can Recall Tagged Items': 0.2,
  'Store Items': 0.1,
  'Can View Advisor': 0.1
};

function parseRankData(linkElement, responseText) {
  // Makes a weighted calculation of available permissions and gets tax rate
  var doc = createDocument(responseText);
  var checkBoxes = doc.querySelectorAll(
    '#pCC input[type="checkbox"]:checked');
  var count = 0;
  Array.prototype.forEach.call(checkBoxes, function(checkbox) {
    var privName = checkbox.nextElementSibling.textContent.trim();
    if (privName in privLookup) {
      count += privLookup[privName];
    } else {count += 1;}
  });
  var taxRate = doc.querySelector('#pCC input[name="rank_tax"]').value;
  insertHtmlAfterBegin(linkElement, '(' +
    Math.round(10 * count) / 10 + ') Tax:(' + taxRate + '%) ');
}

function fetchRankData() { // jQuery.min
  var calcButton = getElementById('getrankweightings');
  calcButton.classList.add('fshHide');
  var allItems = document.querySelectorAll('#pCC input[value="Edit"]');
  Array.prototype.forEach.call(allItems, function(anItem) {
    var targetNode = anItem.parentNode.parentNode.previousElementSibling;
    var href = /window\.location='(.*)';/.exec(anItem
      .getAttribute('onclick'))[1];
    retryAjax(href).done(parseRankData.bind(null, targetNode));
  });
}

function notValidRow(thisRankRowNum, targetRowNum, parentTable) {
  return characterRow >= Math.min(thisRankRowNum, targetRowNum) ||
    targetRowNum < 1 ||
    targetRowNum > parentTable.rows.length;
}

function getTargetRowNumber(val) {
  if (val === 'Up') {return -1;}
  return 2;
}

function getPxScroll(val) {
  if (val === 'Up') {return -22;}
  return 22;
}

function overrideUpDown(evt, val) {
  var onclickHREF = /window.location='(.*)';/
    .exec(evt.target.getAttribute('onclick'))[1];
  var thisRankRow = evt.target.parentNode.parentNode.parentNode;
  var thisRankRowNum = thisRankRow.rowIndex;
  var targetRowNum = thisRankRowNum + getTargetRowNumber(val);
  var parentTable = thisRankRow.parentNode;
  if (notValidRow(thisRankRowNum, targetRowNum, parentTable)) {return;}
  retryAjax(onclickHREF);
  var injectRow = parentTable.rows[targetRowNum];
  parentTable.insertBefore(thisRankRow, injectRow);
  var pxScroll = getPxScroll(val);
  window.scrollBy(0, pxScroll);
  evt.stopPropagation();
}

function ajaxifyRankControls(evt) {
  var val = evt.target.getAttribute('value');
  if (val === 'Up' || val === 'Down') {overrideUpDown(evt, val);}
}

function doButtons() {
  // gather rank info button
  var founder = getElementById('show-guild-founder-rank-name');
  if (founder) {
    var weightButton = createInput({
      id: 'getrankweightings',
      className: 'custombutton',
      type: 'button',
      value: 'Get Rank Weightings'
    });
    weightButton.addEventListener('click', fetchRankData);
    var theTd = founder.parentNode;
    insertHtmlBeforeEnd(theTd, ' ');
    insertElement(theTd, weightButton);
  }
  // var theTd = getElementById('show-guild-founder-rank-name') // TODO why wouldn't you be able to see this?
  //   .parentNode;

  if (getValue('ajaxifyRankControls')) {
    pCC.addEventListener('click',
      ajaxifyRankControls, true);
  }
}

function isMyRank(rankName) {
  if (rankName === myRank) {
    characterRow = rankCount; // limit for ajaxify later
  }
}

function hasMembers(rankCell, rankName) {
  if (ranks[rankName]) { // has members
    isMyRank(rankName);
    insertHtmlBeforeEnd(rankCell, ' - ' +
      ranks[rankName].join(', ') + '');
  }
}

function getRankName(rankCell) {
  if (rankCount === 1) {return 'Guild Founder';}
  return rankCell.textContent;
}

function writeMembers(el) {
  var rankCell = el.firstElementChild;
  var rankName = getRankName(rankCell);
  hasMembers(rankCell, rankName);
}

function paintRanks() {
  var limit = performance.now() + 10;
  while (moreToDo(limit, rankCount, theRows)) {
    var el = theRows[rankCount];

    writeMembers(el);

    rankCount += 1;
  }
  if (rankCount < theRows.length) {
    add(3, paintRanks);
  }
}

function findTheRows() {
  var outerTable = pCC.lastElementChild.previousElementSibling;
  if (outerTable.rows && outerTable.rows.length > 7) {
    return outerTable.rows[7].firstElementChild.firstElementChild.rows;
  }
}

function getRanks(membrList) {
  ranks = Object.keys(membrList).reduce(function(prev, curr) {
    if (curr !== 'lastUpdate') {
      var rankName = membrList[curr].rank_name;
      prev[rankName] = prev[rankName] || [];
      prev[rankName].push(curr);
    }
    return prev;
  }, {});
  myRank = membrList[playerName()].rank_name;
  theRows = findTheRows();
  if (theRows) {
    rankCount = 1;
    add(3, paintRanks);
  }
}

export default function injectGuildRanks() { // jQuery.min
  if (jQueryNotPresent()) {return;}
  getMembrList(true).done(function(membrList) {
    add(3, getRanks, [membrList]);
  });
  add(3, doButtons);
}
<|endoftext|>


<commit_before>const config = require('config');
const Slack = require('node-slack');

class SlackNotifier{
	constructor(){
		try{
			this.slack = new Slack(config.get('slack_url'));
		}catch(e){
			console.error('Could not initialize Slack', e);
			this.slack = null;
		}
	}

	notify(item){
		if(!this.slack){
			return;
		}

		return this.slack.send({
			text: item.text,
			attachments: [item],
		}).then(() => {
			console.log('Slack message sent');
		}, (e) => {
			console.error(e);
		});
	}
}

module.exports = SlackNotifier;<commit_msg>set default text<commit_after>const config = require('config');
const Slack = require('node-slack');

class SlackNotifier{
	constructor(){
		try{
			this.slack = new Slack(config.get('slack_url'));
		}catch(e){
			console.error('Could not initialize Slack', e);
			this.slack = null;
		}
	}

	notify(item){
		if(!this.slack){
			return;
		}

		return this.slack.send({
			text: item.text || "Kubernetes Notification:",
			attachments: [item],
		}).then(() => {
			console.log('Slack message sent');
		}, (e) => {
			console.error(e);
		});
	}
}

module.exports = SlackNotifier;
<|endoftext|>


<commit_before>/**
 * @module ol/ImageTile
 */
import Tile from './Tile.js';
import TileState from './TileState.js';
import {createCanvasContext2D} from './dom.js';
import {listenImage} from './Image.js';

class ImageTile extends Tile {
  /**
   * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
   * @param {import("./TileState.js").default} state State.
   * @param {string} src Image source URI.
   * @param {?string} crossOrigin Cross origin.
   * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function.
   * @param {import("./Tile.js").Options} [opt_options] Tile options.
   */
  constructor(
    tileCoord,
    state,
    src,
    crossOrigin,
    tileLoadFunction,
    opt_options
  ) {
    super(tileCoord, state, opt_options);

    /**
     * @private
     * @type {?string}
     */
    this.crossOrigin_ = crossOrigin;

    /**
     * Image URI
     *
     * @private
     * @type {string}
     */
    this.src_ = src;

    this.key = src;

    /**
     * @private
     * @type {HTMLImageElement|HTMLCanvasElement}
     */
    this.image_ = new Image();
    if (crossOrigin !== null) {
      this.image_.crossOrigin = crossOrigin;
    }

    /**
     * @private
     * @type {?function():void}
     */
    this.unlisten_ = null;

    /**
     * @private
     * @type {import("./Tile.js").LoadFunction}
     */
    this.tileLoadFunction_ = tileLoadFunction;
  }

  /**
   * Get the HTML image element for this tile (may be a Canvas, Image, or Video).
   * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
   * @api
   */
  getImage() {
    return this.image_;
  }

  /**
   * Sets an HTML image element for this tile (may be a Canvas or preloaded Image).
   * @param {HTMLCanvasElement|HTMLImageElement} element Element.
   * @api
   */
  setImage(element) {
    // asynchronous to accomodate reprojection listeners
    const tile = this;
    setTimeout(function () {
      tile.image_ = element;
      tile.state = TileState.LOADED;
      tile.unlistenImage_();
      tile.changed();
    }, 0);
  }

  /**
   * Tracks loading or read errors.
   *
   * @private
   */
  handleImageError_() {
    this.state = TileState.ERROR;
    this.unlistenImage_();
    this.image_ = getBlankImage();
    this.changed();
  }

  /**
   * Tracks successful image load.
   *
   * @private
   */
  handleImageLoad_() {
    const image = /** @type {HTMLImageElement} */ (this.image_);
    if (image.naturalWidth && image.naturalHeight) {
      this.state = TileState.LOADED;
    } else {
      this.state = TileState.EMPTY;
    }
    this.unlistenImage_();
    this.changed();
  }

  /**
   * Load not yet loaded URI.
   * @api
   */
  load() {
    if (this.state == TileState.ERROR) {
      this.state = TileState.IDLE;
      this.image_ = new Image();
      if (this.crossOrigin_ !== null) {
        this.image_.crossOrigin = this.crossOrigin_;
      }
    }
    if (this.state == TileState.IDLE) {
      this.state = TileState.LOADING;
      this.changed();
      this.tileLoadFunction_(this, this.src_);
      this.unlisten_ = listenImage(
        this.image_,
        this.handleImageLoad_.bind(this),
        this.handleImageError_.bind(this)
      );
    }
  }

  /**
   * Discards event handlers which listen for load completion or errors.
   *
   * @private
   */
  unlistenImage_() {
    if (this.unlisten_) {
      this.unlisten_();
      this.unlisten_ = null;
    }
  }
}

/**
 * Get a 1-pixel blank image.
 * @return {HTMLCanvasElement} Blank image.
 */
function getBlankImage() {
  const ctx = createCanvasContext2D(1, 1);
  ctx.fillStyle = 'rgba(0,0,0,0)';
  ctx.fillRect(0, 0, 1, 1);
  return ctx.canvas;
}

export default ImageTile;
<commit_msg>Make setImage() synchronous<commit_after>/**
 * @module ol/ImageTile
 */
import Tile from './Tile.js';
import TileState from './TileState.js';
import {createCanvasContext2D} from './dom.js';
import {listenImage} from './Image.js';

class ImageTile extends Tile {
  /**
   * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate.
   * @param {import("./TileState.js").default} state State.
   * @param {string} src Image source URI.
   * @param {?string} crossOrigin Cross origin.
   * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function.
   * @param {import("./Tile.js").Options} [opt_options] Tile options.
   */
  constructor(
    tileCoord,
    state,
    src,
    crossOrigin,
    tileLoadFunction,
    opt_options
  ) {
    super(tileCoord, state, opt_options);

    /**
     * @private
     * @type {?string}
     */
    this.crossOrigin_ = crossOrigin;

    /**
     * Image URI
     *
     * @private
     * @type {string}
     */
    this.src_ = src;

    this.key = src;

    /**
     * @private
     * @type {HTMLImageElement|HTMLCanvasElement}
     */
    this.image_ = new Image();
    if (crossOrigin !== null) {
      this.image_.crossOrigin = crossOrigin;
    }

    /**
     * @private
     * @type {?function():void}
     */
    this.unlisten_ = null;

    /**
     * @private
     * @type {import("./Tile.js").LoadFunction}
     */
    this.tileLoadFunction_ = tileLoadFunction;
  }

  /**
   * Get the HTML image element for this tile (may be a Canvas, Image, or Video).
   * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.
   * @api
   */
  getImage() {
    return this.image_;
  }

  /**
   * Sets an HTML image element for this tile (may be a Canvas or preloaded Image).
   * @param {HTMLCanvasElement|HTMLImageElement} element Element.
   * @api
   */
  setImage(element) {
    this.image_ = element;
    this.state = TileState.LOADED;
    this.unlistenImage_();
    this.changed();
  }

  /**
   * Tracks loading or read errors.
   *
   * @private
   */
  handleImageError_() {
    this.state = TileState.ERROR;
    this.unlistenImage_();
    this.image_ = getBlankImage();
    this.changed();
  }

  /**
   * Tracks successful image load.
   *
   * @private
   */
  handleImageLoad_() {
    const image = /** @type {HTMLImageElement} */ (this.image_);
    if (image.naturalWidth && image.naturalHeight) {
      this.state = TileState.LOADED;
    } else {
      this.state = TileState.EMPTY;
    }
    this.unlistenImage_();
    this.changed();
  }

  /**
   * Load not yet loaded URI.
   * @api
   */
  load() {
    if (this.state == TileState.ERROR) {
      this.state = TileState.IDLE;
      this.image_ = new Image();
      if (this.crossOrigin_ !== null) {
        this.image_.crossOrigin = this.crossOrigin_;
      }
    }
    if (this.state == TileState.IDLE) {
      this.state = TileState.LOADING;
      this.changed();
      this.tileLoadFunction_(this, this.src_);
      this.unlisten_ = listenImage(
        this.image_,
        this.handleImageLoad_.bind(this),
        this.handleImageError_.bind(this)
      );
    }
  }

  /**
   * Discards event handlers which listen for load completion or errors.
   *
   * @private
   */
  unlistenImage_() {
    if (this.unlisten_) {
      this.unlisten_();
      this.unlisten_ = null;
    }
  }
}

/**
 * Get a 1-pixel blank image.
 * @return {HTMLCanvasElement} Blank image.
 */
function getBlankImage() {
  const ctx = createCanvasContext2D(1, 1);
  ctx.fillStyle = 'rgba(0,0,0,0)';
  ctx.fillRect(0, 0, 1, 1);
  return ctx.canvas;
}

export default ImageTile;
<|endoftext|>


<commit_before>goog.provide('ol.RendererHint');
goog.provide('ol.createMap');

goog.require('goog.object');
goog.require('ol.Array');
goog.require('ol.Map');
goog.require('ol.MapProperty');
goog.require('ol.Projection');
goog.require('ol.control.DblClickZoom');
goog.require('ol.control.DragPan');
goog.require('ol.control.DragZoom');
goog.require('ol.control.MouseWheelZoom');
goog.require('ol.dom');
goog.require('ol.dom.Map');
goog.require('ol.webgl');
goog.require('ol.webgl.Map');

/**
 * @define {string} Default projection code.
 */
ol.DEFAULT_PROJECTION_CODE = 'EPSG:3857';

/**
 * @define {boolean} Whether to enable DOM.
 */
ol.ENABLE_DOM = true;

/**
 * @define {boolean} Whether to enable WebGL.
 */
ol.ENABLE_WEBGL = true;

/**
 * @enum {string}
 */
ol.RendererHint = {
  DOM: 'dom',
  WEBGL: 'webgl'
};

/**
 * @type {Array.<ol.RendererHint>}}
 */
ol.DEFAULT_RENDERER_HINT = [
  ol.RendererHint.WEBGL,
  ol.RendererHint.DOM
];

/**
 * @param {!HTMLDivElement} target Target.
 * @param {Object.<string, *>=} opt_values Values.
 * @param {ol.RendererHint|Array.<ol.RendererHint>=} opt_rendererHints
 *     Renderer hints.
 * @return {ol.Map} Map.
 */
ol.createMap = function(target, opt_values, opt_rendererHints) {

  var values = {};
  if (goog.isDef(opt_values)) {
    goog.object.extend(values, opt_values);
  }

  if (!goog.object.containsKey(values, ol.MapProperty.CONTROLS)) {
    var controls = new ol.Array();
    controls.push(new ol.control.DblClickZoom());
    controls.push(new ol.control.DragZoom());
    controls.push(new ol.control.DragPan());
    controls.push(new ol.control.MouseWheelZoom());
    values[ol.MapProperty.CONTROLS] = controls;
  }

  if (!goog.object.containsKey(values, ol.MapProperty.LAYERS)) {
    values[ol.MapProperty.LAYERS] = new ol.Array();
  }

  if (!goog.object.containsKey(values, ol.MapProperty.PROJECTION)) {
    values[ol.MapProperty.PROJECTION] =
        ol.Projection.getFromCode(ol.DEFAULT_PROJECTION_CODE);
  }

  /**
   * @type {Array.<ol.RendererHint>}
   */
  var rendererHints;
  if (goog.isDef(opt_rendererHints)) {
    if (goog.isArray(opt_rendererHints)) {
      rendererHints = opt_rendererHints;
    } else {
      rendererHints = [opt_rendererHints];
    }
  } else {
    rendererHints = ol.DEFAULT_RENDERER_HINT;
  }

  var i, rendererHint;
  for (i = 0; i < rendererHints.length; ++i) {
    rendererHint = rendererHints[i];
    if (rendererHint == ol.RendererHint.DOM) {
      if (ol.ENABLE_DOM && ol.dom.isSupported()) {
        return new ol.dom.Map(target, values);
      }
    } else if (rendererHint == ol.RendererHint.WEBGL) {
      if (ol.ENABLE_WEBGL && ol.webgl.isSupported()) {
        return new ol.webgl.Map(target, values);
      }
    }
  }

  return null;

};
<commit_msg>Set default user projection to EPSG:4326<commit_after>goog.provide('ol.RendererHint');
goog.provide('ol.createMap');

goog.require('goog.object');
goog.require('ol.Array');
goog.require('ol.Map');
goog.require('ol.MapProperty');
goog.require('ol.Projection');
goog.require('ol.control.DblClickZoom');
goog.require('ol.control.DragPan');
goog.require('ol.control.DragZoom');
goog.require('ol.control.MouseWheelZoom');
goog.require('ol.dom');
goog.require('ol.dom.Map');
goog.require('ol.webgl');
goog.require('ol.webgl.Map');

/**
 * @define {string} Default projection code.
 */
ol.DEFAULT_PROJECTION_CODE = 'EPSG:3857';

/**
 * @define {string} Default user projection code.
 */
ol.DEFAULT_USER_PROJECTION_CODE = 'EPSG:4326';

/**
 * @define {boolean} Whether to enable DOM.
 */
ol.ENABLE_DOM = true;

/**
 * @define {boolean} Whether to enable WebGL.
 */
ol.ENABLE_WEBGL = true;

/**
 * @enum {string}
 */
ol.RendererHint = {
  DOM: 'dom',
  WEBGL: 'webgl'
};

/**
 * @type {Array.<ol.RendererHint>}}
 */
ol.DEFAULT_RENDERER_HINT = [
  ol.RendererHint.WEBGL,
  ol.RendererHint.DOM
];

/**
 * @param {!HTMLDivElement} target Target.
 * @param {Object.<string, *>=} opt_values Values.
 * @param {ol.RendererHint|Array.<ol.RendererHint>=} opt_rendererHints
 *     Renderer hints.
 * @return {ol.Map} Map.
 */
ol.createMap = function(target, opt_values, opt_rendererHints) {

  var values = {};
  if (goog.isDef(opt_values)) {
    goog.object.extend(values, opt_values);
  }

  if (!goog.object.containsKey(values, ol.MapProperty.CONTROLS)) {
    var controls = new ol.Array();
    controls.push(new ol.control.DblClickZoom());
    controls.push(new ol.control.DragZoom());
    controls.push(new ol.control.DragPan());
    controls.push(new ol.control.MouseWheelZoom());
    values[ol.MapProperty.CONTROLS] = controls;
  }

  if (!goog.object.containsKey(values, ol.MapProperty.LAYERS)) {
    values[ol.MapProperty.LAYERS] = new ol.Array();
  }

  if (!goog.object.containsKey(values, ol.MapProperty.PROJECTION)) {
    values[ol.MapProperty.PROJECTION] =
        ol.Projection.getFromCode(ol.DEFAULT_PROJECTION_CODE);
  }

  if (!goog.object.containsKey(values, ol.MapProperty.USER_PROJECTION)) {
    values[ol.MapProperty.USER_PROJECTION] =
        ol.Projection.getFromCode(ol.DEFAULT_USER_PROJECTION_CODE);
  }

  /**
   * @type {Array.<ol.RendererHint>}
   */
  var rendererHints;
  if (goog.isDef(opt_rendererHints)) {
    if (goog.isArray(opt_rendererHints)) {
      rendererHints = opt_rendererHints;
    } else {
      rendererHints = [opt_rendererHints];
    }
  } else {
    rendererHints = ol.DEFAULT_RENDERER_HINT;
  }

  var i, rendererHint;
  for (i = 0; i < rendererHints.length; ++i) {
    rendererHint = rendererHints[i];
    if (rendererHint == ol.RendererHint.DOM) {
      if (ol.ENABLE_DOM && ol.dom.isSupported()) {
        return new ol.dom.Map(target, values);
      }
    } else if (rendererHint == ol.RendererHint.WEBGL) {
      if (ol.ENABLE_WEBGL && ol.webgl.isSupported()) {
        return new ol.webgl.Map(target, values);
      }
    }
  }

  return null;

};
<|endoftext|>