<commit_before>/*jshint browser:true, jquery:true */
/*global Ember, FLOW */

FLOW.placemarkControl = Ember.ArrayController.create({
  content: null,

  populate: function () {
    this.set('content', FLOW.store.findAll(FLOW.Placemark));
  }

});

FLOW.placemarkDetailControl = Ember.ArrayController.create({
  content: null,
  selectedDetailImage: null,
  selectedPointCode: null,

  populate: function (placemarkId) {
    if(typeof placemarkId === 'undefined') {
      this.set('content', null);
    } else {
      this.set('content', FLOW.store.find(FLOW.PlacemarkDetail, {
        "placemarkId": placemarkId
      }));
    }
  }

});

FLOW.countryControl = Ember.Object.create({
  content: null,

  init: function() {
    this._super();
    this.set('content', this.getContent(Ember.ENV.countries));
  },

  getContent: function (countries) {
    var countryList = [];

    for (var i = 0; i < countries.length; i++) {
      countryList.push(
        Ember.Object.create({
          label: countries[i].label,
          lat: countries[i].lat,
          lon: countries[i].lon,
          zoom: countries[i].zoom
        })
      );
    }
    return countryList;
  }

});<commit_msg>Sort the maps country selector items<commit_after>/*jshint browser:true, jquery:true */
/*global Ember, FLOW */

FLOW.placemarkControl = Ember.ArrayController.create({
  content: null,

  populate: function () {
    this.set('content', FLOW.store.findAll(FLOW.Placemark));
  }

});

FLOW.placemarkDetailControl = Ember.ArrayController.create({
  content: null,
  selectedDetailImage: null,
  selectedPointCode: null,

  populate: function (placemarkId) {
    if(typeof placemarkId === 'undefined') {
      this.set('content', null);
    } else {
      this.set('content', FLOW.store.find(FLOW.PlacemarkDetail, {
        "placemarkId": placemarkId
      }));
    }
  }

});

FLOW.countryControl = Ember.Object.create({
  content: null,

  init: function() {
    this._super();
    this.set('content', this.getContent(Ember.ENV.countries));
  },

  getContent: function (countries) {
    var countryList = [];

    countries.sort(function (a, b) {
      if (a.label < b.label) return -1;
      if (a.label > b.label) return 1;
      return 0;
    });

    for (var i = 0; i < countries.length; i++) {
      countryList.push(
        Ember.Object.create({
          label: countries[i].label,
          lat: countries[i].lat,
          lon: countries[i].lon,
          zoom: countries[i].zoom
        })
      );
    }
    return countryList;
  }

});<|endoftext|>


<commit_before>'use strict';

var staticx = require('../../lib/staticx.js');
var fs = require('fs-extra');
var async = require('async');

describe('Scaffolding', function() {

  var createdPages = [];

  it('Should remove a directory', function(){

    var scaffold = staticx.scaffold;
    var complete = false;

    fs.mkdir('spec/fixtures/tmp/remove',function(err) {
      if (err) {
        console.error(err);
      }
      scaffold.remove('spec/fixtures/tmp/remove', function(err) {
        if (err) throw err;
        fs.exists('spec/fixtures/tmp/remove', function (exists) {
          complete = !exists;
        });
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Removing the directory took too long.', 1000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should copy the skeleton files to a new directory', function(){

    var scaffold = staticx.scaffold;
    var source = 'spec/fixtures/site_skeleton';
    var dest = 'spec/fixtures/tmp/site_skeleton';
    var complete = false;

    scaffold.copy(source, dest, function(err) {
      if (err) throw err;
      fs.exists(dest, function (exists) {
        // Ensure the copied files are removed.
        scaffold.remove(dest, function(err) {
          if (err) throw err;
          complete = exists;
        });
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Copy the skeleton took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should create pages in markdown format', function() {

    var scaffold = staticx.scaffold;
    var complete = false;

    scaffold.createPages('spec/fixtures/tmp', 7, function(err, pages) {

      if (err) {
        throw err;
      }

      createdPages = pages;

      // Here we check there's actually some content in the generated files.
      async.series(pages.map(function(page) {
        return function(done) {
          fs.exists(page.filePath, function(exists) {
            if (exists) {
              fs.readFile(page.filePath, function(err, data) {
                if (err) {
                  throw err;
                }
                if (!data.toString().trim()) {
                  done('No data in file create scaffold page file.');
                } else {
                  done(null);
                }
              });
            }
          });
        };
      }), function(err) {
        if (err) {
          throw err;
        }
        complete = true;
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Creation of pages took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should remove all created pages', function() {

    var scaffold = staticx.scaffold;
    var complete = false;

    scaffold.removePages(createdPages, function(err) {
      if (err) {
        throw err;
      }
      complete = true;
    });

    waitsFor(function() {
      return complete;
    }, 'Removal of pages took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });
});
<commit_msg>Fixed tests<commit_after>'use strict';

var staticx = require('../../lib/staticx.js');
var fs = require('fs-extra');
var async = require('async');

describe('Scaffolding', function() {

  var createdPages = [];

  it('Should remove a directory', function(){

    var scaffold = staticx.scaffold;
    var complete = false;

    fs.mkdir('spec/fixtures/tmp/remove',function(err) {
      if (err) {
        console.error(err);
      }
      scaffold.remove('spec/fixtures/tmp/remove', function(err) {
        if (err) throw err;
        fs.exists('spec/fixtures/tmp/remove', function (exists) {
          complete = !exists;
        });
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Removing the directory took too long.', 1000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should copy the skeleton files to a new directory', function(){

    var scaffold = staticx.scaffold;
    var source = 'skeleton';
    var dest = 'spec/fixtures/tmp/skeleton';
    var complete = false;

    scaffold.copy(source, dest, function(err) {
      if (err) {
        throw err;
      }
      fs.exists(dest, function (exists) {
        // Ensure the copied files are removed.
        scaffold.remove(dest, function(err) {
          if (err) throw err;
          complete = exists;
        });
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Copy the skeleton took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should create pages in markdown format', function() {

    var scaffold = staticx.scaffold;
    var complete = false;

    scaffold.createPages('spec/fixtures/tmp', 7, function(err, pages) {

      if (err) {
        throw err;
      }

      createdPages = pages;

      // Here we check there's actually some content in the generated files.
      async.series(pages.map(function(page) {
        return function(done) {
          fs.exists(page.filePath, function(exists) {
            if (exists) {
              fs.readFile(page.filePath, function(err, data) {
                if (err) {
                  throw err;
                }
                if (!data.toString().trim()) {
                  done('No data in file create scaffold page file.');
                } else {
                  done(null);
                }
              });
            }
          });
        };
      }), function(err) {
        if (err) {
          throw err;
        }
        complete = true;
      });
    });

    waitsFor(function() {
      return complete;
    }, 'Creation of pages took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });

  it('Should remove all created pages', function() {

    var scaffold = staticx.scaffold;
    var complete = false;

    scaffold.removePages(createdPages, function(err) {
      if (err) {
        throw err;
      }
      complete = true;
    });

    waitsFor(function() {
      return complete;
    }, 'Removal of pages took too long.', 3000);

    runs(function () {
      // If the test runs without timing out or erroring then it passed.
      expect(1).toBe(1);
    });
  });
});
<|endoftext|>


<commit_before>/* globals Inject */
import _ from 'underscore';

const renderDynamicCssList = _.debounce(Meteor.bindEnvironment(() => {
	// const variables = RocketChat.models.Settings.findOne({_id:'theme-custom-variables'}, {fields: { value: 1}});
	const colors = RocketChat.models.Settings.find({_id:/theme-color-rc/i}, {fields: { value: 1, editor: 1}}).fetch().filter(color => color && color.value);

	if (!colors) {
		return;
	}
	const css = colors.map(({_id, value, editor}) => {
		if (editor === 'expression') {
			return `--${ _id.replace('theme-color-', '') }: var(--${ value });`;
		}
		return `--${ _id.replace('theme-color-', '') }: ${ value };`;
	}).join('\n');
	Inject.rawBody('dynamic-variables', `<style id='css-variables'> :root {${ css }}</style>`);
}), 500);

renderDynamicCssList();

// RocketChat.models.Settings.find({_id:'theme-custom-variables'}, {fields: { value: 1}}).observe({
// 	changed: renderDynamicCssList
// });

RocketChat.models.Settings.find({_id:/theme-color-rc/i}, {fields: { value: 1}}).observe({
	changed: renderDynamicCssList
});

Inject.rawHead('dynamic', `<script>${ Assets.getText('server/dynamic-css.js') }</script>`);

Inject.rawBody('icons', Assets.getText('public/icons.svg'));

Inject.rawBody('page-loading-div', `

`);

if (process.env.DISABLE_ANIMATION || process.env.TEST_MODE === 'true') {
	Inject.rawHead('disable-animation', `

	`);
}

RocketChat.settings.get('Assets_SvgFavicon_Enable', (key, value) => {
	const standardFavicons = `
		<link rel="icon" sizes="16x16" type="image/png" href="assets/favicon_16.png" />
		<link rel="icon" sizes="32x32" type="image/png" href="assets/favicon_32.png" />`;

	if (value) {
		Inject.rawHead(key,
			`${ standardFavicons }
			<link rel="icon" sizes="any" type="image/svg+xml" href="assets/favicon.svg" />`);
	} else {
		Inject.rawHead(key, standardFavicons);
	}
});

RocketChat.settings.get('theme-color-sidebar-background', (key, value) => {
	Inject.rawHead(key, `<meta name="msapplication-TileColor" content="${ value }" />` +
						`<meta name="theme-color" content="${ value }" />`);
});

RocketChat.settings.get('Accounts_ForgetUserSessionOnWindowClose', (key, value) => {
	if (value) {
		Inject.rawModHtml(key, (html) => {
			const script = `

			`;
			return html.replace(/<\/body>/, `${ script }\n</body>`);
		});
	} else {
		Inject.rawModHtml(key, (html) => {
			return html;
		});
	}
});

RocketChat.settings.get('Site_Name', (key, value = 'Rocket.Chat') => {
	Inject.rawHead(key,
		`<title>${ value }</title>` +
		`<meta name="application-name" content="${ value }">` +
		`<meta name="apple-mobile-web-app-title" content="${ value }">`);
});

RocketChat.settings.get('Meta_language', (key, value = '') => {
	Inject.rawHead(key,
		`<meta http-equiv="content-language" content="${ value }">` +
		`<meta name="language" content="${ value }">`);
});

RocketChat.settings.get('Meta_robots', (key, value = '') => {
	Inject.rawHead(key, `<meta name="robots" content="${ value }">`);
});

RocketChat.settings.get('Meta_msvalidate01', (key, value = '') => {
	Inject.rawHead(key, `<meta name="msvalidate.01" content="${ value }">`);
});

RocketChat.settings.get('Meta_google-site-verification', (key, value = '') => {
	Inject.rawHead(key, `<meta name="google-site-verification" content="${ value }" />`);
});

RocketChat.settings.get('Meta_fb_app_id', (key, value = '') => {
	Inject.rawHead(key, `<meta property="fb:app_id" content="${ value }">`);
});

RocketChat.settings.get('Meta_custom', (key, value = '') => {
	Inject.rawHead(key, value);
});

Meteor.defer(() => {
	let baseUrl;
	if (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX && __meteor_runtime_config__.ROOT_URL_PATH_PREFIX.trim() !== '') {
		baseUrl = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX;
	} else {
		baseUrl = '/';
	}
	if (/\/$/.test(baseUrl) === false) {
		baseUrl += '/';
	}
	Inject.rawHead('base', `<base href="${ baseUrl }">`);
});
<commit_msg>Added meta referrer tag<commit_after>/* globals Inject */
import _ from 'underscore';

const renderDynamicCssList = _.debounce(Meteor.bindEnvironment(() => {
	// const variables = RocketChat.models.Settings.findOne({_id:'theme-custom-variables'}, {fields: { value: 1}});
	const colors = RocketChat.models.Settings.find({_id:/theme-color-rc/i}, {fields: { value: 1, editor: 1}}).fetch().filter(color => color && color.value);

	if (!colors) {
		return;
	}
	const css = colors.map(({_id, value, editor}) => {
		if (editor === 'expression') {
			return `--${ _id.replace('theme-color-', '') }: var(--${ value });`;
		}
		return `--${ _id.replace('theme-color-', '') }: ${ value };`;
	}).join('\n');
	Inject.rawBody('dynamic-variables', `<style id='css-variables'> :root {${ css }}</style>`);
}), 500);

renderDynamicCssList();

// RocketChat.models.Settings.find({_id:'theme-custom-variables'}, {fields: { value: 1}}).observe({
// 	changed: renderDynamicCssList
// });

RocketChat.models.Settings.find({_id:/theme-color-rc/i}, {fields: { value: 1}}).observe({
	changed: renderDynamicCssList
});

Inject.rawHead('noreferrer', '<meta name="referrer" content="origin-when-crossorigin">');
Inject.rawHead('dynamic', `<script>${ Assets.getText('server/dynamic-css.js') }</script>`);

Inject.rawBody('icons', Assets.getText('public/icons.svg'));

Inject.rawBody('page-loading-div', `

`);

if (process.env.DISABLE_ANIMATION || process.env.TEST_MODE === 'true') {
	Inject.rawHead('disable-animation', `

	`);
}

RocketChat.settings.get('Assets_SvgFavicon_Enable', (key, value) => {
	const standardFavicons = `
		<link rel="icon" sizes="16x16" type="image/png" href="assets/favicon_16.png" />
		<link rel="icon" sizes="32x32" type="image/png" href="assets/favicon_32.png" />`;

	if (value) {
		Inject.rawHead(key,
			`${ standardFavicons }
			<link rel="icon" sizes="any" type="image/svg+xml" href="assets/favicon.svg" />`);
	} else {
		Inject.rawHead(key, standardFavicons);
	}
});

RocketChat.settings.get('theme-color-sidebar-background', (key, value) => {
	Inject.rawHead(key, `<meta name="msapplication-TileColor" content="${ value }" />` +
						`<meta name="theme-color" content="${ value }" />`);
});

RocketChat.settings.get('Accounts_ForgetUserSessionOnWindowClose', (key, value) => {
	if (value) {
		Inject.rawModHtml(key, (html) => {
			const script = `

			`;
			return html.replace(/<\/body>/, `${ script }\n</body>`);
		});
	} else {
		Inject.rawModHtml(key, (html) => {
			return html;
		});
	}
});

RocketChat.settings.get('Site_Name', (key, value = 'Rocket.Chat') => {
	Inject.rawHead(key,
		`<title>${ value }</title>` +
		`<meta name="application-name" content="${ value }">` +
		`<meta name="apple-mobile-web-app-title" content="${ value }">`);
});

RocketChat.settings.get('Meta_language', (key, value = '') => {
	Inject.rawHead(key,
		`<meta http-equiv="content-language" content="${ value }">` +
		`<meta name="language" content="${ value }">`);
});

RocketChat.settings.get('Meta_robots', (key, value = '') => {
	Inject.rawHead(key, `<meta name="robots" content="${ value }">`);
});

RocketChat.settings.get('Meta_msvalidate01', (key, value = '') => {
	Inject.rawHead(key, `<meta name="msvalidate.01" content="${ value }">`);
});

RocketChat.settings.get('Meta_google-site-verification', (key, value = '') => {
	Inject.rawHead(key, `<meta name="google-site-verification" content="${ value }" />`);
});

RocketChat.settings.get('Meta_fb_app_id', (key, value = '') => {
	Inject.rawHead(key, `<meta property="fb:app_id" content="${ value }">`);
});

RocketChat.settings.get('Meta_custom', (key, value = '') => {
	Inject.rawHead(key, value);
});

Meteor.defer(() => {
	let baseUrl;
	if (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX && __meteor_runtime_config__.ROOT_URL_PATH_PREFIX.trim() !== '') {
		baseUrl = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX;
	} else {
		baseUrl = '/';
	}
	if (/\/$/.test(baseUrl) === false) {
		baseUrl += '/';
	}
	Inject.rawHead('base', `<base href="${ baseUrl }">`);
});
<|endoftext|>


<commit_before>/* Magic Mirror
 * Module: MMM-Hello-Mirror
 *
 * By Mathias Kaniut
 * MIT Licensed
 */

Module.register("MMM-Hello-Mirror", {

	// Default module config.
    defaults: {
        language: "de",
        voice: "Deutsch Female",
        wakeUp: "Hallo (magischer) Spiegel",
        animationSpeed: 2000,
        debug: true,
        broadcastEvents: true
    },

	// Load required additional scripts
	getScripts: function() {
		return [
			//'//cdnjs.cloudflare.com/ajax/libs/annyang/2.6.0/annyang.min.js',     // annyang! SpeechRecognition
            'script/annyang.min.js',                                             // annyang! SpeechRecognition (modified)
			'http://code.responsivevoice.org/responsivevoice.js',                // ResponsiveVoice
			'moment.js'                                                          // Parse, validate, manipulate, and display dates in JavaScript
		];
	},

	// Define additional styles
	getStyles: function() {
		return [
			"font-awesome.css",
			this.file('css/MMM-Hello-Mirror.css')
		];
	},

	// Request translation files
	getTranslations: function() {
        return {
            en: "translations/en.json",
            de: "translations/de.json"
		};
	},

    textMessage: "",

	// Called when all modules are loaded an the system is ready to boot up
	start: function() {
		if (responsiveVoice) {
			responsiveVoice.setDefaultVoice(this.config.voice);
		}

		if (annyang) {
            Log.info("Starting module: " + this.name);

            var self = this;

			// Set language for date object
			moment.locale(this.config.language);

			// Set the debug mode
			annyang.debug(this.config.debug);

			// Set the language of annyang
			annyang.setLanguage(this.config.language);

			// Define the commands
            var sentence = self.config.wakeUp + ' *command';
			var commands = {
				sentence: function(command) {
					Log.info('Voice command recognized in module ' + self.name + ': ' + command);
					if (self.config.broadcastEvents) {
						self.sendNotification("VOICE_COMMAND", command);
					}
					if (responsiveVoice) {
						responsiveVoice.speak( self.translate("VOICE_ACCEPTED") );
					}
                }
			};

			// Add the commands to annyang
  			annyang.addCommands(commands);

			// Add callback functions for errors
			annyang.addCallback('error', function() {
				Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because an undefined error occured');
			});
			annyang.addCallback('errorNetwork', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because of a network error');
			});
			annyang.addCallback('errorPermissionBlocked', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'Browser blocks the permission request to use Speech Recognition');
			});
			annyang.addCallback('errorPermissionDenied', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'The user blocks the permission request to use Speech Recognition');
			});
			annyang.addCallback('resultNoMatch', function(phrases) {
				Log.error('ERROR in module ' + self.name + ': ' + 'No match for voice command ' + phrases);
			});
			annyang.addCallback('soundstart', function() {
				self.textMessage = self.translate("HEAR_YOU");
  				self.updateDom(self.config.animationSpeed);
			});
			annyang.addCallback('result', function() {
				self.textMessage = "";
  				self.updateDom(self.config.animationSpeed);
			});

			// Start listening
			annyang.start();
		} else {
			Log.error('ERROR in module ' + self.name + ': ' + 'Google Speech Recognizer is down :(');
		}
	},

    // Override dom generator.
    getDom: function() {
        var wrapper = document.createElement("div");
        wrapper.className = "small light";
        wrapper.innerHTML = this.textMessage;
        return wrapper;
    },
});
<commit_msg>modify annyang<commit_after>/* Magic Mirror
 * Module: MMM-Hello-Mirror
 *
 * By Mathias Kaniut
 * MIT Licensed
 */

Module.register("MMM-Hello-Mirror", {

	// Default module config.
    defaults: {
        language: "de",
        voice: "Deutsch Female",
        wakeUp: "Hallo (magischer) Spiegel",
        animationSpeed: 2000,
        debug: true,
        broadcastEvents: true
    },

	// Load required additional scripts
	getScripts: function() {
		return [
			//'//cdnjs.cloudflare.com/ajax/libs/annyang/2.6.0/annyang.min.js',     // annyang! SpeechRecognition
            this.file('script/annyang.min.js'),                                  // annyang! SpeechRecognition (modified)
			'http://code.responsivevoice.org/responsivevoice.js',                // ResponsiveVoice
			'moment.js'                                                          // Parse, validate, manipulate, and display dates in JavaScript
		];
	},

	// Define additional styles
	getStyles: function() {
		return [
			"font-awesome.css",
			this.file('css/MMM-Hello-Mirror.css')
		];
	},

	// Request translation files
	getTranslations: function() {
        return {
            en: "translations/en.json",
            de: "translations/de.json"
		};
	},

    textMessage: "",

	// Called when all modules are loaded an the system is ready to boot up
	start: function() {
		if (responsiveVoice) {
			responsiveVoice.setDefaultVoice(this.config.voice);
		}

		if (annyang) {
            Log.info("Starting module: " + this.name);

            var self = this;

			// Set language for date object
			moment.locale(this.config.language);

			// Set the debug mode
			annyang.debug(this.config.debug);

			// Set the language of annyang
			annyang.setLanguage(this.config.language);

			// Define the commands
            var sentence = self.config.wakeUp + ' *command';
			var commands = {
				sentence: function(command) {
					Log.info('Voice command recognized in module ' + self.name + ': ' + command);
					if (self.config.broadcastEvents) {
						self.sendNotification("VOICE_COMMAND", command);
					}
					if (responsiveVoice) {
						responsiveVoice.speak( self.translate("VOICE_ACCEPTED") );
					}
                }
			};

			// Add the commands to annyang
  			annyang.addCommands(commands);

			// Add callback functions for errors
			annyang.addCallback('error', function() {
				Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because an undefined error occured');
			});
			annyang.addCallback('errorNetwork', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'Speech Recognition fails because of a network error');
			});
			annyang.addCallback('errorPermissionBlocked', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'Browser blocks the permission request to use Speech Recognition');
			});
			annyang.addCallback('errorPermissionDenied', function() {
		    		Log.error('ERROR in module ' + self.name + ': ' + 'The user blocks the permission request to use Speech Recognition');
			});
			annyang.addCallback('resultNoMatch', function(phrases) {
				Log.error('ERROR in module ' + self.name + ': ' + 'No match for voice command ' + phrases);
			});
			annyang.addCallback('soundstart', function() {
				self.textMessage = self.translate("HEAR_YOU");
  				self.updateDom(self.config.animationSpeed);
			});
			annyang.addCallback('result', function() {
				self.textMessage = "";
  				self.updateDom(self.config.animationSpeed);
			});

			// Start listening
			annyang.start();
		} else {
			Log.error('ERROR in module ' + self.name + ': ' + 'Google Speech Recognizer is down :(');
		}
	},

    // Override dom generator.
    getDom: function() {
        var wrapper = document.createElement("div");
        wrapper.className = "small light";
        wrapper.innerHTML = this.textMessage;
        return wrapper;
    },
});
<|endoftext|>


<commit_before>
/**
 * socket.io
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

(function (exports, io) {

  /**
   * Expose constructor.
   */

  exports.SocketNamespace = SocketNamespace;

  /**
   * Socket namespace constructor.
   *
   * @constructor
   * @api public
   */

  function SocketNamespace (name) {
    this.name = name || '';
    this.flags = {};
    this.json = new Flag(this, 'json');
    this.ackPackets = 0;
    this.acks = {};
  };

  /**
   * Apply EventEmitter mixin.
   */

  io.util.mixin(SocketNamespace, io.EventEmitter);

  /**
   * Copies emit since we override it
   *
   * @api private
   */

  SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;

  /**
   * Sends a packet.
   *
   * @api private
   */

  SocketNamespace.prototype.packet = function (packet) {
    packet.endpoint = this.name;
    this.socket.send(io.parser.encodePacket(packet));
    this.flags = {};
    return this;
  };

  /**
   * Sends a message
   *
   * @api public
   */

  SocketNamespace.prototype.send = function (data, fn) {
    var packet = {
        type: this.flags.json ? 'json' : 'message'
      , data: data
    };

    if ('function' == typeof fn) {
      packet.id = ++this.ackPackets;
      packet.ack = fn.length ? 'data' : true;
      this.acks[packet.id] = fn;
    }

    return this.packet(packet);
  };

  /**
   * Emits an event
   *
   * @api public
   */

  SocketNamespace.prototype.emit = function (name) {
    var args = Array.prototype.slice.call(arguments, 1)
      , lastArg = args[args.length - 1]
      , packet = {
            type: 'event'
          , name: name
        };

    if ('function' == typeof lastArg) {
      packet.id = ++this.ackPackets;
      packet.ack = lastArg.length ? 'data' : true;
      this.acks[packet.id] = lastArg;
      args = args.slice(0, args.length - 1);
    }

    packet.args = args;

    return this.packet(packet);
  };

  /**
   * Handles a packet
   *
   * @api private
   */

  SocketNamespace.prototype.onPacket = function (packet) {
    switch (packet.type) {
      case 'connect':
      case 'disconnect':
        this.$emit(packet.type);
        break;

      case 'message':
      case 'json':
        this.$emit('message', packet.data);
        break;

      case 'event':
        this.$emit.apply(this, [packet.name].concat(packet.args));
        break;
    }
  };

  /**
   * Flag interface.
   *
   * @api private
   */

  function Flag (nsp, name) {
    this.namespace = nsp;
    this.name = name;
  };

  /**
   * Send a message
   *
   * @api public
   */

  Flag.prototype.send = function () {
    this.namespace.flags[this.name] = true;
    this.namespace.send.apply(this, arguments);
  };

  /**
   * Emit an event
   *
   * @api public
   */

  Flag.prototype.emit = function () {
    this.namespace.flags[this.name] = true;
    this.namespace.emit.apply(this, arguments);
  };

})(
    'undefined' != typeof io ? io : module.exports
  , 'undefined' != typeof io ? io : module.parent.exports
);
<commit_msg>SocketNamespace#packet now calls Socket#packet.<commit_after>
/**
 * socket.io
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

(function (exports, io) {

  /**
   * Expose constructor.
   */

  exports.SocketNamespace = SocketNamespace;

  /**
   * Socket namespace constructor.
   *
   * @constructor
   * @api public
   */

  function SocketNamespace (name) {
    this.name = name || '';
    this.flags = {};
    this.json = new Flag(this, 'json');
    this.ackPackets = 0;
    this.acks = {};
  };

  /**
   * Apply EventEmitter mixin.
   */

  io.util.mixin(SocketNamespace, io.EventEmitter);

  /**
   * Copies emit since we override it
   *
   * @api private
   */

  SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;

  /**
   * Sends a packet.
   *
   * @api private
   */

  SocketNamespace.prototype.packet = function (packet) {
    packet.endpoint = this.name;
    this.socket.packet(packet);
    this.flags = {};
    return this;
  };

  /**
   * Sends a message
   *
   * @api public
   */

  SocketNamespace.prototype.send = function (data, fn) {
    var packet = {
        type: this.flags.json ? 'json' : 'message'
      , data: data
    };

    if ('function' == typeof fn) {
      packet.id = ++this.ackPackets;
      packet.ack = fn.length ? 'data' : true;
      this.acks[packet.id] = fn;
    }

    return this.packet(packet);
  };

  /**
   * Emits an event
   *
   * @api public
   */

  SocketNamespace.prototype.emit = function (name) {
    var args = Array.prototype.slice.call(arguments, 1)
      , lastArg = args[args.length - 1]
      , packet = {
            type: 'event'
          , name: name
        };

    if ('function' == typeof lastArg) {
      packet.id = ++this.ackPackets;
      packet.ack = lastArg.length ? 'data' : true;
      this.acks[packet.id] = lastArg;
      args = args.slice(0, args.length - 1);
    }

    packet.args = args;

    return this.packet(packet);
  };

  /**
   * Handles a packet
   *
   * @api private
   */

  SocketNamespace.prototype.onPacket = function (packet) {
    switch (packet.type) {
      case 'connect':
      case 'disconnect':
        this.$emit(packet.type);
        break;

      case 'message':
      case 'json':
        this.$emit('message', packet.data);
        break;

      case 'event':
        this.$emit.apply(this, [packet.name].concat(packet.args));
        break;
    }
  };

  /**
   * Flag interface.
   *
   * @api private
   */

  function Flag (nsp, name) {
    this.namespace = nsp;
    this.name = name;
  };

  /**
   * Send a message
   *
   * @api public
   */

  Flag.prototype.send = function () {
    this.namespace.flags[this.name] = true;
    this.namespace.send.apply(this, arguments);
  };

  /**
   * Emit an event
   *
   * @api public
   */

  Flag.prototype.emit = function () {
    this.namespace.flags[this.name] = true;
    this.namespace.emit.apply(this, arguments);
  };

})(
    'undefined' != typeof io ? io : module.exports
  , 'undefined' != typeof io ? io : module.parent.exports
);
<|endoftext|>


<commit_before>var helper = require('./entityutil');
var Cleaner = helper.Cleaner;
var doRuleSetDetect = require('../browsers/Hacks').doRuleSetDetect
var ALL = require('../browsers/BinaryRule').ALL

var Rule = require('./rule');

function RuleSet(selector, values, comment, styleSheet) {
    var self = this;
    self.extra = false
    self.roughSelector = selector
    self.roughValue = values
    self.roughComment = comment

    self.selector = Cleaner.clearSelector(selector)
    self.values = Cleaner.clearValues(values)
    self.comment = Cleaner.clearComment(comment)

    self.fixedSelector = ''
    self.fixedComment = ''

    self.styleSheet = styleSheet
    self._rules = []

    self.singleLineFlag = (self.roughValue.split('\n').length == 1)

    self.browser = doRuleSetDetect(self.roughSelector)
    self.toBeUsed = {}
}

RuleSet.prototype.rebase = function() {
    var self = this;
    self.fixedSelector = ''
    self.fixedComment = ''
}

RuleSet.prototype.extendSelector = function(other) {
    var self = this;
    var splited = [];
    var selectors = self.selector.split(',');
    for(var i = 0; i < selectors.length; i++) {
        if (selectors[i].trim() != '') {
            splited.push(selectors[i].trim());
        }
    }
    var otherSplited = [];
    var selectors = other.selector.split(',');
    for(var i = 0; i < selectors.length; i++) {
        if (selectors[i].trim() != '') {
            otherSplited.push(selectors[i].trim());
        }
    }

    otherSplited.forEach(function(x) {
        if (splited.indexOf(x) == -1) {
            self.selector = self.selector + ', ' + x
            self.roughSelector = self.roughSelector + ', ' + x
            self.fixedSelector = self.fixedSelector + ',' + x
        }
    });

    if (other.comment.length != 0 && self.comment.indexOf(other.comment) == -1) {
        // do not need duplicated comment
        self.roughComment = self.roughComment + ('\n' + other.roughComment)
        self.comment = self.comment + '\n' + other.comment
        self.fixedComment = self.fixedComment + '\n' + other.fixedComment
    }
}

RuleSet.prototype.compressRules = function(browser) {
    var self = this;
    browser = browser || ALL;
    var collector = []
    self._rules.forEach(function(rule) {
        compressed = rule.compress(browser)
        if (compressed != '') {
            collector.push(compressed)
        }
    });
    var collected = collector.join('')
    if (collected != '') {
        collected = collected.slice(0, -1)
    }
    return collected
}

RuleSet.prototype.compress = function(browser) {
    var self = this;
    browser = browser || ALL;
    if (!self.browser) {
        return '';
    }
    if (!(self.browser & browser))
        return ''
    var result = '';
    var compressedComment = self.comment.replace(/\/\*\s*/, '/*').replace(/\s*\*\//, '*/');
    if (compressedComment.indexOf('/*!') == 0) {
        result = compressedComment.split('*/')[0] + '*/';
    }
    result = result + (self.fixedSelector || self.selector);
    if (result.indexOf(',') != -1) {
        // remove duplicated selectors
        var selectors = []
        var splited = result.split(',');
        splited.forEach(function(x) {
            x = x.trim()
            if (selectors.indexOf(x) != -1) {
                return;
            }
            selectors.push(x)
        })
        result = selectors.join(',');
    }
    var compressed = self.compressRules(browser)
    if (compressed == '')
        return ''
    result = result + '{' + compressed + '}'
    return result
}

RuleSet.prototype.fixedRules = function(config) {
    var self = this;
    var collector = []
    var spaces = '    '
    var seperator = '\n'
    if (config && config.singleLine) {
        spaces = ''
        seperator = ' '
    }
    self._rules.forEach(function(rule) {
        collector.push(spaces + rule.fixed())
    })
    var collected = collector.join(seperator)
    return collected
}

RuleSet.prototype.fixed = function(config) {
    var self = this;
    var comment = self.fixedComment || self.comment
    var selector = self.fixedSelector || self.selector
    if (selector.indexOf(',') != -1) {
        // remove duplicated selectors
        selectors = []
        selector.split(',').forEach(function(x) {
            x = x.trim()
            if (selectors.indexOf(x) != -1)
                return;
            selectors.push(x)
        })
        selector = selectors.join(',\n')
    }
    var seperator = '\n'
    if (config && config.singleLine) {
        seperator = ' '
    }
    var result = selector + ' {' + seperator + self.fixedRules(config) + seperator + '}'
    if (comment != '') {
        result = comment + '\n' + result
    }
    return result
}

RuleSet.prototype.getSingleLineFlag = function() {
    var self = this;
    return self.singleLineFlag
}

RuleSet.prototype.getStyleSheet = function() {
    var self = this;
    return self.styleSheet
}

RuleSet.prototype.addRuleByStr = function(attr, value) {
    var self = this;
    var selector = this.selector.trim()
    self._rules.push(new Rule(selector, attr, value, self))
}
RuleSet.prototype.indexOf = function(name) {
    var self = this;
    var counter = 0
    name = name.trim();
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.roughName.trim() == name) {
            return counter
        }
        counter = counter + 1
    }
    return -1
}
RuleSet.prototype.removeRuleByIndex = function(index) {
    var self = this;
    if (index < self._rules.length) {
        self._rules[index] = null;
    }
}
RuleSet.prototype.clean = function() {
    var self = this;
    var newRules = []
    self._rules.forEach(function(rule) {
        if (!rule) {
            return;
        }
        newRules.push(rule)
    })
    self._rules = newRules
}
RuleSet.prototype.existNames = function(name) {
    var self = this, names;
    if (name.indexOf(',') != -1) {
        names = name.split(',')
    } else {
        names = [name]
    }
    for(var i = 0; i < names.length; i++) {
        var name = names[i];
        name = name.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.name == name) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.existRoughNames = function(name) {
    var self = this, names;
    if (name.indexOf(',') != -1) {
        names = name.split(',')
    } else {
        names = [name]
    }
    for(var i = 0; i < names.length; i++) {
        var name = names[i];
        name = name.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.strippedName == name) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.existValueStarts = function(prefix) {
    var self = this, prefixes;
    if (prefix.indexOf(',') != -1) {
        prefixes = prefix.split(',')
    } else {
        prefixes = [prefix]
    }
    for(var i = 0; i < prefixes.length; i++) {
        var prefix = prefixes[i];
        prefix = prefix.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.strippedValue.indexOf(prefix) == 0) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.getRuleByStrippedName = function(name) {
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.strippedName == name) {
            return rule
        }
    }
}
RuleSet.prototype.getRuleByRoughName = function(name) {
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.roughName == name) {
            return rule
        }
    }
}
RuleSet.prototype.getRuleByName = function(name) {
    if (!name) {
        return;
    }
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.name == name) {
            return rule
        }
    }
}

RuleSet.prototype.eachRule = function(callback) {
    if (!callback) {
        return
    }
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        callback.call(this, rule);
    }
}

RuleSet.prototype.extendRules = function(ruleSet) {
    var self = this;
    var rules = self._rules;
    var other = ruleSet.getRules();
    self._rules = rules.concat(other);
}
RuleSet.prototype.getRules = function() {
    var self = this;
    return self._rules
}
RuleSet.prototype.setRules = function(newRules) {
    var self = this;
    self._rules = newRules
}
RuleSet.prototype.toString = function() {
    var self = this;
    return self.selector + ' {' + self.roughValue + '}';
}

module.exports = RuleSet;<commit_msg>add insertBefore<commit_after>var helper = require('./entityutil');
var Cleaner = helper.Cleaner;
var doRuleSetDetect = require('../browsers/Hacks').doRuleSetDetect
var ALL = require('../browsers/BinaryRule').ALL

var Rule = require('./rule');

function RuleSet(selector, values, comment, styleSheet) {
    var self = this;
    self.extra = false
    self.roughSelector = selector
    self.roughValue = values
    self.roughComment = comment

    self.selector = Cleaner.clearSelector(selector)
    self.values = Cleaner.clearValues(values)
    self.comment = Cleaner.clearComment(comment)

    self.fixedSelector = ''
    self.fixedComment = ''

    self.styleSheet = styleSheet
    self._rules = []

    self.singleLineFlag = (self.roughValue.split('\n').length == 1)

    self.browser = doRuleSetDetect(self.roughSelector)
    self.toBeUsed = {}
}

RuleSet.prototype.rebase = function() {
    var self = this;
    self.fixedSelector = ''
    self.fixedComment = ''
}

RuleSet.prototype.extendSelector = function(other) {
    var self = this;
    var splited = [];
    var selectors = self.selector.split(',');
    for(var i = 0; i < selectors.length; i++) {
        if (selectors[i].trim() != '') {
            splited.push(selectors[i].trim());
        }
    }
    var otherSplited = [];
    var selectors = other.selector.split(',');
    for(var i = 0; i < selectors.length; i++) {
        if (selectors[i].trim() != '') {
            otherSplited.push(selectors[i].trim());
        }
    }

    otherSplited.forEach(function(x) {
        if (splited.indexOf(x) == -1) {
            self.selector = self.selector + ', ' + x
            self.roughSelector = self.roughSelector + ', ' + x
            self.fixedSelector = self.fixedSelector + ',' + x
        }
    });

    if (other.comment.length != 0 && self.comment.indexOf(other.comment) == -1) {
        // do not need duplicated comment
        self.roughComment = self.roughComment + ('\n' + other.roughComment)
        self.comment = self.comment + '\n' + other.comment
        self.fixedComment = self.fixedComment + '\n' + other.fixedComment
    }
}

RuleSet.prototype.compressRules = function(browser) {
    var self = this;
    browser = browser || ALL;
    var collector = []
    self._rules.forEach(function(rule) {
        compressed = rule.compress(browser)
        if (compressed != '') {
            collector.push(compressed)
        }
    });
    var collected = collector.join('')
    if (collected != '') {
        collected = collected.slice(0, -1)
    }
    return collected
}

RuleSet.prototype.compress = function(browser) {
    var self = this;
    browser = browser || ALL;
    if (!self.browser) {
        return '';
    }
    if (!(self.browser & browser))
        return ''
    var result = '';
    var compressedComment = self.comment.replace(/\/\*\s*/, '/*').replace(/\s*\*\//, '*/');
    if (compressedComment.indexOf('/*!') == 0) {
        result = compressedComment.split('*/')[0] + '*/';
    }
    result = result + (self.fixedSelector || self.selector);
    if (result.indexOf(',') != -1) {
        // remove duplicated selectors
        var selectors = []
        var splited = result.split(',');
        splited.forEach(function(x) {
            x = x.trim()
            if (selectors.indexOf(x) != -1) {
                return;
            }
            selectors.push(x)
        })
        result = selectors.join(',');
    }
    var compressed = self.compressRules(browser)
    if (compressed == '')
        return ''
    result = result + '{' + compressed + '}'
    return result
}

RuleSet.prototype.fixedRules = function(config) {
    var self = this;
    var collector = []
    var spaces = '    '
    var seperator = '\n'
    if (config && config.singleLine) {
        spaces = ''
        seperator = ' '
    }
    self._rules.forEach(function(rule) {
        collector.push(spaces + rule.fixed())
    })
    var collected = collector.join(seperator)
    return collected
}

RuleSet.prototype.fixed = function(config) {
    var self = this;
    var comment = self.fixedComment || self.comment
    var selector = self.fixedSelector || self.selector
    if (selector.indexOf(',') != -1) {
        // remove duplicated selectors
        selectors = []
        selector.split(',').forEach(function(x) {
            x = x.trim()
            if (selectors.indexOf(x) != -1)
                return;
            selectors.push(x)
        })
        selector = selectors.join(',\n')
    }
    var seperator = '\n'
    if (config && config.singleLine) {
        seperator = ' '
    }
    var result = selector + ' {' + seperator + self.fixedRules(config) + seperator + '}'
    if (comment != '') {
        result = comment + '\n' + result
    }
    return result
}

RuleSet.prototype.getSingleLineFlag = function() {
    var self = this;
    return self.singleLineFlag
}

RuleSet.prototype.getStyleSheet = function() {
    var self = this;
    return self.styleSheet
}

RuleSet.prototype.addRuleByStr = function(attr, value) {
    var self = this;
    var selector = this.selector.trim()
    self._rules.push(new Rule(selector, attr, value, self))
}
RuleSet.prototype.indexOf = function(name) {
    var self = this;
    var counter = 0
    name = name.trim();
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.roughName.trim() == name) {
            return counter
        }
        counter = counter + 1
    }
    return -1
}
RuleSet.prototype.removeRuleByIndex = function(index) {
    var self = this;
    if (index < self._rules.length) {
        self._rules[index] = null;
    }
}
RuleSet.prototype.clean = function() {
    var self = this;
    var newRules = []
    self._rules.forEach(function(rule) {
        if (!rule) {
            return;
        }
        newRules.push(rule)
    })
    self._rules = newRules
}
RuleSet.prototype.existNames = function(name) {
    var self = this, names;
    if (name.indexOf(',') != -1) {
        names = name.split(',')
    } else {
        names = [name]
    }
    for(var i = 0; i < names.length; i++) {
        var name = names[i];
        name = name.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.name == name) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.existRoughNames = function(name) {
    var self = this, names;
    if (name.indexOf(',') != -1) {
        names = name.split(',')
    } else {
        names = [name]
    }
    for(var i = 0; i < names.length; i++) {
        var name = names[i];
        name = name.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.strippedName == name) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.existValueStarts = function(prefix) {
    var self = this, prefixes;
    if (prefix.indexOf(',') != -1) {
        prefixes = prefix.split(',')
    } else {
        prefixes = [prefix]
    }
    for(var i = 0; i < prefixes.length; i++) {
        var prefix = prefixes[i];
        prefix = prefix.trim()
        for(var j = 0; j < self._rules.length; j++) {
            var rule = self._rules[j]
            if (rule.strippedValue.indexOf(prefix) == 0) {
                return true;
            }
        }
    }
    return false
}

RuleSet.prototype.getRuleByStrippedName = function(name) {
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.strippedName == name) {
            return rule
        }
    }
}
RuleSet.prototype.getRuleByRoughName = function(name) {
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.roughName == name) {
            return rule
        }
    }
}
RuleSet.prototype.getRuleByName = function(name) {
    if (!name) {
        return;
    }
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        if (rule.name == name) {
            return rule
        }
    }
}

RuleSet.prototype.eachRule = function(callback) {
    if (!callback) {
        return
    }
    var self = this;
    for(var i = 0; i < self._rules.length; i++) {
        var rule = self._rules[i];
        callback.call(this, rule);
    }
}

RuleSet.prototype.insertBefore = function(name, value, rule) {
    var self = this;
    var index = 0;
    if (rule) {
        index = self._rules.indexOf(rule);
    }
    if (index == -1) {
        index = 0;
    }
    var selector = this.selector.trim()
    var rule = new Rule(attr, value, self)
    self._rules.splice(index, 0, rule)
}

RuleSet.prototype.extendRules = function(ruleSet) {
    var self = this;
    var rules = self._rules;
    var other = ruleSet.getRules();
    self._rules = rules.concat(other);
}
RuleSet.prototype.getRules = function() {
    var self = this;
    return self._rules
}
RuleSet.prototype.setRules = function(newRules) {
    var self = this;
    self._rules = newRules
}
RuleSet.prototype.toString = function() {
    var self = this;
    return self.selector + ' {' + self.roughValue + '}';
}

module.exports = RuleSet;<|endoftext|>


<commit_before>/**
 * @fileoverview Whiteboard demo
 */

goog.provide('whiteboard');

goog.require('cw.autoTitle');
goog.require('goog.debug.DivConsole');
goog.require('goog.debug.Logger');
goog.require('goog.debug.LogManager');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.BrowserEvent');
goog.require('goog.graphics');
goog.require('goog.json');
goog.require('goog.Uri');
goog.require('cw.eventual');
goog.require('cw.string');
goog.require('cw.net.Stream');
goog.require('cw.net.IMinervaProtocol');
goog.require('cw.net.HttpStreamingMode');
goog.require('cw.net.demo.getEndpoint');
goog.require('cw.net.demo.makeCredentialsData');
goog.require('cw.repr');
goog.require('cw.string');

whiteboard._queryData = new goog.Uri(document.location).getQueryData();
whiteboard.useLogging = Boolean(Number(whiteboard._queryData.get('logging', '0')));

if(whiteboard.useLogging) {
	goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.ALL);
	var logDiv = document.getElementById('log');
	var divConsole = new goog.debug.DivConsole(logDiv);
	divConsole.setCapturing(true);
} else {
	goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.OFF);
}

whiteboard.logger = goog.debug.Logger.getLogger('whiteboard.logger');
whiteboard.logger.info('Logger works.');

window.onerror = function(msg, url, lineNumber) {
	whiteboard.logger.severe('window.onerror: message: ' + cw.repr.repr(msg) +
		'\nURL: ' + url + '\nLine Number: ' + lineNumber)
};

function byId(o) {
	return document.getElementById(o);
}

/**
 * @implements {cw.net.IMinervaProtocol}
 * @constructor
 */
whiteboard.WhiteboardProtocol = function() {

};

whiteboard.WhiteboardProtocol.prototype.streamStarted = function(stream) {
	this.stream_ = stream;
	whiteboard.logger.info('streamStarted');
	this.stream_.sendStrings(['subprotocol:whiteboard']);
};

whiteboard.WhiteboardProtocol.prototype.streamReset = function(reasonString, applicationLevel) {
	whiteboard.logger.info(
		'streamReset: reasonString=' + cw.repr.repr(reasonString) +
		', applicationLevel=' + applicationLevel);
};

whiteboard.WhiteboardProtocol.prototype.handleString_ = function(s) {
	function fail() {
		whiteboard.logger.severe('Could not handle string: ' + cw.repr.repr(s));
	}

	// TODO: do something safer
	var payload = eval('(' + s + ')');
	var msgType = payload[0];
	var body = payload[1];

	if(msgType == 1) { // draw circle
		var x = body[0];
		var y = body[1];
		whiteboard.drawCircleAt(x, y);
	}
};

whiteboard.WhiteboardProtocol.prototype.stringsReceived = function(strings) {
	for(var i=0; i < strings.length; i++) {
		var s = strings[i];
		this.handleString_(s);
	}
};

/**
 * @param {string} reason
 */
whiteboard.WhiteboardProtocol.prototype.reset = function(reason) {
	whiteboard.logger.info('resetting with reason: ' + reason);
	this.stream_.reset(reason);
};

whiteboard.WhiteboardProtocol.prototype.sendCircle = function(x, y) {
	whiteboard.logger.info('telling server about circle at: ' + x + ', ' + y);
	this.stream_.sendStrings([goog.json.serialize([1, [x, y]])]);
};

/**
 * @type {?whiteboard.WhiteboardProtocol}
 */
whiteboard.lastProto = null;

whiteboard.callQueue = new cw.eventual.CallQueue(goog.global['window']);

whiteboard.idleFired = function() {
	whiteboard.resetStream("idle timeout fired");
	whiteboard.lastProto = null;
};

whiteboard.idleTimeout = null;

whiteboard.activityDetected = function(ev) {
	if(whiteboard.idleTimeout != null) {
		whiteboard.callQueue.clock.clearTimeout(whiteboard.idleTimeout);
	}

	// Only need a timeout if we have an active Stream
	if(whiteboard.lastProto) {
		whiteboard.idleTimeout = whiteboard.callQueue.clock.setTimeout(
			whiteboard.idleFired, 600 * 1000);
	}
};

/**
 * @type {!Array.<!goog.events.EventType>}
 */
whiteboard.activityEvents = [
	goog.events.EventType.CLICK,
	goog.events.EventType.FOCUS,
	goog.events.EventType.KEYDOWN,
	goog.events.EventType.KEYPRESS];
whiteboard.clickListen = goog.events.listen(
	goog.global, whiteboard.activityEvents, whiteboard.activityDetected, true);

whiteboard.startStream = function() {
	var streamPolicy = new cw.net.demo.DemoStreamPolicy();
	whiteboard.lastProto = new whiteboard.WhiteboardProtocol();
	// Uncomment to enable the idle timeout.
	//whiteboard.activityDetected();
	var endpointD = cw.net.demo.getEndpoint(whiteboard.callQueue);
	endpointD.addCallback(function(endpoint) {
		var stream = new cw.net.Stream(
			whiteboard.callQueue, whiteboard.lastProto, endpoint, streamPolicy);
		stream.start();
	});
};

/**
 * @param {string} reason
 */
whiteboard.resetStream = function(reason) {
	whiteboard.lastProto.reset(reason);
};

whiteboard.reconnectStream = function() {
	if(whiteboard.lastProto) {
		whiteboard.lastProto.reset('because user clicked reconnect button');
	}
	whiteboard.startStream();
};

whiteboard.drawRandomStuff = function() {
	var fill = new goog.graphics.SolidFill('yellow');
	var stroke = new goog.graphics.Stroke(2, 'green');
	var rectElement = whiteboard.lastDrawArea.drawRect(30, 10, 100, 80, stroke, fill);
};

whiteboard.drawCircleAt = function(x, y) {
	var fill = new goog.graphics.SolidFill('yellow');
	var stroke = new goog.graphics.Stroke(2, 'green');
	var circleElement = whiteboard.lastDrawArea.drawCircle(x, y, 5, stroke, fill);
};

whiteboard.handleClick = function(ev) {
	var patchedEv = new goog.events.BrowserEvent(ev);
	var x = patchedEv.offsetX;
	var y = patchedEv.offsetY;
	whiteboard.drawCircleAt(x, y);
	whiteboard.lastProto.sendCircle(x, y);
};

whiteboard.setupDrawArea = function() {
	var graphics = goog.graphics.createGraphics(800, 600);
	whiteboard._drawAreaDiv = goog.dom.getElement('drawArea');
	graphics.render(whiteboard._drawAreaDiv);
	goog.events.listen(whiteboard._drawAreaDiv, goog.events.EventType.CLICK, whiteboard.handleClick, false);
	whiteboard.lastDrawArea = graphics;
};

whiteboard.init = function() {
	whiteboard.setupDrawArea();
	whiteboard.drawRandomStuff();
	whiteboard.startStream();
};
<commit_msg>js/whiteboard/whiteboard.js: add typedefs; fix minor problems found by Closure Compiler<commit_after>/**
 * @fileoverview Whiteboard demo
 */

goog.provide('whiteboard');

goog.require('cw.autoTitle');
goog.require('goog.asserts');
goog.require('goog.debug.DivConsole');
goog.require('goog.debug.Logger');
goog.require('goog.debug.LogManager');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.BrowserEvent');
goog.require('goog.graphics');
goog.require('goog.json');
goog.require('goog.Uri');
goog.require('cw.eventual');
goog.require('cw.string');
goog.require('cw.net.Stream');
goog.require('cw.net.IMinervaProtocol');
goog.require('cw.net.HttpStreamingMode');
goog.require('cw.net.demo.getEndpoint');
goog.require('cw.net.demo.makeCredentialsData');
goog.require('cw.repr');
goog.require('cw.string');

whiteboard._queryData = new goog.Uri(document.location).getQueryData();
whiteboard.useLogging = Boolean(Number(whiteboard._queryData.get('logging', '0')));

if(whiteboard.useLogging) {
	goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.ALL);
	var logDiv = document.getElementById('log');
	var divConsole = new goog.debug.DivConsole(logDiv);
	divConsole.setCapturing(true);
} else {
	goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.OFF);
}

whiteboard.logger = goog.debug.Logger.getLogger('whiteboard.logger');
whiteboard.logger.info('Logger works.');

window.onerror = function(msg, url, lineNumber) {
	whiteboard.logger.severe('window.onerror: message: ' + cw.repr.repr(msg) +
		'\nURL: ' + url + '\nLine Number: ' + lineNumber)
};

function byId(o) {
	return document.getElementById(o);
}

/**
 * @implements {cw.net.IMinervaProtocol}
 * @constructor
 */
whiteboard.WhiteboardProtocol = function() {

};

whiteboard.WhiteboardProtocol.prototype.streamStarted = function(stream) {
	this.stream_ = stream;
	whiteboard.logger.info('streamStarted');
	this.stream_.sendStrings(['subprotocol:whiteboard']);
};

whiteboard.WhiteboardProtocol.prototype.streamReset = function(reasonString, applicationLevel) {
	whiteboard.logger.info(
		'streamReset: reasonString=' + cw.repr.repr(reasonString) +
		', applicationLevel=' + applicationLevel);
};

/**
 * @param {string} s
 */
whiteboard.WhiteboardProtocol.prototype.handleString_ = function(s) {
	function fail() {
		whiteboard.logger.severe('Could not handle string: ' + cw.repr.repr(s));
	}

	// TODO: do something safer
	var payload = eval('(' + s + ')');
	var msgType = payload[0];
	var body = payload[1];

	if(msgType == 1) { // draw circle
		var x = body[0];
		var y = body[1];
		whiteboard.drawCircleAt(x, y);
	}
};

/**
 * @param {!Array.<string>} strings
 */
whiteboard.WhiteboardProtocol.prototype.stringsReceived = function(strings) {
	for(var i=0; i < strings.length; i++) {
		var s = strings[i];
		this.handleString_(s);
	}
};

/**
 * @param {string} reason
 */
whiteboard.WhiteboardProtocol.prototype.reset = function(reason) {
	whiteboard.logger.info('resetting with reason: ' + reason);
	this.stream_.reset(reason);
};

/**
 * @param {number} x
 * @param {number} y
 */
whiteboard.WhiteboardProtocol.prototype.sendCircle = function(x, y) {
	whiteboard.logger.info('telling server about circle at: ' + x + ', ' + y);
	this.stream_.sendStrings([goog.json.serialize([1, [x, y]])]);
};

/**
 * @type {?whiteboard.WhiteboardProtocol}
 */
whiteboard.lastProto = null;

whiteboard.callQueue = new cw.eventual.CallQueue(goog.global['window']);

whiteboard.idleFired = function() {
	whiteboard.resetStream("idle timeout fired");
	whiteboard.lastProto = null;
};

whiteboard.idleTimeout = null;

whiteboard.activityDetected = function(ev) {
	if(whiteboard.idleTimeout != null) {
		whiteboard.callQueue.clock.clearTimeout(whiteboard.idleTimeout);
	}

	// Only need a timeout if we have an active Stream
	if(whiteboard.lastProto) {
		whiteboard.idleTimeout = whiteboard.callQueue.clock.setTimeout(
			whiteboard.idleFired, 600 * 1000);
	}
};

/**
 * @type {!Array.<!goog.events.EventType>}
 */
whiteboard.activityEvents = [
	goog.events.EventType.CLICK,
	goog.events.EventType.FOCUS,
	goog.events.EventType.KEYDOWN,
	goog.events.EventType.KEYPRESS];
whiteboard.clickListen = goog.events.listen(
	window, whiteboard.activityEvents, whiteboard.activityDetected, true);

whiteboard.startStream = function() {
	var streamPolicy = new cw.net.demo.DemoStreamPolicy();
	whiteboard.lastProto = new whiteboard.WhiteboardProtocol();
	// Uncomment to enable the idle timeout.
	//whiteboard.activityDetected();
	var endpointD = cw.net.demo.getEndpoint(whiteboard.callQueue);
	endpointD.addCallback(function(endpoint) {
		goog.asserts.assert(whiteboard.lastProto, 'lastProto falsy?');
		var stream = new cw.net.Stream(
			whiteboard.callQueue, whiteboard.lastProto, endpoint, streamPolicy);
		stream.start();
	});
};

/**
 * @param {string} reason
 */
whiteboard.resetStream = function(reason) {
	whiteboard.lastProto.reset(reason);
};

whiteboard.reconnectStream = function() {
	if(whiteboard.lastProto) {
		whiteboard.lastProto.reset('because user clicked reconnect button');
	}
	whiteboard.startStream();
};

whiteboard.drawRandomStuff = function() {
	var fill = new goog.graphics.SolidFill('yellow');
	var stroke = new goog.graphics.Stroke(2, 'green');
	var rectElement = whiteboard.lastDrawArea.drawRect(30, 10, 100, 80, stroke, fill);
};

whiteboard.drawCircleAt = function(x, y) {
	var fill = new goog.graphics.SolidFill('yellow');
	var stroke = new goog.graphics.Stroke(2, 'green');
	var circleElement = whiteboard.lastDrawArea.drawCircle(x, y, 5, stroke, fill);
};

whiteboard.handleClick = function(ev) {
	var patchedEv = new goog.events.BrowserEvent(ev);
	var x = patchedEv.offsetX;
	var y = patchedEv.offsetY;
	whiteboard.drawCircleAt(x, y);
	whiteboard.lastProto.sendCircle(x, y);
};

whiteboard.setupDrawArea = function() {
	var graphics = goog.graphics.createGraphics(800, 600);
	whiteboard._drawAreaDiv = goog.dom.getElement('drawArea');
	graphics.render(whiteboard._drawAreaDiv);
	goog.events.listen(whiteboard._drawAreaDiv, goog.events.EventType.CLICK, whiteboard.handleClick, false);
	whiteboard.lastDrawArea = graphics;
};

whiteboard.init = function() {
	whiteboard.setupDrawArea();
	whiteboard.drawRandomStuff();
	whiteboard.startStream();
};
<|endoftext|>


<commit_before>/*leaflet -- control*/
// import './leaflet/control/ChangeTileVersionSpec.js';

/*leaflet -- core*/
import './leaflet/core/NonEarthCRSSpec.js';
import './leaflet/core/TransformUtilSpec.js';
import './leaflet/core/Proj4LeafletSpec.js';

/*leaflet -- mapping*/
// import './leaflet/mapping/ImageMapLayerSpec.js';
import './leaflet/mapping/TiledMapLayerSpec.js';
import './leaflet/mapping/TileLayer.WMTSSpec.js';
// import './leaflet/mapping/WebMapSpec.js';

/*leaflet -- overlay*/

import './leaflet/overlay/EchartsLayerSpec.js';
/*deck相关测试未通过，待解决后打开注释*/
import './leaflet/overlay/graphic/GraphicSpec.js';
import './leaflet/overlay/GraphicLayerSpec.js';
import './leaflet/overlay/graphic/CloverStyleSpec';
import './leaflet/overlay/GraphThemeLayerSpec.js';
import './leaflet/overlay/HeatMapLayerSpec.js';
import './leaflet/overlay/LabelThemeLayerSpec.js';
import './leaflet/overlay/MapVLayerSpec.js';
import './leaflet/overlay/RangeThemeLayerSpec.js';
import './leaflet/overlay/RankSymbolThemeLayerSpec.js';
import './leaflet/overlay/TileVectorLayerSpec.js';
import './leaflet/overlay/UniqueThemeLayerSpec.js';
import './leaflet/overlay/vectortile/PointSymbolizerSpec.js';
import './leaflet/overlay/vectortile/TextSymbolizerSpec.js';
import './leaflet/overlay/TurfLayerSpec.js';
import './leaflet/overlay/mapv/MapVRendererSpec.js';
/**leaflet -- services**/
import './leaflet/services/AddressMatchServiceSpec.js';
import './leaflet/services/BufferAnalysisSpec.js';
import './leaflet/services/DensityAnalysisSpec.js';
import './leaflet/services/EditFeaturesLineSpec.js';
import './leaflet/services/EditFeaturesPointSpec.js';
import './leaflet/services/EditFeaturesRegionSpec.js';
import './leaflet/services/FieldServiceSpec.js';
import './leaflet/services/GenerateSpatialDataSpec.js';
import './leaflet/services/GeoRelationAnalysisSpec.js';
import './leaflet/services/GeometryBatchAnalysisSpec.js';
import './leaflet/services/GetFeaturesByBoundsSpec.js';
import './leaflet/services/GetFeaturesByBufferSpec.js';
import './leaflet/services/GetFeaturesByGeometrySpec.js';
import './leaflet/services/GetFeaturesByIDsSpec.js';
import './leaflet/services/GetFeaturesBySQLSpec.js';
import './leaflet/services/GridCellInfosServiceSpec.js';
import './leaflet/services/InterpolationAnalysisSpec.js';
import './leaflet/services/LayerInfoServiceSpec.js';
import './leaflet/services/MapServiceSpec.js';
import './leaflet/services/MathExpressionAnalysisSpec.js';
import './leaflet/services/MeasureServiceSpec.js';
import './leaflet/services/NetworkAnalystServiceSpec.js';
import './leaflet/services/OverlayAnalysisSpec.js';
import './leaflet/services/ProcessingServiceSpec.js';
import './leaflet/services/QueryByBoundsSpec.js';
import './leaflet/services/QueryByDistanceSpec.js';
import './leaflet/services/QueryByGeometrySpec.js';
import './leaflet/services/QueryBySQLSpec.js';
import './leaflet/services/RouteCalculateMeasureSpec.js';
import './leaflet/services/RouteLocateSpec.js';
import './leaflet/services/SurfaceAnalysisSpec.js';
import './leaflet/services/TerrainCurvatureCalculateSpec.js';
import './leaflet/services/ThemeServiceSpec.js';
import './leaflet/services/ThiessenAnalysisSpec.js';
import './leaflet/services/TrafficTransferAnalystServiceSpec.js';

/* component */
import './leaflet/components/openfile/OpenFileViewSpec.js';
import './leaflet/components/dataservicequery/DataServiceQueryViewSpec.js';
import './leaflet/components/distributedanalysis/DistributedAnalysisViewSpec.js';
import './leaflet/components/clientcomputation/ClientComputationViewSpec.js';
import './leaflet/components/search/SearchViewSpec.js';
import './leaflet/components/dataflow/DataFlowViewSpec.js';
import './leaflet/overlay/DataFlowLayerSpec.js';

<commit_msg>Update test-main-leaflet.js<commit_after>/*leaflet -- control*/
// import './leaflet/control/ChangeTileVersionSpec.js';

/*leaflet -- core*/
import './leaflet/core/NonEarthCRSSpec.js';
import './leaflet/core/TransformUtilSpec.js';
import './leaflet/core/Proj4LeafletSpec.js';

/*leaflet -- mapping*/
// import './leaflet/mapping/ImageMapLayerSpec.js';
import './leaflet/mapping/TiledMapLayerSpec.js';
import './leaflet/mapping/TileLayer.WMTSSpec.js';
// import './leaflet/mapping/WebMapSpec.js';

/*leaflet -- overlay*/

// import './leaflet/overlay/EchartsLayerSpec.js';
/*deck相关测试未通过，待解决后打开注释*/
import './leaflet/overlay/graphic/GraphicSpec.js';
import './leaflet/overlay/GraphicLayerSpec.js';
import './leaflet/overlay/graphic/CloverStyleSpec';
import './leaflet/overlay/GraphThemeLayerSpec.js';
import './leaflet/overlay/HeatMapLayerSpec.js';
import './leaflet/overlay/LabelThemeLayerSpec.js';
import './leaflet/overlay/MapVLayerSpec.js';
import './leaflet/overlay/RangeThemeLayerSpec.js';
import './leaflet/overlay/RankSymbolThemeLayerSpec.js';
import './leaflet/overlay/TileVectorLayerSpec.js';
import './leaflet/overlay/UniqueThemeLayerSpec.js';
import './leaflet/overlay/vectortile/PointSymbolizerSpec.js';
import './leaflet/overlay/vectortile/TextSymbolizerSpec.js';
import './leaflet/overlay/TurfLayerSpec.js';
import './leaflet/overlay/mapv/MapVRendererSpec.js';
/**leaflet -- services**/
import './leaflet/services/AddressMatchServiceSpec.js';
import './leaflet/services/BufferAnalysisSpec.js';
import './leaflet/services/DensityAnalysisSpec.js';
import './leaflet/services/EditFeaturesLineSpec.js';
import './leaflet/services/EditFeaturesPointSpec.js';
import './leaflet/services/EditFeaturesRegionSpec.js';
import './leaflet/services/FieldServiceSpec.js';
import './leaflet/services/GenerateSpatialDataSpec.js';
import './leaflet/services/GeoRelationAnalysisSpec.js';
import './leaflet/services/GeometryBatchAnalysisSpec.js';
import './leaflet/services/GetFeaturesByBoundsSpec.js';
import './leaflet/services/GetFeaturesByBufferSpec.js';
import './leaflet/services/GetFeaturesByGeometrySpec.js';
import './leaflet/services/GetFeaturesByIDsSpec.js';
import './leaflet/services/GetFeaturesBySQLSpec.js';
import './leaflet/services/GridCellInfosServiceSpec.js';
import './leaflet/services/InterpolationAnalysisSpec.js';
import './leaflet/services/LayerInfoServiceSpec.js';
import './leaflet/services/MapServiceSpec.js';
import './leaflet/services/MathExpressionAnalysisSpec.js';
import './leaflet/services/MeasureServiceSpec.js';
import './leaflet/services/NetworkAnalystServiceSpec.js';
import './leaflet/services/OverlayAnalysisSpec.js';
import './leaflet/services/ProcessingServiceSpec.js';
import './leaflet/services/QueryByBoundsSpec.js';
import './leaflet/services/QueryByDistanceSpec.js';
import './leaflet/services/QueryByGeometrySpec.js';
import './leaflet/services/QueryBySQLSpec.js';
import './leaflet/services/RouteCalculateMeasureSpec.js';
import './leaflet/services/RouteLocateSpec.js';
import './leaflet/services/SurfaceAnalysisSpec.js';
import './leaflet/services/TerrainCurvatureCalculateSpec.js';
import './leaflet/services/ThemeServiceSpec.js';
import './leaflet/services/ThiessenAnalysisSpec.js';
import './leaflet/services/TrafficTransferAnalystServiceSpec.js';

/* component */
import './leaflet/components/openfile/OpenFileViewSpec.js';
import './leaflet/components/dataservicequery/DataServiceQueryViewSpec.js';
import './leaflet/components/distributedanalysis/DistributedAnalysisViewSpec.js';
import './leaflet/components/clientcomputation/ClientComputationViewSpec.js';
import './leaflet/components/search/SearchViewSpec.js';
import './leaflet/components/dataflow/DataFlowViewSpec.js';
import './leaflet/overlay/DataFlowLayerSpec.js';

<|endoftext|>


<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps', 'Controls',
function (B, canvas, Entities, Physics, Utils, Maps, Controls) {
	var car,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));
		Controls.init();

		setInterval(updateAll, 1000 / fps);

		/*
		 * Create the tracks, The whole game is a grid and tracks are on the grid
		 * The tracks are organised on a rectangle of the grid started at the
		 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
		 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
		 * Each track is an instance of the class Entities.Track
		 */
		var col, row,
			trackWidth = canvas.width() / Maps[0].width,
			trackHeight = canvas.height() / Maps[0].height,
			startX, startY;
		for (row = 0; row < Maps[0].height; row++ ) {
			for (col = 0; col < Maps[0].width; col++ ) {
				tracks.push(new Entities.Track(
					// 5 is the initial left margin
					trackWidth * col, trackHeight * row,
					trackWidth, trackHeight,
					// @TODO remove destructable field
					true, Maps[0].map[row][col]
				));

				if (Maps[0].map[row][col] == Entities.Track.STATE_START) {
					startX = trackWidth * col + trackWidth / 2;
					startY = trackHeight * row + trackHeight / 2;
				}
			}
		}

		// Init the car
		car = new Entities.Car(startX, startY, CAR_RADIUS, Math.PI / 2, CAR_SPEED);
		// Position of the car in the grid
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		car.setGraphic(B.create('img'));
		car.graphic.onload = function () {
			car.setGraphicLoaded(true);
		};
		car.graphic.src = '/images/player1car.png';

		B.Events.on('keydown', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(true);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(true);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(true);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(true);
			}
		});

		B.Events.on('keyup', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(false);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(false);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(false);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(false);
			}
		});
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			car.x = mouseX;
			car.y = mouseY;
			car.speed = CAR_SPEED;
		}
	});
	/* End of Events */

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Car and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		/* End of Car and edges collision*/

		/* Car and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			car.gridCellCol,
			car.gridCellRow
		)];

		// if the car is on an active track
		if (TRACK_GRID_START_COL <= car.gridCellCol && car.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= car.gridCellRow && car.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			car.bumpBack();
		}
		/* End of Car and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([car, tracks]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			// @TODO adapt with angle
			// canvas.line([car.x, car.y], [car.x + car.speedX * 30, car.y + car.speedY * 30]);
		}
	}
});
<commit_msg>car displayed on top of the tracks<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'Maps', 'Controls',
function (B, canvas, Entities, Physics, Utils, Maps, Controls) {
	var car,
		tracks = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));
		Controls.init();

		setInterval(updateAll, 1000 / fps);

		/*
		 * Create the tracks, The whole game is a grid and tracks are on the grid
		 * The tracks are organised on a rectangle of the grid started at the
		 * position (TRACK_GRID_START_COL, TRACK_GRID_START_COL) and ends at the
		 * position (TRACK_GRID_COL, TRACK_GRID_ROW)
		 * Each track is an instance of the class Entities.Track
		 */
		var col, row,
			trackWidth = canvas.width() / Maps[0].width,
			trackHeight = canvas.height() / Maps[0].height,
			startX, startY;
		for (row = 0; row < Maps[0].height; row++ ) {
			for (col = 0; col < Maps[0].width; col++ ) {
				tracks.push(new Entities.Track(
					// 5 is the initial left margin
					trackWidth * col, trackHeight * row,
					trackWidth, trackHeight,
					// @TODO remove destructable field
					true, Maps[0].map[row][col]
				));

				if (Maps[0].map[row][col] == Entities.Track.STATE_START) {
					startX = trackWidth * col + trackWidth / 2;
					startY = trackHeight * row + trackHeight / 2;
				}
			}
		}

		// Init the car
		car = new Entities.Car(startX, startY, CAR_RADIUS, Math.PI / 2, CAR_SPEED);
		// Position of the car in the grid
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		car.setGraphic(B.create('img'));
		car.graphic.onload = function () {
			car.setGraphicLoaded(true);
		};
		car.graphic.src = '/images/player1car.png';

		B.Events.on('keydown', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(true);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(true);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(true);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(true);
			}
		});

		B.Events.on('keyup', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(false);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(false);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(false);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(false);
			}
		});
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			car.x = mouseX;
			car.y = mouseY;
			car.speed = CAR_SPEED;
		}
	});
	/* End of Events */

	/**
	 * Method to convert a pair of coordinates to the index of the cell in the
	 * grid the coordinates are in
	 */
	colRowToGridIndex = function (col, row) {
		return col - TRACK_GRID_START_COL +
			(TRACK_GRID_COL - TRACK_GRID_START_COL) * (row - TRACK_GRID_START_ROW);
	};

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();
		car.setGridCoordinates(TRACK_SPACE_WIDTH, TRACK_SPACE_HEIGHT);

		/* Car and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		/* End of Car and edges collision*/

		/* Car and active track collision */
		var track,
			trackSide,
			trackTopBot;

		track = tracks[colRowToGridIndex(
			car.gridCellCol,
			car.gridCellRow
		)];

		// if the car is on an active track
		if (TRACK_GRID_START_COL <= car.gridCellCol && car.gridCellCol < TRACK_GRID_COL
			&& TRACK_GRID_START_COL <= car.gridCellRow && car.gridCellRow < TRACK_GRID_ROW
			&& track.state == Entities.Track.STATE_ACTIVE
		) {
			car.bumpBack();
		}
		/* End of Car and active track collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([tracks, car]);

		if (DEBUG) {
			canvas.drawText('(' +
				Math.floor(mouseX / TRACK_SPACE_WIDTH) + ', ' +
				Math.floor(mouseY / TRACK_SPACE_HEIGHT) + ', ' +
				colRowToGridIndex(Math.floor(mouseX / TRACK_SPACE_WIDTH), Math.floor(mouseY / TRACK_SPACE_HEIGHT)) + ')', mouseX, mouseY, 'white');

			// @TODO adapt with angle
			// canvas.line([car.x, car.y], [car.x + car.speedX * 30, car.y + car.speedY * 30]);
		}
	}
});
<|endoftext|>