<commit_before>var drag = function(el, dx, dy, complete) {

	// speed = sync -> Drag syncrhonously.
	// speed = fast|slow -> Drag asyncrhonously - animated.

	return $(el).userAction("drag", {
		dx: dx||0, dy: dy||0, speed: 'sync', complete: complete
	});
};

module("Simple Resize");

test("ui-resizable-e resize x", function() {

	var handle = '.ui-resizable-e', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 50);

	equals( 149, target.width(), "compare width");

	drag(handle, -50);

	equals( 100, target.width(), "compare width" );

});

test("ui-resizable-w resize x", function() {

	var handle = '.ui-resizable-w', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, -50);

	equals( 149, target.width(), "compare width" );

	drag(handle, 50);

	equals( 100, target.width(), "compare width" );

});

test("ui-resizable-n resize y", function() {

	var handle = '.ui-resizable-n', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 0, -50);

	equals( 149, target.height(), "compare height" );

	drag(handle, 0, 50);

	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-s resize y", function() {

	var handle = '.ui-resizable-s', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 0, 50);

	equals( 149, target.height(), "compare height" );

	drag(handle, 0, -50);

	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-se resize xy", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, 50, 50);

	equals( 149, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, -50, -50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-sw resize xy", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 149, target.width(), "compare width" );
	equals( 51, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-ne resize xy", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 51, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-nw resize xy", function() {

	var handle = '.ui-resizable-nw', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 149, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

/**
 * Conditional Resize
 * min/max Height/Width
 */

module("Dimensions limit");

test("ui-resizable-se { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, -50, -50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, 70, 70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-sw { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, 50, -50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, -70, 70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-ne { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, -50, 50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, 70, -70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-nw { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-nw', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, 70, 70);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, -70, -70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

/**
 * Respecting ratio resize with dimensions limit
 */

module("Respecting ratio resize with dimensions limits");

test("ui-resizable-e { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-e', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80);

	equals( 150, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 70, target.height(), "compare minHeight");

});

test("ui-resizable-w { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-w', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, -80);

	equals( 150, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 70, target.height(), "compare minHeight");

});

test("ui-resizable-n { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-n', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 0, -80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 0, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-s { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-s', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 0, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 0, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-se { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-sw { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, -80, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 130, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-ne { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80, -80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-nw { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-nw', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, -80, -80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 130, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});
<commit_msg>Resizable grid option automated test added<commit_after>var drag = function(el, dx, dy, complete) {

	// speed = sync -> Drag syncrhonously.
	// speed = fast|slow -> Drag asyncrhonously - animated.

	return $(el).userAction("drag", {
		dx: dx||0, dy: dy||0, speed: 'sync', complete: complete
	});
};

module("Simple Resize");

test("ui-resizable-e resize x", function() {

	var handle = '.ui-resizable-e', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 50);

	equals( 149, target.width(), "compare width");

	drag(handle, -50);

	equals( 100, target.width(), "compare width" );

});

test("ui-resizable-w resize x", function() {

	var handle = '.ui-resizable-w', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, -50);

	equals( 149, target.width(), "compare width" );

	drag(handle, 50);

	equals( 100, target.width(), "compare width" );

});

test("ui-resizable-n resize y", function() {

	var handle = '.ui-resizable-n', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 0, -50);

	equals( 149, target.height(), "compare height" );

	drag(handle, 0, 50);

	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-s resize y", function() {

	var handle = '.ui-resizable-s', target = $('#resizable1').resizable({ handles: 'all' });

	expect(2);

	drag(handle, 0, 50);

	equals( 149, target.height(), "compare height" );

	drag(handle, 0, -50);

	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-se resize xy", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, 50, 50);

	equals( 149, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, -50, -50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-sw resize xy", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 149, target.width(), "compare width" );
	equals( 51, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-ne resize xy", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 51, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

test("ui-resizable-nw resize xy", function() {

	var handle = '.ui-resizable-nw', target = $('#resizable1').resizable({ handles: 'all' });

	expect(4);

	drag(handle, -50, -50);

	equals( 149, target.width(), "compare width" );
	equals( 149, target.height(), "compare height" );

	drag(handle, 50, 50);

	equals( 100, target.width(), "compare width" );
	equals( 100, target.height(), "compare height" );

});

/**
 * Conditional Resize
 * min/max Height/Width
 */

module("Dimensions limit");

test("ui-resizable-se { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, -50, -50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, 70, 70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-sw { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, 50, -50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, -70, 70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-ne { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, -50, 50);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, 70, -70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

test("ui-resizable-nw { handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 }", function() {

	var handle = '.ui-resizable-nw', target = $('#resizable1').resizable({ handles: 'all', minWidth: 60, minHeight: 60, maxWidth: 100, maxHeight: 100 });

	expect(4);

	drag(handle, 70, 70);

	equals( 60, target.width(), "compare minWidth" );
	equals( 60, target.height(), "compare minHeight" );

	drag(handle, -70, -70);

	equals( 100, target.width(), "compare maxWidth" );
	equals( 100, target.height(), "compare maxHeight" );

});

/**
 * Respecting ratio resize with dimensions limit
 */

module("Respecting ratio resize with dimensions limits");

test("ui-resizable-e { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-e', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80);

	equals( 150, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 70, target.height(), "compare minHeight");

});

test("ui-resizable-w { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-w', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, -80);

	equals( 150, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 70, target.height(), "compare minHeight");

});

test("ui-resizable-n { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-n', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 0, -80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 0, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-s { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-s', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 0, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 0, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-se { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-sw { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-sw', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, -80, 80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, 130, -130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

test("ui-resizable-ne { aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 }", function() {

	var handle = '.ui-resizable-ne', target = $('#resizable1').resizable({ aspectRatio: 'preserve', handles: 'all', minWidth: 70, minHeight: 50, maxWidth: 150, maxHeight: 130 });

	expect(4);

	drag(handle, 80, -80);

	equals( 130, target.width(), "compare maxWidth");
	equals( 130, target.height(), "compare maxHeight");

	drag(handle, -130, 130);

	equals( 70, target.width(), "compare minWidth");
	equals( 50, target.height(), "compare minHeight");

});

module("Options");

test("ui-resizable-se { handles: 'all', gird: [20, 20] }", function() {

	var handle = '.ui-resizable-se', target = $('#resizable1').resizable({ handles: 'all', grid: [20, 20] });

	expect(4);

	drag(handle, 10, 10);

	equals( 100, target.width(), "compare width");
	equals( 100, target.height(), "compare height");

	drag(handle, 30, 30);

	equals( 120, target.width(), "compare width");
	equals( 120, target.height(), "compare height");

});
<|endoftext|>


<commit_before>/// <reference path="//code.createjs.com/createjs-2013.12.12.min.js" />
/// <reference path="../../../Content/GamesDownloadTemplate/lib/ScormHelper.js" />
var Game = Game || (function (createjs) {
    //alert("Game starting");

    function Game(canvas, gameData) {
        StartitALL()
        function StartitALL() {

            var self = this;
            self.stage = new createjs.Stage(canvas);
            var stageBG = new createjs.Shape();
            stageBG.name = "stageBG";
            stageBG.graphics.setStrokeStyle(3).beginStroke("black").beginFill("silver").drawRect(0, 0, 800, 600).endStroke().endFill();
            self.stage.addChild(stageBG);
            createjs.Touch.enable(self.stage, false, true);
            self.stage.enableMouseOver(25);
            self.stage.mouseMoveOutside = true; // keep tracking the mouse even when it leaves the canvas

            // ***********     Declare all assests and preload them. (declare the path) ************************
            var assetsPath = gameData.assetsPath || "";

            assetsPath += "Assets/"

            var QuestionsRandomized = [];

            for (var d = 0; d < gameData.Questions.length; d++) {
                gameData.Questions[d].OrderId = d;
            }

            function shuffle(array) {
                var currentIndex = array.length, temporaryValue, randomIndex;

                // While there remain elements to shuffle...
                while (0 !== currentIndex) {

                    // Pick a remaining element...
                    randomIndex = Math.floor(Math.random() * currentIndex);

                    usedQuestions.splice(0, 0, randomIndex);

                    currentIndex -= 1;

                    // And swap it with the current element.
                    temporaryValue = array[currentIndex];
                    array[currentIndex] = array[randomIndex];
                    array[randomIndex] = temporaryValue;
                }
                //alert("ran it")
                return array;
            }

            //declare each individual asset
            var assets = [

                { id: "start_button", src: assetsPath + "SequencePlayButton.png" },
                 { id: "background", src: assetsPath + "background.jpg" },
                   { id: "panel", src: assetsPath + "Panel.png" },
                   { id: "playbutton", src: assetsPath + "SequencePlayButton.png" },
                   { id: "crate", src: assetsPath + "crate.png" },
                   { id: "enemy", src: assetsPath + "enemy.png" },
                  { id: "beam", src: assetsPath + "beam.png" }
            ];

            var queue = new createjs.LoadQueue(false);
            queue.installPlugin(createjs.Sound);
            queue.addEventListener("complete", function (event) {
                //Paint board
                addBackground();
            });
            queue.loadManifest(assets);

            //loads background image
            function addBackground() {
                var gameBackground = new createjs.Container();
                gameBackground.x = 0;
                gameBackground.y = 0;
                var bgimage = new createjs.Bitmap(queue.getResult("background"))
                gameBackground.addChild(bgimage)

                self.stage.addChild(gameBackground);
                introductionScreen();

            }
            //load introduction screen /play button
            function introductionScreen() {

                var instructionsScreen = new createjs.Container();

                var panelBG = new createjs.Bitmap(queue.getResult("panel"));
                panelBG.x = 50;
                panelBG.y = 100;

                titleText = new createjs.Text(gameData.Title, "24px Alegreya", "#FFFFFF");
                titleText.x = panelBG.x + 45;
                titleText.y = panelBG.y + 30;

                var playButton = new createjs.Bitmap(queue.getResult("playbutton"))

                playButton.regX = 97;
                playButton.regY = 100;
                playButton.x = panelBG.x + 550;
                playButton.y = panelBG.y + 300;
                playButton.scaleX = playButton.scaleY = 0.20;

                var descriptionText = new createjs.Text(gameData.Description, "20px Alegreya", "#FFFFF2");
                descriptionText.x = panelBG.x + 80;
                descriptionText.y = panelBG.y + 100;

                var directionsText = new createjs.Text("Directions:" + " " + gameData.Directions, "20px Alegreya", "#FFFFFF");
                directionsText.x = panelBG.x + 80;
                directionsText.y = panelBG.y + 200;

                instructionsScreen.addChild(panelBG, titleText, descriptionText, directionsText, playButton);
                createjs.Tween.get(playButton, { loop: false }).to({ rotation: 360, scaleX: .4, scaleY: .4 }, 2000);
                self.stage.addChild(instructionsScreen);

                playButton.addEventListener("click", handleClick);
                function handleClick(event) {
                    self.stage.removeChild(instructionsScreen);

                    StartInteraction();
                };

            }

            // var player;
            // var playerContainer;

           // var beamContainer = new createjs.Container();
           // var beam = new createjs.Bitmap(queue.getResult("beam"));
            var beamContainer;
            var beam;
            var enemy;

            function StartInteraction() {

                //madeEnemy();

                // load player
                var playerContainer = new createjs.Container();
                var player = new createjs.Bitmap(queue.getResult("crate"))
                var playerMovement = 6
                //player.x = 000
                //player.y = 500

                playerContainer.addChild(player)

                //load controls
                this.document.onkeydown = keyPressed;
                var KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39, KEYCODE_SPACEBAR = 32

                self.stage.addChild(playerContainer);
                playerContainer.x = 400;
                playerContainer.y = 550;

                //load enemy
                console.log("made enemy")
                var enemyContainer = new createjs.Container();
                enemy = new createjs.Bitmap(queue.getResult("enemy"));
                enemy.x = 350
                enemy.y = 100

                enemyContainer.addChild(enemy)

                self.stage.addChild(enemyContainer);

                function keyPressed(event) {
                    //  console.log(event.keyCode);
                    switch (event.keyCode) {
                        case KEYCODE_LEFT:
                            moveLeft();
                            event.preventDefault();
                            break;
                        case KEYCODE_RIGHT:
                            moveRight();
                            event.preventDefault();
                            break;
                            //beam mapped to spacebar
                        case KEYCODE_SPACEBAR:
                            makeBeam();
                            event.preventDefault();
                            break;

                    }

                    function moveRight() {
                        // Console.log("in move right")
                        playerContainer.x += playerMovement;
                        if (playerContainer.x > 730) {
                            playerContainer.x = 730
                        }
                    }

                    function moveLeft() {
                        // console.log(playerContainer.x)
                        playerContainer.x -= playerMovement;
                        if (playerContainer.x < 20) {
                            playerContainer.x = 20
                        }

                    }
                    //beam display when space pressed ////////i should add an if or a do while here
                    //to only have 1 beam on screen at a time

                    function makeBeam() {

                        console.log("making beam")
                        beamContainer = new createjs.Container();
                        beam = new createjs.Bitmap(queue.getResult("beam"));
                        beamContainer.addChild(beam);
                        self.stage.addChild(beamContainer);

                        beamContainer.x = playerContainer.x;
                        beamContainer.y = 500;

                        madeBeam = true;

                    }

                }

            }

            var madeBeam = false;

            function moveBeam() {
               // console.log("did it")
              beamContainer.y -= 10
          //      enemy.alpha = 0.2
           //     var pt = beamContainer.localToLocal(100, 0, enemy);
           //     if (enemy.hitTest(pt.x, pt.y)) {
           //         enemy.alpha = 1
           //     }

            }

            //load enemy
            function madeEnemy() {

               //    console.log("made enemy")
               //     var enemyContainer = new createjs.Container();
               //     var enemy = new createjs.Bitmap(queue.getResult("enemy"));
               //         enemy.x = 350
               //         enemy.y = 100

               //enemyContainer.addChild(enemy)

               //self.stage.addChild(enemyContainer);

            }

            function deliverQuestions() {

            }

            function deliverAnswers() {

            }

            function gameOverScreen() {

            }

            function DisplayEndingNotes(EndedHow) {
                replayContainer.addEventListener("click", handleClick);
                function handleClick(event) {
                    StartitALL()
                }
            }

            var fps = 30;
            var tickCount = 0;
            //this updates the stage every tick not sure if we need it but
            createjs.Ticker.addEventListener("tick", handleTick);
            createjs.Ticker.on("tick", handleTick);
            createjs.Ticker.setFPS(fps);

            function handleTick(event) {
                tickCount++

               // if (tickCount == 30) {
                  //  console.log("hey" + tickCount)
                    tickCount = 0;
                    if (madeBeam == true) {
                        moveBeam();

                    }

              //  }

                self.stage.update();

            }

        }
    }
    return Game;
})(createjs);

<commit_msg>beam collision / squid disappear tween<commit_after>/// <reference path="//code.createjs.com/createjs-2013.12.12.min.js" />
/// <reference path="../../../Content/GamesDownloadTemplate/lib/ScormHelper.js" />
var Game = Game || (function (createjs) {
    //alert("Game starting");

    function Game(canvas, gameData) {
        StartitALL()
        function StartitALL() {

            var self = this;
            self.stage = new createjs.Stage(canvas);
            var stageBG = new createjs.Shape();
            stageBG.name = "stageBG";
            stageBG.graphics.setStrokeStyle(3).beginStroke("black").beginFill("silver").drawRect(0, 0, 800, 600).endStroke().endFill();
            self.stage.addChild(stageBG);
            createjs.Touch.enable(self.stage, false, true);
            self.stage.enableMouseOver(25);
            self.stage.mouseMoveOutside = true; // keep tracking the mouse even when it leaves the canvas

            // ***********     Declare all assests and preload them. (declare the path) ************************
            var assetsPath = gameData.assetsPath || "";

            assetsPath += "Assets/"

            var QuestionsRandomized = [];

            for (var d = 0; d < gameData.Questions.length; d++) {
                gameData.Questions[d].OrderId = d;
            }

            function shuffle(array) {
                var currentIndex = array.length, temporaryValue, randomIndex;

                // While there remain elements to shuffle...
                while (0 !== currentIndex) {

                    // Pick a remaining element...
                    randomIndex = Math.floor(Math.random() * currentIndex);

                    usedQuestions.splice(0, 0, randomIndex);

                    currentIndex -= 1;

                    // And swap it with the current element.
                    temporaryValue = array[currentIndex];
                    array[currentIndex] = array[randomIndex];
                    array[randomIndex] = temporaryValue;
                }
                //alert("ran it")
                return array;
            }

            //declare each individual asset
            var assets = [

                { id: "start_button", src: assetsPath + "SequencePlayButton.png" },
                 { id: "background", src: assetsPath + "background.jpg" },
                   { id: "panel", src: assetsPath + "Panel.png" },
                   { id: "playbutton", src: assetsPath + "SequencePlayButton.png" },
                   { id: "crate", src: assetsPath + "crate.png" },
                   { id: "enemy", src: assetsPath + "enemy.png" },
                  { id: "beam", src: assetsPath + "beam.png" }
            ];

            var queue = new createjs.LoadQueue(false);
            queue.installPlugin(createjs.Sound);
            queue.addEventListener("complete", function (event) {
                //Paint board
                addBackground();
            });
            queue.loadManifest(assets);

            //loads background image
            function addBackground() {
                var gameBackground = new createjs.Container();
                gameBackground.x = 0;
                gameBackground.y = 0;
                var bgimage = new createjs.Bitmap(queue.getResult("background"))
                gameBackground.addChild(bgimage)

                self.stage.addChild(gameBackground);
                introductionScreen();

            }
            //load introduction screen /play button
            function introductionScreen() {

                var instructionsScreen = new createjs.Container();

                var panelBG = new createjs.Bitmap(queue.getResult("panel"));
                panelBG.x = 50;
                panelBG.y = 100;

                titleText = new createjs.Text(gameData.Title, "24px Alegreya", "#FFFFFF");
                titleText.x = panelBG.x + 45;
                titleText.y = panelBG.y + 30;

                var playButton = new createjs.Bitmap(queue.getResult("playbutton"))

                playButton.regX = 97;
                playButton.regY = 100;
                playButton.x = panelBG.x + 550;
                playButton.y = panelBG.y + 300;
                playButton.scaleX = playButton.scaleY = 0.20;

                var descriptionText = new createjs.Text(gameData.Description, "20px Alegreya", "#FFFFF2");
                descriptionText.x = panelBG.x + 80;
                descriptionText.y = panelBG.y + 100;

                var directionsText = new createjs.Text("Directions:" + " " + gameData.Directions, "20px Alegreya", "#FFFFFF");
                directionsText.x = panelBG.x + 80;
                directionsText.y = panelBG.y + 200;

                instructionsScreen.addChild(panelBG, titleText, descriptionText, directionsText, playButton);
                createjs.Tween.get(playButton, { loop: false }).to({ rotation: 360, scaleX: .4, scaleY: .4 }, 2000);
                self.stage.addChild(instructionsScreen);

                playButton.addEventListener("click", handleClick);
                function handleClick(event) {
                    self.stage.removeChild(instructionsScreen);

                    StartInteraction();
                };

            }

            // var player;
            // var playerContainer;

            // var beamContainer = new createjs.Container();
            // var beam = new createjs.Bitmap(queue.getResult("beam"));
            var beamContainer;
            var beam;
            var enemyContainer;

            function StartInteraction() {

                //madeEnemy();

                // load player
                var playerContainer = new createjs.Container();
                var player = new createjs.Bitmap(queue.getResult("crate"))
                var playerMovement = 6
                //player.x = 000
                //player.y = 500

                playerContainer.addChild(player)

                //load controls
                this.document.onkeydown = keyPressed;
                var KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39, KEYCODE_SPACEBAR = 32

                self.stage.addChild(playerContainer);
                playerContainer.x = 400;
                playerContainer.y = 550;

                var widthOfSquid = 200;

                //load enemy
                console.log("made enemy")
                enemyContainer = new createjs.Container();
                enemyContainer.x = Math.random() * (self.stage.canvas.width - widthOfSquid);
                enemyContainer.y = 100
                var enemy = new createjs.Bitmap(queue.getResult("enemy"));

                createjs.Tween.get(enemyContainer, {loop: true}).to({ x: 0 }, 5000)
                                                  .to({ x: self.stage.canvas.width - widthOfSquid }, 10000);
                enemyContainer.addChild(enemy)
                self.stage.addChild(enemyContainer);

                //load enemies
                //  console.log("made enemies")
                // function generate enemy (every 10 shots)
              // new enemy = new enemyContainer
                //array
                //var newenemy
                //for (var i=0;i<10;i++) {
                //newenemy[i] = new enemyContainer(random(10, 300), random(10, 300), 40, 20);

                function keyPressed(event) {
                    //  console.log(event.keyCode);
                    switch (event.keyCode) {
                        case KEYCODE_LEFT:
                            moveLeft();
                            event.preventDefault();
                            break;
                        case KEYCODE_RIGHT:
                            moveRight();
                            event.preventDefault();
                            break;
                            //beam mapped to spacebar
                        case KEYCODE_SPACEBAR:
                            makeBeam();
                            event.preventDefault();
                            break;

                    }

                    function moveRight() {
                        // Console.log("in move right")
                        playerContainer.x += playerMovement;
                        if (playerContainer.x > 730) {
                            playerContainer.x = 730
                        }
                    }

                    function moveLeft() {
                        // console.log(playerContainer.x)
                        playerContainer.x -= playerMovement;
                        if (playerContainer.x < 20) {
                            playerContainer.x = 20
                        }

                    }

                    //blow up the squid when the beam hits the squid
                    function onBeamContainerTweenChange(evt) {
                        var theTween = evt.target;

                        var theBeamContainer = theTween.target;

                        var pt = enemyContainer.globalToLocal(theBeamContainer.x, theBeamContainer.y);

                        if (enemyContainer.hitTest(pt.x, pt.y)) {

                            createjs.Tween.get(enemyContainer)
                                            .to({ scaleX: 1.25, scaleY: 1.25 }, 200)
                                            .to({ scaleX: 1, scaleY: 1 }, 100)
                                            .to({ alpha: 0 }, 100)

                        }
                    }

                    function makeBeam() {

                        console.log("making beam")
                        beamContainer = new createjs.Container();
                        beam = new createjs.Bitmap(queue.getResult("beam"));
                        beamContainer.addChild(beam);
                        self.stage.addChild(beamContainer);

                        beamContainer.x = playerContainer.x + 9;
                        beamContainer.y = 500;

                        //when beam hits the squid
                        createjs.Tween.get(beamContainer, {
                            onChange: onBeamContainerTweenChange
                        })
                                      .to({ y: -200 }, 500)
                                       .call(function (evt) {
                                           var theThingBeingTweened = evt.target;
                                           self.stage.removeChild(theThingBeingTweened);
                                       });

                        madeBeam = true;

                    }

                }

            }

            var madeBeam = false;

            function moveBeam() {
                // console.log("did it")
                beamContainer.y -= 10

                var pt = beamContainer.localToLocal(beamContainer.x, beamContainer.y, enemyContainer);
                if (enemyContainer.hitTest(pt.x, pt.y)) {
                    enemyContainer.alpha = 1
                }

            }

            //load enemy
            function madeEnemy() {

                //    console.log("made enemy")
                //     var enemyContainer = new createjs.Container();
                //     var enemy = new createjs.Bitmap(queue.getResult("enemy"));
                //         enemy.x = 350
                //         enemy.y = 100

                //enemyContainer.addChild(enemy)

                //self.stage.addChild(enemyContainer);

            }

            function deliverQuestions() {

            }

            function deliverAnswers() {

            }

            function gameOverScreen() {

            }

            function DisplayEndingNotes(EndedHow) {
                replayContainer.addEventListener("click", handleClick);
                function handleClick(event) {
                    StartitALL()
                }
            }

            var fps = 30;
            var tickCount = 0;
            //this updates the stage every tick not sure if we need it but
            createjs.Ticker.addEventListener("tick", handleTick);
            createjs.Ticker.on("tick", handleTick);
            createjs.Ticker.setFPS(fps);

            function handleTick(event) {
                tickCount++

                // if (tickCount == 30) {
                //  console.log("hey" + tickCount)
                tickCount = 0;
                if (madeBeam == true) {
                    //moveBeam();

                }

                //  }

                self.stage.update();

            }

        }
    }
    return Game;
})(createjs);

<|endoftext|>


<commit_before>var x = require('casper').selectXPath;
casper.options.viewportSize = {width: 1855, height: 968};
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});
casper.test.begin('Positive test checker', function(test) {
   casper.start('http://demo.lagrummet.se/');
   casper.waitForSelector("article h1",
       function success() {
           test.assertExists("article h1");
           this.click("article h1");
       },
       function fail() {
           test.assertExists("article h1");
   });
   casper.waitForSelector(x("//*[contains(text(), \'TESTVERSION\')]"),
       function success() {
           test.assertExists(x("//*[contains(text(), \'TESTVERSION\')]"));
         },
       function fail() {
           test.assertExists(x("//*[contains(text(), \'TESTVERSION\')]"));
   });

   casper.run(function() {test.done();});
});<commit_msg>Add failing test to check jenkins build fail. #100<commit_after>var x = require('casper').selectXPath;
casper.on('page.error', function(msg, trace) {
   this.echo('Error: ' + msg, 'ERROR');
   for(var i=0; i<trace.length; i++) {
       var step = trace[i];
       this.echo('   ' + step.file + ' (line ' + step.line + ')', 'ERROR');
   }
});
casper.test.begin('Failing test for correct title', function(test) {
   casper.start('http://checker.regression.lagrummet.se/');
   casper.waitForSelector(x("//*[contains(text(), \'RInfo CheckerXXX\')]"),
       function success() {
           test.assertExists(x("//*[contains(text(), \'RInfo CheckerXXX\')]"));
         },
       function fail() {
           test.assertExists(x("//*[contains(text(), \'RInfo CheckerXXX\')]"));
   });

   casper.run(function() {test.done();});
});<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var argv = require('yargs').argv;
var frontMatter = require('gulp-front-matter');
var merge = require('merge-stream');
var swig = require('swig');
var swigExtras = require('swig-extras');
var through = require('through2');
var rimraf = require('gulp-rimraf');
var marked = require('gulp-marked');
var gulp = require('gulp');
var path = require('path');
var rename = require('gulp-rename');
var gutil = require('gulp-util');

var debug = require('gulp-debug');

var site = {
		'title': 'Maungawhau IT',
	    'url': 'http://talk.maungawhau.net.nz',
	    'urlRoot': '/',
	    'author': 'James Mitchell',
	    'email': 'james.mitchell@maungawhau.net.nz',
	    'twitter': 'saywibble',
	    'google_verify': 'ly8QgWAy0wwtyg5EoDAcuzhxRvsglDkNS740NVwHLco',
	    'analytics_id': 'UA-62644260-2',
	    'time': new Date()
}

if (argv._.indexOf('serve:dist') > -1) {
	site.url = 'http://localhost:9000';
}

swig.setDefaults({
    loader: swig.loaders.fs(__dirname + '/../app/assets/templates'),
    cache: false
});
swigExtras.useFilter(swig, 'truncate');

function summarize(marker) {
    return through.obj(function (file, enc, cb) {
        var summary = file.contents.toString().split(marker)[0]
        file.page.summary = summary
        this.push(file)
        cb()
    })
}

function applyTemplate(templateFile) {
    var tpl = swig.compileFile(path.join(__dirname, '..', templateFile));

    return through.obj(function (file, enc, cb) {
        var data = {
            site: site,
            page: file.page,
            content: file.contents.toString()
        };
        file.contents = new Buffer(tpl(data), 'utf8');
        this.push(file);
        cb();
    });
}

gulp.task('cleanpresentations', function () {
    return gulp.src(['dist/presentations'], {read: false})
        .pipe(rimraf());
});

gulp.task('presentations', ['cleanpresentations'], function () {
    var images = gulp.src(['app/content/presentations/**/*.jpg','app/content/presentations/**/*.png'])
    		.pipe(gulp.dest('dist'));
    var extras = gulp.src(['app/content/presentations/**/*.pdf','app/content/presentations/**/*.txt'])
    		.pipe(gulp.dest('dist'));
		var slides = gulp.src('app/content/presentations/**/*.slides')
				.pipe(frontMatter({property: 'page', remove: true}))
				.pipe(applyTemplate('app/assets/templates/slides.html'))
				.pipe(rename({extname: '.html'}))
				.pipe(gulp.dest('dist'));
    var presentations = gulp.src('app/content/presentations/**/*.md')
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(marked())
        .pipe(summarize('<!--more-->'))
				.pipe(debug({minimal: false}))
        // Collect all the presentations and place them on the site object.
        .pipe((function () {
            var presentations = [];
            var tags = site.tags || [];
            return through.obj(function (file, enc, cb) {
                file.page.url = path.dirname(file.path.replace(file.base,'')) + '/' + path.basename(file.path, '.md');
                presentations.push(file.page);
                presentations[presentations.length - 1].content = file.contents.toString();

                if (file.page.tags) {
                    file.page.tags.forEach(function (tag) {
                        if (tags.indexOf(tag) === -1) {
                            tags.push(tag);
                        }
                    });
                }

                this.push(file);
                cb();
            },
            function (cb) {
                presentations.sort(function (a, b) {
                    return b.created - a.created;
                });
                site.presentations = presentations;
                site.tags = tags;
                cb();
            })
        })())
        .pipe(applyTemplate('app/assets/templates/presentation.html'))
        .pipe(gulp.dest('dist'));
    return merge(images, extras, presentations);
});

gulp.task('cleanpages', function () {
    return gulp.src(['dist/*.html'], {read: false})
        .pipe(rimraf());
});

gulp.task('pages', ['cleanpages'], function () {
    var html = gulp.src(['app/content/pages/*.html'])
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            };
            var tpl = swig.compileFile(file.path);
            file.contents = new Buffer(tpl(data), 'utf8');
            this.push(file);
            cb();
        }));

    var markdown = gulp.src('app/content/pages/*.md')
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(marked())
        .pipe(applyTemplate('app/assets/templates/page.html'))
        .pipe(rename({extname: '.html'}));

    return merge(html, markdown)
        .pipe(gulp.dest('dist'));
});

gulp.task('rss', ['presentations'], function () {
    return gulp.src(['app/content/pages/rss.xml'])
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            }
            var tpl = swig.compileFile(file.path)
            file.contents = new Buffer(tpl(data), 'utf8')
            this.push(file)
            cb()
        }))
        .pipe(gulp.dest('dist'));
});

gulp.task('sitemap', ['presentations', 'pages'], function () {
    return gulp.src(['app/content/pages/sitemap.xml'])
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            }
            var tpl = swig.compileFile(file.path)
            file.contents = new Buffer(tpl(data), 'utf8')
            this.push(file)
            cb()
        }))
        .pipe(gulp.dest('dist'));
});

gulp.task('content', ['presentations', 'pages', 'rss', 'sitemap']);
<commit_msg>Ensure the presentations are generated before making the pages<commit_after>'use strict';

var _ = require('underscore');
var argv = require('yargs').argv;
var frontMatter = require('gulp-front-matter');
var merge = require('merge-stream');
var swig = require('swig');
var swigExtras = require('swig-extras');
var through = require('through2');
var rimraf = require('gulp-rimraf');
var marked = require('gulp-marked');
var gulp = require('gulp');
var path = require('path');
var rename = require('gulp-rename');
var gutil = require('gulp-util');

var debug = require('gulp-debug');

var site = {
		'title': 'Maungawhau IT',
	    'url': 'http://talk.maungawhau.net.nz',
	    'urlRoot': '/',
	    'author': 'James Mitchell',
	    'email': 'james.mitchell@maungawhau.net.nz',
	    'twitter': 'saywibble',
	    'google_verify': 'ly8QgWAy0wwtyg5EoDAcuzhxRvsglDkNS740NVwHLco',
	    'analytics_id': 'UA-62644260-2',
	    'time': new Date()
}

if (argv._.indexOf('serve:dist') > -1) {
	site.url = 'http://localhost:9000';
}

swig.setDefaults({
    loader: swig.loaders.fs(__dirname + '/../app/assets/templates'),
    cache: false
});
swigExtras.useFilter(swig, 'truncate');

function summarize(marker) {
    return through.obj(function (file, enc, cb) {
        var summary = file.contents.toString().split(marker)[0]
        file.page.summary = summary
        this.push(file)
        cb()
    })
}

function applyTemplate(templateFile) {
    var tpl = swig.compileFile(path.join(__dirname, '..', templateFile));

    return through.obj(function (file, enc, cb) {
        var data = {
            site: site,
            page: file.page,
            content: file.contents.toString()
        };
        file.contents = new Buffer(tpl(data), 'utf8');
        this.push(file);
        cb();
    });
}

gulp.task('cleanpresentations', function () {
    return gulp.src(['dist/presentations'], {read: false})
        .pipe(rimraf());
});

gulp.task('presentations', ['cleanpresentations'], function () {
    var images = gulp.src(['app/content/presentations/**/*.jpg','app/content/presentations/**/*.png'])
    		.pipe(gulp.dest('dist'));
    var extras = gulp.src(['app/content/presentations/**/*.pdf','app/content/presentations/**/*.txt'])
    		.pipe(gulp.dest('dist'));
		var slides = gulp.src('app/content/presentations/**/*.slides')
				.pipe(frontMatter({property: 'page', remove: true}))
				.pipe(applyTemplate('app/assets/templates/slides.html'))
				.pipe(rename({extname: '.html'}))
				.pipe(gulp.dest('dist'));
    var presentations = gulp.src('app/content/presentations/**/*.md')
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(marked())
        .pipe(summarize('<!--more-->'))
				.pipe(debug({minimal: false}))
        // Collect all the presentations and place them on the site object.
        .pipe((function () {
            var presentations = [];
            var tags = site.tags || [];
            return through.obj(function (file, enc, cb) {
                file.page.url = path.dirname(file.path.replace(file.base,'')) + '/' + path.basename(file.path, '.md');
                presentations.push(file.page);
                presentations[presentations.length - 1].content = file.contents.toString();

                if (file.page.tags) {
                    file.page.tags.forEach(function (tag) {
                        if (tags.indexOf(tag) === -1) {
                            tags.push(tag);
                        }
                    });
                }

                this.push(file);
                cb();
            },
            function (cb) {
                presentations.sort(function (a, b) {
                    return b.created - a.created;
                });
                site.presentations = presentations;
                site.tags = tags;
                cb();
            })
        })())
        .pipe(applyTemplate('app/assets/templates/presentation.html'))
        .pipe(gulp.dest('dist'));
    return merge(images, extras, slides, presentations);
});

gulp.task('cleanpages', function () {
    return gulp.src(['dist/*.html'], {read: false})
        .pipe(rimraf());
});

gulp.task('pages', ['cleanpages', 'presentations'], function () {
    var html = gulp.src(['app/content/pages/*.html'])
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            };
            var tpl = swig.compileFile(file.path);
            file.contents = new Buffer(tpl(data), 'utf8');
            this.push(file);
            cb();
        }));

    var markdown = gulp.src('app/content/pages/*.md')
        .pipe(frontMatter({property: 'page', remove: true}))
        .pipe(marked())
        .pipe(applyTemplate('app/assets/templates/page.html'))
        .pipe(rename({extname: '.html'}));

    return merge(html, markdown)
        .pipe(gulp.dest('dist'));
});

gulp.task('rss', ['presentations'], function () {
    return gulp.src(['app/content/pages/rss.xml'])
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            }
            var tpl = swig.compileFile(file.path)
            file.contents = new Buffer(tpl(data), 'utf8')
            this.push(file)
            cb()
        }))
        .pipe(gulp.dest('dist'));
});

gulp.task('sitemap', ['presentations', 'pages'], function () {
    return gulp.src(['app/content/pages/sitemap.xml'])
        .pipe(through.obj(function (file, enc, cb) {
            var data = {
                site: site,
                page: {}
            }
            var tpl = swig.compileFile(file.path)
            file.contents = new Buffer(tpl(data), 'utf8')
            this.push(file)
            cb()
        }))
        .pipe(gulp.dest('dist'));
});

gulp.task('content', ['pages', 'rss', 'sitemap']);
<|endoftext|>


<commit_before>module.exports = {
  init,
  onPlayerClose,
  onPlayerOpen,
  onToggleFullScreen,
  onWindowHide,
  onWindowShow,

  // TODO: move these out of menu.js -- they don't belong here
  showOpenSeedFiles,
  showOpenTorrentAddress,
  showOpenTorrentFile,
  toggleFullScreen
}

var electron = require('electron')

var app = electron.app

var config = require('../config')
var log = require('./log')
var windows = require('./windows')

var appMenu

function init () {
  appMenu = electron.Menu.buildFromTemplate(getAppMenuTemplate())
  electron.Menu.setApplicationMenu(appMenu)

  if (app.dock) {
    var dockMenu = electron.Menu.buildFromTemplate(getDockMenuTemplate())
    app.dock.setMenu(dockMenu)
  }
}

function toggleFullScreen (flag) {
  log('toggleFullScreen %s', flag)
  if (windows.main && windows.main.isVisible()) {
    flag = flag != null ? flag : !windows.main.isFullScreen()
    if (flag) {
      // Allows the window to use the full screen in fullscreen mode (OS X).
      windows.main.setAspectRatio(0)
    }
    windows.main.setFullScreen(flag)
  }
}

// Sets whether the window should always show on top of other windows
function toggleFloatOnTop (flag) {
  log('toggleFloatOnTop %s', flag)
  if (windows.main) {
    flag = flag != null ? flag : !windows.main.isAlwaysOnTop()
    windows.main.setAlwaysOnTop(flag)
    getMenuItem('Float on Top').checked = flag
  }
}

function toggleDevTools () {
  log('toggleDevTools')
  if (windows.main) {
    windows.main.toggleDevTools()
  }
}

function showWebTorrentWindow () {
  log('showWebTorrentWindow')
  windows.webtorrent.show()
  windows.webtorrent.webContents.openDevTools({ detach: true })
}

function playPause () {
  if (windows.main) {
    windows.main.send('dispatch', 'playPause')
  }
}

function increaseVolume () {
  if (windows.main) {
    windows.main.send('dispatch', 'changeVolume', 0.1)
  }
}

function decreaseVolume () {
  if (windows.main) {
    windows.main.send('dispatch', 'changeVolume', -0.1)
  }
}

function onWindowShow () {
  log('onWindowShow')
  getMenuItem('Full Screen').enabled = true
  getMenuItem('Float on Top').enabled = true
}

function onWindowHide () {
  log('onWindowHide')
  getMenuItem('Full Screen').enabled = false
  getMenuItem('Float on Top').enabled = false
}

function onPlayerOpen () {
  log('onPlayerOpen')
  getMenuItem('Play/Pause').enabled = true
  getMenuItem('Increase Volume').enabled = true
  getMenuItem('Decrease Volume').enabled = true
}

function onPlayerClose () {
  log('onPlayerClose')
  getMenuItem('Play/Pause').enabled = false
  getMenuItem('Increase Volume').enabled = false
  getMenuItem('Decrease Volume').enabled = false
}

function onToggleFullScreen (isFullScreen) {
  isFullScreen = isFullScreen != null ? isFullScreen : windows.main.isFullScreen()
  windows.main.setMenuBarVisibility(!isFullScreen)
  getMenuItem('Full Screen').checked = isFullScreen
  windows.main.send('fullscreenChanged', isFullScreen)
}

function getMenuItem (label) {
  for (var i = 0; i < appMenu.items.length; i++) {
    var menuItem = appMenu.items[i].submenu.items.find(function (item) {
      return item.label === label
    })
    if (menuItem) return menuItem
  }
}

// Prompts the user for a file, then creates a torrent. Only allows a single file
// selection.
function showOpenSeedFile () {
  electron.dialog.showOpenDialog({
    title: 'Select a file for the torrent file.',
    properties: [ 'openFile' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    var selectedPath = selectedPaths[0]
    windows.main.send('dispatch', 'showCreateTorrent', selectedPath)
  })
}

// Prompts the user for a file or directory, then creates a torrent. Only allows a single
// selection. To create a multi-file torrent, the user must select a directory.
function showOpenSeedFiles () {
  electron.dialog.showOpenDialog({
    title: 'Select a file or folder for the torrent file.',
    properties: [ 'openFile', 'openDirectory' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    var selectedPath = selectedPaths[0]
    windows.main.send('dispatch', 'showCreateTorrent', selectedPath)
  })
}

// Prompts the user to choose a torrent file, then adds it to the app
function showOpenTorrentFile () {
  electron.dialog.showOpenDialog(windows.main, {
    title: 'Select a .torrent file to open.',
    filters: [{ name: 'Torrent Files', extensions: ['torrent'] }],
    properties: [ 'openFile', 'multiSelections' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    selectedPaths.forEach(function (selectedPath) {
      windows.main.send('dispatch', 'addTorrent', selectedPath)
    })
  })
}

// Prompts the user for the URL of a torrent file, then downloads and adds it
function showOpenTorrentAddress () {
  windows.main.send('showOpenTorrentAddress')
}

function getAppMenuTemplate () {
  var template = [
    {
      label: 'File',
      submenu: [
        {
          label: process.platform === 'darwin'
            ? 'Create New Torrent...'
            : 'Create New Torrent from Folder...',
          accelerator: 'CmdOrCtrl+N',
          click: showOpenSeedFiles
        },
        {
          label: 'Open Torrent File...',
          accelerator: 'CmdOrCtrl+O',
          click: showOpenTorrentFile
        },
        {
          label: 'Open Torrent Address...',
          accelerator: 'CmdOrCtrl+U',
          click: showOpenTorrentAddress
        },
        {
          type: 'separator'
        },
        {
          label: process.platform === 'windows'
            ? 'Close'
            : 'Close Window',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste Torrent Address',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Full Screen',
          type: 'checkbox',
          accelerator: process.platform === 'darwin'
            ? 'Ctrl+Command+F'
            : 'F11',
          click: () => toggleFullScreen()
        },
        {
          label: 'Float on Top',
          type: 'checkbox',
          click: () => toggleFloatOnTop()
        },
        {
          type: 'separator'
        },
        {
          label: 'Developer',
          submenu: [
            {
              label: 'Developer Tools',
              accelerator: process.platform === 'darwin'
                ? 'Alt+Command+I'
                : 'Ctrl+Shift+I',
              click: toggleDevTools
            },
            {
              label: 'Show WebTorrent Process',
              accelerator: process.platform === 'darwin'
                ? 'Alt+Command+P'
                : 'Ctrl+Shift+P',
              click: showWebTorrentWindow
            }
          ]
        }
      ]
    },
    {
      label: 'Playback',
      submenu: [
        {
          label: 'Play/Pause',
          accelerator: 'CmdOrCtrl+P',
          click: playPause,
          enabled: false
        },
        {
          type: 'separator'
        },
        {
          label: 'Increase Volume',
          accelerator: 'CmdOrCtrl+Up',
          click: increaseVolume,
          enabled: false
        },
        {
          label: 'Decrease Volume',
          accelerator: 'CmdOrCtrl+Down',
          click: decreaseVolume,
          enabled: false
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn more about ' + config.APP_NAME,
          click: () => electron.shell.openExternal(config.HOME_PAGE_URL)
        },
        {
          label: 'Contribute on GitHub',
          click: () => electron.shell.openExternal(config.GITHUB_URL)
        },
        {
          type: 'separator'
        },
        {
          label: 'Report an Issue...',
          click: () => electron.shell.openExternal(config.GITHUB_URL_ISSUES)
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    // Add WebTorrent app menu (OS X)
    template.unshift({
      label: config.APP_NAME,
      submenu: [
        {
          label: 'About ' + config.APP_NAME,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + config.APP_NAME,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: () => app.quit()
        }
      ]
    })

    // Add Window menu (OS X)
    template.splice(5, 0, {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          type: 'separator'
        },
        {
          label: 'Bring All to Front',
          role: 'front'
        }
      ]
    })
  }

  // In Linux and Windows it is not possible to open both folders and files
  if (process.platform === 'linux' || process.platform === 'windows') {
    // File menu (Windows, Linux)
    template[0].submenu.unshift({
      label: 'Create New Torrent from File...',
      click: showOpenSeedFile
    })

    // Help menu (Windows, Linux)
    template[4].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'About ' + config.APP_NAME,
        click: windows.createAboutWindow
      }
    )
  }
  // Add "File > Quit" menu item so Linux distros where the system tray icon is missing
  // will have a way to quit the app.
  if (process.platform === 'linux') {
    // File menu (Linux)
    template[0].submenu.push({
      label: 'Quit',
      click: () => app.quit()
    })
  }

  return template
}

function getDockMenuTemplate () {
  return [
    {
      label: 'Create New Torrent...',
      accelerator: 'CmdOrCtrl+N',
      click: showOpenSeedFiles
    },
    {
      label: 'Open Torrent File...',
      accelerator: 'CmdOrCtrl+O',
      click: showOpenTorrentFile
    },
    {
      label: 'Open Torrent Address...',
      accelerator: 'CmdOrCtrl+U',
      click: showOpenTorrentAddress
    }
  ]
}
<commit_msg>Fix missing 'About WebTorrent' menu item<commit_after>module.exports = {
  init,
  onPlayerClose,
  onPlayerOpen,
  onToggleFullScreen,
  onWindowHide,
  onWindowShow,

  // TODO: move these out of menu.js -- they don't belong here
  showOpenSeedFiles,
  showOpenTorrentAddress,
  showOpenTorrentFile,
  toggleFullScreen
}

var electron = require('electron')

var app = electron.app

var config = require('../config')
var log = require('./log')
var windows = require('./windows')

var appMenu

function init () {
  appMenu = electron.Menu.buildFromTemplate(getAppMenuTemplate())
  electron.Menu.setApplicationMenu(appMenu)

  if (app.dock) {
    var dockMenu = electron.Menu.buildFromTemplate(getDockMenuTemplate())
    app.dock.setMenu(dockMenu)
  }
}

function toggleFullScreen (flag) {
  log('toggleFullScreen %s', flag)
  if (windows.main && windows.main.isVisible()) {
    flag = flag != null ? flag : !windows.main.isFullScreen()
    if (flag) {
      // Allows the window to use the full screen in fullscreen mode (OS X).
      windows.main.setAspectRatio(0)
    }
    windows.main.setFullScreen(flag)
  }
}

// Sets whether the window should always show on top of other windows
function toggleFloatOnTop (flag) {
  log('toggleFloatOnTop %s', flag)
  if (windows.main) {
    flag = flag != null ? flag : !windows.main.isAlwaysOnTop()
    windows.main.setAlwaysOnTop(flag)
    getMenuItem('Float on Top').checked = flag
  }
}

function toggleDevTools () {
  log('toggleDevTools')
  if (windows.main) {
    windows.main.toggleDevTools()
  }
}

function showWebTorrentWindow () {
  log('showWebTorrentWindow')
  windows.webtorrent.show()
  windows.webtorrent.webContents.openDevTools({ detach: true })
}

function playPause () {
  if (windows.main) {
    windows.main.send('dispatch', 'playPause')
  }
}

function increaseVolume () {
  if (windows.main) {
    windows.main.send('dispatch', 'changeVolume', 0.1)
  }
}

function decreaseVolume () {
  if (windows.main) {
    windows.main.send('dispatch', 'changeVolume', -0.1)
  }
}

function onWindowShow () {
  log('onWindowShow')
  getMenuItem('Full Screen').enabled = true
  getMenuItem('Float on Top').enabled = true
}

function onWindowHide () {
  log('onWindowHide')
  getMenuItem('Full Screen').enabled = false
  getMenuItem('Float on Top').enabled = false
}

function onPlayerOpen () {
  log('onPlayerOpen')
  getMenuItem('Play/Pause').enabled = true
  getMenuItem('Increase Volume').enabled = true
  getMenuItem('Decrease Volume').enabled = true
}

function onPlayerClose () {
  log('onPlayerClose')
  getMenuItem('Play/Pause').enabled = false
  getMenuItem('Increase Volume').enabled = false
  getMenuItem('Decrease Volume').enabled = false
}

function onToggleFullScreen (isFullScreen) {
  isFullScreen = isFullScreen != null ? isFullScreen : windows.main.isFullScreen()
  windows.main.setMenuBarVisibility(!isFullScreen)
  getMenuItem('Full Screen').checked = isFullScreen
  windows.main.send('fullscreenChanged', isFullScreen)
}

function getMenuItem (label) {
  for (var i = 0; i < appMenu.items.length; i++) {
    var menuItem = appMenu.items[i].submenu.items.find(function (item) {
      return item.label === label
    })
    if (menuItem) return menuItem
  }
}

// Prompts the user for a file, then creates a torrent. Only allows a single file
// selection.
function showOpenSeedFile () {
  electron.dialog.showOpenDialog({
    title: 'Select a file for the torrent file.',
    properties: [ 'openFile' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    var selectedPath = selectedPaths[0]
    windows.main.send('dispatch', 'showCreateTorrent', selectedPath)
  })
}

// Prompts the user for a file or directory, then creates a torrent. Only allows a single
// selection. To create a multi-file torrent, the user must select a directory.
function showOpenSeedFiles () {
  electron.dialog.showOpenDialog({
    title: 'Select a file or folder for the torrent file.',
    properties: [ 'openFile', 'openDirectory' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    var selectedPath = selectedPaths[0]
    windows.main.send('dispatch', 'showCreateTorrent', selectedPath)
  })
}

// Prompts the user to choose a torrent file, then adds it to the app
function showOpenTorrentFile () {
  electron.dialog.showOpenDialog(windows.main, {
    title: 'Select a .torrent file to open.',
    filters: [{ name: 'Torrent Files', extensions: ['torrent'] }],
    properties: [ 'openFile', 'multiSelections' ]
  }, function (selectedPaths) {
    if (!Array.isArray(selectedPaths)) return
    selectedPaths.forEach(function (selectedPath) {
      windows.main.send('dispatch', 'addTorrent', selectedPath)
    })
  })
}

// Prompts the user for the URL of a torrent file, then downloads and adds it
function showOpenTorrentAddress () {
  windows.main.send('showOpenTorrentAddress')
}

function getAppMenuTemplate () {
  var template = [
    {
      label: 'File',
      submenu: [
        {
          label: process.platform === 'darwin'
            ? 'Create New Torrent...'
            : 'Create New Torrent from Folder...',
          accelerator: 'CmdOrCtrl+N',
          click: showOpenSeedFiles
        },
        {
          label: 'Open Torrent File...',
          accelerator: 'CmdOrCtrl+O',
          click: showOpenTorrentFile
        },
        {
          label: 'Open Torrent Address...',
          accelerator: 'CmdOrCtrl+U',
          click: showOpenTorrentAddress
        },
        {
          type: 'separator'
        },
        {
          label: process.platform === 'win32'
            ? 'Close'
            : 'Close Window',
          accelerator: 'CmdOrCtrl+W',
          role: 'close'
        }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          role: 'cut'
        },
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          role: 'copy'
        },
        {
          label: 'Paste Torrent Address',
          accelerator: 'CmdOrCtrl+V',
          role: 'paste'
        },
        {
          label: 'Select All',
          accelerator: 'CmdOrCtrl+A',
          role: 'selectall'
        }
      ]
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Full Screen',
          type: 'checkbox',
          accelerator: process.platform === 'darwin'
            ? 'Ctrl+Command+F'
            : 'F11',
          click: () => toggleFullScreen()
        },
        {
          label: 'Float on Top',
          type: 'checkbox',
          click: () => toggleFloatOnTop()
        },
        {
          type: 'separator'
        },
        {
          label: 'Developer',
          submenu: [
            {
              label: 'Developer Tools',
              accelerator: process.platform === 'darwin'
                ? 'Alt+Command+I'
                : 'Ctrl+Shift+I',
              click: toggleDevTools
            },
            {
              label: 'Show WebTorrent Process',
              accelerator: process.platform === 'darwin'
                ? 'Alt+Command+P'
                : 'Ctrl+Shift+P',
              click: showWebTorrentWindow
            }
          ]
        }
      ]
    },
    {
      label: 'Playback',
      submenu: [
        {
          label: 'Play/Pause',
          accelerator: 'CmdOrCtrl+P',
          click: playPause,
          enabled: false
        },
        {
          type: 'separator'
        },
        {
          label: 'Increase Volume',
          accelerator: 'CmdOrCtrl+Up',
          click: increaseVolume,
          enabled: false
        },
        {
          label: 'Decrease Volume',
          accelerator: 'CmdOrCtrl+Down',
          click: decreaseVolume,
          enabled: false
        }
      ]
    },
    {
      label: 'Help',
      role: 'help',
      submenu: [
        {
          label: 'Learn more about ' + config.APP_NAME,
          click: () => electron.shell.openExternal(config.HOME_PAGE_URL)
        },
        {
          label: 'Contribute on GitHub',
          click: () => electron.shell.openExternal(config.GITHUB_URL)
        },
        {
          type: 'separator'
        },
        {
          label: 'Report an Issue...',
          click: () => electron.shell.openExternal(config.GITHUB_URL_ISSUES)
        }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    // Add WebTorrent app menu (OS X)
    template.unshift({
      label: config.APP_NAME,
      submenu: [
        {
          label: 'About ' + config.APP_NAME,
          role: 'about'
        },
        {
          type: 'separator'
        },
        {
          label: 'Services',
          role: 'services',
          submenu: []
        },
        {
          type: 'separator'
        },
        {
          label: 'Hide ' + config.APP_NAME,
          accelerator: 'Command+H',
          role: 'hide'
        },
        {
          label: 'Hide Others',
          accelerator: 'Command+Alt+H',
          role: 'hideothers'
        },
        {
          label: 'Show All',
          role: 'unhide'
        },
        {
          type: 'separator'
        },
        {
          label: 'Quit',
          accelerator: 'Command+Q',
          click: () => app.quit()
        }
      ]
    })

    // Add Window menu (OS X)
    template.splice(5, 0, {
      label: 'Window',
      role: 'window',
      submenu: [
        {
          label: 'Minimize',
          accelerator: 'CmdOrCtrl+M',
          role: 'minimize'
        },
        {
          type: 'separator'
        },
        {
          label: 'Bring All to Front',
          role: 'front'
        }
      ]
    })
  }

  // In Linux and Windows it is not possible to open both folders and files
  if (process.platform === 'linux' || process.platform === 'win32') {
    // File menu (Windows, Linux)
    template[0].submenu.unshift({
      label: 'Create New Torrent from File...',
      click: showOpenSeedFile
    })

    // Help menu (Windows, Linux)
    template[4].submenu.push(
      {
        type: 'separator'
      },
      {
        label: 'About ' + config.APP_NAME,
        click: windows.createAboutWindow
      }
    )
  }
  // Add "File > Quit" menu item so Linux distros where the system tray icon is missing
  // will have a way to quit the app.
  if (process.platform === 'linux') {
    // File menu (Linux)
    template[0].submenu.push({
      label: 'Quit',
      click: () => app.quit()
    })
  }

  return template
}

function getDockMenuTemplate () {
  return [
    {
      label: 'Create New Torrent...',
      accelerator: 'CmdOrCtrl+N',
      click: showOpenSeedFiles
    },
    {
      label: 'Open Torrent File...',
      accelerator: 'CmdOrCtrl+O',
      click: showOpenTorrentFile
    },
    {
      label: 'Open Torrent Address...',
      accelerator: 'CmdOrCtrl+U',
      click: showOpenTorrentAddress
    }
  ]
}
<|endoftext|>


<commit_before>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 *
 * This is an entire µ-web-framework to write Titanium-Alloy apps in HTML/CSS/JS, without native objects.
 *
 * The unique method `WebAlloy.createView` create a WebView with static html inside.
 *
 * To work with WebAlloy, you have to replicate the exact structure in the app directory (Alloy).
 *
 * ### Globals
 *
 * #### app.css
 * Global CSS included in each view.
 *
 * #### app.jslocal
 * Global JS included in each view.
 *
 *	#### controllers/foo.jslocal
 *	Javascript file included in the specific controller, after app.jslocal and jquery.jslocal
 *
 * #### views/foo.tpl
 * HTML/TPL (underscore templating system) file that is parsed and written in the static HTML.
 *
 * #### styles/foo.css
 * CSS file included in the specific controller.
 *
 * ### lib/**.jslocal
 * Put your jslocal files here, they are automatically appended at the end of the HTML.
 *
 * When you have replicated this structure, you can just call:
 *
 * ```
 * WebAlloy.createView({
 * 	name: 'foo',
 * 	webdata: { ... },
 * 	webapi: { ... }
 * 	...
 * });
 * ```
 *
 * The **name** arg is to specific the files to load.
 *
 * The **webdata** object is passed to the HTML file and rendered with the Undescore template system.
 *
 * The **webapi** is an object containing a series of API that are automatically exposed in the webview.
 *
 *	All the other arguments are Ti-UI specific for the classic WebView.
 *
 * ### HTML output
 *
 * So, the final result is an HTML string passed to the WebView, like this:
 *
 * ```
 * <!DOCTYPE html>
 * <html>
 * 	<head>
 * 		... metas ...
 * 		<style>{{ app.css }}</style>
 * 		<style>{{ your_controller.css }}</style>
 * 	</head>
 * 	<body>
 * 		<div id="main">
 * 			{{ controller.tpl (rendered in undescore with webdata argument) }}
 * 		</div>
 * 		<script>{{ lib/**.jslocal }}</script>
 * 		<script>{{ app.jslocal }}</script>
 * 		<script>{{ controller.jslocal }}</script>
 * 	</body>
 * </html>
 * ```
 *
 * ### WebView additional method
 *
 * Basically, you can interact with DOM elements with `evalJS`.
 *
 * There are some proxy methods designed to interact directly:
 *
 * #### render({ data })
 *
 * Re-render the template with new data passed.
 *
 * #### call(...)
 *
 * Call a function in the WebView.
 *
 * For example, `$.wv.call('foo', 1, 2, {x:1})` will be converted to js in `foo(1, 2, {x:1})`.
 *
 * #### $(selector).call(...)
 *
 * Call a function in a DOM-RAW object.
 *
 * #### $(selector).get(...)
 *
 * Get a property of a DOM-RAW object.
 *
 * #### $(selector).set(...)
 *
 * Set a property of a DOM-RAW object.
 *
 * ## WebAPI - Event manager
 *
 * You can easily interface from the WebView to Titanium with the `webapi` object passed to the constructor.
 *
 * In the webview, you've got an helper `WebAlloy` to run the API exposed.
 *
 * For example:
 *
 * ```
 * WebAlloy.createView({
 * 	...
 * 	webapi: {
 *  		close: function() { this.close(); }
 *  	}
 * });
 * ```
 *
 * In the controller file, simply call:
 *
 * ```
 * WebAlloy.run('close');
 * ```
 *
 * **If you use this method, remember to call `.webapiUnbind()` to remove the listeners!!!**
 *
 */

/**
 * * **jsExt**: The extension to use for Javascript files. Default: `.jslocal`
 * @type {Object}
 */
var config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T.weballoy);
exports.config = config;

var libDir = [];
var _helpers = {};

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
function addHelper(name, method) {
	_helpers[name] = method;
}
exports.addHelper = addHelper;

function embedText(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if (!file.exists()) {
		Ti.API.warn("Weballoy: File not found ("+f+")");
		return '';
	}

	var read = file.read().text;
	file = null;
	return read;
}

function embedCSS(f) {
	return '';
}

function embedJS(f) {
	return '';
}

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	if (!args.name) throw new Error('WebAlloy: you must pass a name');
	var uniqid = T('util').uniqid();

	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		uniqid: uniqid,
		enableZoomControls: false,
		backgroundColor: "transparent"
	}, args));

	$ui.addEventListener('load', function(e){
		if (args.autoHeight) $ui.height = $ui.evalJS("document.body.clientHeight");
		if (_.isFunction(args.loaded)) args.loaded();
	});

	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />';

	// Install the global event handler for this specific WebView
	html += '';

	// Include global css
	html += embedCSS('web/app.css');
	html += embedCSS('web/styles/'+args.name+'.css');

	html += '';

	// Include template
	$ui.tpl = _.template(embedText('web/views/'+args.name+'.tpl'));

	html += '
';
	var data = _.extend(_helpers || {}, args.webdata || {});
	html += $ui.tpl(data);
	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app'+config.jsExt);
	html += embedJS('web/controllers/'+args.name+config.jsExt);
	html += '';

	$ui.html = html;

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		data = _.extend(_helpers, data);
		$ui.$('#main').set('innerHTML', $ui.tpl(data));
	};

	// Install the API listener
	if (args.webapi) {

		$ui.__webapiListener = function(event) {
			if (!(event.name in args.webapi)) return;
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('weballoy_'+uniqid, $ui.__webapiListener);
		};

		Ti.App.addEventListener('__weballoy'+uniqid, $ui.__webapiListener);
	}

	return $ui;
};

(function init() {

	_.each(Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing(), function(js) {
		libDir.push('web/lib/'+js);
	});

})();<commit_msg>webApiListener anonim<commit_after>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 *
 * This is an entire µ-web-framework to write Titanium-Alloy apps in HTML/CSS/JS, without native objects.
 *
 * The unique method `WebAlloy.createView` create a WebView with static html inside.
 *
 * To work with WebAlloy, you have to replicate the exact structure in the app directory (Alloy).
 *
 * ### Globals
 *
 * #### app.css
 * Global CSS included in each view.
 *
 * #### app.jslocal
 * Global JS included in each view.
 *
 *	#### controllers/foo.jslocal
 *	Javascript file included in the specific controller, after app.jslocal and jquery.jslocal
 *
 * #### views/foo.tpl
 * HTML/TPL (underscore templating system) file that is parsed and written in the static HTML.
 *
 * #### styles/foo.css
 * CSS file included in the specific controller.
 *
 * ### lib/**.jslocal
 * Put your jslocal files here, they are automatically appended at the end of the HTML.
 *
 * When you have replicated this structure, you can just call:
 *
 * ```
 * WebAlloy.createView({
 * 	name: 'foo',
 * 	webdata: { ... },
 * 	webapi: { ... }
 * 	...
 * });
 * ```
 *
 * The **name** arg is to specific the files to load.
 *
 * The **webdata** object is passed to the HTML file and rendered with the Undescore template system.
 *
 * The **webapi** is an object containing a series of API that are automatically exposed in the webview.
 *
 *	All the other arguments are Ti-UI specific for the classic WebView.
 *
 * ### HTML output
 *
 * So, the final result is an HTML string passed to the WebView, like this:
 *
 * ```
 * <!DOCTYPE html>
 * <html>
 * 	<head>
 * 		... metas ...
 * 		<style>{{ app.css }}</style>
 * 		<style>{{ your_controller.css }}</style>
 * 	</head>
 * 	<body>
 * 		<div id="main">
 * 			{{ controller.tpl (rendered in undescore with webdata argument) }}
 * 		</div>
 * 		<script>{{ lib/**.jslocal }}</script>
 * 		<script>{{ app.jslocal }}</script>
 * 		<script>{{ controller.jslocal }}</script>
 * 	</body>
 * </html>
 * ```
 *
 * ### WebView additional method
 *
 * Basically, you can interact with DOM elements with `evalJS`.
 *
 * There are some proxy methods designed to interact directly:
 *
 * #### render({ data })
 *
 * Re-render the template with new data passed.
 *
 * #### call(...)
 *
 * Call a function in the WebView.
 *
 * For example, `$.wv.call('foo', 1, 2, {x:1})` will be converted to js in `foo(1, 2, {x:1})`.
 *
 * #### $(selector).call(...)
 *
 * Call a function in a DOM-RAW object.
 *
 * #### $(selector).get(...)
 *
 * Get a property of a DOM-RAW object.
 *
 * #### $(selector).set(...)
 *
 * Set a property of a DOM-RAW object.
 *
 * ## WebAPI - Event manager
 *
 * You can easily interface from the WebView to Titanium with the `webapi` object passed to the constructor.
 *
 * In the webview, you've got an helper `WebAlloy` to run the API exposed.
 *
 * For example:
 *
 * ```
 * WebAlloy.createView({
 * 	...
 * 	webapi: {
 *  		close: function() { this.close(); }
 *  	}
 * });
 * ```
 *
 * In the controller file, simply call:
 *
 * ```
 * WebAlloy.run('close');
 * ```
 *
 * **If you use this method, remember to call `.webapiUnbind()` to remove the listeners!!!**
 *
 */

/**
 * * **jsExt**: The extension to use for Javascript files. Default: `.jslocal`
 * @type {Object}
 */
var config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T.weballoy);
exports.config = config;

var libDir = [];
var _helpers = {};

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
function addHelper(name, method) {
	_helpers[name] = method;
}
exports.addHelper = addHelper;

function embedText(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if (!file.exists()) {
		Ti.API.warn("Weballoy: File not found ("+f+")");
		return '';
	}

	var read = file.read().text;
	file = null;
	return read;
}

function embedCSS(f) {
	return '';
}

function embedJS(f) {
	return '';
}

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	if (!args.name) throw new Error('WebAlloy: you must pass a name');
	var uniqid = T('util').uniqid();

	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		uniqid: uniqid,
		enableZoomControls: false,
		backgroundColor: "transparent"
	}, args));

	$ui.addEventListener('load', function(e){
		if (args.autoHeight) $ui.height = $ui.evalJS("document.body.clientHeight");
		if (_.isFunction(args.loaded)) args.loaded();
	});

	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />';

	// Install the global event handler for this specific WebView
	html += '';

	// Include global css
	html += embedCSS('web/app.css');
	html += embedCSS('web/styles/'+args.name+'.css');

	html += '';

	// Include template
	$ui.tpl = _.template(embedText('web/views/'+args.name+'.tpl'));

	html += '
';
	var data = _.extend(_helpers || {}, args.webdata || {});
	html += $ui.tpl(data);
	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app'+config.jsExt);
	html += embedJS('web/controllers/'+args.name+config.jsExt);
	html += '';

	$ui.html = html;

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		data = _.extend(_helpers, data);
		$ui.$('#main').set('innerHTML', $ui.tpl(data));
	};

	// Install the API listener
	if (args.webapi) {

		var webapiListener = function(event) {
			if (!(event.name in args.webapi)) return;
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('weballoy_'+uniqid, webapiListener);
		};

		Ti.App.addEventListener('__weballoy'+uniqid, webapiListener);
	}

	return $ui;
};

(function init() {

	_.each(Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing(), function(js) {
		libDir.push('web/lib/'+js);
	});

})();<|endoftext|>