<commit_before>/// http://samvermette.com/313
/// Forked for CocoaDocs: https://github.com/orta/emphasize.js

(function() {

  var Emphasize = { "rules": {} };
  Emphasize.languages = ["highlight-objective-c", "highlight-objc"];
  Emphasize.rules["highlight-objective-c", "highlight-objc"] = [
    [/(#)(.+)(\n)/g, "$1$2$3"],
    [/(\[|^|<|\(|\s+)([A-Z]{2}[a-zA-Z]{3,})(\s|\*|>|;|,)/g, "$1$2$3"],
    [/(\[|^|\(|\s+)(\w{3,})(\()/g, "$1$2$3"],
    [/(@")([^"]+)(",|"])/g, "$1$2$3"],
    [/(#.*)("|<)(.*)("|>)/g, "$1$2$3$4"],
    [/(\s+)(\w+)(:|])/g, "$1$2$3"],
    [/(\.)([a-zA-Z]{3,})(\s{1}|]|;|\)|,)/g, "$1$2$3"],
    [/(:|\s+)([A-Z]{2}\w{3,})(;|\s|])/g, "$1$2$3"],
    [/(self|super|nil|@end|@implementation|@synthesize|@property|@interface|@selector|@class)/g, "$1"],
    [/(\s+|\(|,)(strong|retain|weak|assign|nonatomic|atomic|readonly|readwrite)(\s+|,|\))/g, "$1$2$3"],
    [/(\s+)(for|while|do|if|else|break|in)(\s+|\()/g, "$1$2$3"],
    [/(\s+|:)(YES|NO|return|break|continue|)(\s+|;)/g, "$1$2$3"],
    [/(\s+|\()(void|BOOL)(\s+|\))/g, "$1$2$3"],
    [/(\/\*(?:[\s\S]*?)\*\/)|(\/\/(?:.*)$)/gm, "$1$2"],
    [/(\s+|:|,)([0-9])(\s+|:|,|;)/g, "$1$2$3"]
  ];

  Emphasize.query = ".highlight." + Emphasize.languages.join(" , .highlight.");
  Emphasize.regex = new RegExp("(\\s|^)(" + Emphasize.languages.join("|") + ")(\\s|$)", "i");

  var blocks = document.querySelectorAll(Emphasize.query);
  for(var i = 0; i < blocks.length; i++) {
      var block = blocks[i],
          text = (block.textContent || block.innerText).replace(/</g, "<").replace(/>/g, ">"),
          language;

      if(language = block.className.match(Emphasize.regex)) {
        var rules = Emphasize.rules[language[2]];
        for(var r = 0; r < rules.length; r++) {
          var rule = rules[r];
          text = text.replace(rule[0], rule[1]);
        }
      }

      block.innerHTML = "
" + text + "
";
  };

})();
<commit_msg>Fix syntax highlighting<commit_after>/// http://samvermette.com/313
/// Forked for CocoaDocs: https://github.com/orta/emphasize.js

(function() {

  var Emphasize = { "rules": {} };
  Emphasize.languages = ["highlight-objective-c", "highlight-objc"];
  var objc_rules = [
    [/(#)(.+)(\n)/g, "$1$2$3"],
    [/(\[|^|<|\(|\s+)([A-Z]{2}[a-zA-Z]{3,})(\s|\*|>|;|,)/g, "$1$2$3"],
    [/(\[|^|\(|\s+)(\w{3,})(\()/g, "$1$2$3"],
    [/(@")([^"]+)(",|"])/g, "$1$2$3"],
    [/(#.*)("|<)(.*)("|>)/g, "$1$2$3$4"],
    [/(\s+)(\w+)(:|])/g, "$1$2$3"],
    [/(\.)([a-zA-Z]{3,})(\s{1}|]|;|\)|,)/g, "$1$2$3"],
    [/(:|\s+)([A-Z]{2}\w{3,})(;|\s|])/g, "$1$2$3"],
    [/(self|super|nil|@end|@implementation|@synthesize|@property|@interface|@selector|@class)/g, "$1"],
    [/(\s+|\(|,)(strong|retain|weak|assign|nonatomic|atomic|readonly|readwrite)(\s+|,|\))/g, "$1$2$3"],
    [/(\s+)(for|while|do|if|else|break|in)(\s+|\()/g, "$1$2$3"],
    [/(\s+|:)(YES|NO|return|break|continue|)(\s+|;)/g, "$1$2$3"],
    [/(\s+|\()(void|BOOL)(\s+|\))/g, "$1$2$3"],
    [/(\/\*(?:[\s\S]*?)\*\/)|(\/\/(?:.*)$)/gm, "$1$2"],
    [/(\s+|:|,)([0-9])(\s+|:|,|;)/g, "$1$2$3"]
  ];
  Emphasize.rules["highlight-objective-c"] = objc_rules
  Emphasize.rules["highlight-objc"] = objc_rules

  Emphasize.query = ".highlight." + Emphasize.languages.join(" , .highlight.");
  Emphasize.regex = new RegExp("(\\s|^)(" + Emphasize.languages.join("|") + ")(\\s|$)", "i");

  var blocks = document.querySelectorAll(Emphasize.query);
  for(var i = 0; i < blocks.length; i++) {
      var block = blocks[i],
          text = (block.textContent || block.innerText).replace(/</g, "<").replace(/>/g, ">"),
          language;

      if(language = block.className.match(Emphasize.regex)) {
        var rules = Emphasize.rules[language[2]];
        for(var r = 0; r < rules.length; r++) {
          var rule = rules[r];
          text = text.replace(rule[0], rule[1]);
        }
      }

      block.innerHTML = "
" + text + "
";
  };

})();
<|endoftext|>


<commit_before>goog.provide('olcs.RasterSynchronizer');

goog.require('goog.events');

goog.require('olcs.OLImageryProvider');

/**
 * This object takes care of one-directional synchronization of
 * ol3 raster layers to the given Cesium globe.
 * @param {!ol.Collection} olLayers
 * @param {!Cesium.ImageryLayerCollection} cesiumLayers
 * @constructor
 */
olcs.RasterSynchronizer = function(olLayers, cesiumLayers) {
  /**
   * @type {!ol.Collection}
   * @private
   */
  this.olLayers_ = olLayers;

  /**
   * @type {!Cesium.ImageryLayerCollection}
   * @private
   */
  this.cesiumLayers_ = cesiumLayers;

  /**
   * Map of ol3 layer ids (from goog.getUid) to the Cesium ImageryLayers.
   * null value means, that we are unable to create equivalent layer.
   * @type {Object.<number, ?Cesium.ImageryLayer>}
   * @private
   */
  this.layerMap_ = {};

  goog.events.listen(/** @type {!goog.events.EventTarget} */(this.olLayers_),
      goog.events.EventType.CHANGE, function(e) {
        this.synchronize_();
      }, false, this);

  this.synchronize_();
};

/**
 * @private
 */
olcs.RasterSynchronizer.prototype.synchronize_ = function() {
  var unusedCesiumLayers = goog.object.transpose(this.layerMap_);
  this.cesiumLayers_.removeAll(false);

  this.olLayers_.forEach(function(el, i, arr) {
    var olLayerId = goog.getUid(el);
    var cesiumLayer = this.layerMap_[olLayerId];

    // no mapping -> create new layer and set up synchronization
    if (!goog.isDef(cesiumLayer)) {
      cesiumLayer = olcs.RasterSynchronizer.createCorrespondingLayer(el);
      if (!goog.isNull(cesiumLayer)) {
        goog.events.listen(el,
            ['change:brightness', 'change:contrast', 'change:hue',
             'change:opacity', 'change:saturation', 'change:visible'],
            function(e) {
              olcs.RasterSynchronizer.syncLayerProperties(el, cesiumLayer);
            });

        // there is no way to modify Cesium layer extent,
        // we have to recreate when ol3 layer extent changes:
        goog.events.listen(el, 'change:extent', function(e) {
          this.cesiumLayers_.remove(cesiumLayer, true); // destroy
          delete this.layerMap_[olLayerId]; // invalidate the map entry
          this.synchronize_();
        }, false, this);
      }
      this.layerMap_[olLayerId] = cesiumLayer;
    }

    // add Cesium layers
    if (cesiumLayer) {
      this.cesiumLayers_.add(cesiumLayer);
      delete unusedCesiumLayers[cesiumLayer];
    }
  }, this);

  // destroy unused Cesium ImageryLayers
  goog.object.forEach(unusedCesiumLayers, function(val, key, obj) {
    if (goog.isDefAndNotNull(val)) {
      delete this.layerMap_[key];
      val.destroy();
    }
  }, this);
};

/**
 * @param {!ol.layer.Layer} olLayer
 * @return {?Cesium.ImageryLayer}
 */
olcs.RasterSynchronizer.createCorrespondingLayer = function(olLayer) {
  if (!(olLayer instanceof ol.layer.Tile)) {
    return null;
  }

  var provider = null;

  var source = olLayer.getSource();
  // handle special cases before this general synchronization
  if (source instanceof ol.source.TileImage) {
    var projection = source.getProjection();
    var is3857 = projection === ol.proj.get('EPSG:3857');
    var is4326 = projection === ol.proj.get('EPSG:4326');
    if (is3857 || is4326) {
      provider = new olcs.OLImageryProvider(source);
    }
  }

  if (goog.isNull(provider)) {
    return null;
  } else {
    var ext = olLayer.getExtent();
    var rectangle = goog.isDefAndNotNull(ext) ?
        new Cesium.Rectangle(ext[0], ext[1], ext[2], ext[3]) : undefined;
    var cesiumLayer = new Cesium.ImageryLayer(provider, {
      rectangle: rectangle
    });
    olcs.RasterSynchronizer.syncLayerProperties(olLayer, cesiumLayer);
    return cesiumLayer;
  }
};

/**
 * Synchronizes the layer rendering properties (brightness, contrast, hue,
 * opacity, saturation, visible) to the given Cesium ImageryLayer.
 * @param {!ol.layer.Layer} olLayer
 * @param {!Cesium.ImageryLayer} csLayer
 */
olcs.RasterSynchronizer.syncLayerProperties = function(olLayer, csLayer) {
  var brightness = olLayer.getBrightness();
  if (goog.isDef(brightness)) {
    csLayer.brightness = 1 + brightness;
  }

  var contrast = olLayer.getContrast();
  if (goog.isDef(contrast)) {
    csLayer.contrast = contrast;
  }

  var hue = olLayer.getHue();
  if (goog.isDef(hue)) {
    csLayer.hue = hue;
  }

  var opacity = olLayer.getOpacity();
  if (goog.isDef(opacity)) {
    csLayer.alpha = opacity;
  }

  var saturation = olLayer.getSaturation();
  if (goog.isDef(saturation)) {
    csLayer.saturation = saturation;
  }

  var visible = olLayer.getVisible();
  if (goog.isDef(visible)) {
    csLayer.show = visible;
  }
};
<commit_msg>Improved synchronization of raster layer properties<commit_after>goog.provide('olcs.RasterSynchronizer');

goog.require('goog.events');

goog.require('olcs.OLImageryProvider');

/**
 * This object takes care of one-directional synchronization of
 * ol3 raster layers to the given Cesium globe.
 * @param {!ol.Collection} olLayers
 * @param {!Cesium.ImageryLayerCollection} cesiumLayers
 * @constructor
 */
olcs.RasterSynchronizer = function(olLayers, cesiumLayers) {
  /**
   * @type {!ol.Collection}
   * @private
   */
  this.olLayers_ = olLayers;

  /**
   * @type {!Cesium.ImageryLayerCollection}
   * @private
   */
  this.cesiumLayers_ = cesiumLayers;

  /**
   * Map of ol3 layer ids (from goog.getUid) to the Cesium ImageryLayers.
   * null value means, that we are unable to create equivalent layer.
   * @type {Object.<number, ?Cesium.ImageryLayer>}
   * @private
   */
  this.layerMap_ = {};

  goog.events.listen(/** @type {!goog.events.EventTarget} */(this.olLayers_),
      goog.events.EventType.CHANGE, function(e) {
        this.synchronize_();
      }, false, this);

  this.synchronize_();
};

/**
 * @private
 */
olcs.RasterSynchronizer.prototype.synchronize_ = function() {
  var unusedCesiumLayers = goog.object.transpose(this.layerMap_);
  this.cesiumLayers_.removeAll(false);

  this.olLayers_.forEach(function(el, i, arr) {
    var olLayerId = goog.getUid(el);
    var cesiumLayer = this.layerMap_[olLayerId];

    // no mapping -> create new layer and set up synchronization
    if (!goog.isDef(cesiumLayer)) {
      cesiumLayer = olcs.RasterSynchronizer.createCorrespondingLayer(el);
      if (!goog.isNull(cesiumLayer)) {
        goog.events.listen(el,
            ['change:brightness', 'change:contrast', 'change:hue',
             'change:opacity', 'change:saturation', 'change:visible'],
            function(e) {
              olcs.RasterSynchronizer.syncLayerProperties(el, cesiumLayer);
            });

        // there is no way to modify Cesium layer extent,
        // we have to recreate when ol3 layer extent changes:
        goog.events.listen(el, 'change:extent', function(e) {
          this.cesiumLayers_.remove(cesiumLayer, true); // destroy
          delete this.layerMap_[olLayerId]; // invalidate the map entry
          this.synchronize_();
        }, false, this);
      }
      this.layerMap_[olLayerId] = cesiumLayer;
    }

    // add Cesium layers
    if (cesiumLayer) {
      this.cesiumLayers_.add(cesiumLayer);
      delete unusedCesiumLayers[cesiumLayer];
    }
  }, this);

  // destroy unused Cesium ImageryLayers
  goog.object.forEach(unusedCesiumLayers, function(val, key, obj) {
    if (goog.isDefAndNotNull(val)) {
      delete this.layerMap_[key];
      val.destroy();
    }
  }, this);
};

/**
 * @param {!ol.layer.Layer} olLayer
 * @return {?Cesium.ImageryLayer}
 */
olcs.RasterSynchronizer.createCorrespondingLayer = function(olLayer) {
  if (!(olLayer instanceof ol.layer.Tile)) {
    return null;
  }

  var provider = null;

  var source = olLayer.getSource();
  // handle special cases before this general synchronization
  if (source instanceof ol.source.TileImage) {
    var projection = source.getProjection();
    var is3857 = projection === ol.proj.get('EPSG:3857');
    var is4326 = projection === ol.proj.get('EPSG:4326');
    if (is3857 || is4326) {
      provider = new olcs.OLImageryProvider(source);
    }
  }

  if (goog.isNull(provider)) {
    return null;
  } else {
    var ext = olLayer.getExtent();
    var rectangle = goog.isDefAndNotNull(ext) ?
        new Cesium.Rectangle(ext[0], ext[1], ext[2], ext[3]) : undefined;
    var cesiumLayer = new Cesium.ImageryLayer(provider, {
      rectangle: rectangle
    });
    olcs.RasterSynchronizer.syncLayerProperties(olLayer, cesiumLayer);
    return cesiumLayer;
  }
};

/**
 * Synchronizes the layer rendering properties (brightness, contrast, hue,
 * opacity, saturation, visible) to the given Cesium ImageryLayer.
 * @param {!ol.layer.Layer} olLayer
 * @param {!Cesium.ImageryLayer} csLayer
 */
olcs.RasterSynchronizer.syncLayerProperties = function(olLayer, csLayer) {
  var opacity = olLayer.getOpacity();
  if (goog.isDef(opacity)) {
    csLayer.alpha = opacity;
  }
  var visible = olLayer.getVisible();
  if (goog.isDef(visible)) {
    csLayer.show = visible;
  }

  // saturation and contrast are working ok
  var saturation = olLayer.getSaturation();
  if (goog.isDef(saturation)) {
    csLayer.saturation = saturation;
  }
  var contrast = olLayer.getContrast();
  if (goog.isDef(contrast)) {
    csLayer.contrast = contrast;
  }

  // Cesium actually operates in YIQ space -> hard to emulate
  // The following values are only a rough approximations:

  // The hue in Cesium has different meaning than the OL equivalent.
  // var hue = olLayer.getHue();
  // if (goog.isDef(hue)) {
  //   csLayer.hue = hue;
  // }

  var brightness = olLayer.getBrightness();
  if (goog.isDef(brightness)) {
    // rough estimation
    csLayer.brightness = Math.pow(1 + parseFloat(brightness), 2);
  }
};
<|endoftext|>


<commit_before>enyo.kind({
	name: 'Bootplate.TestRouter'
  , kind: 'enyo.Router',

		//*@public
		/**
			If true, the router will respond to hash changes or internal events.
			If this flag is set to false, it will stop responding. This may be
			changed at any time.
		*/
		listening: true,

		//*@public
		/**
			If true, the router will neither respond to hash changes in the
			browser nor be able to trigger them. Instead, it may be used
			internally to maintain or trigger state changes in an application
			without changing location.
		*/
		internalOnly: false,

		//*@public
		/**
			The _defaultRoute_ should have the same structure as a normal
			route (hash). It may be arbitrarily assigned to this property
			or mixed into the routes array with a special _default: true_
			flag set. For any unmatched hash changes, this route will be
			executed and passed the path that was not matched.
		*/
		defaultRoute: null,

		//*@public
		/**
			By default, when a router is created, it will attempt to trigger
			the correct route for the current browser location. Set this
			to false to prevent this from happening.
		*/
		triggerOnStart: true,

		//*@public
		/**
			The _routes_ array constitutes the handlers for this router.
			Routes are string paths, static or dynamic, that route particular
			hash change events. They are defined in an array of hashes with
			a _handler_ (function), _path_ (for static and dynamic paths), an
			optional _context_ (for the handler), or a _default_ boolean true|false
			where that handler will be used when no other route can handle the
			hashchange event.
		*/
		routes: null,

		// ...........................
		// PROTECTED PROPERTIES

		//*@protected
		kind: "enyo.Controller",

		//*@protected
		_static_routes: null,

		//*@protected
		_dynamic_routes: null,

		//*@protected
		_current: "",

		// ...........................
		// COMPUTED PROPERTIES

		//*@public
		/**
			A computed property that will return the location as
			known by this router. This property will be synchronized
			with _window.location.hash_ unless it's _internalOnly_
			flag was set to true. Passing a string to this property
			via _set("location", "mylocation")_ will update the inner
			location known by this router.
		*/
		location: enyo.computed(function (loc) {
			if (loc) {
				loc = prepare(loc);
				if (!this.internalOnly) {
					window.location.hash = loc;
				} else {
					this.set("_current", loc);
				}
			} else {
				return prepare(this.get("_current"));
			}
		}, "_current", {cached: true}),

		// ...........................
		// PUBLIC METHODS

		//*@public
		/**
			Triggers a change without necessarily requiring a change to	occur.
			If called without a parameter, it will force the route that matches
			the current browser location to fire. If a string is passed in, this
			method will trigger an internal-only event (i.e., the	browser
			location will not be changed). If it is passed a hash, the method
			will try to use a _location_ property while looking for optional
			_change_ and _global_ properties.

			If the _change_ property is present and true, it will force a
			_location.hash_ change in the browser (this is always global).
			If the _global_ property is present and true and _change_ is
			not present or false, it will trigger an internal event that
			all routers will respond to (not just this instance).
		*/
		trigger: function (params) {
			if (!params) {
				params = {location: this.get("_current")};
			} else if ("string" === typeof params) {
				params = {location: params};
			}
			var loc = params.location;
			var global = params.global;
			var change = params.change;
			if (change) {
				window.location.hash = loc;
			} else {
				if (global) {
					hashDidChange(loc);
				} else {
					this._hash_changed(loc);
				}
			}
		},

		//*@public
		/**
			In very rare circumstances it may be useful to pass a path
			to the routes without using trigger or global hash changes
			with _path_ being a string that will be evaluated against
			the routes owned by this router.
		*/
		handle: function (path) {
			// fast track is to check against static routes first
			if (this._handle_static(path)) {
				return;
			}
			// then we check against dynamic paths in this simple scheme
			else if (this._handle_dynamic(path)) {
				/* do nothing */
			}
			else {
				this._handle_default(path);
			}
		},

		//*@public
		/**
			Can be used to programmatically add routes to the router
			where _route_ is a hash as described by the _routes_ array.
		*/
		addRoute: function (route) {
			var statics = this._static_routes;
			var dynamic = this._dynamic_routes;
			var regex;
			if (true === route['default']) {
				this.defaultRoute = route;
			}
			else if (token.test(route.path)) {
				regex = new RegExp(route.path.replace(token, "([a-zA-Z0-9]*)"));
				route.regex = regex;
				dynamic.push(route);
			} else {
				statics[route.path] = route;
			}
		},

		// ...........................
		// PROTECTED METHODS

		//*@protected
		constructor: function () {
			this._static_routes = {};
			this._dynamic_routes = [];
			this.inherited(arguments);
		},

		//*@protected
		create: function () {
			this.inherited(arguments);
			// make sure to initialize our routes prior
			// to registering for events
			this._setup_routes();
			// make sure we're up to date
			this.set("_current", prepare(window.location.hash));
			// ok, register for events
			listeners.push(this);
			// ok, if we need to go ahead and route our current
			// location, lets do it
			if (this.triggerOnStart) {
				this.trigger();
			}
		},

		//*@protected
		destroy: function () {
			var idx = enyo.indexOf(this, listeners);
			if (!~idx) {
				listeners.splice(idx, 1);
			}
			this.inherited(arguments);
		},

		//*@protected
		_hash_changed: function (hash) {
			hash = (function (prop) {
				if ("string" !== typeof hash) {
					// some browsers do not support the newUrl property
					// so we're forced to look at the current hash
					prop = hash.newUrl || window.location.hash;
				}
				return prepare(prop);
			})(hash || {});
			if (this.listening) {
				this.set("_current", hash);
				this.handle(hash);
			}
		},

		//*@protected
		_exec_handler: function (context, handler, args, route) {
			var fn = handler;
			// if the handler is defined as a string, we need to determine if
			// it is relative to the router, relative to the context, or a named
			// function in the global scope
			if ("string" === typeof handler) {
				if (context) {
					if ("string" === typeof context) {
						context = enyo.getPath(context);
					}
				}
				else {
					context = this;
				}
				// first check to see if the handler is a named property
				// on the router; otherwise, try the context itself
				fn = this[handler] || context[handler];
				if ("function" === typeof fn) {
					// in case we actually found it, let's not go hunting
					// next time
					route.handler = fn;
					route.context = context;
				}
			}
			// if we have an actual handler, let's execute it now
			if (fn && "function" === typeof fn) {
				fn.apply(context, args);
				return true;
			}
			// otherwise we couldn't determine what we were supposed to
			// do here
			return false;
		},

		//*@protected
		_handle_static: function (path) {
			var statics = this._static_routes;
			var route;
			var handler;
			var context;
			if ((route = statics[path])) {
				handler = route.handler;
				context = route.context;
				return this._exec_handler(context, handler, [path], route);
			}
			return false;
		},

		//*@protected
		_handle_dynamic: function (path) {
			var dynamic = this._dynamic_routes;
			var regex;
			var route;
			var handler;
			var context;
			var matches;
			var idx = 0;
			var len = dynamic.length;
			for (; idx < len; ++idx) {
				route = dynamic[idx];
				regex = route.regex;
				if ((matches = regex.exec(path))) {
					// we need to strip off the full match so we can
					// use the other matches as parameters
					matches = matches.slice(1);
					handler = route.handler;
					context = route.context;
					return this._exec_handler(context, handler, matches, route);
				}
			}
			return false;
		},

		//*@protected
		_handle_default: function (path) {
			var route = this.defaultRoute || {};
			var context = route.context;
			var handler = route.handler;
			return this._exec_handler(context, handler, [path], route);
		},

		//*@protected
		_setup_routes: function () {
			var routes = this.routes;
			var idx = 0;
			var len = routes.length;
			var route;
			for (; idx < len; ++idx) {
				route = routes[idx];
				if (!route) {
					continue;
				}
				this.addRoute(route);
			}
		}

	});<commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';
import {updateIntl} from 'react-intl-redux';

import i18n from './../../utils/i18n';

export const SET_APP_LOCALE = 'garchen-panel/main/SET_APP_LOCALE';
export const OPEN_EXTERNAL = 'garchen-panel/main/OPEN_EXTERNAL';
export const OPEN_EXTERNAL_SUCCESS = 'garchen-panel/main/OPEN_EXTERNAL_SUCCESS';
export const OPEN_EXTERNAL_FAIL = 'garchen-panel/main/OPEN_EXTERNAL_FAIL';
export const SET_WRITE_DELAY = 'garchen-panel/main/SET_WRITE_DELAY';
export const SET_APP_FONT = 'garchen-panel/main/SET_APP_FONT';
export const SET_INTERFACE_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_INTERFACE_FONT_SIZE_SCALING_FACTOR';
export const SET_CONTENT_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_CONTENT_FONT_SIZE_SCALING_FACTOR';
export const GET_APP_VERSION = 'garchen-panel/main/GET_APP_VERSION';
export const GET_APP_VERSION_SUCCESS = 'garchen-panel/main/GET_APP_VERSION_SUCCESS';
export const GET_APP_VERSION_FAIL = 'garchen-panel/main/GET_APP_VERSION_FAIL';
export const ADD_ROUTE_HISTORY = 'garchen-panel/main/ADD_ROUTE_HISTORY';
export const CLEAR_ROUTE_HISTORY = 'garchen-panel/main/CLEAR_ROUTE_HISTORY';

const initialState = Map({
  appVersion: '',
  appLocale: 'en',
  appFont: 'Tibetan Machine Uni',
  writeDelay: 50,
  routeHistory: []
});

export default createReducer(initialState, {

  [SET_APP_LOCALE]: (state, action) => {
    return state.set('appLocale', action.appLocale);
  },

  [SET_WRITE_DELAY]: (state, action) => {
    return state.set('writeDelay', action.writeDelay);
  },

  [SET_APP_FONT]: (state, action) => {
    return state.set('appFont', action.appFont);
  },

  [GET_APP_VERSION_SUCCESS]: (state, action) => {
    return state.set('appVersion', action.result.appVersion);
  },

  [ADD_ROUTE_HISTORY]: (state, action) => {
    let routeHistory = state.get('routeHistory');
    routeHistory.push(action.record);

    // keep the newest two history records
    if (routeHistory.length > 2) {
      routeHistory = [routeHistory[1], routeHistory[2]];
    }

    return state.set('routeHistory', routeHistory);
  }
});

export function setAppFont(appFont) {
  return {
    type: SET_APP_FONT,
    appFont
  };
}

export function setAppLocale(appLocale) {
  return {
    type: SET_APP_LOCALE,
    appLocale
  };
}

export function setWriteDelay(writeDelay) {
  return {
    type: SET_WRITE_DELAY,
    writeDelay
  };
}

export function setIntl(locale = 'en') {
  return (dispatch) => {
    dispatch(setAppLocale(locale));
    return dispatch(updateIntl({
      locale,
      messages: i18n.getLocaleData(locale)
    }));
  };
}

export function openExternal(url) {
  return {
    types: [OPEN_EXTERNAL, OPEN_EXTERNAL_SUCCESS, OPEN_EXTERNAL_FAIL],
    promise: (client) => {
      return client.send('open-external', {url});
    }
  };
}

export function getAppVersion() {
  return {
    types: [GET_APP_VERSION, GET_APP_VERSION_SUCCESS, GET_APP_VERSION_FAIL],
    promise: (client) => {
      return client.send('get-app-version');
    }
  };
}

export function addRouteHistory(record) {
  return {
    type: ADD_ROUTE_HISTORY,
    record
  };
}
<commit_msg>add function clearRouteHistory<commit_after>import {Map} from 'immutable';
import {createReducer} from 'redux-immutablejs';
import {updateIntl} from 'react-intl-redux';

import i18n from './../../utils/i18n';

export const SET_APP_LOCALE = 'garchen-panel/main/SET_APP_LOCALE';
export const OPEN_EXTERNAL = 'garchen-panel/main/OPEN_EXTERNAL';
export const OPEN_EXTERNAL_SUCCESS = 'garchen-panel/main/OPEN_EXTERNAL_SUCCESS';
export const OPEN_EXTERNAL_FAIL = 'garchen-panel/main/OPEN_EXTERNAL_FAIL';
export const SET_WRITE_DELAY = 'garchen-panel/main/SET_WRITE_DELAY';
export const SET_APP_FONT = 'garchen-panel/main/SET_APP_FONT';
export const SET_INTERFACE_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_INTERFACE_FONT_SIZE_SCALING_FACTOR';
export const SET_CONTENT_FONT_SIZE_SCALING_FACTOR = 'garchen/main/SET_CONTENT_FONT_SIZE_SCALING_FACTOR';
export const GET_APP_VERSION = 'garchen-panel/main/GET_APP_VERSION';
export const GET_APP_VERSION_SUCCESS = 'garchen-panel/main/GET_APP_VERSION_SUCCESS';
export const GET_APP_VERSION_FAIL = 'garchen-panel/main/GET_APP_VERSION_FAIL';
export const ADD_ROUTE_HISTORY = 'garchen-panel/main/ADD_ROUTE_HISTORY';
export const CLEAR_ROUTE_HISTORY = 'garchen-panel/main/CLEAR_ROUTE_HISTORY';

const initialState = Map({
  appVersion: '',
  appLocale: 'en',
  appFont: 'Tibetan Machine Uni',
  writeDelay: 50,
  routeHistory: []
});

export default createReducer(initialState, {

  [SET_APP_LOCALE]: (state, action) => {
    return state.set('appLocale', action.appLocale);
  },

  [SET_WRITE_DELAY]: (state, action) => {
    return state.set('writeDelay', action.writeDelay);
  },

  [SET_APP_FONT]: (state, action) => {
    return state.set('appFont', action.appFont);
  },

  [GET_APP_VERSION_SUCCESS]: (state, action) => {
    return state.set('appVersion', action.result.appVersion);
  },

  [ADD_ROUTE_HISTORY]: (state, action) => {
    let routeHistory = state.get('routeHistory');
    routeHistory.push(action.record);

    // keep the newest two history records
    if (routeHistory.length > 2) {
      routeHistory = [routeHistory[1], routeHistory[2]];
    }

    return state.set('routeHistory', routeHistory);
  },

  [CLEAR_ROUTE_HISTORY]: state => {
    return state.set('routeHistory', []);
  }
});

export function setAppFont(appFont) {
  return {
    type: SET_APP_FONT,
    appFont
  };
}

export function setAppLocale(appLocale) {
  return {
    type: SET_APP_LOCALE,
    appLocale
  };
}

export function setWriteDelay(writeDelay) {
  return {
    type: SET_WRITE_DELAY,
    writeDelay
  };
}

export function setIntl(locale = 'en') {
  return (dispatch) => {
    dispatch(setAppLocale(locale));
    return dispatch(updateIntl({
      locale,
      messages: i18n.getLocaleData(locale)
    }));
  };
}

export function openExternal(url) {
  return {
    types: [OPEN_EXTERNAL, OPEN_EXTERNAL_SUCCESS, OPEN_EXTERNAL_FAIL],
    promise: (client) => {
      return client.send('open-external', {url});
    }
  };
}

export function getAppVersion() {
  return {
    types: [GET_APP_VERSION, GET_APP_VERSION_SUCCESS, GET_APP_VERSION_FAIL],
    promise: (client) => {
      return client.send('get-app-version');
    }
  };
}

export function addRouteHistory(record) {
  return {
    type: ADD_ROUTE_HISTORY,
    record
  };
}

export function clearRouteHistory() {
  return {
    type: CLEAR_ROUTE_HISTORY
  };
}
<|endoftext|>


<commit_before>'use strict'

module.exports = {
  env: {
    browser: true,
    node: false,
  },

  plugins: [
    'babel',
    'react',
  ],

  extends: [
    '@strv/javascript/environments/react/v15',
    '@strv/javascript/environments/react/optional',
    '@strv/javascript/coding-styles/recommended',
  ],

  rules: {
    'no-warning-comments': 0,
  }
}
<commit_msg>Tell ESLint we are in Node + Browser environment<commit_after>'use strict'

module.exports = {
  env: {
    'shared-node-browser': true,
  },

  plugins: [
    'babel',
    'react',
  ],

  extends: [
    '@strv/javascript/environments/react/v15',
    '@strv/javascript/environments/react/optional',
    '@strv/javascript/coding-styles/recommended',
  ],

  rules: {
    'no-warning-comments': 0,
  },
}
<|endoftext|>


<commit_before>var eyeballTestData = {};

var eyeball = {
    logger : {
        error : function(){},
        info : function(){}
    },
    DB : {
        find : function(one,two,three) {
            if(typeof two === "function") {
                return two(null,eyeballTestData);
            } else if(typeof three === "function") {
                return three(null,eyeballTestData);
            }
            eyeballTestData = {
                dbQuery : one,
                cfg : two,
                dbCfg : three
            };
            return {
                sort : function(cfg,cb) {
                    cb();
                }
            }
        }
    }
};

var exports = function () {
    return;
};

var spies = {};

var helpers = {
    require : function(name) {

        function returnIfExists(funcName) {
            if(window[funcName]) {
                return window[funcName]();
            }
            return null;
        }

        if(name === "fs") {

            var obj = {
                writeFile : function(file,data,cb) {
                    return cb();
                },
                readFile: function() {},
                unlink : function(){}
            };
            spies.writeFile = spyOn(obj,"writeFile");

            return obj;

        } else if(name === "yslow") {
            return {
                YSLOW : {
                    harImporter : {
                        run : function() {
                            return {
                                context : {
                                    PAGE : {
                                        overallScore : 90
                                    },
                                    result_set : {
                                        getRulesetApplied : function(){
                                            return {};
                                        },
                                        getResults: function(){
                                            return [{score : 90, message : 'I love eyeball',rule_id : "overall"}];
                                        }
                                    }
                                }
                            };
                        }
                    },
                    util : {
                        isArray : function(){},
                        getPageSpaceid : function(){}
                    },
                    doc : {
                        rules : {
                            myMadeUpRule : {
                                name : "Test rule"
                            }
                        }
                    }
                }
            }
        } else if (name === "jsdom") {
            return {
                jsdom : function() {}
            }
        } else if (name.indexOf('/conf/test') !== -1){
            return returnIfExists("configTest");
        } else if (name.indexOf('/conf/report') !== -1){
            return returnIfExists("configReport");
        } else if (name === './grader'){
            return returnIfExists("EyeballControllersTestGrader");
        } else if (name === './yslowOverride'){
           return returnIfExists("EyeballControllersTestYslowOverride");
        } else if (name === './phantom'){
            return returnIfExists("EyeballControllersTestPhantom");
        } else if (name === './validator'){
            return returnIfExists("EyeballControllersTestValidator");
        } else if (name.indexOf('controllers/test/test') !== -1){
            return EyeballControllersTestTest;
        } else if(name === "child_process") {
            var on = function(evt,cb){
                return cb();
            };
            var stdout = {
                on : on
            };
            var stderr = stdout;
            return {
                exec : function(){
                    return {
                        on : on,
                        stdout : stdout,
                        stderr : stderr
                    }
                }
            }
        } else if(name === "url") {
            return {
                init : function(data) {
                    eyeballTestData = data;
                },
                parse : function() {
                    eyeballTestData.path = {
                        match : function() {
                            return eyeballTestData;
                        }
                    };
                    return eyeballTestData;
                }
            }
        } else if (name === "phantom") {
            return {
                create : function(){}
            }
        } else if (name === "phantomjs") {
            return {
                path : "somepath"
            }
        } else if (name === "mongojs") {
            return {
                ObjectId : function(){}
            }
        } else if (name.indexOf("/util") !== -1) {
            return EyeballUtil();
        } else if (name === "q") {
            return {
                defer : function(){
                    return {
                        resolve : function() {}
                    }
                }
            }
        } else if (name === "lodash") {
            return {
                find : function(){}
            }
        }

        return function(args) {
            return args || {};
        }
    },
    res : {
        headers : {},
        setHeader : function(name,value) {
            this.headers[name] = value;
        },
        send : function(output) {
            this.output = output;
        }
    },

    process : {
        on : function(){}
    }
};

require = helpers.require;
process = helpers.process;<commit_msg>remove caching from phantom because its pretty shoddy. Use the proxy to do the caching instead. Revert to node-phantom-simple as it seems more stable (presumably cos its not using WS)<commit_after>var eyeballTestData = {};

var eyeball = {
    logger : {
        error : function(){},
        info : function(){}
    },
    DB : {
        find : function(one,two,three) {
            if(typeof two === "function") {
                return two(null,eyeballTestData);
            } else if(typeof three === "function") {
                return three(null,eyeballTestData);
            }
            eyeballTestData = {
                dbQuery : one,
                cfg : two,
                dbCfg : three
            };
            return {
                sort : function(cfg,cb) {
                    cb();
                }
            }
        }
    }
};

var exports = function () {
    return;
};

var spies = {};

var helpers = {
    require : function(name) {

        function returnIfExists(funcName) {
            if(window[funcName]) {
                return window[funcName]();
            }
            return null;
        }

        if(name === "fs") {

            var obj = {
                writeFile : function(file,data,cb) {
                    return cb();
                },
                readFile: function() {},
                unlink : function(){}
            };
            spies.writeFile = spyOn(obj,"writeFile");

            return obj;

        } else if(name === "yslow") {
            return {
                YSLOW : {
                    harImporter : {
                        run : function() {
                            return {
                                context : {
                                    PAGE : {
                                        overallScore : 90
                                    },
                                    result_set : {
                                        getRulesetApplied : function(){
                                            return {};
                                        },
                                        getResults: function(){
                                            return [{score : 90, message : 'I love eyeball',rule_id : "overall"}];
                                        }
                                    }
                                }
                            };
                        }
                    },
                    util : {
                        isArray : function(){},
                        getPageSpaceid : function(){}
                    },
                    doc : {
                        rules : {
                            myMadeUpRule : {
                                name : "Test rule"
                            }
                        }
                    }
                }
            }
        } else if (name === "jsdom") {
            return {
                jsdom : function() {}
            }
        } else if (name.indexOf('/conf/test') !== -1){
            return returnIfExists("configTest");
        } else if (name.indexOf('/conf/report') !== -1){
            return returnIfExists("configReport");
        } else if (name === './grader'){
            return returnIfExists("EyeballControllersTestGrader");
        } else if (name === './yslowOverride'){
           return returnIfExists("EyeballControllersTestYslowOverride");
        } else if (name === './phantom'){
            return returnIfExists("EyeballControllersTestPhantom");
        } else if (name === './validator'){
            return returnIfExists("EyeballControllersTestValidator");
        } else if (name.indexOf('controllers/test/test') !== -1){
            return EyeballControllersTestTest;
        } else if(name === "child_process") {
            var on = function(evt,cb){
                return cb();
            };
            var stdout = {
                on : on
            };
            var stderr = stdout;
            return {
                exec : function(){
                    return {
                        on : on,
                        stdout : stdout,
                        stderr : stderr
                    }
                }
            }
        } else if(name === "url") {
            return {
                init : function(data) {
                    eyeballTestData = data;
                },
                parse : function() {
                    eyeballTestData.path = {
                        match : function() {
                            return eyeballTestData;
                        }
                    };
                    return eyeballTestData;
                }
            }
        } else if (name === "node-phantom-simple") {
            return {
                create : function(){}
            }
        } else if (name === "phantomjs") {
            return {
                path : "somepath"
            }
        } else if (name === "mongojs") {
            return {
                ObjectId : function(){}
            }
        } else if (name.indexOf("/util") !== -1) {
            return EyeballUtil();
        } else if (name === "q") {
            return {
                defer : function(){
                    return {
                        resolve : function() {}
                    }
                }
            }
        } else if (name === "lodash") {
            return {
                find : function(){}
            }
        }

        return function(args) {
            return args || {};
        }
    },
    res : {
        headers : {},
        setHeader : function(name,value) {
            this.headers[name] = value;
        },
        send : function(output) {
            this.output = output;
        }
    },

    process : {
        on : function(){}
    }
};

require = helpers.require;
process = helpers.process;<|endoftext|>


<commit_before>"use strict";

class gsuiDAW extends HTMLElement {
	#currentActionInd = -1
	#dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiDAW" )
	#children = GSUI.getTemplate( "gsui-daw" )
	#elements = GSUI.findElements( this.#children, {
		bpm: ".gsuiDAW-tempo-bpm",
		bPM: ".gsuiDAW-tempo-beatsPerMeasure",
		sPB: ".gsuiDAW-tempo-stepsPerBeat",
		name: ".gsuiDAW-cmp-name",
		vers: ".gsuiDAW-version-num",
		cmpSave: ".gsuiDAW-cmp-saveBtn",
		cmpIcon: ".gsuiDAW-cmp-localIcon",
		clock: "gsui-clock",
		spectrum: "gsui-spectrum",
		volume: ".gsuiDAW-volume gsui-slider",
		currentTime: ".gsuiDAW-areaTime gsui-slider",
		userAvatar: ".gsuiDAW-btn[data-action='profile']",
		historyList: ".gsuiDAW-history .gsuiDAW-dropdown-list",
	} )

	constructor() {
		super();
		Object.seal( this );

		this.onclick = this.#onclick.bind( this );
		GSUI.listenEvents( this, {
			gsuiSlider: {
				input: ( d, tar ) => this.#dispatch( tar.dataset.action, d.args[ 0 ] ),
				inputStart: GSUI.noop,
				inputEnd: GSUI.noop,
				change: GSUI.noop,
			},
		} );
	}

	// .........................................................................
	connectedCallback() {
		if ( this.#children ) {
			this.append( ...this.#children );
			this.#children = null;
			GSUI.recallAttributes( this, {
				saved: true,
				name: "",
				location: "local",
				bpm: 60,
				timedivision: "1/1",
				currenttime: 0,
				maxtime: 1,
				volume: 1,
			} );
		}
	}
	disconnectedCallback() {
	}
	static get observedAttributes() {
		return [ "bpm", "timedivision", "name", "volume", "currenttime", "maxtime", "location", "userAvatar", "version" ];
	}
	attributeChangedCallback( prop, prev, val ) {
		if ( !this.#children && prev !== val ) {
			switch ( prop ) {
				case "name":
					this.#elements.name.textContent = val;
					break;
				case "bpm":
					this.#elements.bpm.textContent = val;
					break;
				case "timedivision":
					this.#elements.bPM.textContent = val.split( "/" )[ 0 ];
					this.#elements.sPB.textContent = val.split( "/" )[ 1 ];
					break;
				case "volume":
					this.#elements.volume.setValue( val );
					break;
				case "currenttime":
					this.#elements.clock.setTime( val );
					this.#elements.currentTime.setValue( val );
					break;
				case "maxtime":
					GSUI.setAttribute( this.#elements.currentTime, "max", val );
					break;
				case "location":
					GSUI.setAttribute( this.#elements.cmpIcon, "data-icon", val === "local" ? "local" : "cloud" );
					GSUI.setAttribute( this.#elements.cmpSave, "data-icon", val === "local" ? "save" : "upload" );
					break;
				case "userAvatar":
					this.#elements.userAvatar.style.backgroundImage = `url("${ val }")`;
					break;
				case "version":
					this.#elements.vers.textContent = val;
					break;
			}
		}
	}

	// .........................................................................
	updateSpectrum( data ) {
		this.#elements.spectrum.draw( data );
	}
	clearHistory() {
		Array.prototype.forEach.call( this.#getActions(), a => a.remove() );
		this.#currentActionInd = -1;
	}
	stackAction( icon, desc ) {
		Array.prototype.forEach.call( this.#getActions(), a => "undone" in a.dataset && a.remove() );
		this.#elements.historyList.append( GSUI.getTemplate( "gsui-daw-history-action", { icon, desc } ) );
		this.#elements.historyList.scroll( 0, Number.MAX_SAFE_INTEGER );
		this.#currentActionInd = this.#getActions().length - 1;
	}
	undo() {
		if ( this.#currentActionInd >= 0 ) {
			GSUI.setAttribute( this.#getActions()[ this.#currentActionInd-- ], "data-undone", true );
		}
	}
	redo() {
		if ( this.#currentActionInd < this.#getActions().length - 1 ) {
			GSUI.setAttribute( this.#getActions()[ ++this.#currentActionInd ], "data-undone", false );
		}
	}
	#getActions() {
		return this.#elements.historyList.children;
	}

	// .........................................................................
	#onclick( e ) {
		const act = e.target.dataset.action;

		if ( act ) {
			switch ( act ) {
				case "focusSwitch":
				case "play":
				case "stop":
				case "reset":
				case "undo":
				case "redo":
					this.#dispatch( act );
					break;
				case "login":
				case "tempo":
				case "export":
				case "settings":
				case "cookie":
				case "keyboard":
				case "about":
					lg( "popup", act );
					break;
				case "rename":
					GSUI.popup.prompt( "Composition's title", "", this.getAttribute( "name" ), "Rename" )
						.then( n => {
							if ( n !== this.getAttribute( "name" ) ) {
								this.#dispatch( "rename", n );
							}
						} );
					break;
				default:
					lg( {act} );
					break;
			}
		}
	}
}

Object.seal( gsuiDAW );
customElements.define( "gsui-daw", gsuiDAW );
<commit_msg>gsuiDAW: event switch debug<commit_after>"use strict";

class gsuiDAW extends HTMLElement {
	#currentActionInd = -1
	#dispatch = GSUI.dispatchEvent.bind( null, this, "gsuiDAW" )
	#children = GSUI.getTemplate( "gsui-daw" )
	#elements = GSUI.findElements( this.#children, {
		bpm: ".gsuiDAW-tempo-bpm",
		bPM: ".gsuiDAW-tempo-beatsPerMeasure",
		sPB: ".gsuiDAW-tempo-stepsPerBeat",
		name: ".gsuiDAW-cmp-name",
		vers: ".gsuiDAW-version-num",
		cmpSave: ".gsuiDAW-cmp-saveBtn",
		cmpIcon: ".gsuiDAW-cmp-localIcon",
		clock: "gsui-clock",
		spectrum: "gsui-spectrum",
		volume: ".gsuiDAW-volume gsui-slider",
		currentTime: ".gsuiDAW-areaTime gsui-slider",
		userAvatar: ".gsuiDAW-btn[data-action='profile']",
		historyList: ".gsuiDAW-history .gsuiDAW-dropdown-list",
	} )

	constructor() {
		super();
		Object.seal( this );

		this.onclick = this.#onclick.bind( this );
		GSUI.listenEvents( this, {
			gsuiSlider: {
				input: ( d, tar ) => this.#dispatch( tar.dataset.action, d.args[ 0 ] ),
				inputStart: GSUI.noop,
				inputEnd: GSUI.noop,
				change: GSUI.noop,
			},
		} );
	}

	// .........................................................................
	connectedCallback() {
		if ( this.#children ) {
			this.append( ...this.#children );
			this.#children = null;
			GSUI.recallAttributes( this, {
				saved: true,
				name: "",
				location: "local",
				bpm: 60,
				timedivision: "1/1",
				currenttime: 0,
				maxtime: 1,
				volume: 1,
			} );
		}
	}
	disconnectedCallback() {
	}
	static get observedAttributes() {
		return [ "bpm", "timedivision", "name", "volume", "currenttime", "maxtime", "location", "userAvatar", "version" ];
	}
	attributeChangedCallback( prop, prev, val ) {
		if ( !this.#children && prev !== val ) {
			switch ( prop ) {
				case "name":
					this.#elements.name.textContent = val;
					break;
				case "bpm":
					this.#elements.bpm.textContent = val;
					break;
				case "timedivision":
					this.#elements.bPM.textContent = val.split( "/" )[ 0 ];
					this.#elements.sPB.textContent = val.split( "/" )[ 1 ];
					break;
				case "volume":
					this.#elements.volume.setValue( val );
					break;
				case "currenttime":
					this.#elements.clock.setTime( val );
					this.#elements.currentTime.setValue( val );
					break;
				case "maxtime":
					GSUI.setAttribute( this.#elements.currentTime, "max", val );
					break;
				case "location":
					GSUI.setAttribute( this.#elements.cmpIcon, "data-icon", val === "local" ? "local" : "cloud" );
					GSUI.setAttribute( this.#elements.cmpSave, "data-icon", val === "local" ? "save" : "upload" );
					break;
				case "userAvatar":
					this.#elements.userAvatar.style.backgroundImage = `url("${ val }")`;
					break;
				case "version":
					this.#elements.vers.textContent = val;
					break;
			}
		}
	}

	// .........................................................................
	updateSpectrum( data ) {
		this.#elements.spectrum.draw( data );
	}
	clearHistory() {
		Array.prototype.forEach.call( this.#getActions(), a => a.remove() );
		this.#currentActionInd = -1;
	}
	stackAction( icon, desc ) {
		Array.prototype.forEach.call( this.#getActions(), a => "undone" in a.dataset && a.remove() );
		this.#elements.historyList.append( GSUI.getTemplate( "gsui-daw-history-action", { icon, desc } ) );
		this.#elements.historyList.scroll( 0, Number.MAX_SAFE_INTEGER );
		this.#currentActionInd = this.#getActions().length - 1;
	}
	undo() {
		if ( this.#currentActionInd >= 0 ) {
			GSUI.setAttribute( this.#getActions()[ this.#currentActionInd-- ], "data-undone", true );
		}
	}
	redo() {
		if ( this.#currentActionInd < this.#getActions().length - 1 ) {
			GSUI.setAttribute( this.#getActions()[ ++this.#currentActionInd ], "data-undone", false );
		}
	}
	#getActions() {
		return this.#elements.historyList.children;
	}

	// .........................................................................
	#onclick( e ) {
		const act = e.target.dataset.action;

		if ( act ) {
			switch ( act ) {
				case "focusSwitch":
				case "play":
				case "stop":
				case "reset":
				case "undo":
				case "redo":
					this.#dispatch( act );
					break;
				case "login":
				case "tempo":
				case "export":
				case "settings":
				case "cookies":
				case "keyboard":
				case "about":
					lg( "popup", act );
					break;
				case "rename":
					GSUI.popup.prompt( "Composition's title", "", this.getAttribute( "name" ), "Rename" )
						.then( n => {
							if ( n !== this.getAttribute( "name" ) ) {
								this.#dispatch( "rename", n );
							}
						} );
					break;
				case "help":
				case "undoMore":
				case "changelog":
					break;
				default:
					lg( "ignored", act );
					break;
			}
		}
	}
}

Object.seal( gsuiDAW );
customElements.define( "gsui-daw", gsuiDAW );
<|endoftext|>


<commit_before>// Global tokenizer
//  tokenizes expressions and all that great stuff

import CheddarLexer from './tok/lex';
import CheddarEXPLICIT from './patterns/EXPLICIT';

import * as CheddarError from './consts/err';
import CheddarErrorMessage from './consts/err_msg';
import HelperLoc from '../helpers/loc';

import S1_ASSIGN from './states/assign';
import S2_IF from './states/if';
import S2_FOR from './states/for';
import S3_EXPR from './states/expr';

var CLOSES = '\n;';

const VALID_END = chr =>
    (CLOSES.indexOf(chr) > -1) || !chr;

const FORMAT_ERROR = (TOK, LEXER) => TOK
    .replace(/\$LOC/, HelperLoc(LEXER.Code, LEXER.Index).slice(0, 2).join(":"))
    .replace(/\$1/, LEXER.Code[LEXER.Index]);

export default class CheddarTokenize extends CheddarLexer {
    exec(ENDS = "") {

        let MATCH = this.attempt(
            S1_ASSIGN,
            S2_IF,
            S2_FOR,
            S3_EXPR
        );

        if (MATCH instanceof CheddarLexer && MATCH.Errored !== true) {

            this.Tokens = MATCH;
            this.Index = MATCH.Index;

            while (this.Code[this.Index] && /[\t\f ]/.test(this.Code[this.Index]) || this._jumpComment()) {
                this.Index++;
            }

            if (ENDS.indexOf(this.Code[this.Index]) > -1) {
                return this.close();
            }

            if (!(MATCH instanceof CheddarEXPLICIT) && !(VALID_END(this.Code[this.Index]))) {
                console.log("hahahahahahahahsidfuahsdodcbuav riulcas")
                return this.error(
                    FORMAT_ERROR(
                        CheddarErrorMessage.get(
                            CheddarError.UNEXPECTED_TOKEN
                        )
                    , this)
                );
            }

            this.Index++;

            this.jumpWhite();

            if (this.Code[this.Index]) {
                let M2 = new CheddarTokenize(this.Code, this.Index);
                let response = M2.exec(...arguments);

                if (response instanceof CheddarLexer) {
                    this._Tokens.push(...M2._Tokens);
                    this.Index = M2.Index;
                }
                else {
                    if (response !== CheddarError.EXIT_NOTFOUND)
                        return this.error(response);
                }

            }

            return this.close();
        }
        else {
            console.log("ERROR");
            if (MATCH instanceof CheddarLexer) {
                return this.error(
                    FORMAT_ERROR(
                        CheddarErrorMessage.get(
                            CheddarError.UNEXPECTED_TOKEN
                        )
                    , this)
                );
            } else {
                return this.error(
                    FORMAT_ERROR(
                        typeof MATCH === 'symbol'
                        ? CheddarErrorMessage.get( MATCH )
                        : MATCH.toString()
                    , this)
                );
            }
        }
    }

}<commit_msg>fix [tok]: implicit semicolons now work<commit_after>// Global tokenizer
//  tokenizes expressions and all that great stuff

import CheddarLexer from './tok/lex';
import CheddarEXPLICIT from './patterns/EXPLICIT';

import * as CheddarError from './consts/err';
import CheddarErrorMessage from './consts/err_msg';
import HelperLoc from '../helpers/loc';

import S1_ASSIGN from './states/assign';
import S2_IF from './states/if';
import S2_FOR from './states/for';
import S3_EXPR from './states/expr';

var CLOSES = '\n;';

const VALID_END = chr =>
    (CLOSES.indexOf(chr) > -1) || !chr;

const FORMAT_ERROR = (TOK, LEXER) => TOK
    .replace(/\$LOC/, HelperLoc(LEXER.Code, LEXER.Index).slice(0, 2).join(":"))
    .replace(/\$1/, LEXER.Code[LEXER.Index]);

const SINGLELINE_WHITESPACE = /[\t\f ]/;
const NEWLINE = /[\r\n]/;

export default class CheddarTokenize extends CheddarLexer {
    exec(ENDS = "") {

        let MATCH = this.attempt(
            S1_ASSIGN,
            S2_IF,
            S2_FOR,
            S3_EXPR
        );

        if (MATCH instanceof CheddarLexer && MATCH.Errored !== true) {

            this.Tokens = MATCH;
            this.Index = MATCH.Index;

            while (SINGLELINE_WHITESPACE.test(this.Code[this.Index])) {
                this.Index--;
            }
            if (NEWLINE.test(this.Code[this.Index - 1])) {
                this.Index--;
            }

            while (this.Code[this.Index] && SINGLELINE_WHITESPACE.test(this.Code[this.Index]) || this._jumpComment()) {
                this.Index++;
            }

            if (ENDS.indexOf(this.Code[this.Index]) > -1) {
                return this.close();
            }

            if (!(MATCH instanceof CheddarEXPLICIT) && !(VALID_END(this.Code[this.Index]))) {
                return this.error(
                    FORMAT_ERROR(
                        CheddarErrorMessage.get(
                            CheddarError.UNEXPECTED_TOKEN
                        )
                    , this)
                );
            }

            this.Index++;

            this.jumpWhite();

            if (this.Code[this.Index]) {
                let M2 = new CheddarTokenize(this.Code, this.Index);
                let response = M2.exec(...arguments);

                if (response instanceof CheddarLexer) {
                    this._Tokens.push(...M2._Tokens);
                    this.Index = M2.Index;
                }
                else {
                    if (response !== CheddarError.EXIT_NOTFOUND)
                        return this.error(response);
                }

            }

            return this.close();
        }
        else {
            if (MATCH instanceof CheddarLexer) {
                return this.error(
                    FORMAT_ERROR(
                        CheddarErrorMessage.get(
                            CheddarError.UNEXPECTED_TOKEN
                        )
                    , this)
                );
            } else {
                return this.error(
                    FORMAT_ERROR(
                        typeof MATCH === 'symbol'
                        ? CheddarErrorMessage.get( MATCH )
                        : MATCH.toString()
                    , this)
                );
            }
        }
    }

}<|endoftext|>


<commit_before>const React = require('react');
const {PropTypes} = React;
const ReactModal2 = require('react-modal2').default;
const {Gateway} = require('react-gateway');
const ReactCSSTransitionGroup = require('react-addons-css-transition-group');

class Modal extends React.Component {
  render() {
    var modalClassName = 'cf-modal';

    if (this.props.type === 'confirm') {
      modalClassName += ' cf-modal--confirm';
    }

    return (
      <Gateway into="modal">
        <ReactCSSTransitionGroup
          transitionName="cf-transition-modal"
          transitionAppear={true}
          transitionAppearTimeout={200}
          transitionEnterTimeout={200}
          transitionLeaveTimeout={200}>
          {this.props.isOpen && (

                <ReactModal2
                  ref="modal"
                  key="modal"
                  backdropClassName="cf-modal__backdrop"
                  modalClassName={modalClassName}
                  closeOnEsc={this.props.closeOnEsc}
                  closeOnBackdropClick={this.props.closeOnBackdropClick}
                  onClose={this.props.onRequestClose}>
                  {this.props.children}
                </ReactModal2>

          )}
        </ReactCSSTransitionGroup>
      </Gateway>
    );
  }
}

Modal.propTypes = {
  type: PropTypes.oneOf([
    'confirm'
  ]),
  isOpen: PropTypes.bool.isRequired,
  onRequestClose: PropTypes.func.isRequired,
  closeOnEsc: PropTypes.bool,
  closeOnBackdropClick: PropTypes.bool,
  children: PropTypes.node
};

Modal.defaultProps = {
  closeOnEsc: true,
  closeOnBackdropClick: true
};

module.exports = Modal;
<commit_msg>Add a wide modifier to Modal component<commit_after>const React = require('react');
const {PropTypes} = React;
const ReactModal2 = require('react-modal2').default;
const {Gateway} = require('react-gateway');
const ReactCSSTransitionGroup = require('react-addons-css-transition-group');

class Modal extends React.Component {
  render() {
    var modalClassName = 'cf-modal';

    if (this.props.type === 'confirm') {
      modalClassName += ' cf-modal--confirm';
    }

    if (this.props.width === 'wide') {
      modalClassName += ' cf-modal--wide';
    }

    return (
      <Gateway into="modal">
        <ReactCSSTransitionGroup
          transitionName="cf-transition-modal"
          transitionAppear={true}
          transitionAppearTimeout={200}
          transitionEnterTimeout={200}
          transitionLeaveTimeout={200}>
          {this.props.isOpen && (

                <ReactModal2
                  ref="modal"
                  key="modal"
                  backdropClassName="cf-modal__backdrop"
                  modalClassName={modalClassName}
                  closeOnEsc={this.props.closeOnEsc}
                  closeOnBackdropClick={this.props.closeOnBackdropClick}
                  onClose={this.props.onRequestClose}>
                  {this.props.children}
                </ReactModal2>

          )}
        </ReactCSSTransitionGroup>
      </Gateway>
    );
  }
}

Modal.propTypes = {
  type: PropTypes.oneOf([
    'confirm'
  ]),
  isOpen: PropTypes.bool.isRequired,
  onRequestClose: PropTypes.func.isRequired,
  closeOnEsc: PropTypes.bool,
  closeOnBackdropClick: PropTypes.bool,
  children: PropTypes.node,
  width: PropTypes.oneOf([
    'wide',
  ]),
};

Modal.defaultProps = {
  closeOnEsc: true,
  closeOnBackdropClick: true
};

module.exports = Modal;
<|endoftext|>


<commit_before>/*
 @author Zakai Hamilton
 @component MediaFile
 */

screens.media.file = function MediaFile(me, packages) {
    const { core, storage, media } = packages;
    me.rootPath = "/Kab/concepts/private";
    me.cachePath = "cache";
    me.awsBucket = "screens";
    me.init = function () {
        const ffprobePath = require("@ffprobe-installer/ffprobe").path;
        me.ffmpeg = require("fluent-ffmpeg");
        me.ffmpeg.setFfprobePath(ffprobePath);
        me.os = require("os");
        me.tempDir = me.os.tmpdir();
        core.file.makeDir(me.cachePath);
        core.mutex.enable(me.id, true);
        core.broadcast.register(me, {
            startup: "media.file.groups"
        });
    };
    me.info = function (path) {
        return new Promise(resolve => {
            me.ffmpeg.ffprobe(path, function (err, info) {
                if (err) {
                    me.log_error("Cannot parse metadata for file: " + path + " error: " + err);
                    info = null;
                }
                resolve(info);
            });
        });
    };
    me.paths = function (groupName, path) {
        var paths = {
            local: me.cachePath + "/" + path,
            remote: me.rootPath + "/" + groupName + "/" + path
        };
        return paths;
    };
    me.download = async function (groupName, path) {
        var target = await me.manager.file.download(me.rootPath + "/" + groupName + "/" + path,
            me.cachePath + "/" + path);
        return target;
    };
    me.groups = async function (update = false) {
        var files = [];
        try {
            var unlock = await core.mutex.lock(me.id);
            files = await me.db.cache.file.listing(me.rootPath, update);
            for (let file of files) {
                file.path = me.rootPath + "/" + file.name;
                var sessions = await me.listing(file, update);
                sessions = sessions.sort((a, b) => a.label.localeCompare(b.label));
                sessions.reverse();
                file.sessions = sessions;
            }
            files = files.sort((a, b) => a.name.localeCompare(b.name));
            files.sort();
        }
        finally {
            unlock();
        }
        return files;
    };
    me.exists = async function (name) {
        var groups = await me.groups();
        for (var group of groups) {
            for (var session of group.sessions) {
                if (session.name.includes(name)) {
                    return group.name;
                }
            }
        }
        return null;
    };
    me.listing = async function (parent, update = false) {
        var files = await me.db.cache.file.listing(parent.path, update, async (file) => {
            file.group = parent.name;
            file.session = core.path.fileName(file.name);
            file.extension = core.path.extension(file.name);
            file.label = core.string.title(core.path.fileName(file.name));
            file.remote = parent.path + "/" + file.name;
            file.local = me.cachePath + "/" + file.name;
            let awsPath = me.awsBucket + "/" + parent.name + "/" + file.name;
            if (!await me.storage.aws.exists(awsPath)) {
                me.log("Downloading file: " + file.local + ", size: " + file.size);
                await me.manager.file.download(file.remote, file.local);
                me.log("Uploading file: " + file.local + ", size: " + file.size);
                await me.storage.aws.uploadFile(file.local, awsPath);
                if (file.extension === "mp4") {
                    await core.file.delete(file.local);
                    me.log("Deleted file: " + file.local);
                }
                me.log("Finished uploading file: " + file.local);
            }
            if (file.local.endsWith(".m4a")) {
                await me.manager.file.download(file.remote, file.local);
                var metadata = await me.info(file.local);
                if (metadata) {
                    if (metadata.format) {
                        file.duration = metadata.format.duration;
                        file.durationText = core.string.formatDuration(file.duration);
                    }
                }
            }
        });
        files.reverse();
        return files;
    };
    me.size = async function () {
        var info = { groups: {}, total: 0, count: 0 };
        var groups = await me.groups(true, true);
        for (let group of groups) {
            var files = group.sessions;
            ["m4a", "mp4"].map(extension => {
                let list = files.filter(file => file.extension === extension);
                var diskSize = list.reduce((total, item) => total + item.size, 0);
                let infoGroup = info.groups[group.name];
                if (!infoGroup) {
                    infoGroup = info.groups[group.name] = { total: 0, count: 0 };
                }
                infoGroup.total += diskSize;
                infoGroup.count += list.length;
                info.total += diskSize;
                info.total += list.length;
            });
        }
        for (let infoName in info.groups) {
            let group = info.groups[infoName];
            for (let key in group) {
                if (key === "total") {
                    continue;
                }
                group[key].total = core.string.formatBytes(group[key].total);
            }
            group.total = core.string.formatBytes(group.total);
        }
        info.total = core.string.formatBytes(info.total);
        return info;
    };
    me.updateListing = async function () {
        me.log("updateListing");
        var groups = await me.groups(true, true);
        for (let group of groups) {
            var files = group.sessions;
            var diskSize = files.reduce((total, item) => total + item.size, 0);
            me.log("Requires " + core.string.formatBytes(diskSize) + " Disk space for files");
            for (var file of files) {
                if (file.extension === "m4a") {
                    try {
                        if (!me.media.speech.exists(file.local)) {
                            me.log("transcribing: " + file.local);
                            await me.media.speech.transcribe(file.local);
                            var info = await me.manager.download.clean(me.tempDir, "flac");
                            me.log("cleaned cache, deleted: " + info.deleted + " failed: " + info.failed + " skipped: " + info.skipped);
                        }
                    }
                    catch (err) {
                        me.log_error("Failed to transcribe: " + file.local);
                    }
                }
            }
        }
        me.log("finished update");
    };
    me.streamingPath = function (group, name, extension, resolution) {
        let path = me.awsBucket + "/" + group + "/" + name + (resolution ? "_" + resolution : "") + "." + extension;
        return me.storage.aws.url(path);
    };
    me.convertListing = async function (resolution, skipIndex) {
        var groups = await me.groups();
        for (let group of groups) {
            var list = group.sessions.filter(session => session.extension === "mp4");
            for (let item of list) {
                try {
                    var remote = me.awsBucket + "/" + group.name + "/" + item.session + ".mp4";
                    var local = me.cachePath + "/" + item.session + ".mp4";
                    var local_convert = me.cachePath + "/" + item.session + "_" + resolution + ".mp4";
                    var remote_convert = me.awsBucket + "/" + group.name + "/" + item.session + "_" + resolution + ".mp4";
                    if (await storage.aws.exists(remote_convert)) {
                        continue;
                    }
                    if (!await core.file.exists(local_convert)) {
                        if (skipIndex) {
                            me.log("skipping: " + local);
                            skipIndex--;
                            continue;
                        }
                        if (!await core.file.exists(local)) {
                            me.log("downloading: " + remote + " to: " + local);
                            await storage.aws.downloadFile(remote, local);
                        }
                        me.log("converting: " + local + " to: " + local_convert);
                        await media.ffmpeg.convert(local, local_convert, {
                            size: resolution
                        });
                    }
                    me.log("uploading: " + local_convert + " to: " + remote_convert);
                    await storage.aws.uploadFile(local_convert, remote_convert);
                    me.log("deleting: " + local_convert);
                    await core.file.delete(local_convert);
                    me.log("finished: " + item.name);
                }
                catch (err) {
                    me.log_error("Failed on item: " + item.name + " error: " + err);
                }
            }
        }
    };
    return "server";
};
<commit_msg>bug fix<commit_after>/*
 @author Zakai Hamilton
 @component MediaFile
 */

screens.media.file = function MediaFile(me, packages) {
    const { core, storage, media } = packages;
    me.rootPath = "/Kab/concepts/private";
    me.cachePath = "cache";
    me.awsBucket = "screens";
    me.init = function () {
        const ffprobePath = require("@ffprobe-installer/ffprobe").path;
        me.ffmpeg = require("fluent-ffmpeg");
        me.ffmpeg.setFfprobePath(ffprobePath);
        me.os = require("os");
        me.tempDir = me.os.tmpdir();
        core.file.makeDir(me.cachePath);
        core.mutex.enable(me.id, true);
        core.broadcast.register(me, {
            startup: "media.file.groups"
        });
    };
    me.info = function (path) {
        return new Promise(resolve => {
            me.ffmpeg.ffprobe(path, function (err, info) {
                if (err) {
                    me.log_error("Cannot parse metadata for file: " + path + " error: " + err);
                    info = null;
                }
                resolve(info);
            });
        });
    };
    me.paths = function (groupName, path) {
        var paths = {
            local: me.cachePath + "/" + path,
            remote: me.rootPath + "/" + groupName + "/" + path
        };
        return paths;
    };
    me.download = async function (groupName, path) {
        var target = await me.manager.file.download(me.rootPath + "/" + groupName + "/" + path,
            me.cachePath + "/" + path);
        return target;
    };
    me.groups = async function (update = false) {
        var files = [];
        try {
            var unlock = await core.mutex.lock(me.id);
            files = await me.db.cache.file.listing(me.rootPath, update);
            for (let file of files) {
                file.path = me.rootPath + "/" + file.name;
                var sessions = await me.listing(file, update);
                sessions = sessions.sort((a, b) => a.label.localeCompare(b.label));
                sessions.reverse();
                file.sessions = sessions;
            }
            files = files.sort((a, b) => a.name.localeCompare(b.name));
            files.sort();
        }
        finally {
            unlock();
        }
        return files;
    };
    me.exists = async function (name) {
        var groups = await me.groups();
        for (var group of groups) {
            for (var session of group.sessions) {
                if (session.name.includes(name)) {
                    return group.name;
                }
            }
        }
        return null;
    };
    me.listing = async function (parent, update = false) {
        var files = await me.db.cache.file.listing(parent.path, update, async (file) => {
            file.group = parent.name;
            file.session = core.path.fileName(file.name);
            file.extension = core.path.extension(file.name);
            file.label = core.string.title(core.path.fileName(file.name));
            file.remote = parent.path + "/" + file.name;
            file.local = me.cachePath + "/" + file.name;
            let awsPath = me.awsBucket + "/" + parent.name + "/" + file.name;
            if (!await me.storage.aws.exists(awsPath)) {
                me.log("Downloading file: " + file.local + ", size: " + file.size);
                await me.manager.file.download(file.remote, file.local);
                me.log("Uploading file: " + file.local + ", size: " + file.size);
                await me.storage.aws.uploadFile(file.local, awsPath);
                if (file.extension === "mp4") {
                    await core.file.delete(file.local);
                    me.log("Deleted file: " + file.local);
                }
                me.log("Finished uploading file: " + file.local);
            }
            if (file.local.endsWith(".m4a")) {
                await me.manager.file.download(file.remote, file.local);
                var metadata = await me.info(file.local);
                if (metadata) {
                    if (metadata.format) {
                        file.duration = metadata.format.duration;
                        file.durationText = core.string.formatDuration(file.duration);
                    }
                }
            }
        });
        files.reverse();
        return files;
    };
    me.size = async function () {
        var info = { groups: {}, total: 0, count: 0 };
        var groups = await me.groups(true, true);
        for (let group of groups) {
            var files = group.sessions;
            ["m4a", "mp4"].map(extension => {
                let list = files.filter(file => file.extension === extension);
                var diskSize = list.reduce((total, item) => total + item.size, 0);
                let infoGroup = info.groups[group.name];
                if (!infoGroup) {
                    infoGroup = info.groups[group.name] = { total: 0, count: 0 };
                }
                infoGroup.total += diskSize;
                infoGroup.count += list.length;
                info.total += diskSize;
                info.total += list.length;
            });
        }
        for (let infoName in info.groups) {
            let group = info.groups[infoName];
            for (let key in group) {
                if (key === "total") {
                    continue;
                }
                group[key].total = core.string.formatBytes(group[key].total);
            }
            group.total = core.string.formatBytes(group.total);
        }
        info.total = core.string.formatBytes(info.total);
        return info;
    };
    me.updateListing = async function () {
        me.log("updateListing");
        var groups = await me.groups(true, true);
        for (let group of groups) {
            var files = group.sessions;
            var diskSize = files.reduce((total, item) => total + item.size, 0);
            me.log("Requires " + core.string.formatBytes(diskSize) + " Disk space for files");
            for (var file of files) {
                if (file.extension === "m4a") {
                    try {
                        if (!me.media.speech.exists(file.local)) {
                            me.log("transcribing: " + file.local);
                            await me.media.speech.transcribe(file.local);
                            var info = await me.manager.download.clean(me.tempDir, "flac");
                            me.log("cleaned cache, deleted: " + info.deleted + " failed: " + info.failed + " skipped: " + info.skipped);
                        }
                    }
                    catch (err) {
                        me.log_error("Failed to transcribe: " + file.local);
                    }
                }
            }
        }
        me.log("finished update");
    };
    me.streamingPath = function (group, name, extension, resolution) {
        let path = me.awsBucket + "/" + group + "/" + name + (resolution ? "_" + resolution : "") + "." + extension;
        return me.storage.aws.url(path);
    };
    me.convertListing = async function (resolution, skipIndex) {
        var groups = await me.groups();
        for (let group of groups) {
            var list = group.sessions.filter(session => session.extension === "mp4");
            for (let item of list) {
                try {
                    var remote = me.awsBucket + "/" + group.name + "/" + item.session + ".mp4";
                    var local = me.cachePath + "/" + item.session + ".mp4";
                    var local_convert = me.cachePath + "/" + item.session + "_" + resolution + ".mp4";
                    var remote_convert = me.awsBucket + "/" + group.name + "/" + item.session + "_" + resolution + ".mp4";
                    if (await storage.aws.exists(remote_convert)) {
                        continue;
                    }
                    if (!await core.file.exists(local_convert)) {
                        if (skipIndex) {
                            me.log("skipping: " + local);
                            skipIndex--;
                            continue;
                        }
                        if (!await core.file.exists(local)) {
                            me.log("downloading: " + remote + " to: " + local);
                            await storage.aws.downloadFile(remote, local);
                        }
                        me.log("converting: " + local + " to: " + local_convert);
                        await media.ffmpeg.convert(local, local_convert, {
                            size: resolution
                        });
                    }
                    me.log("uploading: " + local_convert + " to: " + remote_convert);
                    await storage.aws.uploadFile(local_convert, remote_convert);
                    me.log("deleting: " + local_convert);
                    await core.file.delete(local_convert);
                    me.log("deleting: " + local);
                    await core.file.delete(local);
                    me.log("finished: " + item.name);
                }
                catch (err) {
                    me.log_error("Failed on item: " + item.name + " error: " + err);
                }
            }
        }
    };
    return "server";
};
<|endoftext|>


<commit_before>import ui.SpriteView as SpriteView;
import ui.resource.loader as loader;
var _imageMap = loader.getMap();

import .Rect;
import .Circle;

var ShapeFactory = Class(function () {
  /**
   * returns a new shape
   */
  this.getShape = function (opts) {
    var hitOpts = opts.hitOpts;
    var viewOpts = opts.viewOpts || opts;
    if (!hitOpts.radius) {
      hitOpts.image = viewOpts.image;
      hitOpts.url = viewOpts.url;
      this.applyImageDimensions(hitOpts);
    }

    if (hitOpts.radius) {
      return new Circle(hitOpts);
    } else {
      return new Rect(hitOpts);
    }
  };

  /**
   * returns a hit bounds object with defaults based on image or sprite url
   */
  this.applyImageDimensions = function (opts) {
    if (!opts) {
      return null;
    }

    // TODO: This assumes image is a string. Should probably check for this?
    var imageId = opts.image || opts.url;
    if (!imageId) { return opts; }

    var map;

    // First check if sprite animation exists
    var spriteData = SpriteView.allAnimations[imageId];
    if (spriteData) {
      // Grab the first animation frame
      for (var prop in spriteData) {
        map = spriteData[prop][0];
        break;
      }
    } else {
      map = _imageMap[imageId];
    }

    // auto-size based on provided width and/or height
    if (map) {
      var imgWidth = map.w + map.marginLeft + map.marginRight;
      var imgHeight = map.h + map.marginTop + map.marginBottom;
      if (!opts.width && !opts.height) {
        opts.width = imgWidth;
        opts.height = imgHeight;
      } else if (!opts.width) {
        var scale = opts.height / imgHeight;
        opts.width = scale * imgWidth;
      } else if (!opts.height) {
        var scale = opts.width / imgWidth;
        opts.height = scale * imgHeight;
      }
    }

    return opts;
  };
});

// class exposed for inheritance
exports = ShapeFactory;

// used as a singleton
var _instance = new ShapeFactory();
exports.get = function () {
  return _instance;
};
<commit_msg>removing comment<commit_after>import ui.SpriteView as SpriteView;
import ui.resource.loader as loader;
var _imageMap = loader.getMap();

import .Rect;
import .Circle;

var ShapeFactory = Class(function () {
  /**
   * returns a new shape
   */
  this.getShape = function (opts) {
    var hitOpts = opts.hitOpts;
    var viewOpts = opts.viewOpts || opts;
    if (!hitOpts.radius) {
      hitOpts.image = viewOpts.image;
      hitOpts.url = viewOpts.url;
      this.applyImageDimensions(hitOpts);
    }

    if (hitOpts.radius) {
      return new Circle(hitOpts);
    } else {
      return new Rect(hitOpts);
    }
  };

  /**
   * returns a hit bounds object with defaults based on image or sprite url
   */
  this.applyImageDimensions = function (opts) {
    if (!opts) {
      return null;
    }

    var imageId = opts.image || opts.url;
    if (!imageId) { return opts; }

    var map;

    // First check if sprite animation exists
    var spriteData = SpriteView.allAnimations[imageId];
    if (spriteData) {
      // Grab the first animation frame
      for (var prop in spriteData) {
        map = spriteData[prop][0];
        break;
      }
    } else {
      map = _imageMap[imageId];
    }

    // auto-size based on provided width and/or height
    if (map) {
      var imgWidth = map.w + map.marginLeft + map.marginRight;
      var imgHeight = map.h + map.marginTop + map.marginBottom;
      if (!opts.width && !opts.height) {
        opts.width = imgWidth;
        opts.height = imgHeight;
      } else if (!opts.width) {
        var scale = opts.height / imgHeight;
        opts.width = scale * imgWidth;
      } else if (!opts.height) {
        var scale = opts.width / imgWidth;
        opts.height = scale * imgHeight;
      }
    }

    return opts;
  };
});

// class exposed for inheritance
exports = ShapeFactory;

// used as a singleton
var _instance = new ShapeFactory();
exports.get = function () {
  return _instance;
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name           _Common.uc.js
// @description    Common library for UserChrome.js.
// @charset        UTF-8
// @history        2020-12-30  Added support for Firefox 84.
// @homepageURL    https://github.com/nonoroazoro/firefox/tree/master/userchrome/quantum
// ==/UserScript==

const Common = {
    /**
     * Gets Firefox IOService.
     */
    get IOService()
    {
        return Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
    },

    /**
     * Gets Firefox StyleSheetService.
     */
    get StyleSheetService()
    {
        return Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
    },

    /**
     * Gets Firefox ClipboardService.
     */
    get ClipboardService()
    {
        return Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
    },

    /**
     * Copies string to clipboard.
     */
    copy(str)
    {
        this.ClipboardService.copyString(str);
    },

    /**
     * Creates an HTML Element.
     */
    createElement(tagName, attributes)
    {
        const element = document.createElement(tagName);
        if (attributes)
        {
            Object.keys(attributes).forEach(key =>
            {
                element.setAttribute(key, attributes[key])
            });
        }
        return element;
    },

    /**
     * Creates an XUL element.
     */
    createXULElement(localName, attributes)
    {
        const element = document.createXULElement(localName);
        if (attributes)
        {
            Object.keys(attributes).forEach(key =>
            {
                element.setAttribute(key, attributes[key])
            });
        }
        return element;
    },

    /**
     * Creates a widget.
     */
    createWidget(id, label, tooltiptext, defaultArea, onCreated)
    {
        CustomizableUI.createWidget({
            defaultArea,
            id,
            label,
            tooltiptext,
            onCreated
        });
    },

    /**
     * Eval expression in current content document, return the expression result as the data param of the callback.
     *
     * @param {string | () => any} expression
     * @param {(data: any) => void} callback
     */
    evalInContent(expression, callback)
    {
        const eventId = Math.random().toString(36).substr(1, 9);
        const messageManager = gBrowser.selectedBrowser.messageManager;
        messageManager.addMessageListener(eventId, _handler);
        function _handler(message)
        {
            messageManager.removeMessageListener(eventId, _handler, true);
            if (callback)
            {
                callback(message.data);
            }
        }
        const script = encodeURIComponent(typeof expression === "function" ? "(" + expression.toString() + ")()" : expression);
        messageManager.loadFrameScript(`data:application/javascript;charset=utf-8,sendAsyncMessage("${eventId}", ${script})`, false);
    },

    /**
     * Loads CSS.
     *
     * @param {string} cssStr CSS string.
     */
    loadCSS(cssStr)
    {
        this.StyleSheetService.loadAndRegisterSheet(
            this.IOService.newURI("data:text/css;base64," + btoa(cssStr), null, null),
            this.StyleSheetService.USER_SHEET
        );
    },

    /**
     * Launch program.
     */
    launch(filename)
    {
        FileUtils.getFile("UChrm", ["program", filename]).launch();
    },

    /**
     * Open URL in new Tab.
     *
     * See https://github.com/alice0775/userChrome.js/blob/master/MouseGestures2_e10s.uc.js
     */
    openURL(url, inBackground = false)
    {
        openTrustedLinkIn(url, "tab", { inBackground, relatedToCurrent: true });
    },

    toast(message, title = "UserChrome.js")
    {
        Components.classes["@mozilla.org/alerts-service;1"]
            .getService(Components.interfaces.nsIAlertsService)
            .showAlertNotification("", title, message, false, "", null);
    },

    /**
     * Find the element of Firefox and do the command.
     *
     * @param {string} id The id of the addon.
     * @param {boolean} [inNavbar=false] Indicates if the addon is currently hidden in the nav bar.
     */
    doCommand(id, inNavbar = false)
    {
        if (inNavbar)
        {
            document.getElementById("nav-bar-overflow-button").click();
            setTimeout(() =>
            {
                document.getElementById(id).doCommand();
            }, 250);
        }
        else
        {
            document.getElementById(id).doCommand();
        }
    },

    /**
     * Gets Firefox preference.
     *
     * @param {string} name Preference name.
     * @param {any} type Preference type.
     * @param {any} defaultValue Preference default value.
     */
    getPreference(name, type, defaultValue)
    {
        try
        {
            switch (type)
            {
                case "complex":
                    return Services.prefs.getComplexValue(name, Components.interfaces.nsIFile);

                case "str":
                    return unescape(Services.prefs.getCharPref(name).toString());

                case "int":
                    return Services.prefs.getIntPref(name);

                case "bool":
                default:
                    return Services.prefs.getBoolPref(name);
            }
        } catch { }
        return defaultValue;
    },

    /**
     * Sets Firefox preference.
     *
     * @param {string} name Preference name.
     * @param {any} type Preference type.
     * @param {any} defaultValue Preference default value.
     */
    setPreference(name, type, defaultValue)
    {
        try
        {
            switch (type)
            {
                case "complex":
                    return Services.prefs.setComplexValue(name, Components.interfaces.nsIFile, defaultValue);

                case "str":
                    return Services.prefs.setCharPref(name, escape(defaultValue));

                case "int":
                    defaultValue = parseInt(defaultValue);
                    return Services.prefs.setIntPref(name, defaultValue);

                case "bool":
                default:
                    return Services.prefs.setBoolPref(name, defaultValue);
            }
        } catch { }
        return;
    },

    getSelectedText()
    {
        return BrowserUtils.getSelectionDetails(content).fullText;
    },

    restartFirefox()
    {
        Services.startup.quit(Services.startup.eAttemptQuit | Services.startup.eRestart);

        // Components.classes["@mozilla.org/toolkit/app-startup;1"]
        //     .getService(Components.interfaces.nsIAppStartup)
        //     .quit(Components.interfaces.nsIAppStartup.eAttemptQuit | Components.interfaces.nsIAppStartup.eRestart);
    }
};
<commit_msg>add register<commit_after>// ==UserScript==
// @name           _Common.uc.js
// @description    Common library for UserChrome.js.
// @charset        UTF-8
// @history        2020-12-30  Added support for Firefox 84.
// @homepageURL    https://github.com/nonoroazoro/firefox/tree/master/userchrome/quantum
// ==/UserScript==

const Common = {
    /**
     * Gets Firefox IOService.
     */
    get IOService()
    {
        return Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
    },

    /**
     * Gets Firefox StyleSheetService.
     */
    get StyleSheetService()
    {
        return Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
    },

    /**
     * Gets Firefox ClipboardService.
     */
    get ClipboardService()
    {
        return Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
    },

    /**
     * Copies string to clipboard.
     */
    copy(str)
    {
        this.ClipboardService.copyString(str);
    },

    /**
     * Creates an HTML Element.
     */
    createElement(tagName, attributes)
    {
        const element = document.createElement(tagName);
        if (attributes)
        {
            Object.keys(attributes).forEach(key =>
            {
                element.setAttribute(key, attributes[key])
            });
        }
        return element;
    },

    /**
     * Creates an XUL element.
     */
    createXULElement(localName, attributes)
    {
        const element = document.createXULElement(localName);
        if (attributes)
        {
            Object.keys(attributes).forEach(key =>
            {
                element.setAttribute(key, attributes[key])
            });
        }
        return element;
    },

    /**
     * Creates a widget.
     */
    createWidget(id, label, tooltiptext, defaultArea, onCreated)
    {
        CustomizableUI.createWidget({
            defaultArea,
            id,
            label,
            tooltiptext,
            onCreated
        });
    },

    /**
     * Eval expression in current content document, return the expression result as the data param of the callback.
     *
     * @param {string | () => any} expression
     * @param {(data: any) => void} callback
     */
    evalInContent(expression, callback)
    {
        const eventId = Math.random().toString(36).substr(1, 9);
        const messageManager = gBrowser.selectedBrowser.messageManager;
        messageManager.addMessageListener(eventId, _handler);
        function _handler(message)
        {
            messageManager.removeMessageListener(eventId, _handler, true);
            if (callback)
            {
                callback(message.data);
            }
        }
        const script = encodeURIComponent(typeof expression === "function" ? "(" + expression.toString() + ")()" : expression);
        messageManager.loadFrameScript(`data:application/javascript;charset=utf-8,sendAsyncMessage("${eventId}", ${script})`, false);
    },

    /**
     * Loads CSS.
     *
     * @param {string} cssStr CSS string.
     */
    loadCSS(cssStr)
    {
        this.StyleSheetService.loadAndRegisterSheet(
            this.IOService.newURI("data:text/css;base64," + btoa(cssStr), null, null),
            this.StyleSheetService.USER_SHEET
        );
    },

    /**
     * Launch program.
     */
    launch(filename)
    {
        FileUtils.getFile("UChrm", ["program", filename]).launch();
    },

    /**
     * Open URL in new Tab.
     *
     * See https://github.com/alice0775/userChrome.js/blob/master/MouseGestures2_e10s.uc.js
     */
    openURL(url, inBackground = false)
    {
        openTrustedLinkIn(url, "tab", { inBackground, relatedToCurrent: true });
    },

    toast(message, title = "UserChrome.js")
    {
        Components.classes["@mozilla.org/alerts-service;1"]
            .getService(Components.interfaces.nsIAlertsService)
            .showAlertNotification("", title, message, false, "", null);
    },

    /**
     * Find the element of Firefox and do the command.
     *
     * @param {string} id The id of the addon.
     * @param {boolean} [inNavbar=false] Indicates if the addon is currently hidden in the nav bar.
     */
    doCommand(id, inNavbar = false)
    {
        if (inNavbar)
        {
            document.getElementById("nav-bar-overflow-button").click();
            setTimeout(() =>
            {
                document.getElementById(id).doCommand();
            }, 250);
        }
        else
        {
            document.getElementById(id).doCommand();
        }
    },

    /**
     * Gets Firefox preference.
     *
     * @param {string} name Preference name.
     * @param {any} type Preference type.
     * @param {any} defaultValue Preference default value.
     */
    getPreference(name, type, defaultValue)
    {
        try
        {
            switch (type)
            {
                case "complex":
                    return Services.prefs.getComplexValue(name, Components.interfaces.nsIFile);

                case "str":
                    return unescape(Services.prefs.getCharPref(name).toString());

                case "int":
                    return Services.prefs.getIntPref(name);

                case "bool":
                default:
                    return Services.prefs.getBoolPref(name);
            }
        } catch { }
        return defaultValue;
    },

    /**
     * Sets Firefox preference.
     *
     * @param {string} name Preference name.
     * @param {any} type Preference type.
     * @param {any} defaultValue Preference default value.
     */
    setPreference(name, type, defaultValue)
    {
        try
        {
            switch (type)
            {
                case "complex":
                    return Services.prefs.setComplexValue(name, Components.interfaces.nsIFile, defaultValue);

                case "str":
                    return Services.prefs.setCharPref(name, escape(defaultValue));

                case "int":
                    defaultValue = parseInt(defaultValue);
                    return Services.prefs.setIntPref(name, defaultValue);

                case "bool":
                default:
                    return Services.prefs.setBoolPref(name, defaultValue);
            }
        } catch { }
        return;
    },

    getSelectedText()
    {
        return BrowserUtils.getSelectionDetails(content).fullText;
    },

    restartFirefox()
    {
        Services.startup.quit(Services.startup.eAttemptQuit | Services.startup.eRestart);

        // Components.classes["@mozilla.org/toolkit/app-startup;1"]
        //     .getService(Components.interfaces.nsIAppStartup)
        //     .quit(Components.interfaces.nsIAppStartup.eAttemptQuit | Components.interfaces.nsIAppStartup.eRestart);
    },

    /**
     * Registers a plugin that has implemented the `activate` and `deactivate` methods.
     */
    register(plugin)
    {
        // plugin: { activate, deactivate }
        if (typeof plugin.activate === "function")
        {
            function _handleUnload()
            {
                plugin.deactivate();
                window.removeEventListener("unload", _handleUnload);
            };

            function start()
            {
                // Activate when the Firefox window has finished starting up.
                plugin.activate();
                if (typeof plugin.deactivate === "function")
                {
                    // Deactivate when the Firefox window has closed.
                    window.addEventListener("unload", _handleUnload);
                }
            }

            // Register when the browser window has finished starting up.
            if (gBrowserInit.delayedStartupFinished)
            {
                start();
            }
            else
            {
                const handleDelayedStartupFinished = (subject, topic) =>
                {
                    if (
                        topic == "browser-delayed-startup-finished"
                        && subject == window
                    )
                    {
                        Services.obs.removeObserver(handleDelayedStartupFinished, topic);
                        start();
                    }
                };
                Services.obs.addObserver(handleDelayedStartupFinished, "browser-delayed-startup-finished");
            }
        }
    }
};
<|endoftext|>