<commit_before>/*global describe, it*/
var sinon = require('sinon');
var expect = require('unexpected')
    .installPlugin(require('unexpected-sinon'));
var LogBus = require('../../lib/LogBus');
var augmentFunctionWithEventEmitter = require('../../lib/augmentFunctionWithEventEmitter');
var relayEvents = require('../../lib/relayEvents');

describe('augmentFunctionWithEventEmitter', function () {
    it('should return a wrapped function', function () {
        expect(augmentFunctionWithEventEmitter(function () {}), 'to be a function');
    });
    it('should set the proper context for the augmented function', function () {
        augmentFunctionWithEventEmitter(function () {
            if (this === this.global) {
                // assert that the context is NOT global
                expect.fail('not executed in the proper context');
            }
        })();
    });
    it('should augment the function with .on and .emit methods', function () {
        augmentFunctionWithEventEmitter(function originalFunction() {
            expect(this, 'to satisfy', {
                on: expect.it('to be a function'),
                emit: expect.it('to be a function')
            });
        })();
    });
    it('should properly propagate the arguments to the original function', function () {
        augmentFunctionWithEventEmitter(function originalFunction() {
            var expectedArguments = (function () {
                return arguments;
            })('first arg', 'second arg');

            expect(arguments, 'to satisfy', expectedArguments);
        })('first arg', 'second arg');
    });
    it('should return a function useable as an EventEmitter', function (done) {
        var logBus = new LogBus();
        var logSpy = sinon.spy();

        var someAsyncTask = augmentFunctionWithEventEmitter(function () {
            var that = this;
            that.emit('log', 'starting some async task');
            setImmediate(function () {
                that.emit('log', 'completed some async task');
            });
        });

        relayEvents('log', logBus, someAsyncTask);

        logBus.subscribe({ type: 'log' }, logSpy);

        someAsyncTask();

        expect(someAsyncTask.on, 'to be a function');
        expect(logSpy, 'was called once');
        expect(logSpy, 'was called with', {
            type: 'log',
            message: 'starting some async task'
        });
        setImmediate(function () {
            expect(logSpy, 'was called twice');
            expect(logSpy, 'was called with', {
                type: 'log',
                message: 'completed some async task'
            });
            done();
        });
    });
});
<commit_msg>add skipped test documenting #7<commit_after>/*global describe, it*/
var sinon = require('sinon');
var expect = require('unexpected')
    .installPlugin(require('unexpected-sinon'));
var LogBus = require('../../lib/LogBus');
var augmentFunctionWithEventEmitter = require('../../lib/augmentFunctionWithEventEmitter');
var relayEvents = require('../../lib/relayEvents');

describe('augmentFunctionWithEventEmitter', function () {
    it('should return a wrapped function', function () {
        expect(augmentFunctionWithEventEmitter(function () {}), 'to be a function');
    });
    it('should set the proper context for the augmented function', function () {
        augmentFunctionWithEventEmitter(function () {
            if (this === this.global) {
                // assert that the context is NOT global
                expect.fail('not executed in the proper context');
            }
        })();
    });
    it('should augment the function with .on and .emit methods', function () {
        augmentFunctionWithEventEmitter(function originalFunction() {
            expect(this, 'to satisfy', {
                on: expect.it('to be a function'),
                emit: expect.it('to be a function')
            });
        })();
    });
    it('should properly propagate the arguments to the original function', function () {
        augmentFunctionWithEventEmitter(function originalFunction() {
            var expectedArguments = (function () {
                return arguments;
            })('first arg', 'second arg');

            expect(arguments, 'to satisfy', expectedArguments);
        })('first arg', 'second arg');
    });
    it('should return a function useable as an EventEmitter', function (done) {
        var logBus = new LogBus();
        var logSpy = sinon.spy();

        var someAsyncTask = augmentFunctionWithEventEmitter(function () {
            var that = this;
            that.emit('log', 'starting some async task');
            setImmediate(function () {
                that.emit('log', 'completed some async task');
            });
        });

        relayEvents('log', logBus, someAsyncTask);

        logBus.subscribe({ type: 'log' }, logSpy);

        someAsyncTask();

        expect(someAsyncTask.on, 'to be a function');
        expect(logSpy, 'was called once');
        expect(logSpy, 'was called with', {
            type: 'log',
            message: 'starting some async task'
        });
        setImmediate(function () {
            expect(logSpy, 'was called twice');
            expect(logSpy, 'was called with', {
                type: 'log',
                message: 'completed some async task'
            });
            done();
        });
    });
    it.skip('should allow relayEvents to overwrite the augmented emit method', function (done) {
        var logBus = new LogBus();
        var logSpy = sinon.spy();

        var method = augmentFunctionWithEventEmitter(function () {
            this.emit('foo', 'bar');
        });

        relayEvents('*', logBus, method); // Subscribing to all events will wrap emit

        logBus.subscribe({ type: 'foo' }, logSpy);

        method();

        setImmediate(function () {
            expect(logSpy, 'was called once');
            expect(logSpy, 'was called with', { type: 'foo', message: 'bar' });
            done();
        });
    });
});
<|endoftext|>


<commit_before>wof.World = function() {
    this.name = "";

    this.description = "";

    this.setting = "";

    this.scale = "";
    /*
    "local","small-scale","vast","epic","large-scale","world spanning","civilization level","galaxy level","dimension level","city","town","nation"
     */

    this.numberOfIssues = 2;

    this.bigIssues = ["",""];
    /*
     Current
      Impending

      issues for elements of the setting
     */

    this.faces = [];

    this.places = [];

    this.groups = [];

};
<commit_msg>Definir mundo<commit_after>wof.World = function() {
    this.name = "";

    this.description = "";

    this.setting = "";

    this.scale = "";
    /*
    "local","small-scale","vast","epic","large-scale","world spanning","civilization level","galaxy level","dimension level","city","town","nation"
     */

    this.numberOfIssues = 2;

    this.bigIssues = ["",""];
    /*
     Current
      Impending

      issues for elements of the setting
     */

    this.faces = [];

    this.places = [];

    this.groups = [];

    this.numberOfAspects = 5;

    this.numberOfPhases = 3;

    this.skillCap = 4;

    this.skillPyramid = true;

    this.numberOfColumns = 0;

    this.refreshRate = 3;

    this.numberOfInitialStunts = 3;

    this.stressTracks = ["Physical", "Mental"];

    this.defaultNumberOfStressBoxes = 2;

    this.defaultConsequenfceSlots = [2,4,6];

    this.skils = [];

    this.stunts = [];

    this.extras = [];

};
<|endoftext|>


<commit_before>var model;
var handlers = {};

loadScript( 'coui://download/community-mods-replay_loading.js');

$(document).ready(function () {

    function ReplayLoadingViewModel() {
        var self = this;

        self.reconnectToGameInfo = ko.observable().extend({ local: 'reconnect_to_game_info' });

        self.displayName = ko.observable().extend({ session: 'displayName' });

        self.replay_loading_msg = ko.observable().extend({ session: 'replay_loading_msg' });

        var forwardLoadGame = ko.observable().extend({ session: 'load_game' });
        self.loadGame = ko.observable(forwardLoadGame());
        forwardLoadGame(false);

        self.heartbeat = function () {
            model.send_message('heartbeat', {}, function (success, response) {
                if (!success)
                    api.debug.log('heartbeatFailed');
            });
        };
        self.heartbeatInterval = setInterval(self.heartbeat, 10000);

        self.clearHeartbeat = function () {
            if (self.heartbeatInterval !== undefined) {
                clearInterval(self.heartbeatInterval);
                self.heartbeatInterval = undefined;
            }
        }

        self.transitPrimaryMessage = ko.observable().extend({ session: 'transit_primary_message' });
        self.transitSecondaryMessage = ko.observable().extend({ session: 'transit_secondary_message' });
        self.transitDestination = ko.observable().extend({ session: 'transit_destination' });
        self.transitDelay = ko.observable(0).extend({ session: 'transit_delay' });

        self.navToMainMenu = function () {
            self.reconnectToGameInfo(undefined);
            self.disconnect();
            self.replay_loading_msg({});
            self.clearHeartbeat();
            self.config('');
            model.transitPrimaryMessage(loc('!LOC:Returning to Main Menu'));
            model.transitSecondaryMessage('');
            model.transitDestination('coui://ui/main/game/start/start.html');
            model.transitDelay(0);
            window.location.href = 'coui://ui/main/game/transit/transit.html';
            return; /* window.location.href will not stop execution. */
        };

        /* should only exist for gw */
        self.config = ko.observable().extend({ memory: 'gw_battle_config' });

        self.connected = ko.observable(false);

        self.handleDisconnect = function()
        {
            self.reconnectToGameInfo(undefined);
            self.connected(false);

            var lastSceneUrl = ko.observable('coui://ui/main/game/start/start.html').extend({ session: 'last_scene_url' });
            var transitPrimaryMessage = ko.observable().extend({ session: 'transit_primary_message' });
            var transitSecondaryMessage = ko.observable().extend({ session: 'transit_secondary_message' });
            var transitDestination = ko.observable().extend({ session: 'transit_destination' });
            var transitDelay = ko.observable().extend({ session: 'transit_delay' });

            transitDelay(5000);
            transitDestination(lastSceneUrl());
            if (self.loadGame())
                transitPrimaryMessage('!LOC:Unable to load save game');
            else
                transitPrimaryMessage('!LOC:Unable to load replay')
            transitSecondaryMessage('!LOC:Returning to menu');

            window.location.href = 'coui://ui/main/game/transit/transit.html';
        };

        self.setup = function () {
            model.send_message('heartbeat', {});
        };
    }
    model = new ReplayLoadingViewModel();

    handlers.login_rejected = function() {
        console.error("Login rejected from server");
        model.handleDisconnect();
    };

    handlers.connection_disconnected = function() {
        console.error("Login disconnected from server");
        model.handleDisconnect();
    };

    handlers.request_config = function() {
        model.sendConfig();
    };

    handlers.server_state = function (msg) {
        if (msg.url && msg.url !== window.location.href) {
            model.config('');
            model.clearHeartbeat();
            window.location.href = msg.url;
            return; /* window.location.href will not stop execution. */
        } else if (msg.data) {
            model.connected(true);
            model.replay_loading_msg(loc("!LOC:Starting replay server, please be patient..."));
        }
    };

    /* not really sure when this should be used, and I don't know what sv_ccl stands for. */
    handlers.mod_msg_sv_ccl_set_replay_config = function (msg) {
        if (msg.files) {
            var cookedFiles = _.mapValues(msg.files, function (value) {
                if (typeof value !== 'string')
                    return JSON.stringify(value);
                else
                    return value;
            });
            api.game.getUnitSpecTag().then(function (tag) {
                if (tag === '') {
                    api.file.unmountAllMemoryFiles().then* function() {
                        api.file.mountMemoryFiles(cookedFiles);
                        api.game.setUnitSpecTag('.player');
                    };
                }
                model.send_message('mod_msg_ccl_sv_replay_config_received', {}, function (success, response) {});
            });
        } else {
            model.send_message('mod_msg_ccl_sv_replay_config_received', {}, function (success, response) {});
        }
    }

    /* if you attempt to load a replay file (saves are replays) which contains mounted files,
       it will send this message and wait for a response */
    handlers.memory_files = function (msg) {
        /* the server is sending file overwrites. if we already have file overwrites,
           then we don't want to use the files, because the local files have higher priority */
        api.game.getUnitSpecTag().then(function (tag) {
            if (tag === '') {
                var cookedFiles = _.mapValues(msg, function (value) {
                    if (typeof value !== 'string')
                        return JSON.stringify(value);
                    else
                        return value;
                });

                api.file.unmountAllMemoryFiles().then( function() {
                    api.file.mountMemoryFiles(cookedFiles);
                    api.game.setUnitSpecTag('.player');
                });
            }
        });

        model.send_message('memory_files_received', {}, function (success, response) {});
    };

    if ( window.CommunityMods ) {
        CommunityMods();
    }

    // inject per scene mods
    loadSceneMods('replay_loading');

    // setup send/recv messages and signals
    app.registerWithCoherent(model, handlers);

    // Activates knockout.js
    ko.applyBindings(model);

    model.setup();

    app.hello(handlers.server_state, handlers.connection_disconnected);
});
<commit_msg>Wrapped community mods with exception handling<commit_after>var model;
var handlers = {};

loadScript( 'coui://download/community-mods-replay_loading.js');

$(document).ready(function () {

    function ReplayLoadingViewModel() {
        var self = this;

        self.reconnectToGameInfo = ko.observable().extend({ local: 'reconnect_to_game_info' });

        self.displayName = ko.observable().extend({ session: 'displayName' });

        self.replay_loading_msg = ko.observable().extend({ session: 'replay_loading_msg' });

        var forwardLoadGame = ko.observable().extend({ session: 'load_game' });
        self.loadGame = ko.observable(forwardLoadGame());
        forwardLoadGame(false);

        self.heartbeat = function () {
            model.send_message('heartbeat', {}, function (success, response) {
                if (!success)
                    api.debug.log('heartbeatFailed');
            });
        };
        self.heartbeatInterval = setInterval(self.heartbeat, 10000);

        self.clearHeartbeat = function () {
            if (self.heartbeatInterval !== undefined) {
                clearInterval(self.heartbeatInterval);
                self.heartbeatInterval = undefined;
            }
        }

        self.transitPrimaryMessage = ko.observable().extend({ session: 'transit_primary_message' });
        self.transitSecondaryMessage = ko.observable().extend({ session: 'transit_secondary_message' });
        self.transitDestination = ko.observable().extend({ session: 'transit_destination' });
        self.transitDelay = ko.observable(0).extend({ session: 'transit_delay' });

        self.navToMainMenu = function () {
            self.reconnectToGameInfo(undefined);
            self.disconnect();
            self.replay_loading_msg({});
            self.clearHeartbeat();
            self.config('');
            model.transitPrimaryMessage(loc('!LOC:Returning to Main Menu'));
            model.transitSecondaryMessage('');
            model.transitDestination('coui://ui/main/game/start/start.html');
            model.transitDelay(0);
            window.location.href = 'coui://ui/main/game/transit/transit.html';
            return; /* window.location.href will not stop execution. */
        };

        /* should only exist for gw */
        self.config = ko.observable().extend({ memory: 'gw_battle_config' });

        self.connected = ko.observable(false);

        self.handleDisconnect = function()
        {
            self.reconnectToGameInfo(undefined);
            self.connected(false);

            var lastSceneUrl = ko.observable('coui://ui/main/game/start/start.html').extend({ session: 'last_scene_url' });
            var transitPrimaryMessage = ko.observable().extend({ session: 'transit_primary_message' });
            var transitSecondaryMessage = ko.observable().extend({ session: 'transit_secondary_message' });
            var transitDestination = ko.observable().extend({ session: 'transit_destination' });
            var transitDelay = ko.observable().extend({ session: 'transit_delay' });

            transitDelay(5000);
            transitDestination(lastSceneUrl());
            if (self.loadGame())
                transitPrimaryMessage('!LOC:Unable to load save game');
            else
                transitPrimaryMessage('!LOC:Unable to load replay')
            transitSecondaryMessage('!LOC:Returning to menu');

            window.location.href = 'coui://ui/main/game/transit/transit.html';
        };

        self.setup = function () {
            model.send_message('heartbeat', {});
        };
    }
    model = new ReplayLoadingViewModel();

    handlers.login_rejected = function() {
        console.error("Login rejected from server");
        model.handleDisconnect();
    };

    handlers.connection_disconnected = function() {
        console.error("Login disconnected from server");
        model.handleDisconnect();
    };

    handlers.request_config = function() {
        model.sendConfig();
    };

    handlers.server_state = function (msg) {
        if (msg.url && msg.url !== window.location.href) {
            model.config('');
            model.clearHeartbeat();
            window.location.href = msg.url;
            return; /* window.location.href will not stop execution. */
        } else if (msg.data) {
            model.connected(true);
            model.replay_loading_msg(loc("!LOC:Starting replay server, please be patient..."));
        }
    };

    /* not really sure when this should be used, and I don't know what sv_ccl stands for. */
    handlers.mod_msg_sv_ccl_set_replay_config = function (msg) {
        if (msg.files) {
            var cookedFiles = _.mapValues(msg.files, function (value) {
                if (typeof value !== 'string')
                    return JSON.stringify(value);
                else
                    return value;
            });
            api.game.getUnitSpecTag().then(function (tag) {
                if (tag === '') {
                    api.file.unmountAllMemoryFiles().then* function() {
                        api.file.mountMemoryFiles(cookedFiles);
                        api.game.setUnitSpecTag('.player');
                    };
                }
                model.send_message('mod_msg_ccl_sv_replay_config_received', {}, function (success, response) {});
            });
        } else {
            model.send_message('mod_msg_ccl_sv_replay_config_received', {}, function (success, response) {});
        }
    }

    /* if you attempt to load a replay file (saves are replays) which contains mounted files,
       it will send this message and wait for a response */
    handlers.memory_files = function (msg) {
        /* the server is sending file overwrites. if we already have file overwrites,
           then we don't want to use the files, because the local files have higher priority */
        api.game.getUnitSpecTag().then(function (tag) {
            if (tag === '') {
                var cookedFiles = _.mapValues(msg, function (value) {
                    if (typeof value !== 'string')
                        return JSON.stringify(value);
                    else
                        return value;
                });

                api.file.unmountAllMemoryFiles().then( function() {
                    api.file.mountMemoryFiles(cookedFiles);
                    api.game.setUnitSpecTag('.player');
                });
            }
        });

        model.send_message('memory_files_received', {}, function (success, response) {});
    };

    if ( window.CommunityMods ) {
        try {
            CommunityMods();
        } catch ( e ) {
            console.error( e );
        }
    }

    // inject per scene mods
    loadSceneMods('replay_loading');

    // setup send/recv messages and signals
    app.registerWithCoherent(model, handlers);

    // Activates knockout.js
    ko.applyBindings(model);

    model.setup();

    app.hello(handlers.server_state, handlers.connection_disconnected);
});
<|endoftext|>


<commit_before>
function ModelViewer(canvasId) {

	this.addScene = function(elemId, modelName) {

		var element = document.getElementById(elemId);

		var scene = new THREE.Scene();
		scene.userData.element = element;

		var rect = element.getBoundingClientRect();
		var camera = new THREE.PerspectiveCamera( 60, rect.width/rect.height, 0.1, 100 );
		camera.position.x = 0.5;
		camera.position.y = 0.5;
		camera.position.z = -1;
		scene.userData.camera = camera;

		var controls = new THREE.OrbitControls( scene.userData.camera, scene.userData.element );
		controls.minDistance = 2;
		controls.maxDistance = 5;
		controls.enablePan = false;
		controls.enableZoom = false;
		controls.autoRotate = true;
		controls.autoRotateSpeed = 2.0;
		scene.userData.controls = controls;

		var mtlLoader = new THREE.MTLLoader();
		mtlLoader.setBaseUrl( 'assets/' );
		mtlLoader.setPath( 'assets/' );
		mtlLoader.load( modelName + '.mtl', function( materials ) {
			materials.preload();
			var objLoader = new THREE.OBJLoader();
			objLoader.setMaterials( materials );
			objLoader.setPath( 'assets/' );
			objLoader.load( modelName + '.obj', function ( object ) {
				object.traverse(function(obj){
					obj.receiveShadow = true;
					obj.castShadow = true;
				})
				scene.add( object );
			}, function(){}, function(){
				console.log("Ops!");
			} );
		});

		var hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.8 );
		hemiLight.color.setHSL( 0.6, 1, 0.6 );
		hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
		hemiLight.position.set( 0, 1, 0 );
		scene.add( hemiLight );

		var light = new THREE.DirectionalLight( 0xfffffa, 0.7 );
		light.position.set( 4, 5, 2 );
		light.castShadow = true;
		light.shadow.mapSize.width = 512;
		light.shadow.mapSize.height = 512;
		var shadowWidth = 2;
		light.shadow.camera.left = -shadowWidth;
		light.shadow.camera.right = shadowWidth;
		light.shadow.camera.top = shadowWidth;
		light.shadow.camera.bottom = -shadowWidth;
		light.shadow.camera.far = 20;
		light.shadow.camera.near = 0.1;
		//light.shadow.bias = 0.0001;
		scene.add( light );

		scenes.push( scene );
	}

	var updateSize = function() {
		var width = canvas.clientWidth;
		var height = canvas.clientHeight;
		if ( canvas.width !== width || canvas.height != height ) {
			renderer.setSize( width, height, false );
		}
	}

	var render = function() {
		var canvasStyle = window.getComputedStyle(canvas);
    	if (canvasStyle.display === 'none') return;

		updateSize();

		renderer.setClearColor( 0xffffff );
		renderer.setScissorTest( false );
		renderer.clear();
		renderer.setScissorTest( true );

		scenes.forEach( function( scene ) {
			var element = scene.userData.element;
			var rect = element.getBoundingClientRect();

			if ( rect.bottom < 0 || rect.top  > renderer.domElement.clientHeight ||
				 rect.right  < 0 || rect.left > renderer.domElement.clientWidth ) {
				return;  // it's off screen
			}

			var width = rect.right - rect.left;
			var height = rect.bottom - rect.top;
			var left  = rect.left;
			var bottom = renderer.domElement.clientHeight - rect.bottom;

			renderer.setViewport( left, bottom, width, height );
			renderer.setScissor( left, bottom, width, height );

			var camera = scene.userData.camera;
			scene.userData.controls.update();
			renderer.render( scene, camera );
		} );
	}

	var animate = function() {
		requestAnimationFrame(animate.bind(this));
		render();
	}

	if ( !Detector.webgl ) {
		Detector.addGetWebGLMessage();
	}

	var canvas = document.getElementById(canvasId);
	var scenes = [];
	var renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
	renderer.shadowMap.enabled = true;
	renderer.shadowMap.type = THREE.PCFSoftShadowMap;
	//renderer.shadowMap.cullFace = THREE.CullFaceBack;
	renderer.setClearColor( 0xffffff, 1 );
	renderer.setPixelRatio( window.devicePixelRatio );

	animate();
}
<commit_msg>Delayed init and loading of 3D models until the canvas is on display. Fixes issues in tablets and saves time on phones never displaying the models.<commit_after>
function ModelViewer(canvasId) {

	var createScene = function(elemId, modelName) {
		var element = document.getElementById(elemId);

		var scene = new THREE.Scene();
		scene.userData.element = element;

		var rect = element.getBoundingClientRect();
		var camera = new THREE.PerspectiveCamera( 60, rect.width/rect.height, 0.1, 100 );
		camera.position.x = 0.5;
		camera.position.y = 0.5;
		camera.position.z = -1;
		scene.userData.camera = camera;

		var controls = new THREE.OrbitControls( scene.userData.camera, scene.userData.element );
		controls.minDistance = 2;
		controls.maxDistance = 5;
		controls.enablePan = false;
		controls.enableZoom = false;
		controls.autoRotate = true;
		controls.autoRotateSpeed = 2.0;
		scene.userData.controls = controls;

		var mtlLoader = new THREE.MTLLoader();
		mtlLoader.setBaseUrl( 'assets/' );
		mtlLoader.setPath( 'assets/' );
		mtlLoader.load( modelName + '.mtl', function( materials ) {
			materials.preload();
			var objLoader = new THREE.OBJLoader();
			objLoader.setMaterials( materials );
			objLoader.setPath( 'assets/' );
			objLoader.load( modelName + '.obj', function ( object ) {
				object.traverse(function(obj){
					obj.receiveShadow = true;
					obj.castShadow = true;
				})
				scene.add( object );
			}, function(){}, function(){
				console.log("Ops!");
			} );
		});

		var hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.8 );
		hemiLight.color.setHSL( 0.6, 1, 0.6 );
		hemiLight.groundColor.setHSL( 0.095, 1, 0.75 );
		hemiLight.position.set( 0, 1, 0 );
		scene.add( hemiLight );

		var light = new THREE.DirectionalLight( 0xfffffa, 0.7 );
		light.position.set( 4, 5, 2 );
		light.castShadow = true;
		light.shadow.mapSize.width = 512;
		light.shadow.mapSize.height = 512;
		var shadowWidth = 2;
		light.shadow.camera.left = -shadowWidth;
		light.shadow.camera.right = shadowWidth;
		light.shadow.camera.top = shadowWidth;
		light.shadow.camera.bottom = -shadowWidth;
		light.shadow.camera.far = 20;
		light.shadow.camera.near = 0.1;
		//light.shadow.bias = 0.0001;
		scene.add( light );

		scenes.push( scene );
	}

	this.addScene = function(elemId, modelName) {
		if (renderer !== null) {
			createScene(elemId, modelName);
		} else {
			definitions[elemId] = modelName;
		}
	}

	var updateSize = function() {
		var width = canvas.clientWidth;
		var height = canvas.clientHeight;
		if ( canvas.width !== width || canvas.height !== height ) {
			renderer.setSize( width, height, false );
		}
	}

	var isDisplayed = function() {
		var canvasStyle = window.getComputedStyle(canvas);
		return canvasStyle.display !== 'none';
	}

	var render = function() {
		if (renderer === null || !isDisplayed()) return;

		updateSize();

		renderer.setClearColor( 0xffffff );
		renderer.setScissorTest( false );
		renderer.clear();
		renderer.setScissorTest( true );

		scenes.forEach( function( scene ) {
			var element = scene.userData.element;
			var rect = element.getBoundingClientRect();

			if ( rect.bottom < 0 || rect.top  > renderer.domElement.clientHeight ||
				 rect.right  < 0 || rect.left > renderer.domElement.clientWidth ) {
				return;  // it's off screen
			}

			var width = rect.right - rect.left;
			var height = rect.bottom - rect.top;
			var left  = rect.left;
			var bottom = renderer.domElement.clientHeight - rect.bottom;

			renderer.setViewport( left, bottom, width, height );
			renderer.setScissor( left, bottom, width, height );

			var camera = scene.userData.camera;
			scene.userData.controls.update();
			renderer.render( scene, camera );
		} );
	}

	var init = function() {
		renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
		renderer.shadowMap.enabled = true;
		renderer.shadowMap.type = THREE.PCFSoftShadowMap;
		//renderer.shadowMap.cullFace = THREE.CullFaceBack;
		renderer.setClearColor( 0xffffff, 1 );
		renderer.setPixelRatio( window.devicePixelRatio );

		for (var elemId in definitions) {
			createScene(elemId, definitions[elemId]);
		}
	}

	var animate = function() {
		requestAnimationFrame(animate.bind(this));
		if (renderer === null && isDisplayed()) {
			init();
		}
		render();
	}

	if ( !Detector.webgl ) {
		Detector.addGetWebGLMessage();
	}

	var canvas = document.getElementById(canvasId);
	var scenes = [];
	var renderer = null;
	var definitions = {};

	animate();
}
<|endoftext|>


<commit_before>//Manage the orientation
jviz.modules.karyoviewer.prototype.orientation = function(value)
{
  //Check the orientation value
  if(typeof value !== 'string'){ return this._orientation.actual; }

  //convert to lower case
  value = value.toLowerCase();

  //Save the orientation
  this._orientation.actual = (this._orientation.values.indexOf(value) === -1) ? this._orientation.default : value;

  //Resize the canvas
  this.resize();

  //Continue
  return this;
};

//Check if is landscape
jviz.modules.karyoviewer.prototype.isLandscape = function()
{
  //Check if the actual orientation is landscape
  return this._orientation.actual === 'landscape';
};

//Set landscape orientation
jviz.modules.karyoviewer.prototype.setLandscape = function()
{
  //Set landscape orientation
  return this.orientation('landscape');
};

//Check if orientation is protrait
jviz.modules.karyoviewer.prototype.isPortrait = function()
{
  //Check if actual orientation is portrait
  return this._orientation.actual === 'portrait';
};
<commit_msg>js/orientation.js: set portrait orientation method<commit_after>//Manage the orientation
jviz.modules.karyoviewer.prototype.orientation = function(value)
{
  //Check the orientation value
  if(typeof value !== 'string'){ return this._orientation.actual; }

  //convert to lower case
  value = value.toLowerCase();

  //Save the orientation
  this._orientation.actual = (this._orientation.values.indexOf(value) === -1) ? this._orientation.default : value;

  //Resize the canvas
  this.resize();

  //Continue
  return this;
};

//Check if is landscape
jviz.modules.karyoviewer.prototype.isLandscape = function()
{
  //Check if the actual orientation is landscape
  return this._orientation.actual === 'landscape';
};

//Set landscape orientation
jviz.modules.karyoviewer.prototype.setLandscape = function()
{
  //Set landscape orientation
  return this.orientation('landscape');
};

//Check if orientation is protrait
jviz.modules.karyoviewer.prototype.isPortrait = function()
{
  //Check if actual orientation is portrait
  return this._orientation.actual === 'portrait';
};

//Set portrait orientation
jviz.modules.karyoviewer.prototype.setPortrait = function()
{
  //Set portrait orientation
  return this.orientation('portrait');
};
<|endoftext|>


<commit_before>
/**
 * Common JS
 *
 * LICENSE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Monitoring
 * @author    Cyril Feraudet <cyril@feraudet.com>
 * @copyright 2011 Cyril Feraudet
 * @license   http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
 * @link      http://www.perfwatcher.org/
 **/
var json_item_datas = new Array();
var current_graph = null;
var current_tab = null;
graphid = 0;
var treecollapsed = false;
var contextMenu;
$(document).ready(function() {
	$.ajax({
		async : false, type: 'GET', url: 'action.php',
		data : { 'action': 'get_js', 'tpl': 'json_actions', '_': (new Date()).getTime(), 'id': 0 },
		complete : function (r) {
			if(r.status) {
				var jsfiles = jQuery.parseJSON(r.responseText);
				for (i in jsfiles) {
					$(document).find('head').append('<script type="text/javascript" src="'+jsfiles[i]+'"></script>');
				}
			}
		}
	});
	$('#mainMenu').html(ich.mainMenutpl({}));
	$(ich.contextmenutpl({})).appendTo('body');
	theme = getTheme();
	$('#mainMenu').jqxMenu({ theme: theme });
	$('#mainSplitter').jqxSplitter({
		panels: [{ size: '300px' }],
		theme: theme,
		height: $(document).height() - $('#mainMenu').height() - 1,
		splitBarSize: '2px'
	});
	window.setTimeout(function () {
		auto_refresh_status();
	}, 10000);

	$('#timebutton').html(ich.timebuttontpl({}));
	$('#timebutton').hide();
	$('#timespan').hide();
	$('#timespan').dblclick(function() {
		$(current_graph).pwgraph('applytimespan').pwgraph('display');
		$(this).hide();
	});
	$('#timebutton div div').click(function () {
		var method = $(this).attr('class');
		$(current_graph).pwgraph(method).pwgraph('display');
	});
	$('#datetime').html((new Date).toString()).hide();

	$('#mainSplitter').bind('collapsed', function (event) {
		treecollapsed = true;
	});

	$('li[id^="menu_"]').click(function () {
		//console.log($(this).attr("id"));
		switch($(this).attr("id")) {
			case 'menu_view_new':
				askfor({ title: 'New view name' }, function(title) {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "new_view", "view_title" : title },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								ids = jQuery.parseJSON(r.responseText);
								if((ids['id'] != -1) && (ids['view_id'] != -1)) {
									view_id = ids['view_id'];
									location.hash = "id_"+view_id;
									$('#tree').jstree("refresh");
									notify_ok("New view is created");
								} else {
									notify_ko("New view creation failed");
								}
							}
						}
					});
				});
			break;
			case 'menu_view_open':
				select_view(function() {
						location.hash = "id_"+view_id;
						$('#tree').jstree("refresh");
				});
			break;
			case 'menu_view_delete':
				confirmfor({title: 'Do you really want to delete this view ?'}, function() {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "delete_view", "view_id" : view_id },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								result = jQuery.parseJSON(r.responseText);
								if(result['view_id'] > 0) {
									view_id = result['view_id'];
									location.hash = "id_"+view_id;
									$('#tree').jstree("refresh");
									notify_ok("View deleted");
								} else {
									notify_ko("View could not be deleted");
								}
							}
						}
					});
				});
			break;
			case 'menu_new_tab':
				askfornewtab({ }, function(title, lifetime) {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "add_tab", "view_id" : view_id, "id" : json_item_datas['jstree']['id'], "tab_title" : title == '' ? 'Custom view' : title, "lifetime": lifetime },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								select_node(json_item_datas['jstree']['id']);
								notify_ok("Tab added");
							}
						}
					});
				});
			break;
			case 'menu_rename_node':
				$('#tree').jstree("rename");
			break;
			case 'menu_rename_tab':
			break;
			case 'menu_delete_node':
				confirmfor({title: 'Do you really want to delete this server / container ?'}, function() {
					$('#tree').jstree("remove");
				});
			break;
			case 'menu_delete_tab':
				confirmfor({title: 'Do you really want to delete this tab ?'}, function() {
					if($('div[tabid="'+current_tab+'"]').attr('custom_tab_id')) {
						$.ajax({
							async : false, type: "POST", url: "action.php?tpl=json_actions",
							data : { "action" : "del_tab", "view_id" : view_id, "id" : json_item_datas['jstree']['id'], "tab_id" : $('div[tabid="'+current_tab+'"]').attr('custom_tab_id') },
							complete : function (r) {
								if(!r.status) {
									notify_ko('Error, can\'t retrieve data from server !');
								} else {
									select_node(json_item_datas['jstree']['id']);
									notify_ok("Tab removed");
								}
							}
						});
					}
				});
			break;
			case 'menu_copy':
				$('#tree').jstree("copy");
			break;
			case 'menu_paste':
				$('#tree').jstree("paste");
			break;
			case 'menu_cut':
				$('#tree').jstree("cut");
			break;
			case 'menu_new_server':
				$('#tree').jstree("create", null, "last", { "attr" : { "rel" : "default" } });
			break;
			case 'menu_new_container':
				$('#tree').jstree("create", null, "last", { "attr" : { "rel" : "folder" } });
			break;
			case 'menu_display_toggle_tree':
				if (treecollapsed) {
					$('#mainSplitter').jqxSplitter('expandAt', 0);
					treecollapsed = false;
				} else {
					$('#mainSplitter').jqxSplitter('collapseAt', 0);
					treecollapsed = true;
				}
			break;
			case 'menu_display_in_new_window':
				alert('not implemented yet');
			break;
			case 'menu_refresh_tree':
				$('#tree').jstree("refresh");
			break;
			case 'menu_refresh_node':
				select_node(json_item_datas['jstree']['id']);
			break;
			case 'menu_refresh_status':
				refresh_status();
			break;
			case 'menu_about_box':
				perfwatcher_alert_box();
			break;
			default:
				console.log('Undefined stuff : '+ $(this).attr("id"));
			break;
		}
	});

	$(function () {
		var cache = {}, lastXhr;
		$('#searchtext').autocomplete({
			minLength: 2,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cache ) {
					response( cache[ term ] );
					return;
				}

				lastXhr = $.getJSON( "action.php?tpl=json_actions&action=search&id=0&view_id="+view_id, request, function( data, status, xhr ) {
					cache[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			select: function(event, ui) {
				$('#tree').jstree("search", ui.item.label);
			}
		});
		$('#searchtext').keypress(function(event) {
			if ( event.which == 13 ) {
				 $('#tree').jstree("search", $('#searchtext').val());
				 $('#searchtext').autocomplete("close");
			}
		});
	});

});

<commit_msg>Fixed a bug with about box<commit_after>
/**
 * Common JS
 *
 * LICENSE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Monitoring
 * @author    Cyril Feraudet <cyril@feraudet.com>
 * @copyright 2011 Cyril Feraudet
 * @license   http://www.gnu.org/copyleft/lesser.html  LGPL License 2.1
 * @link      http://www.perfwatcher.org/
 **/
var json_item_datas = new Array();
var current_graph = null;
var current_tab = null;
graphid = 0;
var treecollapsed = false;
var contextMenu;
$(document).ready(function() {
	$.ajax({
		async : false, type: 'GET', url: 'action.php',
		data : { 'action': 'get_js', 'tpl': 'json_actions', '_': (new Date()).getTime(), 'id': 0 },
		complete : function (r) {
			if(r.status) {
				var jsfiles = jQuery.parseJSON(r.responseText);
				for (i in jsfiles) {
					$(document).find('head').append('<script type="text/javascript" src="'+jsfiles[i]+'"></script>');
				}
			}
		}
	});
	$('#mainMenu').html(ich.mainMenutpl({}));
	$(ich.contextmenutpl({})).appendTo('body');
	theme = getTheme();
	$('#mainMenu').jqxMenu({ theme: theme });
	$('#mainSplitter').jqxSplitter({
		panels: [{ size: '300px' }],
		theme: theme,
		height: $(document).height() - $('#mainMenu').height() - 1,
		splitBarSize: '2px'
	});
	window.setTimeout(function () {
		auto_refresh_status();
	}, 10000);

	$('#timebutton').html(ich.timebuttontpl({}));
	$('#timebutton').hide();
	$('#timespan').hide();
	$('#timespan').dblclick(function() {
		$(current_graph).pwgraph('applytimespan').pwgraph('display');
		$(this).hide();
	});
	$('#timebutton div div').click(function () {
		var method = $(this).attr('class');
		$(current_graph).pwgraph(method).pwgraph('display');
	});
	$('#datetime').html((new Date).toString()).hide();

	$('#mainSplitter').bind('collapsed', function (event) {
		treecollapsed = true;
	});

	$('li[id^="menu_"]').click(function () {
		//console.log($(this).attr("id"));
		switch($(this).attr("id")) {
			case 'menu_view_new':
				askfor({ title: 'New view name' }, function(title) {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "new_view", "view_title" : title },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								ids = jQuery.parseJSON(r.responseText);
								if((ids['id'] != -1) && (ids['view_id'] != -1)) {
									view_id = ids['view_id'];
									location.hash = "id_"+view_id;
									$('#tree').jstree("refresh");
									notify_ok("New view is created");
								} else {
									notify_ko("New view creation failed");
								}
							}
						}
					});
				});
			break;
			case 'menu_view_open':
				select_view(function() {
						location.hash = "id_"+view_id;
						$('#tree').jstree("refresh");
				});
			break;
			case 'menu_view_delete':
				confirmfor({title: 'Do you really want to delete this view ?'}, function() {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "delete_view", "view_id" : view_id },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								result = jQuery.parseJSON(r.responseText);
								if(result['view_id'] > 0) {
									view_id = result['view_id'];
									location.hash = "id_"+view_id;
									$('#tree').jstree("refresh");
									notify_ok("View deleted");
								} else {
									notify_ko("View could not be deleted");
								}
							}
						}
					});
				});
			break;
			case 'menu_new_tab':
				askfornewtab({ }, function(title, lifetime) {
					$.ajax({
						async : false, type: "POST", url: "action.php?tpl=json_actions",
						data : { "action" : "add_tab", "view_id" : view_id, "id" : json_item_datas['jstree']['id'], "tab_title" : title == '' ? 'Custom view' : title, "lifetime": lifetime },
						complete : function (r) {
							if(!r.status) {
								notify_ko('Error, can\'t retrieve data from server !');
							} else {
								select_node(json_item_datas['jstree']['id']);
								notify_ok("Tab added");
							}
						}
					});
				});
			break;
			case 'menu_rename_node':
				$('#tree').jstree("rename");
			break;
			case 'menu_rename_tab':
			break;
			case 'menu_delete_node':
				confirmfor({title: 'Do you really want to delete this server / container ?'}, function() {
					$('#tree').jstree("remove");
				});
			break;
			case 'menu_delete_tab':
				confirmfor({title: 'Do you really want to delete this tab ?'}, function() {
					if($('div[tabid="'+current_tab+'"]').attr('custom_tab_id')) {
						$.ajax({
							async : false, type: "POST", url: "action.php?tpl=json_actions",
							data : { "action" : "del_tab", "view_id" : view_id, "id" : json_item_datas['jstree']['id'], "tab_id" : $('div[tabid="'+current_tab+'"]').attr('custom_tab_id') },
							complete : function (r) {
								if(!r.status) {
									notify_ko('Error, can\'t retrieve data from server !');
								} else {
									select_node(json_item_datas['jstree']['id']);
									notify_ok("Tab removed");
								}
							}
						});
					}
				});
			break;
			case 'menu_copy':
				$('#tree').jstree("copy");
			break;
			case 'menu_paste':
				$('#tree').jstree("paste");
			break;
			case 'menu_cut':
				$('#tree').jstree("cut");
			break;
			case 'menu_new_server':
				$('#tree').jstree("create", null, "last", { "attr" : { "rel" : "default" } });
			break;
			case 'menu_new_container':
				$('#tree').jstree("create", null, "last", { "attr" : { "rel" : "folder" } });
			break;
			case 'menu_display_toggle_tree':
				if (treecollapsed) {
					$('#mainSplitter').jqxSplitter('expandAt', 0);
					treecollapsed = false;
				} else {
					$('#mainSplitter').jqxSplitter('collapseAt', 0);
					treecollapsed = true;
				}
			break;
			case 'menu_display_in_new_window':
				alert('not implemented yet');
			break;
			case 'menu_refresh_tree':
				$('#tree').jstree("refresh");
			break;
			case 'menu_refresh_node':
				select_node(json_item_datas['jstree']['id']);
			break;
			case 'menu_refresh_status':
				refresh_status();
			break;
			case 'menu_about_box':
				perfwatcher_about_box();
			break;
			default:
				console.log('Undefined stuff : '+ $(this).attr("id"));
			break;
		}
	});

	$(function () {
		var cache = {}, lastXhr;
		$('#searchtext').autocomplete({
			minLength: 2,
			source: function( request, response ) {
				var term = request.term;
				if ( term in cache ) {
					response( cache[ term ] );
					return;
				}

				lastXhr = $.getJSON( "action.php?tpl=json_actions&action=search&id=0&view_id="+view_id, request, function( data, status, xhr ) {
					cache[ term ] = data;
					if ( xhr === lastXhr ) {
						response( data );
					}
				});
			},
			select: function(event, ui) {
				$('#tree').jstree("search", ui.item.label);
			}
		});
		$('#searchtext').keypress(function(event) {
			if ( event.which == 13 ) {
				 $('#tree').jstree("search", $('#searchtext').val());
				 $('#searchtext').autocomplete("close");
			}
		});
	});

});

<|endoftext|>


<commit_before>// Copyright 2002-2012, University of Colorado

/**
 * Draws an arc.
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'kite' );

  var kite = require( 'KITE/kite' );

  var Vector2 = require( 'DOT/Vector2' );

  var Piece = require( 'KITE/pieces/Piece' );
  require( 'KITE/pieces/MoveTo' );
  require( 'KITE/pieces/Close' );
  require( 'KITE/util/Subpath' );
  require( 'KITE/segments/Line' );

  // for brevity
  function p( x,y ) { return new Vector2( x, y ); }

  Piece.Rect = function( x, y, width, height ) {
    assert && assert( x !== undefined && y !== undefined && width !== undefined && height !== undefined, 'Undefined argument for Piece.Rect' );
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  };
  Piece.Rect.prototype = {
    constructor: Piece.Rect,

    writeToContext: function( context ) {
      context.rect( this.x, this.y, this.width, this.height );
    },

    transformed: function( matrix ) {
      var a = matrix.timesVector2( p( this.x, this.y ) );
      var b = matrix.timesVector2( p( this.x + this.width, this.y ) );
      var c = matrix.timesVector2( p( this.x + this.width, this.y + this.height ) );
      var d = matrix.timesVector2( p( this.x, this.y + this.height ) );
      return [new Piece.MoveTo( a ), new Piece.LineTo( b ), new Piece.LineTo( c ), new Piece.LineTo( d ), new Piece.Close(), new Piece.MoveTo( a )];
    },

    applyPiece: function( shape ) {
      var subpath = new kite.Subpath();
      shape.addSubpath( subpath );
      subpath.addPoint( p( this.x, this.y ) );
      subpath.addPoint( p( this.x + this.width, this.y ) );
      subpath.addPoint( p( this.x + this.width, this.y + this.height ) );
      subpath.addPoint( p( this.x, this.y + this.height ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[0], subpath.points[1] ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[1], subpath.points[2] ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[2], subpath.points[3] ) );
      subpath.close();
      shape.addSubpath( new kite.Subpath() );
      shape.getLastSubpath().addPoint( p( this.x, this.y ) );
      shape.bounds = shape.bounds.withCoordinates( this.x, this.y ).withCoordinates( this.x + this.width, this.y + this.height );
      assert && assert( !isNaN( shape.bounds.getX() ) );
    }
  };

  return Piece.Rect;
} );
<commit_msg>fix doc for kite.pieces.Rect<commit_after>// Copyright 2002-2012, University of Colorado

/**
 * Draws a rectangle.
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'kite' );

  var kite = require( 'KITE/kite' );

  var Vector2 = require( 'DOT/Vector2' );

  var Piece = require( 'KITE/pieces/Piece' );
  require( 'KITE/pieces/MoveTo' );
  require( 'KITE/pieces/Close' );
  require( 'KITE/util/Subpath' );
  require( 'KITE/segments/Line' );

  // for brevity
  function p( x,y ) { return new Vector2( x, y ); }

  Piece.Rect = function( x, y, width, height ) {
    assert && assert( x !== undefined && y !== undefined && width !== undefined && height !== undefined, 'Undefined argument for Piece.Rect' );
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  };
  Piece.Rect.prototype = {
    constructor: Piece.Rect,

    writeToContext: function( context ) {
      context.rect( this.x, this.y, this.width, this.height );
    },

    transformed: function( matrix ) {
      var a = matrix.timesVector2( p( this.x, this.y ) );
      var b = matrix.timesVector2( p( this.x + this.width, this.y ) );
      var c = matrix.timesVector2( p( this.x + this.width, this.y + this.height ) );
      var d = matrix.timesVector2( p( this.x, this.y + this.height ) );
      return [new Piece.MoveTo( a ), new Piece.LineTo( b ), new Piece.LineTo( c ), new Piece.LineTo( d ), new Piece.Close(), new Piece.MoveTo( a )];
    },

    applyPiece: function( shape ) {
      var subpath = new kite.Subpath();
      shape.addSubpath( subpath );
      subpath.addPoint( p( this.x, this.y ) );
      subpath.addPoint( p( this.x + this.width, this.y ) );
      subpath.addPoint( p( this.x + this.width, this.y + this.height ) );
      subpath.addPoint( p( this.x, this.y + this.height ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[0], subpath.points[1] ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[1], subpath.points[2] ) );
      subpath.addSegment( new kite.Segment.Line( subpath.points[2], subpath.points[3] ) );
      subpath.close();
      shape.addSubpath( new kite.Subpath() );
      shape.getLastSubpath().addPoint( p( this.x, this.y ) );
      shape.bounds = shape.bounds.withCoordinates( this.x, this.y ).withCoordinates( this.x + this.width, this.y + this.height );
      assert && assert( !isNaN( shape.bounds.getX() ) );
    }
  };

  return Piece.Rect;
} );
<|endoftext|>


<commit_before>window.fbAsyncInit = function() {
    FB.init({
      appId      : '1199157660137686',
      xfbml      : true,
      version    : 'v2.5'
    });

    FB.getLoginStatus(function(response) {
        handleLoginStatusResponse(response);
    });
};

(function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = 'http://connect.facebook.net/en_US/sdk.js';
     fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Preferred profile image size
var IMAGE_SIZE = 480;
// Final image, i.e. profile image with overlay
var finalImage;
// Object received from successful authorization (includes userID and access token)
var authData;

function handleLoginStatusResponse(response) {
    var profileImageElement = document.getElementById('profile_image');
    var placeholderUrl = 'images/placeholder.png';
    var loginButton = document.getElementById('login_button');
    var logoutButton = document.getElementById('logout_button');
    var uploadDiv = document.getElementById('upload_div');

    if (response.status === 'connected') {
        // Logged into the app and Facebook.
        setAlertMessage('');
        authData = response.authResponse;
        createFinalImage(authData.userID);
        loginButton.style.display = 'none';
        logoutButton.style.display = 'inline-block';
        uploadDiv.style.display = 'block';
    } else {
        if (response.status === 'not_authorized') {
            setAlertMessage('Please log into this app');
        } else {
            setAlertMessage('Please log into Facebook');
        }

        profileImageElement.src = placeholderUrl;
        loginButton.style.display = 'inline-block';
        logoutButton.style.display = 'none';
        uploadDiv.style.display = 'none';
    }
}

function createFinalImage(userID) {
    var profilePic = new Image();
    profilePic.setAttribute('crossOrigin', 'anonymous');
    profilePic.src = 'http://graph.facebook.com/' + userID
        + '/picture?type=square&width=' + IMAGE_SIZE + '&height=' + IMAGE_SIZE;

    profilePic.onload = function() {
        canvas = document.createElement('canvas');
        canvas.width = IMAGE_SIZE;
        canvas.height = IMAGE_SIZE;
        var context = canvas.getContext('2d');
        context.drawImage(profilePic, 0, 0, profilePic.width, profilePic.height, 0, 0, IMAGE_SIZE, IMAGE_SIZE);
        var overlay = new Image();
        overlay.src = 'images/overlay.png';
        overlay.onload = function() {
            context.drawImage(overlay, 0, 0);
            finalImage = canvas.toDataURL('image/jpeg', 0.8);
            document.getElementById('profile_image').src = finalImage;
        }
    }
}

var uploadInProgress = false;

function uploadImage() {
    if (uploadInProgress) return;

    makeSpinnerVisible(true);
    setAlertMessage('');
    uploadInProgress = true;

    var formData = prepareUploadFormData();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload.php');
    xhr.onload = function() {
        makeSpinnerVisible(false);
        uploadInProgress = false;
        if (xhr.status != 200) {
            reportUploadError('Network error ' + xhr.status);
            return;
        }
        var response = JSON.parse(xhr.responseText);
        if (response.success) {
            handleUploadSuccess(response.photo_id);
        } else {
            reportUploadError(response.error);
        }
    };
    xhr.send(formData);
}

function prepareUploadFormData() {
    var message = document.getElementById('message_area').value;
    var shouldPost = document.getElementById('should_post_checkbox').checked;
    var formData = new FormData();
    formData.append('img', dataURLtoBlob(finalImage));
    formData.append('token', authData.accessToken);
    formData.append('message', message);
    formData.append('should_post', shouldPost);
    return formData;
}

function handleUploadSuccess(photo_id) {
    // Redirecting this window to Facebook page showing our just-uploaded image with overlay.
    // There the user will be able to set it as their profile image.
    document.location.assign('https://www.facebook.com/photo.php?fbid=' + photo_id + '&makeprofile=1');
}

function reportUploadError(errorMessage) {
    setAlertMessage('Upload failed: ' + errorMessage)
}

function setAlertMessage(message) {
    document.getElementById('status_div').innerHTML = message;
}

function makeSpinnerVisible(visible) {
    var spinner = document.getElementById('spinner');
    spinner.style.display = (visible) ? 'block' : 'none';
}

// From http://stackoverflow.com/a/30470303/2857040
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

function logIn() {
    FB.login(handleLoginStatusResponse, {scope: 'user_photos,publish_actions'});
}

function logOut() {
    FB.api('/me/permissions', 'delete', function(response){
        handleLoginStatusResponse({status: 'not_authorized'});
    });
}<commit_msg>Made app ID more prominent in JavaScript file<commit_after>// Facebook app ID
var APP_ID = '1199157660137686';
// Preferred profile image size
var IMAGE_SIZE = 480;

window.fbAsyncInit = function() {
    FB.init({
      appId      : APP_ID,
      xfbml      : true,
      version    : 'v2.5'
    });

    FB.getLoginStatus(function(response) {
        handleLoginStatusResponse(response);
    });
};

(function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = 'http://connect.facebook.net/en_US/sdk.js';
     fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Final image, i.e. profile image with overlay
var finalImage;
// Object received from successful authorization (includes userID and access token)
var authData;

function handleLoginStatusResponse(response) {
    var profileImageElement = document.getElementById('profile_image');
    var placeholderUrl = 'images/placeholder.png';
    var loginButton = document.getElementById('login_button');
    var logoutButton = document.getElementById('logout_button');
    var uploadDiv = document.getElementById('upload_div');

    if (response.status === 'connected') {
        // Logged into the app and Facebook.
        setAlertMessage('');
        authData = response.authResponse;
        createFinalImage(authData.userID);
        loginButton.style.display = 'none';
        logoutButton.style.display = 'inline-block';
        uploadDiv.style.display = 'block';
    } else {
        if (response.status === 'not_authorized') {
            setAlertMessage('Please log into this app');
        } else {
            setAlertMessage('Please log into Facebook');
        }

        profileImageElement.src = placeholderUrl;
        loginButton.style.display = 'inline-block';
        logoutButton.style.display = 'none';
        uploadDiv.style.display = 'none';
    }
}

function createFinalImage(userID) {
    var profilePic = new Image();
    profilePic.setAttribute('crossOrigin', 'anonymous');
    profilePic.src = 'http://graph.facebook.com/' + userID
        + '/picture?type=square&width=' + IMAGE_SIZE + '&height=' + IMAGE_SIZE;

    profilePic.onload = function() {
        canvas = document.createElement('canvas');
        canvas.width = IMAGE_SIZE;
        canvas.height = IMAGE_SIZE;
        var context = canvas.getContext('2d');
        context.drawImage(profilePic, 0, 0, profilePic.width, profilePic.height, 0, 0, IMAGE_SIZE, IMAGE_SIZE);
        var overlay = new Image();
        overlay.src = 'images/overlay.png';
        overlay.onload = function() {
            context.drawImage(overlay, 0, 0);
            finalImage = canvas.toDataURL('image/jpeg', 0.8);
            document.getElementById('profile_image').src = finalImage;
        }
    }
}

var uploadInProgress = false;

function uploadImage() {
    if (uploadInProgress) return;

    makeSpinnerVisible(true);
    setAlertMessage('');
    uploadInProgress = true;

    var formData = prepareUploadFormData();
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload.php');
    xhr.onload = function() {
        makeSpinnerVisible(false);
        uploadInProgress = false;
        if (xhr.status != 200) {
            reportUploadError('Network error ' + xhr.status);
            return;
        }
        var response = JSON.parse(xhr.responseText);
        if (response.success) {
            handleUploadSuccess(response.photo_id);
        } else {
            reportUploadError(response.error);
        }
    };
    xhr.send(formData);
}

function prepareUploadFormData() {
    var message = document.getElementById('message_area').value;
    var shouldPost = document.getElementById('should_post_checkbox').checked;
    var formData = new FormData();
    formData.append('img', dataURLtoBlob(finalImage));
    formData.append('token', authData.accessToken);
    formData.append('message', message);
    formData.append('should_post', shouldPost);
    return formData;
}

function handleUploadSuccess(photo_id) {
    // Redirecting this window to Facebook page showing our just-uploaded image with overlay.
    // There the user will be able to set it as their profile image.
    document.location.assign('https://www.facebook.com/photo.php?fbid=' + photo_id + '&makeprofile=1');
}

function reportUploadError(errorMessage) {
    setAlertMessage('Upload failed: ' + errorMessage)
}

function setAlertMessage(message) {
    document.getElementById('status_div').innerHTML = message;
}

function makeSpinnerVisible(visible) {
    var spinner = document.getElementById('spinner');
    spinner.style.display = (visible) ? 'block' : 'none';
}

// From http://stackoverflow.com/a/30470303/2857040
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

function logIn() {
    FB.login(handleLoginStatusResponse, {scope: 'user_photos,publish_actions'});
}

function logOut() {
    FB.api('/me/permissions', 'delete', function(response){
        handleLoginStatusResponse({status: 'not_authorized'});
    });
}<|endoftext|>


<commit_before>import adagioAnalyticsAdapter from 'modules/adagioAnalyticsAdapter';
import { expect } from 'chai';
import * as utils from 'src/utils';

let adapterManager = require('src/adapterManager').default;
let events = require('src/events');
let constants = require('src/constants.json');

describe.skip('adagio analytics adapter', () => {
  let xhr;
  let requests;
  let sandbox

  beforeEach(() => {
    sandbox = sinon.createSandbox();

    xhr = sandbox.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = request => requests.push(request);
    sandbox.stub(events, 'getEvents').returns([]);

    adapterManager.registerAnalyticsAdapter({
      code: 'adagio',
      adapter: adagioAnalyticsAdapter
    });
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('track', () => {
    beforeEach(() => {
      adapterManager.enableAnalytics({
        provider: 'adagio'
      });
    });

    afterEach(() => {
      adagioAnalyticsAdapter.disableAnalytics();
    });

    it('builds and sends auction data', () => {
      const w = utils.getWindowTop();

      let bidRequest = {
        bids: [{
          adUnitCode: 'div-1',
          params: {
            features: {
              siteId: '2',
              placement: 'pave_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          }
        }, {
          adUnitCode: 'div-2',
          params: {
            features: {
              siteId: '2',
              placement: 'ban_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          },
        }],
      };
      let bidResponse = {
        bidderCode: 'adagio',
        width: 300,
        height: 250,
        statusMessage: 'Bid available',
        cpm: 6.2189757658226075,
        currency: '',
        netRevenue: false,
        adUnitCode: 'div-1',
        timeToRespond: 132,
      };

      // Step 1: Send bid requested event
      events.emit(constants.EVENTS.BID_REQUESTED, bidRequest);

      // Step 2: Send bid response event
      events.emit(constants.EVENTS.BID_RESPONSE, bidResponse);

      // Step 3: Send auction end event
      events.emit(constants.EVENTS.AUCTION_END, {});

      expect(w.ADAGIO.queue).length(3);

      let o = w.ADAGIO.queue.shift();
      expect(o).to.not.be.undefined;
      expect(o.action).to.equal('pb-analytics-event');
      expect(o.ts).to.not.be.undefined;
      expect(o.data).to.not.be.undefined;
      expect(o.data).to.deep.equal({eventName: constants.EVENTS.BID_REQUESTED, args: bidRequest});

      o = w.ADAGIO.queue.shift();
      expect(o).to.not.be.undefined;
      expect(o.action).to.equal('pb-analytics-event');
      expect(o.ts).to.not.be.undefined;
      expect(o.data).to.not.be.undefined;
      expect(o.data).to.deep.equal({eventName: constants.EVENTS.BID_RESPONSE, args: bidResponse});

      o = w.ADAGIO.queue.shift();
      expect(o).to.not.be.undefined;
      expect(o.action).to.equal('pb-analytics-event');
      expect(o.ts).to.not.be.undefined;
      expect(o.data).to.not.be.undefined;
      expect(o.data).to.deep.equal({eventName: constants.EVENTS.AUCTION_END, args: {}});
    });
  });

  describe('no track', () => {
    beforeEach(() => {
      sandbox.stub(utils, 'getWindowTop').throws();

      adapterManager.enableAnalytics({
        provider: 'adagio'
      });
    });

    afterEach(() => {
      adagioAnalyticsAdapter.disableAnalytics();
      sandbox.restore();
    });

    it('builds and sends auction data', () => {
      let bidRequest = {
        bids: [{
          adUnitCode: 'div-1',
          params: {
            features: {
              siteId: '2',
              placement: 'pave_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          }
        }, {
          adUnitCode: 'div-2',
          params: {
            features: {
              siteId: '2',
              placement: 'ban_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          },
        }],
      };
      let bidResponse = {
        bidderCode: 'adagio',
        width: 300,
        height: 250,
        statusMessage: 'Bid available',
        cpm: 6.2189757658226075,
        currency: '',
        netRevenue: false,
        adUnitCode: 'div-1',
        timeToRespond: 132,
      };

      // Step 1: Send bid requested event
      events.emit(constants.EVENTS.BID_REQUESTED, bidRequest);

      // Step 2: Send bid response event
      events.emit(constants.EVENTS.BID_RESPONSE, bidResponse);

      // Step 3: Send auction end event
      events.emit(constants.EVENTS.AUCTION_END, {});

      utils.getWindowTop.restore();

      expect(utils.getWindowTop().ADAGIO.queue).length(0);
    });
  });
});
<commit_msg>adagioAnalyticsAdapter: fix inconsistent tests (#4417)<commit_after>import adagioAnalyticsAdapter from 'modules/adagioAnalyticsAdapter';
import { expect } from 'chai';
import * as utils from 'src/utils';

let adapterManager = require('src/adapterManager').default;
let events = require('src/events');
let constants = require('src/constants.json');

describe('adagio analytics adapter', () => {
  let xhr;
  let requests;
  let sandbox
  let adagioQueuePushSpy;

  beforeEach(() => {
    sandbox = sinon.createSandbox();

    xhr = sandbox.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = request => requests.push(request);
    sandbox.stub(events, 'getEvents').returns([]);

    const w = utils.getWindowTop();

    adapterManager.registerAnalyticsAdapter({
      code: 'adagio',
      adapter: adagioAnalyticsAdapter
    });

    w.ADAGIO = w.ADAGIO || {};
    w.ADAGIO.queue = w.ADAGIO.queue || [];

    adagioQueuePushSpy = sandbox.spy(w.ADAGIO.queue, 'push');
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('track', () => {
    beforeEach(() => {
      adapterManager.enableAnalytics({
        provider: 'adagio'
      });
    });

    afterEach(() => {
      adagioAnalyticsAdapter.disableAnalytics();
    });

    it('builds and sends auction data', () => {
      const w = utils.getWindowTop();

      let bidRequest = {
        bids: [{
          adUnitCode: 'div-1',
          params: {
            features: {
              siteId: '2',
              placement: 'pave_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          }
        }, {
          adUnitCode: 'div-2',
          params: {
            features: {
              siteId: '2',
              placement: 'ban_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          },
        }],
      };
      let bidResponse = {
        bidderCode: 'adagio',
        width: 300,
        height: 250,
        statusMessage: 'Bid available',
        cpm: 6.2189757658226075,
        currency: '',
        netRevenue: false,
        adUnitCode: 'div-1',
        timeToRespond: 132,
      };

      // Step 1: Send bid requested event
      events.emit(constants.EVENTS.BID_REQUESTED, bidRequest);

      // Step 2: Send bid response event
      events.emit(constants.EVENTS.BID_RESPONSE, bidResponse);

      // Step 3: Send auction end event
      events.emit(constants.EVENTS.AUCTION_END, {});

      sandbox.assert.callCount(adagioQueuePushSpy, 3);

      const call0 = adagioQueuePushSpy.getCall(0);
      expect(call0.args[0].action).to.equal('pb-analytics-event');
      expect(call0.args[0].ts).to.not.be.undefined;
      expect(call0.args[0].data).to.not.be.undefined;
      expect(call0.args[0].data).to.deep.equal({eventName: constants.EVENTS.BID_REQUESTED, args: bidRequest});

      const call1 = adagioQueuePushSpy.getCall(1);
      expect(call1.args[0].action).to.equal('pb-analytics-event');
      expect(call1.args[0].ts).to.not.be.undefined;
      expect(call1.args[0].data).to.not.be.undefined;
      expect(call1.args[0].data).to.deep.equal({eventName: constants.EVENTS.BID_RESPONSE, args: bidResponse});

      const call2 = adagioQueuePushSpy.getCall(2);
      expect(call2.args[0].action).to.equal('pb-analytics-event');
      expect(call2.args[0].ts).to.not.be.undefined;
      expect(call2.args[0].data).to.not.be.undefined;
      expect(call2.args[0].data).to.deep.equal({eventName: constants.EVENTS.AUCTION_END, args: {}});
    });
  });

  describe('no track', () => {
    beforeEach(() => {
      sandbox.stub(utils, 'getWindowTop').throws();

      adapterManager.enableAnalytics({
        provider: 'adagio'
      });
    });

    afterEach(() => {
      adagioAnalyticsAdapter.disableAnalytics();
      sandbox.restore();
    });

    it('builds and sends auction data', () => {
      let bidRequest = {
        bids: [{
          adUnitCode: 'div-1',
          params: {
            features: {
              siteId: '2',
              placement: 'pave_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          }
        }, {
          adUnitCode: 'div-2',
          params: {
            features: {
              siteId: '2',
              placement: 'ban_top',
              pagetype: 'article',
              category: 'IAB12,IAB12-2',
              device: '2',
            }
          },
        }],
      };
      let bidResponse = {
        bidderCode: 'adagio',
        width: 300,
        height: 250,
        statusMessage: 'Bid available',
        cpm: 6.2189757658226075,
        currency: '',
        netRevenue: false,
        adUnitCode: 'div-1',
        timeToRespond: 132,
      };

      // Step 1: Send bid requested event
      events.emit(constants.EVENTS.BID_REQUESTED, bidRequest);

      // Step 2: Send bid response event
      events.emit(constants.EVENTS.BID_RESPONSE, bidResponse);

      // Step 3: Send auction end event
      events.emit(constants.EVENTS.AUCTION_END, {});

      utils.getWindowTop.restore();

      sandbox.assert.callCount(adagioQueuePushSpy, 0);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * USB Disk manager.
 * @constructor
 */
function usbdisk(){

    this.mounted = false;
    this.onmount_callbacks  = [];
    this.onumount_callbacks = [];

    this.dirs  = [];
    this.files = [];

    try{
        stb.SetListFilesExt('.mpg .mkv .avi .ts .mp4 .wmv .mp3 .ac3 .mov .vob .wav');
    }catch(e){
        _debug(e);
    }

    var self = this;

    (function(){
        try{
            self.drive_mounted();
        }catch(e){
            _debug(e);
        }
    }).bind(key.USB_MOUNTED);

    (function(){
        self.drive_umounted();
    }).bind(key.USB_UNMOUNTED);

    this.check_mounted();
}

usbdisk.prototype.drive_mounted = function(){
    _debug('usbdisk.drive_mounted');

    this.mounted = true;

    stb.notice.show(word['mbrowser_title'] + ' ' + word['mbrowser_connected']);

    var self = this;

    window.setTimeout(function(){self.fire_onmount_callbacks()}, 100);
}

usbdisk.prototype.drive_umounted = function(){
    _debug('usbdisk.drive_umounted');

    this.mounted = false;

    stb.notice.show(word['mbrowser_title'] + ' ' + word['mbrowser_disconnected']);

    this.fire_onumount_callbacks();
}

usbdisk.prototype.is_drive_mounted = function(){
    _debug('usbdisk.is_drive_mounted');

    if (this.mounted){
        return true;
    }

    return false;
}

usbdisk.prototype.check_mounted = function(){
    _debug('usbdisk.check_mounted');

    try{

        var list = this.read_dir("/media/usbdisk/");

        for (var i=0; i < list.length; i++){
            if (!empty(list[i])){
                this.drive_mounted();
                return;
            }
        }
    }catch(e){
        _debug(e);
    }

    return;
}

usbdisk.prototype.read_dir = function(path){
    _debug('usbdisk.read_dir');

    try{

        var txt = stb.ListDir(path);

        _debug(txt);

        eval(txt);

        this.dirs = dirs;
        this.files = files;

        return this.dirs.concat(this.files);
    }catch(e){
        _debug(e);
    }
}

usbdisk.prototype.add_onmount_callback = function(func){
    _debug('usbdisk.add_onmount_callback');

    this.onmount_callbacks.push(func);
}

usbdisk.prototype.add_onumount_callback = function(func){
    _debug('usbdisk.add_onumount_callback');

    this.onumount_callbacks.push(func);
}

usbdisk.prototype.fire_onmount_callbacks = function(){
    _debug('usbdisk.fire_onmount_callbacks')

    for(var i=0; i<this.onmount_callbacks.length; i++){
        this.onmount_callbacks[i]();
    }
}

usbdisk.prototype.fire_onumount_callbacks = function(){
    _debug('usbdisk.fire_onumount_callbacks');

    for(var i=0; i<this.onumount_callbacks.length; i++){
        this.onumount_callbacks[i]();
    }
}<commit_msg>"Replace all word[] on get_word()"<commit_after>/**
 * USB Disk manager.
 * @constructor
 */
function usbdisk(){

    this.mounted = false;
    this.onmount_callbacks  = [];
    this.onumount_callbacks = [];

    this.dirs  = [];
    this.files = [];

    try{
        stb.SetListFilesExt('.mpg .mkv .avi .ts .mp4 .wmv .mp3 .ac3 .mov .vob .wav');
    }catch(e){
        _debug(e);
    }

    var self = this;

    (function(){
        try{
            self.drive_mounted();
        }catch(e){
            _debug(e);
        }
    }).bind(key.USB_MOUNTED);

    (function(){
        self.drive_umounted();
    }).bind(key.USB_UNMOUNTED);

    this.check_mounted();
}

usbdisk.prototype.drive_mounted = function(){
    _debug('usbdisk.drive_mounted');

    this.mounted = true;

    stb.notice.show(get_word('mbrowser_title') + ' ' + get_word('mbrowser_connected'));

    var self = this;

    window.setTimeout(function(){self.fire_onmount_callbacks()}, 100);
}

usbdisk.prototype.drive_umounted = function(){
    _debug('usbdisk.drive_umounted');

    this.mounted = false;

    stb.notice.show(get_word('mbrowser_title') + ' ' + get_word('mbrowser_disconnected'));

    this.fire_onumount_callbacks();
}

usbdisk.prototype.is_drive_mounted = function(){
    _debug('usbdisk.is_drive_mounted');

    if (this.mounted){
        return true;
    }

    return false;
}

usbdisk.prototype.check_mounted = function(){
    _debug('usbdisk.check_mounted');

    try{

        var list = this.read_dir("/media/usbdisk/");

        for (var i=0; i < list.length; i++){
            if (!empty(list[i])){
                this.drive_mounted();
                return;
            }
        }
    }catch(e){
        _debug(e);
    }

    return;
}

usbdisk.prototype.read_dir = function(path){
    _debug('usbdisk.read_dir');

    try{

        var txt = stb.ListDir(path);

        _debug(txt);

        eval(txt);

        this.dirs = dirs;
        this.files = files;

        return this.dirs.concat(this.files);
    }catch(e){
        _debug(e);
    }
}

usbdisk.prototype.add_onmount_callback = function(func){
    _debug('usbdisk.add_onmount_callback');

    this.onmount_callbacks.push(func);
}

usbdisk.prototype.add_onumount_callback = function(func){
    _debug('usbdisk.add_onumount_callback');

    this.onumount_callbacks.push(func);
}

usbdisk.prototype.fire_onmount_callbacks = function(){
    _debug('usbdisk.fire_onmount_callbacks')

    for(var i=0; i<this.onmount_callbacks.length; i++){
        this.onmount_callbacks[i]();
    }
}

usbdisk.prototype.fire_onumount_callbacks = function(){
    _debug('usbdisk.fire_onumount_callbacks');

    for(var i=0; i<this.onumount_callbacks.length; i++){
        this.onumount_callbacks[i]();
    }
}<|endoftext|>


<commit_before>import {getUid} from '../../../../../src/ol/index.js';
import Feature from '../../../../../src/ol/Feature.js';
import Map from '../../../../../src/ol/Map.js';
import View from '../../../../../src/ol/View.js';
import {buffer as bufferExtent, getWidth} from '../../../../../src/ol/extent.js';
import Point from '../../../../../src/ol/geom/Point.js';
import VectorLayer from '../../../../../src/ol/layer/Vector.js';
import {clear} from '../../../../../src/ol/obj.js';
import {get as getProjection} from '../../../../../src/ol/proj.js';
import {checkedFonts} from '../../../../../src/ol/render/canvas.js';
import CanvasVectorLayerRenderer from '../../../../../src/ol/renderer/canvas/VectorLayer.js';
import VectorSource from '../../../../../src/ol/source/Vector.js';
import Style from '../../../../../src/ol/style/Style.js';
import Text from '../../../../../src/ol/style/Text.js';

describe('ol.renderer.canvas.VectorLayer', function() {

  describe('constructor', function() {

    const head = document.getElementsByTagName('head')[0];
    const font = document.createElement('link');
    font.href = 'https://fonts.googleapis.com/css?family=Droid+Sans';
    font.rel = 'stylesheet';

    let target;

    beforeEach(function() {
      target = document.createElement('div');
      target.style.width = '256px';
      target.style.height = '256px';
      document.body.appendChild(target);
    });

    afterEach(function() {
      document.body.removeChild(target);
    });

    it('creates a new instance', function() {
      const layer = new VectorLayer({
        source: new VectorSource()
      });
      const renderer = new CanvasVectorLayerRenderer(layer);
      expect(renderer).to.be.a(CanvasVectorLayerRenderer);
    });

    it('gives precedence to feature styles over layer styles', function() {
      const target = document.createElement('div');
      target.style.width = '256px';
      target.style.height = '256px';
      document.body.appendChild(target);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = [new Style({
        text: new Text({
          text: 'layer'
        })
      })];
      const featureStyle = [new Style({
        text: new Text({
          text: 'feature'
        })
      })];
      const feature1 = new Feature(new Point([0, 0]));
      const feature2 = new Feature(new Point([0, 0]));
      feature2.setStyle(featureStyle);
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature1, feature2]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const spy = sinon.spy(map.getRenderer().getLayerRenderer(layer),
        'renderFeature');
      map.renderSync();
      expect(spy.getCall(0).args[3]).to.be(layerStyle);
      expect(spy.getCall(1).args[3]).to.be(featureStyle);
      document.body.removeChild(target);
    });

    it('does not re-render for unavailable fonts', function(done) {
      clear(checkedFonts);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px "Unavailable Font",sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision);
        done();
      }, 800);
    });

    it('does not re-render for available fonts', function(done) {
      clear(checkedFonts);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision);
        done();
      }, 800);
    });

    it('re-renders for fonts that become available', function(done) {
      clear(checkedFonts);
      head.appendChild(font);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px "Droid Sans",sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision + 1);
        head.removeChild(font);
        done();
      }, 1600);
    });

  });

  describe('#forEachFeatureAtCoordinate', function() {
    let layer, renderer;

    beforeEach(function() {
      layer = new VectorLayer({
        source: new VectorSource()
      });
      renderer = new CanvasVectorLayerRenderer(layer);
      const replayGroup = {};
      renderer.replayGroup_ = replayGroup;
      replayGroup.forEachFeatureAtCoordinate = function(coordinate,
        resolution, rotation, hitTolerance, skippedFeaturesUids, callback) {
        const feature = new Feature();
        callback(feature);
        callback(feature);
      };
    });

    it('calls callback once per feature with a layer as 2nd arg', function() {
      const spy = sinon.spy();
      const coordinate = [0, 0];
      const frameState = {
        layerStates: {},
        skippedFeatureUids: {},
        viewState: {
          resolution: 1,
          rotation: 0
        }
      };
      frameState.layerStates[getUid(layer)] = {};
      renderer.forEachFeatureAtCoordinate(
        coordinate, frameState, 0, spy, undefined);
      expect(spy.callCount).to.be(1);
      expect(spy.getCall(0).args[1]).to.equal(layer);
    });
  });

  describe('#prepareFrame and #compose', function() {
    let frameState, projExtent, renderer, worldWidth, buffer;

    beforeEach(function() {
      const layer = new VectorLayer({
        source: new VectorSource({wrapX: true})
      });
      renderer = new CanvasVectorLayerRenderer(layer);
      const projection = getProjection('EPSG:3857');
      projExtent = projection.getExtent();
      worldWidth = getWidth(projExtent);
      buffer = layer.getRenderBuffer();
      frameState = {
        skippedFeatureUids: {},
        viewHints: [],
        viewState: {
          projection: projection,
          resolution: 1,
          rotation: 0
        }
      };
    });

    it('sets correct extent for small viewport near dateline', function() {

      frameState.extent =
          [projExtent[0] - 10000, -10000, projExtent[0] + 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));

    });

    it('sets correct extent for viewport less than 1 world wide', function() {

      frameState.extent =
          [projExtent[0] - 10000, -10000, projExtent[1] - 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));
    });

    it('sets correct extent for viewport more than 1 world wide', function() {

      frameState.extent =
          [2 * projExtent[0] - 10000, -10000, 2 * projExtent[1] + 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));
    });

    it('sets correct extent for viewport more than 2 worlds wide', function() {

      frameState.extent = [
        projExtent[0] - 2 * worldWidth - 10000,
        -10000, projExtent[1] + 2 * worldWidth + 10000, 10000
      ];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - 2 * worldWidth - 10000,
        -10000, projExtent[2] + 2 * worldWidth + 10000, 10000
      ], buffer));
    });

    it('sets replayGroupChanged correctly', function() {
      frameState.extent = [-10000, -10000, 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroupChanged).to.be(true);
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroupChanged).to.be(false);
    });

    it.only('dispatches a render event when rendering to own context', function(done) {
      const layer = renderer.getLayer();
      layer.getSource().addFeature(new Feature(new Point([0, 0])));
      layer.once('render', function() {
        expect(true);
        done();
      });
      frameState.extent = [-10000, -10000, 10000, 10000];
      frameState.size = [100, 100];
      frameState.viewState.center = [0, 0];
      let composed = false;
      if (renderer.prepareFrame(frameState, {})) {
        composed = true;
        renderer.compose(renderer.context, frameState, layer.getLayerState);
      }
      expect(composed).to.be(true);
    });

  });

});
<commit_msg>Remove accidently added .only()<commit_after>import {getUid} from '../../../../../src/ol/index.js';
import Feature from '../../../../../src/ol/Feature.js';
import Map from '../../../../../src/ol/Map.js';
import View from '../../../../../src/ol/View.js';
import {buffer as bufferExtent, getWidth} from '../../../../../src/ol/extent.js';
import Point from '../../../../../src/ol/geom/Point.js';
import VectorLayer from '../../../../../src/ol/layer/Vector.js';
import {clear} from '../../../../../src/ol/obj.js';
import {get as getProjection} from '../../../../../src/ol/proj.js';
import {checkedFonts} from '../../../../../src/ol/render/canvas.js';
import CanvasVectorLayerRenderer from '../../../../../src/ol/renderer/canvas/VectorLayer.js';
import VectorSource from '../../../../../src/ol/source/Vector.js';
import Style from '../../../../../src/ol/style/Style.js';
import Text from '../../../../../src/ol/style/Text.js';

describe('ol.renderer.canvas.VectorLayer', function() {

  describe('constructor', function() {

    const head = document.getElementsByTagName('head')[0];
    const font = document.createElement('link');
    font.href = 'https://fonts.googleapis.com/css?family=Droid+Sans';
    font.rel = 'stylesheet';

    let target;

    beforeEach(function() {
      target = document.createElement('div');
      target.style.width = '256px';
      target.style.height = '256px';
      document.body.appendChild(target);
    });

    afterEach(function() {
      document.body.removeChild(target);
    });

    it('creates a new instance', function() {
      const layer = new VectorLayer({
        source: new VectorSource()
      });
      const renderer = new CanvasVectorLayerRenderer(layer);
      expect(renderer).to.be.a(CanvasVectorLayerRenderer);
    });

    it('gives precedence to feature styles over layer styles', function() {
      const target = document.createElement('div');
      target.style.width = '256px';
      target.style.height = '256px';
      document.body.appendChild(target);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = [new Style({
        text: new Text({
          text: 'layer'
        })
      })];
      const featureStyle = [new Style({
        text: new Text({
          text: 'feature'
        })
      })];
      const feature1 = new Feature(new Point([0, 0]));
      const feature2 = new Feature(new Point([0, 0]));
      feature2.setStyle(featureStyle);
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature1, feature2]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const spy = sinon.spy(map.getRenderer().getLayerRenderer(layer),
        'renderFeature');
      map.renderSync();
      expect(spy.getCall(0).args[3]).to.be(layerStyle);
      expect(spy.getCall(1).args[3]).to.be(featureStyle);
      document.body.removeChild(target);
    });

    it('does not re-render for unavailable fonts', function(done) {
      clear(checkedFonts);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px "Unavailable Font",sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision);
        done();
      }, 800);
    });

    it('does not re-render for available fonts', function(done) {
      clear(checkedFonts);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision);
        done();
      }, 800);
    });

    it('re-renders for fonts that become available', function(done) {
      clear(checkedFonts);
      head.appendChild(font);
      const map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 0
        }),
        target: target
      });
      const layerStyle = new Style({
        text: new Text({
          text: 'layer',
          font: '12px "Droid Sans",sans-serif'
        })
      });

      const feature = new Feature(new Point([0, 0]));
      const layer = new VectorLayer({
        source: new VectorSource({
          features: [feature]
        }),
        style: layerStyle
      });
      map.addLayer(layer);
      const revision = layer.getRevision();
      setTimeout(function() {
        expect(layer.getRevision()).to.be(revision + 1);
        head.removeChild(font);
        done();
      }, 1600);
    });

  });

  describe('#forEachFeatureAtCoordinate', function() {
    let layer, renderer;

    beforeEach(function() {
      layer = new VectorLayer({
        source: new VectorSource()
      });
      renderer = new CanvasVectorLayerRenderer(layer);
      const replayGroup = {};
      renderer.replayGroup_ = replayGroup;
      replayGroup.forEachFeatureAtCoordinate = function(coordinate,
        resolution, rotation, hitTolerance, skippedFeaturesUids, callback) {
        const feature = new Feature();
        callback(feature);
        callback(feature);
      };
    });

    it('calls callback once per feature with a layer as 2nd arg', function() {
      const spy = sinon.spy();
      const coordinate = [0, 0];
      const frameState = {
        layerStates: {},
        skippedFeatureUids: {},
        viewState: {
          resolution: 1,
          rotation: 0
        }
      };
      frameState.layerStates[getUid(layer)] = {};
      renderer.forEachFeatureAtCoordinate(
        coordinate, frameState, 0, spy, undefined);
      expect(spy.callCount).to.be(1);
      expect(spy.getCall(0).args[1]).to.equal(layer);
    });
  });

  describe('#prepareFrame and #compose', function() {
    let frameState, projExtent, renderer, worldWidth, buffer;

    beforeEach(function() {
      const layer = new VectorLayer({
        source: new VectorSource({wrapX: true})
      });
      renderer = new CanvasVectorLayerRenderer(layer);
      const projection = getProjection('EPSG:3857');
      projExtent = projection.getExtent();
      worldWidth = getWidth(projExtent);
      buffer = layer.getRenderBuffer();
      frameState = {
        skippedFeatureUids: {},
        viewHints: [],
        viewState: {
          projection: projection,
          resolution: 1,
          rotation: 0
        }
      };
    });

    it('sets correct extent for small viewport near dateline', function() {

      frameState.extent =
          [projExtent[0] - 10000, -10000, projExtent[0] + 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));

    });

    it('sets correct extent for viewport less than 1 world wide', function() {

      frameState.extent =
          [projExtent[0] - 10000, -10000, projExtent[1] - 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));
    });

    it('sets correct extent for viewport more than 1 world wide', function() {

      frameState.extent =
          [2 * projExtent[0] - 10000, -10000, 2 * projExtent[1] + 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - worldWidth + buffer,
        -10000, projExtent[2] + worldWidth - buffer, 10000
      ], buffer));
    });

    it('sets correct extent for viewport more than 2 worlds wide', function() {

      frameState.extent = [
        projExtent[0] - 2 * worldWidth - 10000,
        -10000, projExtent[1] + 2 * worldWidth + 10000, 10000
      ];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroup_.maxExtent_).to.eql(bufferExtent([
        projExtent[0] - 2 * worldWidth - 10000,
        -10000, projExtent[2] + 2 * worldWidth + 10000, 10000
      ], buffer));
    });

    it('sets replayGroupChanged correctly', function() {
      frameState.extent = [-10000, -10000, 10000, 10000];
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroupChanged).to.be(true);
      renderer.prepareFrame(frameState, {});
      expect(renderer.replayGroupChanged).to.be(false);
    });

    it('dispatches a render event when rendering to own context', function(done) {
      const layer = renderer.getLayer();
      layer.getSource().addFeature(new Feature(new Point([0, 0])));
      layer.once('render', function() {
        expect(true);
        done();
      });
      frameState.extent = [-10000, -10000, 10000, 10000];
      frameState.size = [100, 100];
      frameState.viewState.center = [0, 0];
      let composed = false;
      if (renderer.prepareFrame(frameState, {})) {
        composed = true;
        renderer.compose(renderer.context, frameState, layer.getLayerState);
      }
      expect(composed).to.be(true);
    });

  });

});
<|endoftext|>