<commit_before>"use strict";
/**
 * 读取全局变量
 */
var keywords = require("./keywords");
var ieSpecialWords = Object.assign({
    valueOf: true
}, keywords);
var merge = function (dst, o) {
    for (var k in o) {
        if (o[k] instanceof Array) {
            if (!(dst[k] instanceof Array)) {
                dst[k] = [];
            }
            dst[k] = dst[k].concat(o[k]);
            continue;
        }
        dst[k] = o[k] === true ? true : dst[k] || o[k];
    }
};
var regrep = function (v) {
    return v.replace(/\\[\s\S]|\//g, r => r === "/" ? '\\/' : r);
};

var setUndeclaredType = function (unDeclaredVariables, type) {
    for (var k in unDeclaredVariables) {
        unDeclaredVariables[k] = unDeclaredVariables[k] instanceof Array ? unDeclaredVariables[k] : type;
    }
};

var getUndeclearedOnly = function (a) {
    var { unDeclaredVariables: u } = getVariables(a);
    merge(this, u);
};

var setComputed = function (a) {
    if (a.type === "Identifier") {
        var name = a.name;
        if (name in ieSpecialWords || Variables.computed) {
            a.type = "Literal";
            a.value = name;
            a.raw = JSON.stringify(name);
            delete a.name;
            return true;
        }
    }
    else if (a.type === "Literal") {
        var value = a.value;
        if (value in ieSpecialWords || Variables.computed) return true;
    }
    return false;
}

var getVariables = function (ast) {

    var DeclaredVariables = Object.create(null),
        unDeclaredVariables = Object.create(null);
    var required = [];
    if (ast instanceof Array) {
        ast.forEach(function (a) {
            var { DeclaredVariables: d, unDeclaredVariables: u } = getVariables(a);
            merge(DeclaredVariables, d);
            merge(unDeclaredVariables, u);
        });
    }
    else if (ast instanceof Object) {
        switch (ast.type) {
            case "SequenceExpression":
                ast.expressions.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ArrayExpression":
                ast.elements.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ObjectExpression":
                ast.properties.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ReturnStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.argument);
                break;

            case "VariableDeclaration":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.declarations);
                for (var k in DeclaredVariables) {
                    if (DeclaredVariables[k] === true) {
                        DeclaredVariables[k] = ast.kind;
                    }
                }
                for (var k in unDeclaredVariables) {
                    if (unDeclaredVariables[k] === true) {
                        DeclaredVariables[k] = ast.kind;
                    }
                }
                break;
            case "AssignmentPattern":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.left);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u,
                } = getVariables(ast.right);
                setUndeclaredType(u, 'assign');
                setUndeclaredType(d, 'assign');
                merge(unDeclaredVariables, u);
                merge(DeclaredVariables, d);
                break;
            case "VariableDeclarator":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.id);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.init);
                setUndeclaredType(u, 'initer');
                setUndeclaredType(d, 'initer');
                merge(unDeclaredVariables, u);
                merge(DeclaredVariables, d);
                break;
            case "BlockStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                setUndeclaredType(unDeclaredVariables, 'block');
                for (var k in DeclaredVariables) {
                    if (DeclaredVariables[k] !== "var") {
                        delete DeclaredVariables[k];
                    }
                }
                break;
            case "MemberExpression":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.object);
                if ("Identifier" === ast.property.type || "Literal" === ast.property.type) {
                    //用以兼容IE5-9
                    if (!ast.computed) ast.computed = setComputed(ast.property);

                } else {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast.property);
                    merge(unDeclaredVariables, u);
                    merge(DeclaredVariables, d);
                }
                break;
            case "Property":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.value);
                if (!ast.computed) {
                    //用以兼容IE5-9
                    ast.computed = false;
                    ast.raw = JSON.stringify(ast.value);
                }
                ast.shorthand = false; //让esmangle兼容shorthand
                break;
            case "CatchClause":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.param);
                for (var k in u) {
                    delete unDeclaredVariables[k];
                }
                break;
            case "FunctionDeclaration":
            case "ClassDeclaration":
                DeclaredVariables[ast.id.name] = true;
            case "FunctionExpression":
            case "ArrowFunctionExpression":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.params);
                for (var k in u) {
                    delete unDeclaredVariables[k];
                }
                setUndeclaredType(unDeclaredVariables, 'function');
                ast.id ? DeclaredVariables = {
                    [ast.id.name]: "function"
                } :
                    DeclaredVariables = {};
                break;
            case "Identifier":
                if (!unDeclaredVariables[ast.name]) unDeclaredVariables[ast.name] = true;
                break;
            case "":
            case "LabeledStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
            case "BreakStatement":
            case "ContinueStatement":
                break;
            case "CallExpression":
                if (ast.callee.name === "require") {
                    var argument = ast.arguments[0];
                    if (argument.type === 'Literal') {
                        required.push(argument);
                        merge(unDeclaredVariables, { require: required });
                        break;
                    }
                }

                for (var k in ast) {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast[k]);
                    merge(unDeclaredVariables, u);
                }

                break;

            case "ExpressionStatement":
                //去除测试脚本
                var expression = ast.expression;
                if (expression.type === "CallExpression" && expression.callee.type === "Identifier") {
                    if (expression.callee.name.toLowerCase() === "describe") {
                        for (var k in ast) {
                            delete ast[k];
                        }
                        ast.type = "EmptyStatement";
                        break;
                    }
                }
                var { DeclaredVariables, unDeclaredVariables } = getVariables(expression);
                break;
            case "UnaryExpression":
                if (ast.operator === "typeof" && ast.argument.type === 'Identifier') {
                    break;
                }
            case "Literal":
                if (ast.regex) {
                    ast.regex.pattern = regrep(ast.regex.pattern);
                    ast.value = new RegExp(ast.regex.pattern, ast.regex.flags);
                    ast.raw = String(ast.value);
                    break;
                }
            // break;
            default:
                for (var k in ast) {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast[k]);
                    merge(DeclaredVariables, d);
                    merge(unDeclaredVariables, u);
                }
                break;
        }
    }
    for (var k in DeclaredVariables) {
        allVariables[k] = true;
        delete unDeclaredVariables[k];
    }
    for (var k in unDeclaredVariables) {
        if (k in keywords) {
            delete unDeclaredVariables[k];
        } else {
            allVariables[k] = true;
        }
    }
    return {
        DeclaredVariables,
        unDeclaredVariables
    };
};
var allVariables = Object.create(null);

function Variables(ast) {
    var res = getVariables(ast);
    res.allVariables = allVariables;
    allVariables = Object.create(null);
    return res;
};
module.exports = Variables;<commit_msg>修复一些问题<commit_after>"use strict";
/**
 * 读取全局变量
 */
var keywords = require("./keywords");
var ieSpecialWords = Object.assign({
    valueOf: true
}, keywords);
var merge = function (dst, o) {
    for (var k in o) {
        if (o[k] instanceof Array) {
            if (!(dst[k] instanceof Array)) {
                dst[k] = [];
            }
            dst[k] = dst[k].concat(o[k]);
            continue;
        }
        dst[k] = o[k] === true ? true : dst[k] || o[k];
    }
};
var regrep = function (v) {
    return v.replace(/\\[\s\S]|\//g, r => r === "/" ? '\\/' : r);
};

var setUndeclaredType = function (unDeclaredVariables, type) {
    for (var k in unDeclaredVariables) {
        unDeclaredVariables[k] = unDeclaredVariables[k] instanceof Array ? unDeclaredVariables[k] : type;
    }
};

var getUndeclearedOnly = function (a) {
    var { unDeclaredVariables: u } = getVariables(a);
    merge(this, u);
};

var setComputed = function (a) {
    if (a.type === "Identifier") {
        var name = a.name;
        if (name in ieSpecialWords || Variables.computed) {
            a.type = "Literal";
            a.value = name;
            a.raw = JSON.stringify(name);
            delete a.name;
            return true;
        }
    }
    else if (a.type === "Literal") {
        var value = a.value;
        if (value in ieSpecialWords || Variables.computed) return true;
    }
    return false;
}

var getVariables = function (ast) {

    var DeclaredVariables = Object.create(null),
        unDeclaredVariables = Object.create(null);
    var required = [];
    if (ast instanceof Array) {
        ast.forEach(function (a) {
            var { DeclaredVariables: d, unDeclaredVariables: u } = getVariables(a);
            merge(DeclaredVariables, d);
            merge(unDeclaredVariables, u);
        });
    }
    else if (ast instanceof Object) {
        switch (ast.type) {
            case "SequenceExpression":
                ast.expressions.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ArrayExpression":
                ast.elements.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ObjectExpression":
                ast.properties.forEach(getUndeclearedOnly, unDeclaredVariables);
                break;
            case "ReturnStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.argument);
                break;

            case "VariableDeclaration":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.declarations);
                for (var k in DeclaredVariables) {
                    if (DeclaredVariables[k] === true) {
                        DeclaredVariables[k] = ast.kind;
                    }
                }
                for (var k in unDeclaredVariables) {
                    if (unDeclaredVariables[k] === true) {
                        DeclaredVariables[k] = ast.kind;
                    }
                }
                break;
            case "AssignmentPattern":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.left);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u,
                } = getVariables(ast.right);
                setUndeclaredType(u, 'assign');
                setUndeclaredType(d, 'assign');
                merge(unDeclaredVariables, u);
                merge(DeclaredVariables, d);
                break;
            case "VariableDeclarator":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.id);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.init);
                setUndeclaredType(u, 'initer');
                setUndeclaredType(d, 'initer');
                merge(unDeclaredVariables, u);
                merge(DeclaredVariables, d);
                break;
            case "BlockStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                setUndeclaredType(unDeclaredVariables, 'block');
                for (var k in DeclaredVariables) {
                    if (DeclaredVariables[k] !== "var") {
                        delete DeclaredVariables[k];
                    }
                }
                break;
            case "MemberExpression":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.object);
                if ("Identifier" === ast.property.type || "Literal" === ast.property.type) {
                    //用以兼容IE5-9
                    if (!ast.computed) ast.computed = setComputed(ast.property);

                } else {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast.property);
                    merge(unDeclaredVariables, u);
                    merge(DeclaredVariables, d);
                }
                break;
            case "Property":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.value);
                if (!ast.computed && Variables.computed) {
                    //用以兼容IE5-9
                    ast.computed = setComputed(ast.key);
                }
                ast.shorthand = false; //让esmangle兼容shorthand
                break;
            case "CatchClause":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.param);
                for (var k in u) {
                    delete unDeclaredVariables[k];
                }
                break;
            case "FunctionDeclaration":
            case "ClassDeclaration":
                DeclaredVariables[ast.id.name] = true;
            case "FunctionExpression":
            case "ArrowFunctionExpression":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
                var {
                    DeclaredVariables: d,
                    unDeclaredVariables: u
                } = getVariables(ast.params);
                for (var k in u) {
                    delete unDeclaredVariables[k];
                }
                setUndeclaredType(unDeclaredVariables, 'function');
                ast.id ? DeclaredVariables = {
                    [ast.id.name]: "function"
                } :
                    DeclaredVariables = {};
                break;
            case "Identifier":
                if (!unDeclaredVariables[ast.name]) unDeclaredVariables[ast.name] = true;
                break;
            case "":
            case "LabeledStatement":
                var {
                    DeclaredVariables,
                    unDeclaredVariables
                } = getVariables(ast.body);
            case "BreakStatement":
            case "ContinueStatement":
                break;
            case "CallExpression":
                if (ast.callee.name === "require") {
                    var argument = ast.arguments[0];
                    if (argument.type === 'Literal') {
                        required.push(argument);
                        merge(unDeclaredVariables, { require: required });
                        break;
                    }
                }

                for (var k in ast) {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast[k]);
                    merge(unDeclaredVariables, u);
                }

                break;

            case "ExpressionStatement":
                //去除测试脚本
                var expression = ast.expression;
                if (expression.type === "CallExpression" && expression.callee.type === "Identifier") {
                    if (expression.callee.name.toLowerCase() === "describe") {
                        for (var k in ast) {
                            delete ast[k];
                        }
                        ast.type = "EmptyStatement";
                        break;
                    }
                }
                var { DeclaredVariables, unDeclaredVariables } = getVariables(expression);
                break;
            case "UnaryExpression":
                if (ast.operator === "typeof" && ast.argument.type === 'Identifier') {
                    break;
                }
            case "Literal":
                if (ast.regex) {
                    ast.regex.pattern = regrep(ast.regex.pattern);
                    ast.value = new RegExp(ast.regex.pattern, ast.regex.flags);
                    ast.raw = String(ast.value);
                    break;
                }
            // break;
            default:
                for (var k in ast) {
                    var {
                        DeclaredVariables: d,
                        unDeclaredVariables: u
                    } = getVariables(ast[k]);
                    merge(DeclaredVariables, d);
                    merge(unDeclaredVariables, u);
                }
                break;
        }
    }
    for (var k in DeclaredVariables) {
        allVariables[k] = true;
        delete unDeclaredVariables[k];
    }
    for (var k in unDeclaredVariables) {
        if (k in keywords) {
            delete unDeclaredVariables[k];
        } else {
            allVariables[k] = true;
        }
    }
    return {
        DeclaredVariables,
        unDeclaredVariables
    };
};
var allVariables = Object.create(null);

function Variables(ast) {
    var res = getVariables(ast);
    res.allVariables = allVariables;
    allVariables = Object.create(null);
    return res;
};
module.exports = Variables;<|endoftext|>


<commit_before>var game = new Phaser.Game(680, 480, Phaser.AUTO, '', {preload: preload, create: create, update: update });

/* variables for ball, pad and bricks */
var ball;
var paddle;
var bricks;

/* boolen variable if ball is on the pad */
var ballOnPaddle = true;

/* variables for lives and score */
var lives = 3;
var score = 0;

/* variables for output text */
var scoreText;
var livesText;
var introText;

/* variable for... Something? */
var s;

function preload(){
    game.load.image('background', 'assets/background.jpg');
}

function create(){
    /*
    game.phisics.startSystem(Phaser.Phisics.ARCADE);
    game.phisics.arcade.checkCollision.down = false;
*/
    s = game.add.tileSprite(0, 0, 680, 480, 'background');
/*
    bricks = game.add.group();
    bricks.enableBody = true;
    bricks.phisicsBodyType = Phaser.Phisics.ARCADE;

    var brick;

    for(var y = 0; y < 4; y++){
        for(var x = 0; x < 15; x++){
            brick = bricks.create(120 + (x * 36), 100 + (y * 52), 'brick' + (y + 1) + '.png');
            brick.body.bounce.set(1);
            brick.body.immovable = true;
        }
    }
*/
    paddle = game.add.sprite(game.world.centerX, 400, 'paddle.png');
    paddle.anchor.setTo(0.5, 0.5);
    /*

    game.physics.enable(paddle, Phaser.Phisics.ARCADE);

    paddle.body.collideWorlBounds = true;
    paddle.body.bounce.set(1);
    paddle.body.immovable = true;
*/
    ball = game.add.sprite(game.world.centerX, paddle.y - 16, 'ball.png');
    ball.anchor.set(0.5);
/*
    ball.checkWorldBounds = true;

    game.physics.enable(ball, Phaser.Physics.ARCADE);

    ball.body.collideWorldBounds = true;
    ball.body.bounce.set(1);

    ball.events.onOutOfBounds.add(ballLost, this);

    scoreText = game.add.text(32, 480, 'score: 0', { font: "20px Arial", fill: "#ffffff", align: "left" });
    livesText = game.add.text(680, 480, 'lives: 3', { font: "20px Arial", fill: "#ffffff", align: "left" });
    introText = game.add.text(game.world.centerX, 400, '- click to start -', { font: "40px Arial", fill: "#ffffff", align: "center" });
    game.input.onDown.add(releaseBall, this);

*/
}
function update(){/*
    paddle.body.x = game.input.x;

    if (paddle.x < 24)
    {
        paddle.x = 24;
    }
    else if (paddle.x > game.width - 24)
    {
        paddle.x = game.width - 24;
    }

    if(ballOnPaddle){
        ball.body.x = paddle.x;
    }else{
        game.physics.arcade.collide(ball, paddle, ballHitPaddle, null, this);
        game.physics.arcade.collide(ball, bricks, ballHitBrick, null, this);
    }*/
}

function releaseBall(){
    if(ballOnPaddle){
        ballOnPaddle = false;
        ball.body.velocity.y = -300;
        ball.body.velocity.x = -75;
        introText.visible = false;
    }
}

function ballLost(){
    lives--;
    livesText.text = 'lives: ' + lives;
    if(lives === 0){
        gameOver();
    }else{
        ballOnPaddle = true;
        ball.reset(paddle.body.x + 16, paddle.y - 16);
        }
}

function gameOver(){
    ball.body.velocity.setTo(0,0);

    introText.text = 'Game Over, Neo..';
    introText.visible = true;
}

function ballHitBrick (_ball, _brick) {

    _brick.kill();

    score += 10;

    scoreText.text = 'score: ' + score;

    //  Are they any bricks left?
    if (bricks.countLiving() == 0)
    {
        //  New level starts
        score += 1000;
        scoreText.text = 'score: ' + score;
        introText.text = '- Next Level -';

        //  Let's move the ball back to the paddle
        ballOnPaddle = true;
        ball.body.velocity.set(0);
        ball.x = paddle.x + 16;
        ball.y = paddle.y - 16;
        ball.animations.stop();

        //  And bring the bricks back from the dead :)
        bricks.callAll('revive');
    }

}

function ballHitPaddle (_ball, _paddle) {

    var diff = 0;

    if (_ball.x < _paddle.x)
    {
        //  Ball is on the left-hand side of the paddle
        diff = _paddle.x - _ball.x;
        _ball.body.velocity.x = (-10 * diff);
    }
    else if (_ball.x > _paddle.x)
    {
        //  Ball is on the right-hand side of the paddle
        diff = _ball.x -_paddle.x;
        _ball.body.velocity.x = (10 * diff);
    }
    else
    {
        //  Ball is perfectly in the middle
        //  Add a little random X to stop it bouncing straight up!
        _ball.body.velocity.x = 2 + Math.random() * 8;
    }

}
<commit_msg>fix ball size<commit_after>var game = new Phaser.Game(680, 480, Phaser.AUTO, '', {preload: preload, create: create, update: update });

/* variables for ball, pad and bricks */
var ball;
var paddle;
var bricks;

/* boolen variable if ball is on the pad */
var ballOnPaddle = true;

/* variables for lives and score */
var lives = 3;
var score = 0;

/* variables for output text */
var scoreText;
var livesText;
var introText;

/* variable for... Something? */
var s;

function preload(){
    game.load.image('background', 'assets/background.jpg');
}

function create(){
    /*
    game.phisics.startSystem(Phaser.Phisics.ARCADE);
    game.phisics.arcade.checkCollision.down = false;
*/
    s = game.add.tileSprite(0, 0, 680, 480, 'background');
/*
    bricks = game.add.group();
    bricks.enableBody = true;
    bricks.phisicsBodyType = Phaser.Phisics.ARCADE;

    var brick;

    for(var y = 0; y < 4; y++){
        for(var x = 0; x < 15; x++){
            brick = bricks.create(120 + (x * 36), 100 + (y * 52), 'brick' + (y + 1) + '.png');
            brick.body.bounce.set(1);
            brick.body.immovable = true;
        }
    }
*/
    paddle = game.add.sprite(game.world.centerX, 400, 'paddle.png');
    paddle.anchor.setTo(0.5, 0.5);
    /*

    game.physics.enable(paddle, Phaser.Phisics.ARCADE);

    paddle.body.collideWorlBounds = true;
    paddle.body.bounce.set(1);
    paddle.body.immovable = true;
*/
    ball = game.add.sprite(game.world.centerX, 100, 'ball.png');
    ball.anchor.set(0.5);
/*
paddle.y-16
    ball.checkWorldBounds = true;

    game.physics.enable(ball, Phaser.Physics.ARCADE);

    ball.body.collideWorldBounds = true;
    ball.body.bounce.set(1);

    ball.events.onOutOfBounds.add(ballLost, this);

    scoreText = game.add.text(32, 480, 'score: 0', { font: "20px Arial", fill: "#ffffff", align: "left" });
    livesText = game.add.text(680, 480, 'lives: 3', { font: "20px Arial", fill: "#ffffff", align: "left" });
    introText = game.add.text(game.world.centerX, 400, '- click to start -', { font: "40px Arial", fill: "#ffffff", align: "center" });
    game.input.onDown.add(releaseBall, this);

*/
}
function update(){/*
    paddle.body.x = game.input.x;

    if (paddle.x < 24)
    {
        paddle.x = 24;
    }
    else if (paddle.x > game.width - 24)
    {
        paddle.x = game.width - 24;
    }

    if(ballOnPaddle){
        ball.body.x = paddle.x;
    }else{
        game.physics.arcade.collide(ball, paddle, ballHitPaddle, null, this);
        game.physics.arcade.collide(ball, bricks, ballHitBrick, null, this);
    }*/
}

function releaseBall(){
    if(ballOnPaddle){
        ballOnPaddle = false;
        ball.body.velocity.y = -300;
        ball.body.velocity.x = -75;
        introText.visible = false;
    }
}

function ballLost(){
    lives--;
    livesText.text = 'lives: ' + lives;
    if(lives === 0){
        gameOver();
    }else{
        ballOnPaddle = true;
        ball.reset(paddle.body.x + 16, paddle.y - 16);
        }
}

function gameOver(){
    ball.body.velocity.setTo(0,0);

    introText.text = 'Game Over, Neo..';
    introText.visible = true;
}

function ballHitBrick (_ball, _brick) {

    _brick.kill();

    score += 10;

    scoreText.text = 'score: ' + score;

    //  Are they any bricks left?
    if (bricks.countLiving() == 0)
    {
        //  New level starts
        score += 1000;
        scoreText.text = 'score: ' + score;
        introText.text = '- Next Level -';

        //  Let's move the ball back to the paddle
        ballOnPaddle = true;
        ball.body.velocity.set(0);
        ball.x = paddle.x + 16;
        ball.y = paddle.y - 16;
        ball.animations.stop();

        //  And bring the bricks back from the dead :)
        bricks.callAll('revive');
    }

}

function ballHitPaddle (_ball, _paddle) {

    var diff = 0;

    if (_ball.x < _paddle.x)
    {
        //  Ball is on the left-hand side of the paddle
        diff = _paddle.x - _ball.x;
        _ball.body.velocity.x = (-10 * diff);
    }
    else if (_ball.x > _paddle.x)
    {
        //  Ball is on the right-hand side of the paddle
        diff = _ball.x -_paddle.x;
        _ball.body.velocity.x = (10 * diff);
    }
    else
    {
        //  Ball is perfectly in the middle
        //  Add a little random X to stop it bouncing straight up!
        _ball.body.velocity.x = 2 + Math.random() * 8;
    }

}
<|endoftext|>


<commit_before>var _ = require('lodash');

exports.definition = function(modelName) {
	var Model = sails.models[modelName];
	var actions = {

		// Fetch a single model from testtable
		findOne: function(req, res) {
			// No id specified
			if(!req.param('id')) return res.send('No id specified!', 404);

			Model.findOne(req.param('id')).done(function(err, model) {

				// An error occurred
				if(err) return res.send(err, 500);

				// Model not found
				if(!model) return res.send(404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {

					// Subscribe to the models that were returned
					Model.subscribe(req, model);
				}

				// If a view exists, and this isn't an JSONy request,
				// pass down model as "model"
				if (res.viewExists && !(req.isAjax || req.isSocket || req.isJson)) return res.view({
					model: model.toJSON()
				});

				// Otherwise serve a JSON API
				return res.json(model.toJSON());
			});
		},

		// Fetch paginated list of models from testtable
		find: function(req, res) {

			var where = req.param('where');

			// If WHERE is a string, try to interpret it as JSON
			if (_.isString(where)) {
				where = sails.parseJSON(where);
			}

			// If WHERE has not been specified, but other params ARE specified build the WHERE option using them
			var params;
			if (!where) {
				params = _.extend(req.query || {}, req.params || {}, req.body || {});

				// Remove undefined params
				// (as well as limit, skip, and sort)
				// to build a proper where query
				params = sails.util.objReject(params, function (param, key) {
					return _.isUndefined(param) ||
						key === 'limit' || key === 'skip' || key === 'sort';
				});

				where = params;
			}

			// Build options object
			var options = {
				limit: req.param('limit') || undefined,
				skip: req.param('skip') || req.param('offset') || undefined,
				sort: req.param('sort') || req.param('order') || undefined,
				where: where || undefined
			};

			// Respond to queries
			var finding = Model.find(options);

			finding.done(function afterFound(err, models) {

				// An error occurred
				if(err) return res.send(err, 500);

				// No models found
				if(!models) return res.send(404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {

					// Subscribe to the models that were returned
					Model.subscribe(req, models);
				}

				// Build set of model values
				var modelValues = [];

				models.forEach(function(model) {
					modelValues.push(model.toJSON());
				});

				// If a view exists, and this isn't an JSONy request,
				// render it and pass down models as "models"
				var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);
				if (showView) return res.view({
					models: modelValues
				});

				// Otherwise serve a JSON API
				return res.json(modelValues);
			});
		},

		// Store a new model
		create: function(req, res) {

			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});
			params = applyFilter(req.param("sails_filter") || req.param('param_filter'),params, Model);

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			Model.create(params, function(err, model) {
				if(err) return res.send(err, 500);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {
					Model.publishCreate(model.toJSON());
				}

				// If redirect was provided, use it
				if (!handleRedirect(req,res)) {

					// Otherwise return JSON
					return res.json(model.toJSON());
				}
			});
		},

		// Edit an existing model
		update: function(req, res) {
			var id = req.param('id');
			if(!id) return res.send('No id specified!');

			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});

			// Ignore id in params
			delete params['id'];

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			// Otherwise find and update the model in question
			Model.update(id, params, function(err, model) {
				if(err) return res.send(err, 500);
				if(!model) return res.send('Model cannot be found.', 404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {
					Model.publishUpdate(id, model.toJSON());
				}

				// If redirect was provided, use it
				if (!handleRedirect(req,res)) {

					// Otherwise return JSON
					return res.json(model.toJSON());
				}
			});
		},

		// Destroy a model
		destroy: function(req, res) {
			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});

			var id = req.param('id');
			if(!id) return res.send("No id provided.",404);

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			// Otherwise, find and destroy the model in question
			Model.findOne(id).done(function(err, result) {
				if(err) return res.send(err, 500);
				if(!result) return res.send(404);

				Model.destroy(id, function(err) {
					if(err) return res.send(err, 500);

					// If the model is silent, don't use the built-in pubsub
					if (!Model.silent) {
						Model.publishDestroy(result);
					}

					// Respond with model which was destroyed

					// If redirect was provided, use it
					if (!handleRedirect(req,res)) {

						// Otherwise return JSON
						return res.json(result);
					}
				});
			});
		}
	};

	return actions;
};

// Take care of a redirect, if it was provided
// Returns false if no redirect was provided
function handleRedirect(req,res) {
	// If redirect provided, use it
	if (req.param('redirect')) {

		// TODO: sanitize redirect
		res.redirect(req.param('redirect'));

		return true;
	}
	else return false;
}

// Attempt to parse JSON
// If the parse fails, return the error object
// If JSON is falsey, return null
// (this is so that it will be ignored if not specified)
sails.parseJSON = function (json) {
	if (!_.isString(json)) return null;
	try {
		return JSON.parse(json);
	}
	catch (e) {
		return e;
	}
};

<commit_msg>Got rid of the last applyFilter<commit_after>var _ = require('lodash');

exports.definition = function(modelName) {
	var Model = sails.models[modelName];
	var actions = {

		// Fetch a single model from testtable
		findOne: function(req, res) {
			// No id specified
			if(!req.param('id')) return res.send('No id specified!', 404);

			Model.findOne(req.param('id')).done(function(err, model) {

				// An error occurred
				if(err) return res.send(err, 500);

				// Model not found
				if(!model) return res.send(404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {

					// Subscribe to the models that were returned
					Model.subscribe(req, model);
				}

				// If a view exists, and this isn't an JSONy request,
				// pass down model as "model"
				if (res.viewExists && !(req.isAjax || req.isSocket || req.isJson)) return res.view({
					model: model.toJSON()
				});

				// Otherwise serve a JSON API
				return res.json(model.toJSON());
			});
		},

		// Fetch paginated list of models from testtable
		find: function(req, res) {

			var where = req.param('where');

			// If WHERE is a string, try to interpret it as JSON
			if (_.isString(where)) {
				where = sails.parseJSON(where);
			}

			// If WHERE has not been specified, but other params ARE specified build the WHERE option using them
			var params;
			if (!where) {
				params = _.extend(req.query || {}, req.params || {}, req.body || {});

				// Remove undefined params
				// (as well as limit, skip, and sort)
				// to build a proper where query
				params = sails.util.objReject(params, function (param, key) {
					return _.isUndefined(param) ||
						key === 'limit' || key === 'skip' || key === 'sort';
				});

				where = params;
			}

			// Build options object
			var options = {
				limit: req.param('limit') || undefined,
				skip: req.param('skip') || req.param('offset') || undefined,
				sort: req.param('sort') || req.param('order') || undefined,
				where: where || undefined
			};

			// Respond to queries
			var finding = Model.find(options);

			finding.done(function afterFound(err, models) {

				// An error occurred
				if(err) return res.send(err, 500);

				// No models found
				if(!models) return res.send(404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {

					// Subscribe to the models that were returned
					Model.subscribe(req, models);
				}

				// Build set of model values
				var modelValues = [];

				models.forEach(function(model) {
					modelValues.push(model.toJSON());
				});

				// If a view exists, and this isn't an JSONy request,
				// render it and pass down models as "models"
				var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);
				if (showView) return res.view({
					models: modelValues
				});

				// Otherwise serve a JSON API
				return res.json(modelValues);
			});
		},

		// Store a new model
		create: function(req, res) {

			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			Model.create(params, function(err, model) {
				if(err) return res.send(err, 500);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {
					Model.publishCreate(model.toJSON());
				}

				// If redirect was provided, use it
				if (!handleRedirect(req,res)) {

					// Otherwise return JSON
					return res.json(model.toJSON());
				}
			});
		},

		// Edit an existing model
		update: function(req, res) {
			var id = req.param('id');
			if(!id) return res.send('No id specified!');

			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});

			// Ignore id in params
			delete params['id'];

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			// Otherwise find and update the model in question
			Model.update(id, params, function(err, model) {
				if(err) return res.send(err, 500);
				if(!model) return res.send('Model cannot be found.', 404);

				// If the model is silent, don't use the built-in pubsub
				if (!Model.silent) {
					Model.publishUpdate(id, model.toJSON());
				}

				// If redirect was provided, use it
				if (!handleRedirect(req,res)) {

					// Otherwise return JSON
					return res.json(model.toJSON());
				}
			});
		},

		// Destroy a model
		destroy: function(req, res) {
			// Create monolithic parameter object
			var params = _.extend(req.query || {}, req.params || {}, req.body || {});

			var id = req.param('id');
			if(!id) return res.send("No id provided.",404);

			// If a view exists, and this isn't an JSONy request,
			// render and pass down model as "model"
			var showView = res.viewExists && !(req.isAjax || req.isSocket || req.isJson);

			// If this is a GET, and showing the view is appropriate, just serve the view
			if (req.method === 'GET' && showView) {
				return res.view();
			}

			// Otherwise, find and destroy the model in question
			Model.findOne(id).done(function(err, result) {
				if(err) return res.send(err, 500);
				if(!result) return res.send(404);

				Model.destroy(id, function(err) {
					if(err) return res.send(err, 500);

					// If the model is silent, don't use the built-in pubsub
					if (!Model.silent) {
						Model.publishDestroy(result);
					}

					// Respond with model which was destroyed

					// If redirect was provided, use it
					if (!handleRedirect(req,res)) {

						// Otherwise return JSON
						return res.json(result);
					}
				});
			});
		}
	};

	return actions;
};

// Take care of a redirect, if it was provided
// Returns false if no redirect was provided
function handleRedirect(req,res) {
	// If redirect provided, use it
	if (req.param('redirect')) {

		// TODO: sanitize redirect
		res.redirect(req.param('redirect'));

		return true;
	}
	else return false;
}

// Attempt to parse JSON
// If the parse fails, return the error object
// If JSON is falsey, return null
// (this is so that it will be ignored if not specified)
sails.parseJSON = function (json) {
	if (!_.isString(json)) return null;
	try {
		return JSON.parse(json);
	}
	catch (e) {
		return e;
	}
};

<|endoftext|>


<commit_before>chorus.alerts.PublishInsight = chorus.alerts.Base.extend({
    constructorName: "PublishInsight",

    setup: function(options){
        this.publish = options.publish;
        this.text = this.publish ? t("insight.publish.alert.body") : t("insight.unpublish.alert.body");
        this.title = this.publish ? t("insight.publish.alert.title") : t("insight.unpublish.alert.title");
        this.ok = this.publish ? t("insight.publish.alert.button") : t("insight.unpublish.alert.button");
    },

    confirmAlert:function () {
        this.publish ? this.model.publish() : this.model.unpublish();
        $(document).trigger("close.facebox");
    }
});
<commit_msg>[#38104389] Not showing the body of insight ( as 2.1 )<commit_after>chorus.alerts.PublishInsight = chorus.alerts.Base.extend({
    constructorName: "PublishInsight",

    setup: function(options){
        this.publish = options.publish;
        this.text = this.publish ? t("insight.publish.alert.body") : t("insight.unpublish.alert.body");
        this.title = this.publish ? t("insight.publish.alert.title") : t("insight.unpublish.alert.title");
        this.ok = this.publish ? t("insight.publish.alert.button") : t("insight.unpublish.alert.button");
        this.body = "";
    },

    confirmAlert:function () {
        this.publish ? this.model.publish() : this.model.unpublish();
        $(document).trigger("close.facebox");
    }
});
<|endoftext|>


<commit_before>var React = require('react');
require('bootstrap/js/collapse');
var _ = require('lodash');
var jsonMarkup = require('json-markup');
var moment = require('moment');

var FeedComponent = React.createClass({

    _formatTimestamp: function(timestamp) {
        var momentTimestamp = moment(timestamp);

        return {
            date: momentTimestamp.format('MM-DD-YYYY'),
            time: momentTimestamp.format('HH:mm:ss:SSS')
        };
    },

    render: function() {
        return (

Path

Method

Status

Data

Timestamp

                  { this.props.requests.map(this._requestGroup) }

        );
    },

    _toggleServerLogData: function(e) {
        $(e.currentTarget).find('.json-markup').toggleClass('expanded');
    },

    _toggle: function(e) {
        var $requestRow = $(e.currentTarget);

        var $current = $requestRow.next();
        var serverLogRows = [];
        do {
            serverLogRows.push($current);
            $current = $current.next();
        } while ($current.hasClass('server-log'))

            var hide = !serverLogRows[0].hasClass('hidden');

            if(hide) {
                $requestRow.removeClass('active');
                _.each(serverLogRows, function($row) { $row.addClass('hidden'); });
            } else {
                $requestRow.addClass('active');
                _.each(serverLogRows, function($row) { $row.removeClass('hidden'); });
            }
    },

    _requestGroup: function(request, index) {
        var stripe = index % 2 === 0 ? 'dark' : 'light';

        var requestRowMarkup = this._requestRow(request, stripe);
        var serverLogRowsMarkup = request.serverLogs.map(function(serverLog) {
            return this._serverLogRow(serverLog, stripe);
        }.bind(this));

        return _.flatten([requestRowMarkup, serverLogRowsMarkup], true);
    },

    _requestRow: function(request, stripe) {
        rowClasses = ['request', stripe, 'row'];
        var statusCodeContent = request.statusCode !== undefined ? request.statusCode :

;

        if(this._requestHasErrors(request)) {
            rowClasses.push('error');
        } else if(this._requestHasWarnings(request)) {
            rowClasses.push('warning');
        }

        var formattedTimestamp = this._formatTimestamp(request.timestamp);

        return (

{request.path}

{request.method}

{statusCodeContent}

{JSON.stringify(request.data)}

                    {formattedTimestamp.time}
                    {formattedTimestamp.date}

        );
    },

    _requestHasErrors: function(request) {
        return request.responseTimeout || request.statusCode >= 500;
    },

    _requestHasWarnings: function(request) {
        return request.statusCode >= 400 && request.statusCode < 500;
    },

    _serverLogRow: function(serverLog, stripe) {
        var formattedTimestamp = this._formatTimestamp(serverLog.timestamp);
        var serverLogClasses = ['server-log', 'hidden', 'row', stripe].join(' ');

        return (

{serverLog.tags.join(', ')}

                    {formattedTimestamp.time}
                    {formattedTimestamp.date}

        );
    }

});

module.exports = FeedComponent;
<commit_msg>Extend tags column across method and status.<commit_after>var React = require('react');
require('bootstrap/js/collapse');
var _ = require('lodash');
var jsonMarkup = require('json-markup');
var moment = require('moment');

var FeedComponent = React.createClass({

    _formatTimestamp: function(timestamp) {
        var momentTimestamp = moment(timestamp);

        return {
            date: momentTimestamp.format('MM-DD-YYYY'),
            time: momentTimestamp.format('HH:mm:ss:SSS')
        };
    },

    render: function() {
        return (

Path

Method

Status

Data

Timestamp

                  { this.props.requests.map(this._requestGroup) }

        );
    },

    _toggleServerLogData: function(e) {
        $(e.currentTarget).find('.json-markup').toggleClass('expanded');
    },

    _toggle: function(e) {
        var $requestRow = $(e.currentTarget);

        var $current = $requestRow.next();
        var serverLogRows = [];
        do {
            serverLogRows.push($current);
            $current = $current.next();
        } while ($current.hasClass('server-log'))

            var hide = !serverLogRows[0].hasClass('hidden');

            if(hide) {
                $requestRow.removeClass('active');
                _.each(serverLogRows, function($row) { $row.addClass('hidden'); });
            } else {
                $requestRow.addClass('active');
                _.each(serverLogRows, function($row) { $row.removeClass('hidden'); });
            }
    },

    _requestGroup: function(request, index) {
        var stripe = index % 2 === 0 ? 'dark' : 'light';

        var requestRowMarkup = this._requestRow(request, stripe);
        var serverLogRowsMarkup = request.serverLogs.map(function(serverLog) {
            return this._serverLogRow(serverLog, stripe);
        }.bind(this));

        return _.flatten([requestRowMarkup, serverLogRowsMarkup], true);
    },

    _requestRow: function(request, stripe) {
        rowClasses = ['request', stripe, 'row'];
        var statusCodeContent = request.statusCode !== undefined ? request.statusCode :

;

        if(this._requestHasErrors(request)) {
            rowClasses.push('error');
        } else if(this._requestHasWarnings(request)) {
            rowClasses.push('warning');
        }

        var formattedTimestamp = this._formatTimestamp(request.timestamp);

        return (

{request.path}

{request.method}

{statusCodeContent}

{JSON.stringify(request.data)}

                    {formattedTimestamp.time}
                    {formattedTimestamp.date}

        );
    },

    _requestHasErrors: function(request) {
        return request.responseTimeout || request.statusCode >= 500;
    },

    _requestHasWarnings: function(request) {
        return request.statusCode >= 400 && request.statusCode < 500;
    },

    _serverLogRow: function(serverLog, stripe) {
        var formattedTimestamp = this._formatTimestamp(serverLog.timestamp);
        var serverLogClasses = ['server-log', 'hidden', 'row', stripe].join(' ');

        return (

{serverLog.tags.join(', ')}

                    {formattedTimestamp.time}
                    {formattedTimestamp.date}

        );
    }

});

module.exports = FeedComponent;
<|endoftext|>


<commit_before>var entityHPToolTipIds = [];
var selectedToolTipIds = {};
var entityAllDataToolTipIds = [];
var hoveredAllDataToolTipIds = {};

function createToolTips(shapeInfo) {
    createHPToolTip(shapeInfo);
    createAllDataToolTip(shapeInfo);
}

function removeFullShapeIdFromTrackingLists(fullShapeId){
    removeMemoryOfToolTip(selectedToolTipIds, entityHPToolTipIds, fullShapeId);
    removeMemoryOfToolTip(hoveredAllDataToolTipIds, entityAllDataToolTipIds, fullShapeId);
  }

  function removeMemoryOfToolTip(someDict, someArray, someId) {
    var index = someArray.indexOf(someId);
    if (index !== -1) {
      someArray.splice(index, 1);
      delete someDict[someId];
    }
  }

  function cleanToolTips(){
      for (var i in entityHPToolTipIds){
          var id = entityHPToolTipIds[i];
          $("#"+id).remove();
    }
    entityHPToolTipIds = [];
    for (var i in entityAllDataToolTipIds){
          var id = entityAllDataToolTipIds[i];
          $("#"+id).remove();
      }
      entityAllDataToolTipIds = [];
  }

function createHPToolTip(shapeInfo) {
    var si = shapeInfo;
    var z_index = si.entityIndex + 2;
    if (undefined != si.percentHPRemaining) {
        var canvas_bounds = gameboard_canvas.getBoundingClientRect();
        var hpDiv = document.createElement("div");
        var setToShow = selectedToolTipIds[si.shapeId];
        if (setToShow == undefined || setToShow == "hide"){
          hpDiv.setAttribute("class","tooltip-invisible");
        }

        var id = "metadata_hp" + si.shapeId;
        hpDiv.setAttribute("id",id);
         // position it relative to where origin of bounding box of gameboard is
        var y = si.tooltipY + canvas_bounds.top;
        var x = si.tooltipX + canvas_bounds.left;
        var hpWidgetWidth = 20;
        var hpWidgetHeight = 3;
        hpDiv.setAttribute("class", "flex-row");
        hpDiv.setAttribute("style", 'background-color:black;zIndex:' + z_index + ';position:absolute;left:' + x + 'px;top:' + y + 'px;color:' + si.colorRGBA + ';height:' + hpWidgetHeight + 'px;width:' + hpWidgetWidth + 'px');
        $("#scaii-gameboard").append(hpDiv);

        var hpRemainingDivWidth = hpWidgetWidth * si.percentHPRemaining;
        var hpLostDivWidth = hpWidgetWidth - hpRemainingDivWidth;

        var remainingHpDiv = document.createElement("div");
        remainingHpDiv.setAttribute("style", 'background-color:white;height:' + hpWidgetHeight + 'px;width:' + hpRemainingDivWidth + 'px');
        hpDiv.append(remainingHpDiv);

        entityHPToolTipIds.push(id);
      }
}

function createAllDataToolTip(shapeInfo) {
    var si = shapeInfo;
    var z_index = si.entityIndex + 2000;
    var canvas_bounds = gameboard_canvas.getBoundingClientRect();
    var valuesDiv = document.createElement("div");
    var setToShow = hoveredAllDataToolTipIds[si.shapeId];
    if (setToShow == undefined || setToShow == "hide"){
      valuesDiv.setAttribute("class","tooltip-invisible");
    }
    var id = "metadata_all" + si.shapeId;
    hoveredAllDataToolTipIds[id] = "hide";
    valuesDiv.setAttribute("id",id);
     // position it relative to where origin of bounding box of gameboard is
    var y = si.y + canvas_bounds.top + 20;
    var x = si.y + canvas_bounds.left + -125;
    valuesDiv.setAttribute("style", 'padding:4px;background-color:black;zIndex:' + z_index + ';position:absolute;left:' + x + 'px;top:' + y + 'px;color:white;	display: flex;flex-direction: column;font-family:Arial');
    $("#scaii-gameboard").append(valuesDiv);
    entityAllDataToolTipIds.push(id);

    var hpLabel = document.createElement("div");
    var hitPoints = getNumericValueFromFloatStringMap(si.entity,"Hitpoints");
    hpLabel.innerHTML = 'HP   : ' + hitPoints;
    valuesDiv.append(hpLabel);

    var mhpLabel = document.createElement("div");
    var maxHitPoints = getNumericValueFromFloatStringMap(si.entity,"Max Hp");
    mhpLabel.innerHTML = 'Max HP: ' + maxHitPoints;
    valuesDiv.append(mhpLabel);

    var enemyLabel = document.createElement("div");
    var isEnemy = getIsEnemy(si.entity);
    enemyLabel.innerHTML = 'Enemy: ' + isEnemy;
    valuesDiv.append(enemyLabel);

    var friendLabel = document.createElement("div");
    var isFriend = getIsFriend(si.entity);
    friendLabel.innerHTML = 'Friend: ' + isFriend;
    valuesDiv.append(friendLabel);

    var unitTypeLabel = document.createElement("div");
    var type = getUnitType(si.entity);
    unitTypeLabel.innerHTML = 'Unit Type: ' + type;
    valuesDiv.append(unitTypeLabel);
}
<commit_msg>unfold all maps into tooltip<commit_after>var entityHPToolTipIds = [];
var selectedToolTipIds = {};
var entityAllDataToolTipIds = [];
var hoveredAllDataToolTipIds = {};

function createToolTips(shapeInfo) {
    createHPToolTip(shapeInfo);
    createAllDataToolTip(shapeInfo);
}

function removeFullShapeIdFromTrackingLists(fullShapeId){
    removeMemoryOfToolTip(selectedToolTipIds, entityHPToolTipIds, fullShapeId);
    removeMemoryOfToolTip(hoveredAllDataToolTipIds, entityAllDataToolTipIds, fullShapeId);
  }

  function removeMemoryOfToolTip(someDict, someArray, someId) {
    var index = someArray.indexOf(someId);
    if (index !== -1) {
      someArray.splice(index, 1);
      delete someDict[someId];
    }
  }

  function cleanToolTips(){
      for (var i in entityHPToolTipIds){
          var id = entityHPToolTipIds[i];
          $("#"+id).remove();
    }
    entityHPToolTipIds = [];
    for (var i in entityAllDataToolTipIds){
          var id = entityAllDataToolTipIds[i];
          $("#"+id).remove();
      }
      entityAllDataToolTipIds = [];
  }

function createHPToolTip(shapeInfo) {
    var si = shapeInfo;
    var z_index = si.entityIndex + 2;
    if (undefined != si.percentHPRemaining) {
        var canvas_bounds = gameboard_canvas.getBoundingClientRect();
        var hpDiv = document.createElement("div");
        var setToShow = selectedToolTipIds[si.shapeId];
        if (setToShow == undefined || setToShow == "hide"){
          hpDiv.setAttribute("class","tooltip-invisible");
        }

        var id = "metadata_hp" + si.shapeId;
        hpDiv.setAttribute("id",id);
         // position it relative to where origin of bounding box of gameboard is
        var y = si.tooltipY + canvas_bounds.top;
        var x = si.tooltipX + canvas_bounds.left;
        var hpWidgetWidth = 20;
        var hpWidgetHeight = 3;
        hpDiv.setAttribute("class", "flex-row");
        hpDiv.setAttribute("style", 'background-color:black;zIndex:' + z_index + ';position:absolute;left:' + x + 'px;top:' + y + 'px;color:' + si.colorRGBA + ';height:' + hpWidgetHeight + 'px;width:' + hpWidgetWidth + 'px');
        $("#scaii-gameboard").append(hpDiv);

        var hpRemainingDivWidth = hpWidgetWidth * si.percentHPRemaining;
        var hpLostDivWidth = hpWidgetWidth - hpRemainingDivWidth;

        var remainingHpDiv = document.createElement("div");
        remainingHpDiv.setAttribute("style", 'background-color:white;height:' + hpWidgetHeight + 'px;width:' + hpRemainingDivWidth + 'px');
        hpDiv.append(remainingHpDiv);

        entityHPToolTipIds.push(id);
      }
}

function createAllDataToolTip(shapeInfo) {
    var si = shapeInfo;
    var z_index = si.entityIndex + 2000;
    var canvas_bounds = gameboard_canvas.getBoundingClientRect();
    var valuesDiv = document.createElement("div");
    var setToShow = hoveredAllDataToolTipIds[si.shapeId];
    if (setToShow == undefined || setToShow == "hide"){
      valuesDiv.setAttribute("class","tooltip-invisible");
    }
    var id = "metadata_all" + si.shapeId;
    hoveredAllDataToolTipIds[id] = "hide";
    valuesDiv.setAttribute("id",id);
     // position it relative to where origin of bounding box of gameboard is
    var y = si.y + canvas_bounds.top + 20;
    var x = si.y + canvas_bounds.left + -125;
    valuesDiv.setAttribute("style", 'padding:4px;background-color:black;zIndex:' + z_index + ';position:absolute;left:' + x + 'px;top:' + y + 'px;color:white;	display: flex;flex-direction: column;font-family:Arial');
    $("#scaii-gameboard").append(valuesDiv);
    entityAllDataToolTipIds.push(id);

    unfoldMapIntoTooltip(si.entity.stringmetadataMap, valuesDiv, false);
    unfoldMapIntoTooltip(si.entity.boolstringmetadataMap, valuesDiv, false);
    unfoldMapIntoTooltip(si.entity.floatstringmetadataMap, valuesDiv, true);
    unfoldMapIntoTooltip(si.entity.intmetadataMap, valuesDiv, false);
    unfoldMapIntoTooltip(si.entity.boolmetadataMap, valuesDiv,false);
    unfoldMapIntoTooltip(si.entity.floatmetadataMap, valuesDiv, true);

    // var hpLabel = document.createElement("div");
    // var hitPoints = getNumericValueFromFloatStringMap(si.entity,"Hitpoints");
    // hpLabel.innerHTML = 'HP   : ' + hitPoints;
    // valuesDiv.append(hpLabel);

    // var mhpLabel = document.createElement("div");
    // var maxHitPoints = getNumericValueFromFloatStringMap(si.entity,"Max Hp");
    // mhpLabel.innerHTML = 'Max HP: ' + maxHitPoints;
    // valuesDiv.append(mhpLabel);

    // var enemyLabel = document.createElement("div");
    // var isEnemy = getIsEnemy(si.entity);
    // enemyLabel.innerHTML = 'Enemy: ' + isEnemy;
    // valuesDiv.append(enemyLabel);

    // var friendLabel = document.createElement("div");
    // var isFriend = getIsFriend(si.entity);
    // friendLabel.innerHTML = 'Friend: ' + isFriend;
    // valuesDiv.append(friendLabel);

    // var unitTypeLabel = document.createElement("div");
    // var type = getUnitType(si.entity);
    // unitTypeLabel.innerHTML = 'Unit Type: ' + type;
    // valuesDiv.append(unitTypeLabel);
}

function unfoldMapIntoTooltip(map, div, limitToTwoDecimals) {
    var entryList = map.getEntryList();
    for (var i in entryList ){
        var entry = entryList[i];
        var key = entry[0];
        var val = entry[1];
        var label = document.createElement("div");
        if (limitToTwoDecimals) {
            label.innerHTML = key + ':' + (Number(val)).toFixed(2);
        }
        else {
            label.innerHTML = key + ':' + val;
        }

        div.append(label);
    }
}<|endoftext|>


<commit_before>// Copyright 2012 Software Freedom Conservancy. 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.

/**
 * @fileoverview Definitions for various command handlers used by the
 * {@link safaridriver.extension.Server}.
 */

goog.provide('safaridriver.extension.commands');

goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.string');
goog.require('safaridriver.extension.Tab');
goog.require('webdriver.error');
goog.require('webdriver.promise');

/**
 * @type {!goog.debug.Logger}
 * @private
 * @const
 */
safaridriver.extension.commands.LOG_ = goog.debug.Logger.getLogger(
    'safaridriver.extension.commands');

/**
 * Retrieves a session's capabilities.
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!Object.<*>} The session capabilities.
 */
safaridriver.extension.commands.describeSession = function(session) {
  return session.getCapabilities();
};

/**
 * Closes the tab the given session is currently focused on.
 * @param {!safaridriver.extension.Session} session The session object.
 */
safaridriver.extension.commands.closeTab = function(session) {
  session.getCommandTab().getBrowserTab().close();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {string} The handle for the tab the session is currently focused on.
 */
safaridriver.extension.commands.getWindowHandle = function(session) {
  return session.getCommandTab().getId();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!Array.<string>} A list of IDs for the open tabs.
 */
safaridriver.extension.commands.getWindowHandles = function(session) {
  return session.getTabIds();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!webdriver.promise.Promise} A promise that will resolve to the
 *     current tab's URL.
 */
safaridriver.extension.commands.getCurrentUrl = function(session) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    response.resolve(tab.url);
  });
  return response.promise;
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!webdriver.promise.Promise} A promise that will resolve to the
 *     current tab's title.
 */
safaridriver.extension.commands.getTitle = function(session) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    response.resolve(tab.title);
  });
  return response.promise;
};

/**
 * Loads a new page in the provided session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.loadUrl = function(session, command) {
  var url = command.getParameter('url');
  if (!url) {
    throw Error('Invalid command: missing "url" parameter');
  }

  // Extensions do not work with files loaded from file://, so fail fast if
  // we're asked to load such a URL.
  var uri = new goog.Uri(url);
  if (uri.getScheme() === 'file') {
    throw Error('Unsupported URL protocol: ' + url);
  }

  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    var expectLoad = session.getCommandTab().loadsNewPage(uri);
    if (expectLoad) {
      tab.addEventListener('navigate', onNavigate, false);
    }
    safaridriver.extension.commands.sendCommand(session, command).
        then(onSuccess, onFailure);

    function onNavigate() {
      if (response.isPending()) {
        tab.removeEventListener('navigate', onNavigate, false);
        safaridriver.extension.commands.LOG_.info(
            'Page load finished; returning: ' + tab.url);
        response.resolve();
      }
    }

    function onSuccess() {
      if (!expectLoad && response.isPending()) {
        safaridriver.extension.commands.LOG_.info(
            'Not expecting a new page load; returning');
        response.resolve();
      }
    }

    function onFailure(e) {
      if (response.isPending()) {
        safaridriver.extension.commands.LOG_.severe(
            'Error while loading page; failing', e);
        tab.removeEventListener('navigate', onNavigate, false);
        response.reject(e);
      }
    }
  });

  return response.promise;
};

/**
 * Reloads the session's current page.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.refresh = function(session, command) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    tab.addEventListener('navigate', onNavigate, false);

    safaridriver.extension.commands.sendCommand(session, command).
        addErrback(function(e) {
          if (response.isPending()) {
            tab.removeEventListener('navigate', onNavigate, false);
            response.reject(e);
          }
        });

    function onNavigate() {
      if (response.isPending()) {
        tab.removeEventListener('navigate', onNavigate, false);
        response.resolve();
      }
    }
  });
  return response.promise;
};

/**
 * Updates the implicit wait setting for the given session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.implicitlyWait = function(session, command) {
  session.setImplicitWait(
      (/** @type {number} */command.getParameter('ms')) || 0);
};

/**
 * Updates the async script timeout setting for the given session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.setScriptTimeout = function(session, command) {
  session.setScriptTimeout(
      (/** @type {number} */command.getParameter('ms')) || 0);
};

safaridriver.extension.commands.findElement = function(session, command) {
  var started;
  var result = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(findElement);
  return result.promise;

  function findElement() {
    if (!goog.isDef(started)) {
      started = goog.now();
    }
    return safaridriver.extension.commands.sendCommand(session, command).
        then(checkResponse);
  }

  function checkResponse(response) {
    var value = response['value'];
    if ((!value || !value.length) &&
        session.getImplicitWait() > 0 &&
        goog.now() - started < session.getImplicitWait()) {
      findElement();
    } else if (!value) {
      var error = new bot.Error(bot.ErrorCode.NO_SUCH_ELEMENT,
          'Could not find element: ' + JSON.stringify(command.getParameters()));
      result.reject(error);
    } else {
      result.resolve(response);
    }
  }
};

/**
 * Sends a command to the provided session's current tab.
 * @param {!(safaridriver.extension.Session|safaridriver.extension.Tab)} sessionOrTab Either the
 *     session or tab to send the command to. If given a session, the command
 *     will be sent to the tab the session is currently focused on.
 * @param {!webdriver.Command} command The command object.
 * @return {!webdriver.promise.Promise} A promise that will be resolved with
 *     the command response.
 */
safaridriver.extension.commands.sendCommand = function(sessionOrTab, command) {
  var id = goog.string.getRandomString();
  var response = new webdriver.promise.Deferred();

  var json = {
    'id': id,
    'name': command.getName(),
    'parameters': command.getParameters()
  };

  safaridriver.extension.commands.LOG_.info('Sending command: ' +
      JSON.stringify(json));
  var tab = sessionOrTab instanceof safaridriver.extension.Tab
      ? (/** @type {!safaridriver.extension.Tab} */sessionOrTab)
      : (/** @type {!safaridriver.extension.Session} */sessionOrTab).getCommandTab();
  tab.whenReady(function(tab) {
    tab.addEventListener('message', onMessage, false);
    tab.page.dispatchMessage(safaridriver.MessageType.COMMAND, json);

    function onMessage(e) {
      if (e.name !== safaridriver.MessageType.RESPONSE) {
        return;
      }

      if (e.message.id !== id) {
        safaridriver.extension.commands.LOG_.info(
            'Ignoring response to another command: ' +
                e.message.id + ' (' + id + ')');
        return;
      }

      tab.removeEventListener('message', onMessage, false);
      try {
        response.resolve(webdriver.error.checkResponse(e.message.response));
      } catch (ex) {
        response.reject(ex);
      }
    }
  });

  return response.promise;
};

/**
 * Changes focus to another window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.switchToWindow = function(session, command) {
  var id = (/** @type {string} */ command.getParameter('id'));
  if (!id) {
    throw Error('Invalid command: missing required parameter "id"');
  }

  var tab = session.getTab(id);
  if (!tab) {
    // TODO: handle switching by window name.
    throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW, 'No such window: ' + id);
  }
  session.setCommandTab(/** @type {!safaridriver.extension.Tab} */tab);
};

/**
 * Changes focus to another frame in the current window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.switchToFrame = function(session, command) {
  // If switching to default content, we can silently return, since that is all
  // we support right now. If switching to something else, go ahead and throw
  // up. TODO: Implement this correctly.
  if (command.getParameter('id') !== null) {
    throw new Error('Unimplemented command: ' + command.getName());
  }
};

/**
 * Sends a command that should target the currently selected window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.sendWindowCommand = function(session, command) {
  var handle = (/** @type {string} */command.getParameter('windowHandle'));
  var tab;
  if (handle === 'current') {
    tab = session.getCommandTab();
  } else if (!(tab = session.getTab(handle))) {
    throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW,
        'No such window: ' + handle);
  }
  return safaridriver.extension.commands.sendCommand(tab, command);
};
<commit_msg>JariBakken: Make Safari's switchToWindow command spec compliant.<commit_after>// Copyright 2012 Software Freedom Conservancy. 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.

/**
 * @fileoverview Definitions for various command handlers used by the
 * {@link safaridriver.extension.Server}.
 */

goog.provide('safaridriver.extension.commands');

goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.string');
goog.require('safaridriver.extension.Tab');
goog.require('webdriver.error');
goog.require('webdriver.promise');

/**
 * @type {!goog.debug.Logger}
 * @private
 * @const
 */
safaridriver.extension.commands.LOG_ = goog.debug.Logger.getLogger(
    'safaridriver.extension.commands');

/**
 * Retrieves a session's capabilities.
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!Object.<*>} The session capabilities.
 */
safaridriver.extension.commands.describeSession = function(session) {
  return session.getCapabilities();
};

/**
 * Closes the tab the given session is currently focused on.
 * @param {!safaridriver.extension.Session} session The session object.
 */
safaridriver.extension.commands.closeTab = function(session) {
  session.getCommandTab().getBrowserTab().close();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {string} The handle for the tab the session is currently focused on.
 */
safaridriver.extension.commands.getWindowHandle = function(session) {
  return session.getCommandTab().getId();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!Array.<string>} A list of IDs for the open tabs.
 */
safaridriver.extension.commands.getWindowHandles = function(session) {
  return session.getTabIds();
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!webdriver.promise.Promise} A promise that will resolve to the
 *     current tab's URL.
 */
safaridriver.extension.commands.getCurrentUrl = function(session) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    response.resolve(tab.url);
  });
  return response.promise;
};

/**
 * @param {!safaridriver.extension.Session} session The session object.
 * @return {!webdriver.promise.Promise} A promise that will resolve to the
 *     current tab's title.
 */
safaridriver.extension.commands.getTitle = function(session) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    response.resolve(tab.title);
  });
  return response.promise;
};

/**
 * Loads a new page in the provided session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.loadUrl = function(session, command) {
  var url = command.getParameter('url');
  if (!url) {
    throw Error('Invalid command: missing "url" parameter');
  }

  // Extensions do not work with files loaded from file://, so fail fast if
  // we're asked to load such a URL.
  var uri = new goog.Uri(url);
  if (uri.getScheme() === 'file') {
    throw Error('Unsupported URL protocol: ' + url);
  }

  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    var expectLoad = session.getCommandTab().loadsNewPage(uri);
    if (expectLoad) {
      tab.addEventListener('navigate', onNavigate, false);
    }
    safaridriver.extension.commands.sendCommand(session, command).
        then(onSuccess, onFailure);

    function onNavigate() {
      if (response.isPending()) {
        tab.removeEventListener('navigate', onNavigate, false);
        safaridriver.extension.commands.LOG_.info(
            'Page load finished; returning: ' + tab.url);
        response.resolve();
      }
    }

    function onSuccess() {
      if (!expectLoad && response.isPending()) {
        safaridriver.extension.commands.LOG_.info(
            'Not expecting a new page load; returning');
        response.resolve();
      }
    }

    function onFailure(e) {
      if (response.isPending()) {
        safaridriver.extension.commands.LOG_.severe(
            'Error while loading page; failing', e);
        tab.removeEventListener('navigate', onNavigate, false);
        response.reject(e);
      }
    }
  });

  return response.promise;
};

/**
 * Reloads the session's current page.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.refresh = function(session, command) {
  var response = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(function(tab) {
    tab.addEventListener('navigate', onNavigate, false);

    safaridriver.extension.commands.sendCommand(session, command).
        addErrback(function(e) {
          if (response.isPending()) {
            tab.removeEventListener('navigate', onNavigate, false);
            response.reject(e);
          }
        });

    function onNavigate() {
      if (response.isPending()) {
        tab.removeEventListener('navigate', onNavigate, false);
        response.resolve();
      }
    }
  });
  return response.promise;
};

/**
 * Updates the implicit wait setting for the given session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.implicitlyWait = function(session, command) {
  session.setImplicitWait(
      (/** @type {number} */command.getParameter('ms')) || 0);
};

/**
 * Updates the async script timeout setting for the given session.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.setScriptTimeout = function(session, command) {
  session.setScriptTimeout(
      (/** @type {number} */command.getParameter('ms')) || 0);
};

safaridriver.extension.commands.findElement = function(session, command) {
  var started;
  var result = new webdriver.promise.Deferred();
  session.getCommandTab().whenReady(findElement);
  return result.promise;

  function findElement() {
    if (!goog.isDef(started)) {
      started = goog.now();
    }
    return safaridriver.extension.commands.sendCommand(session, command).
        then(checkResponse);
  }

  function checkResponse(response) {
    var value = response['value'];
    if ((!value || !value.length) &&
        session.getImplicitWait() > 0 &&
        goog.now() - started < session.getImplicitWait()) {
      findElement();
    } else if (!value) {
      var error = new bot.Error(bot.ErrorCode.NO_SUCH_ELEMENT,
          'Could not find element: ' + JSON.stringify(command.getParameters()));
      result.reject(error);
    } else {
      result.resolve(response);
    }
  }
};

/**
 * Sends a command to the provided session's current tab.
 * @param {!(safaridriver.extension.Session|safaridriver.extension.Tab)} sessionOrTab Either the
 *     session or tab to send the command to. If given a session, the command
 *     will be sent to the tab the session is currently focused on.
 * @param {!webdriver.Command} command The command object.
 * @return {!webdriver.promise.Promise} A promise that will be resolved with
 *     the command response.
 */
safaridriver.extension.commands.sendCommand = function(sessionOrTab, command) {
  var id = goog.string.getRandomString();
  var response = new webdriver.promise.Deferred();

  var json = {
    'id': id,
    'name': command.getName(),
    'parameters': command.getParameters()
  };

  safaridriver.extension.commands.LOG_.info('Sending command: ' +
      JSON.stringify(json));
  var tab = sessionOrTab instanceof safaridriver.extension.Tab
      ? (/** @type {!safaridriver.extension.Tab} */sessionOrTab)
      : (/** @type {!safaridriver.extension.Session} */sessionOrTab).getCommandTab();
  tab.whenReady(function(tab) {
    tab.addEventListener('message', onMessage, false);
    tab.page.dispatchMessage(safaridriver.MessageType.COMMAND, json);

    function onMessage(e) {
      if (e.name !== safaridriver.MessageType.RESPONSE) {
        return;
      }

      if (e.message.id !== id) {
        safaridriver.extension.commands.LOG_.info(
            'Ignoring response to another command: ' +
                e.message.id + ' (' + id + ')');
        return;
      }

      tab.removeEventListener('message', onMessage, false);
      try {
        response.resolve(webdriver.error.checkResponse(e.message.response));
      } catch (ex) {
        response.reject(ex);
      }
    }
  });

  return response.promise;
};

/**
 * Changes focus to another window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.switchToWindow = function(session, command) {
  var name = (/** @type {string} */ command.getParameter('name'));
  if (!name) {
    throw Error('Invalid command: missing required parameter "name"');
  }

  var tab = session.getTab(name);
  if (!tab) {
    // TODO: handle switching by window name.
    throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW, 'No such window: ' + name);
  }
  session.setCommandTab(/** @type {!safaridriver.extension.Tab} */tab);
};

/**
 * Changes focus to another frame in the current window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.switchToFrame = function(session, command) {
  // If switching to default content, we can silently return, since that is all
  // we support right now. If switching to something else, go ahead and throw
  // up. TODO: Implement this correctly.
  if (command.getParameter('id') !== null) {
    throw new Error('Unimplemented command: ' + command.getName());
  }
};

/**
 * Sends a command that should target the currently selected window.
 * @param {!safaridriver.extension.Session} session The session object.
 * @param {!webdriver.Command} command The command object.
 */
safaridriver.extension.commands.sendWindowCommand = function(session, command) {
  var handle = (/** @type {string} */command.getParameter('windowHandle'));
  var tab;
  if (handle === 'current') {
    tab = session.getCommandTab();
  } else if (!(tab = session.getTab(handle))) {
    throw new bot.Error(bot.ErrorCode.NO_SUCH_WINDOW,
        'No such window: ' + handle);
  }
  return safaridriver.extension.commands.sendCommand(tab, command);
};
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/DeveloperError',
        '../Core/Math'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        CesiumMath) {
    "use strict";

    /**
     * Represents a {@link Packable} number that always interpolates values
     * towards the shortest angle of rotation. This object is never used directly
     * but is instead passed to the constructor of {@link SampledProperty}
     * in order to represent a two-dimensional angle of rotation.
     *
     * @namespace
     * @alias Rotation
     *
     * @see PackableForInterpolation
     *
     * @example
     * var time1 = Cesium.JulianDate.fromIso8601('2010-05-07T00:00:00');
     * var time2 = Cesium.JulianDate.fromIso8601('2010-05-07T00:01:00');
     * var time3 = Cesium.JulianDate.fromIso8601('2010-05-07T00:02:00');
     *
     * var property = new Cesium.SampledProperty(Cesium.Rotation);
     * property.addSample(time1, 0);
     * property.addSample(time3, Cesium.Math.toRadians(350));
     *
     * //Getting the value at time2 will equal 355 degrees instead
     * //of 175 degrees (which is what you get if you construct
     * //a SampledProperty(Number) instead.  Note, the actual
     * //return value is in radians, not degrees.
     * property.getValue(time2);
     */
    var Rotation = {
        /**
         * The number of elements used to pack the object into an array.
         * @type {Number}
         */
        packedLength : 1,

        /**
         * Stores the provided instance into the provided array.
         * @function
         *
         * @param {Rotation} value The value to pack.
         * @param {Number[]} array The array to pack into.
         * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
         */
        pack : function(value, array, startingIndex) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(value)) {
                throw new DeveloperError('value is required');
            }

            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            array[startingIndex] = value;
        },

        /**
         * Retrieves an instance from a packed array.
         * @function
         *
         * @param {Number[]} array The packed array.
         * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
         * @param {Rotation} [result] The object into which to store the result.
         * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
         */
        unpack : function(array, startingIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            return array[startingIndex];
        },

        /**
         * Converts a packed array into a form suitable for interpolation.
         * @function
         *
         * @param {Number[]} packedArray The packed array.
         * @param {Number} [startingIndex=0] The index of the first element to be converted.
         * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
         * @param {Number[]} result The object into which to store the result.
         */
        convertPackedArrayForInterpolation : function(packedArray, startingIndex, lastIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(packedArray)) {
                throw new DeveloperError('packedArray is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            lastIndex = defaultValue(lastIndex, packedArray.length);

            var previousValue;
            for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
                var value = packedArray[startingIndex + i];
                if (i === 0 || Math.abs(previousValue - value) < Math.PI) {
                    result[i] = value;
                } else {
                    result[i] = value - CesiumMath.TWO_PI;
                }
                previousValue = value;
            }
        },

        /**
         * Retrieves an instance from a packed array converted with {@link Rotation.convertPackedArrayForInterpolation}.
         * @function
         *
         * @param {Number[]} array The array previously packed for interpolation.
         * @param {Number[]} sourceArray The original packed array.
         * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
         * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
         * @param {Rotation} [result] The object into which to store the result.
         * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
         */
        unpackInterpolationResult : function(array, sourceArray, firstIndex, lastIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            if (!defined(sourceArray)) {
                throw new DeveloperError('sourceArray is required');
            }
            //>>includeEnd('debug');

            result = array[0];
            if (result < 0) {
                return result + CesiumMath.TWO_PI;
            }
            return result;
        }
    };

    return Rotation;
});
<commit_msg>Update Rotation.js<commit_after>/*global define*/
define([
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/DeveloperError',
        '../Core/Math'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        CesiumMath) {
    "use strict";

    /**
     * Represents a {@link Packable} number that always interpolates values
     * towards the shortest angle of rotation. This object is never used directly
     * but is instead passed to the constructor of {@link SampledProperty}
     * in order to represent a two-dimensional angle of rotation.
     *
     * @namespace
     * @alias Rotation
     *
     * @see PackableForInterpolation
     *
     * @example
     * var time1 = Cesium.JulianDate.fromIso8601('2010-05-07T00:00:00');
     * var time2 = Cesium.JulianDate.fromIso8601('2010-05-07T00:01:00');
     * var time3 = Cesium.JulianDate.fromIso8601('2010-05-07T00:02:00');
     *
     * var property = new Cesium.SampledProperty(Cesium.Rotation);
     * property.addSample(time1, 0);
     * property.addSample(time3, Cesium.Math.toRadians(350));
     *
     * //Getting the value at time2 will equal 355 degrees instead
     * //of 175 degrees (which is what you get if you construct
     * //a SampledProperty(Number) instead.  Note, the actual
     * //return value is in radians, not degrees.
     * property.getValue(time2);
     */
    var Rotation = {
        /**
         * The number of elements used to pack the object into an array.
         * @type {Number}
         */
        packedLength : 1,

        /**
         * Stores the provided instance into the provided array.
         *
         * @param {Rotation} value The value to pack.
         * @param {Number[]} array The array to pack into.
         * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
         */
        pack : function(value, array, startingIndex) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(value)) {
                throw new DeveloperError('value is required');
            }

            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            array[startingIndex] = value;
        },

        /**
         * Retrieves an instance from a packed array.
         *
         * @param {Number[]} array The packed array.
         * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
         * @param {Rotation} [result] The object into which to store the result.
         * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
         */
        unpack : function(array, startingIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            return array[startingIndex];
        },

        /**
         * Converts a packed array into a form suitable for interpolation.
         *
         * @param {Number[]} packedArray The packed array.
         * @param {Number} [startingIndex=0] The index of the first element to be converted.
         * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
         * @param {Number[]} result The object into which to store the result.
         */
        convertPackedArrayForInterpolation : function(packedArray, startingIndex, lastIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(packedArray)) {
                throw new DeveloperError('packedArray is required');
            }
            //>>includeEnd('debug');

            startingIndex = defaultValue(startingIndex, 0);
            lastIndex = defaultValue(lastIndex, packedArray.length);

            var previousValue;
            for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
                var value = packedArray[startingIndex + i];
                if (i === 0 || Math.abs(previousValue - value) < Math.PI) {
                    result[i] = value;
                } else {
                    result[i] = value - CesiumMath.TWO_PI;
                }
                previousValue = value;
            }
        },

        /**
         * Retrieves an instance from a packed array converted with {@link Rotation.convertPackedArrayForInterpolation}.
         *
         * @param {Number[]} array The array previously packed for interpolation.
         * @param {Number[]} sourceArray The original packed array.
         * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
         * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
         * @param {Rotation} [result] The object into which to store the result.
         * @returns {Rotation} The modified result parameter or a new Rotation instance if one was not provided.
         */
        unpackInterpolationResult : function(array, sourceArray, firstIndex, lastIndex, result) {
            //>>includeStart('debug', pragmas.debug);
            if (!defined(array)) {
                throw new DeveloperError('array is required');
            }
            if (!defined(sourceArray)) {
                throw new DeveloperError('sourceArray is required');
            }
            //>>includeEnd('debug');

            result = array[0];
            if (result < 0) {
                return result + CesiumMath.TWO_PI;
            }
            return result;
        }
    };

    return Rotation;
});
<|endoftext|>


<commit_before>import wpConf from './webpack.config.babel.js'
import { initial } from 'lodash/fp'
wpConf.entry = {}

// filter out WebpackBrowserPlugin for tests
wpConf.plugins = wpConf.plugins | initial

module.exports = config => {
    config.set({
        browsers: ['Firefox'],
        customLaunchers: {
            Chrome_travis_ci: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        },
        reporters: ['mocha'],
        singleRun: true,
        frameworks: ['mocha'],
        files: [
            'node_modules/babel-polyfill/dist/polyfill.js',
            'test/**/*.js'
        ],
        preprocessors: {
            'test/**/*.js': ['webpack'],
            'src/**/*.js': ['webpack']
        },
        webpack: wpConf,
        webpackServer: {
            noInfo: true
        }
    })
    if (process.env.TRAVIS)
        config.browsers = [
            // 'Chrome_travis_ci',
            // Chrome is atm buggy https://github.com/karma-runner/karma/issues/1656
            'Firefox']
    if (process.env['CHROME'])
        config.browsers = ['Chrome_travis_ci']
    if (process.env['BROWSERS'])
        config.browsers = ['Chrome', 'Firefox']
    if (process.env['LOOP'])
        config.singleRun = false
}
<commit_msg>move karma config to separate variable<commit_after>import wpConf from './webpack.config.babel.js'
import { initial } from 'lodash/fp'
wpConf.entry = {}

// filter out WebpackBrowserPlugin for tests
wpConf.plugins = wpConf.plugins | initial

const karma_config = {
    browsers: ['Firefox'],
    customLaunchers: {
        Chrome_travis_ci: {
            base: 'Chrome',
            flags: ['--no-sandbox']
        }
    },
    reporters: ['mocha'],
    singleRun: true,
    frameworks: ['mocha'],
    files: [
        'node_modules/babel-polyfill/dist/polyfill.js',
        'test/**/*.js'
    ],
    preprocessors: {
        'test/**/*.js': ['webpack'],
        'src/**/*.js': ['webpack']
    },
    webpack: wpConf,
    webpackServer: {
        noInfo: true
    }
}

module.exports = config => {
    config.set(karma_config)
    if (process.env.TRAVIS)
        config.browsers = [
            // 'Chrome_travis_ci',
            // Chrome is atm buggy https://github.com/karma-runner/karma/issues/1656
            'Firefox']
    if (process.env['CHROME'])
        config.browsers = ['Chrome_travis_ci']
    if (process.env['BROWSERS'])
        config.browsers = ['Chrome', 'Firefox']
    if (process.env['LOOP'])
        config.singleRun = false
}
<|endoftext|>