<commit_before>(function(app) {
  'use strict';
  app.WatsonModel = function() {
    this.data = null;

    this.description = null;
    this.displayName = null;

    this._pendingRequests = [];

    this.configureModel({
      start: -5,
      end: 0,
      entity: null
    });
  };

  app.WatsonModel.TIME_LIMIT = -60;

  app.WatsonModel.prototype._isTimeWithinLimit = function(time) {
    return time >= app.WatsonModel.TIME_LIMIT && time <= 0;
  };

  app.WatsonModel.prototype.abort = function() {
    this._pendingRequests.forEach(function(pendingRequest) {
      pendingRequest.abort();
    });
    this._pendingRequests = [];
  };

  app.WatsonModel.prototype.validateTime = function(start, end) {
    var isValidTime = this._isTimeWithinLimit(start) && this._isTimeWithinLimit(end);
    isValidTime = isValidTime && (start <= end);
    return isValidTime;
  };

  app.WatsonModel.prototype._convertOptionsToQuery = function(options, queryStr) {
    if (!queryStr) {
      queryStr = '';
    }
    var sep = queryStr.length ? '&' : '';

    for (var attr in options) {
      if (options.hasOwnProperty(attr)) {
        queryStr += sep + encodeURIComponent(attr) + '=';
        queryStr += encodeURIComponent(options[attr]);
        sep = '&';
      }
    }
    return queryStr;
  };

  app.WatsonModel.prototype._generateTimeStr = function(time) {
    return time ? ('now' + time + 'd') : 'now';
  };

  app.WatsonModel.prototype._createRequestURL = function(baseUrl, options) {
    var queryStr = this._convertOptionsToQuery(options);
    var defaultQueryOptions = {
      entity: this.entity,
      start: this._generateTimeStr(this.start),
      end: this._generateTimeStr(this.end),
    };
    queryStr = this._convertOptionsToQuery(defaultQueryOptions, queryStr);
    if (queryStr.length) {
      queryStr = '?' + queryStr;
    }
    return baseUrl + queryStr;
  };

  app.WatsonModel.prototype._removePendingRequest = function(req) {
    var index = this._pendingRequests.indexOf(req);
    if (index !== -1) {
      this._pendingRequests.splice(index, 1);
    }
  };

  app.WatsonModel.prototype._sendRequest = function(url, options) {
    var requestURL = this._createRequestURL(url, options);
    var self = this;
    return new Promise(function(resolve, reject) {

      var req = new XMLHttpRequest();

      req.addEventListener('load', function() {
        self._removePendingRequest(req);
        if (this.status >= 200 && this.status < 300) {
          var responseObj = JSON.parse(this.responseText);
          resolve(responseObj);
        } else {
          reject(this);
        }
      });

      req.open('GET', requestURL, true);
      req.send();
      self._pendingRequests.push(req);
    });

  };

  app.WatsonModel.prototype._getSourceId = function(source) {
    var prefix = 'www.';
    var sourceProcessed = source;
    if (source.indexOf(prefix) !== -1) {
      sourceProcessed = source.substring(prefix.length);
    }
    var indexOfSep = sourceProcessed.indexOf('.');
    if (indexOfSep !== -1) {
      sourceProcessed = sourceProcessed.substring(0, indexOfSep);
    }
    return sourceProcessed;
  };

  app.WatsonModel.prototype._fetchTones = function(articles) {
    var self = this;
    return new Promise(function(resolve, reject) {
      var tonePromises = [];
      articles.forEach(function(article) {
        if (!article.tone) {
          tonePromises.push(self._sendRequest(self._getServiceURL('tone'), {
            url: article.url
          }));
        }
      });
      Promise.all(tonePromises).then(function(results) {
        articles.forEach(function(article, articleIndex) {
          article.tone = results[articleIndex];
        });
        resolve(resolve);
      }).catch(function(reason) {
        reject(reason);
      });
    });
  };

  app.WatsonModel.prototype.fetchArticles = function(sourceObj) {
    var self = this;
    var articleLimit = 3;
    return new Promise(function(resolve, reject) {
      if (!sourceObj.articles) {

        self._sendRequest(self._getServiceURL('articles'), {
            source: sourceObj.sourceId
          }).then(function(responseArticles) {
            sourceObj._totalArticles = responseArticles.length;
            sourceObj.articles = responseArticles.splice(0, articleLimit);
            var startDelete = responseArticles.length > articleLimit ?
              (responseArticles.length - articleLimit) : 0;
            sourceObj.articles.push.apply(sourceObj.articles,
              responseArticles.splice(startDelete));
            sourceObj._articleBoundary = articleLimit;
            self._fetchTones(sourceObj.articles).then(function() {
              resolve(sourceObj.articles);
            }).catch(function(reason) {
              reject(reason);
            });

          })
          .catch(function(reason) {
            reject(reason);
          });
      } else {
        resolve(sourceObj.articles);
      }
    });
  };

  app.WatsonModel.prototype.fetchKeywordSentiments = function(keywordObj) {

    var self = this;
    var sentiments = ['positive', 'negative'];
    return new Promise(function(resolve, reject) {
      var sentimentPromises = [];
      if (!keywordObj.sentiments) {
        sentiments.forEach(function(sentiment) {
          var sentimentPromise = self._sendRequest(self._getServiceURL('keywords.0'), {
            keyword: keywordObj.keyword,
            sentiment: sentiment,
            slice: '1d'
          });
          sentimentPromises.push(sentimentPromise);
        });
        Promise.all(sentimentPromises).then(function(responses) {
            keywordObj.sentiments = {};
            sentiments.forEach(function(sentiment, index) {
              keywordObj.sentiments[sentiment] = responses[index];
            });
            resolve(keywordObj.sentiments);
          })
          .catch(function(reason) {
            reject(reason);
          });
      } else {
        resolve(keywordObj.sentiments);
      }
    });
  };

  app.WatsonModel.prototype.fetchKeywords = function() {

    var keywordsPromise = this._sendRequest(this._getServiceURL('keywords'), {
      count: 10
    });
    var self = this;
    return new Promise(function(resolve, reject) {
      keywordsPromise.then(function(results) {
          var keywordCountPromises = [];
          results.forEach(function(result) {
            keywordCountPromises.push(self._sendRequest(self._getServiceURL('keywords'), {
              keyword: result.keyword
            }));
          });
          Promise.all(keywordCountPromises).then(function(countResponses) {
            results.forEach(function(result, index) {
              result.count = countResponses[index].count;
              result.label = result.keyword.replace(/(?!IBM\b)\b\w+/g,
                function(text) {
                  return text.charAt(0).toUpperCase() + text.substring(1).toLowerCase();
                });
              console.log(result.label);
            });
            results.sort(function(item1, item2) {
              return item2.count - item1.count;
            });
            self.data.keywords = results;
            resolve(self.data.keywords);
          }).catch(function(reason) {
            reject(reason);
          });
        })
        .catch(function(reason) {
          reject(reason);
        });
    });

  };

  app.WatsonModel.prototype._fetchActualCount = function(sourceObj) {
    var actualCountPromise = this._sendRequest(this._getServiceURL('sources'), {
      source: sourceObj.sourceId
    });
    return new Promise(function(resolve, reject) {
      actualCountPromise.then(function(actualCountObj) {
        sourceObj.count = actualCountObj.count;
        resolve(sourceObj);
      }).catch(function(reason) {
        reject(reason);
      });
    });
  };

  app.WatsonModel.prototype.fetchTopSources = function() {

    var topSourcePromise = this._sendRequest(this._getServiceURL('sources'), {
      count: 3
    });
    var self = this;
    return new Promise(function(resolve, reject) {
      topSourcePromise.then(function(responses) {
          self.data.topSources = responses;
          var childPromises = [];
          responses.forEach(function(responseSource) {
            responseSource.sourceId = self._getSourceId(responseSource.source);
            childPromises.push(self._fetchActualCount(responseSource));
            childPromises.push(self.fetchSourceSentiment(responseSource));
          });
          Promise.all(childPromises).then(function() {
            resolve(self.data.topSources);
          }).catch(function(reason) {
            reject(reason);
          });
        })
        .catch(function(reason) {
          reject(reason);
        });
    });

  };

  app.WatsonModel.prototype.fetchCoreInfo = function() {
    var self = this;
    return new Promise(function(resolve, reject) {
      Promise.all([
          self.fetchSentiment(),
          self.fetchTopSources()
        ]).then(function() {
          resolve(self);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  app.WatsonModel.prototype.fetchSentiment = function() {
    var sentiments = ['positive', 'negative', 'neutral'];
    var promises = [];
    sentiments.forEach(function(sentiment) {
      promises.push(this._sendRequest(this._getServiceURL('sentiment'), {
        sentiment: sentiment
      }));
    }, this);
    var self = this;
    return new Promise(function(resolve, reject) {
      Promise.all(promises).then(function(responses) {
          self.data.sentiments = {};
          sentiments.forEach(function(sentiment, index) {
            self.data.sentiments[sentiment] = responses[index];
          }, this);
          resolve(self.data.sentiments);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  //TODO: merge this with fetchSentiment
  app.WatsonModel.prototype.fetchSourceSentiment = function(sourceObj) {
    var sentiments = ['positive', 'negative', 'neutral'];
    var promises = [];
    sentiments.forEach(function(sentiment) {
      promises.push(this._sendRequest(this._getServiceURL('sources'), {
        sentiment: sentiment,
        source: sourceObj.sourceId
      }));
    }, this);
    return new Promise(function(resolve, reject) {
      Promise.all(promises).then(function(responses) {
          sourceObj.sentiments = {};
          sentiments.forEach(function(sentiment, index) {
            sourceObj.sentiments[sentiment] = responses[index];
          }, this);
          resolve(sourceObj.sentiments);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  app.WatsonModel.prototype._getServiceURL = function(path) {
    return '/' + window.globalProperties.serviceEndpoint + '/' + path;
  };

  app.WatsonModel.prototype.configureModel = function(defaultOptions) {
    var date = new Date();
    date.setHours(0, 0, 0, 0);
    this.updateDate = date.getTime();
    this.entity = defaultOptions.entity;
    this.start = defaultOptions.start;
    this.end = defaultOptions.end;
    this.data = {};

  };

})(window.app || (window.app = {}));
<commit_msg>Fix typo in sentiments<commit_after>(function(app) {
  'use strict';
  app.WatsonModel = function() {
    this.data = null;

    this.description = null;
    this.displayName = null;

    this._pendingRequests = [];

    this.configureModel({
      start: -5,
      end: 0,
      entity: null
    });
  };

  app.WatsonModel.TIME_LIMIT = -60;

  app.WatsonModel.prototype._isTimeWithinLimit = function(time) {
    return time >= app.WatsonModel.TIME_LIMIT && time <= 0;
  };

  app.WatsonModel.prototype.abort = function() {
    this._pendingRequests.forEach(function(pendingRequest) {
      pendingRequest.abort();
    });
    this._pendingRequests = [];
  };

  app.WatsonModel.prototype.validateTime = function(start, end) {
    var isValidTime = this._isTimeWithinLimit(start) && this._isTimeWithinLimit(end);
    isValidTime = isValidTime && (start <= end);
    return isValidTime;
  };

  app.WatsonModel.prototype._convertOptionsToQuery = function(options, queryStr) {
    if (!queryStr) {
      queryStr = '';
    }
    var sep = queryStr.length ? '&' : '';

    for (var attr in options) {
      if (options.hasOwnProperty(attr)) {
        queryStr += sep + encodeURIComponent(attr) + '=';
        queryStr += encodeURIComponent(options[attr]);
        sep = '&';
      }
    }
    return queryStr;
  };

  app.WatsonModel.prototype._generateTimeStr = function(time) {
    return time ? ('now' + time + 'd') : 'now';
  };

  app.WatsonModel.prototype._createRequestURL = function(baseUrl, options) {
    var queryStr = this._convertOptionsToQuery(options);
    var defaultQueryOptions = {
      entity: this.entity,
      start: this._generateTimeStr(this.start),
      end: this._generateTimeStr(this.end),
    };
    queryStr = this._convertOptionsToQuery(defaultQueryOptions, queryStr);
    if (queryStr.length) {
      queryStr = '?' + queryStr;
    }
    return baseUrl + queryStr;
  };

  app.WatsonModel.prototype._removePendingRequest = function(req) {
    var index = this._pendingRequests.indexOf(req);
    if (index !== -1) {
      this._pendingRequests.splice(index, 1);
    }
  };

  app.WatsonModel.prototype._sendRequest = function(url, options) {
    var requestURL = this._createRequestURL(url, options);
    var self = this;
    return new Promise(function(resolve, reject) {

      var req = new XMLHttpRequest();

      req.addEventListener('load', function() {
        self._removePendingRequest(req);
        if (this.status >= 200 && this.status < 300) {
          var responseObj = JSON.parse(this.responseText);
          resolve(responseObj);
        } else {
          reject(this);
        }
      });

      req.open('GET', requestURL, true);
      req.send();
      self._pendingRequests.push(req);
    });

  };

  app.WatsonModel.prototype._getSourceId = function(source) {
    var prefix = 'www.';
    var sourceProcessed = source;
    if (source.indexOf(prefix) !== -1) {
      sourceProcessed = source.substring(prefix.length);
    }
    var indexOfSep = sourceProcessed.indexOf('.');
    if (indexOfSep !== -1) {
      sourceProcessed = sourceProcessed.substring(0, indexOfSep);
    }
    return sourceProcessed;
  };

  app.WatsonModel.prototype._fetchTones = function(articles) {
    var self = this;
    return new Promise(function(resolve, reject) {
      var tonePromises = [];
      articles.forEach(function(article) {
        if (!article.tone) {
          tonePromises.push(self._sendRequest(self._getServiceURL('tone'), {
            url: article.url
          }));
        }
      });
      Promise.all(tonePromises).then(function(results) {
        articles.forEach(function(article, articleIndex) {
          article.tone = results[articleIndex];
        });
        resolve(resolve);
      }).catch(function(reason) {
        reject(reason);
      });
    });
  };

  app.WatsonModel.prototype.fetchArticles = function(sourceObj) {
    var self = this;
    var articleLimit = 3;
    return new Promise(function(resolve, reject) {
      if (!sourceObj.articles) {

        self._sendRequest(self._getServiceURL('articles'), {
            source: sourceObj.sourceId
          }).then(function(responseArticles) {
            sourceObj._totalArticles = responseArticles.length;
            sourceObj.articles = responseArticles.splice(0, articleLimit);
            var startDelete = responseArticles.length > articleLimit ?
              (responseArticles.length - articleLimit) : 0;
            sourceObj.articles.push.apply(sourceObj.articles,
              responseArticles.splice(startDelete));
            sourceObj._articleBoundary = articleLimit;
            self._fetchTones(sourceObj.articles).then(function() {
              resolve(sourceObj.articles);
            }).catch(function(reason) {
              reject(reason);
            });

          })
          .catch(function(reason) {
            reject(reason);
          });
      } else {
        resolve(sourceObj.articles);
      }
    });
  };

  app.WatsonModel.prototype.fetchKeywordSentiments = function(keywordObj) {

    var self = this;
    var sentiments = ['positive', 'negative'];
    return new Promise(function(resolve, reject) {
      var sentimentPromises = [];
      if (!keywordObj.sentiments) {
        sentiments.forEach(function(sentiment) {
          var sentimentPromise = self._sendRequest(self._getServiceURL('keywords'), {
            keyword: keywordObj.keyword,
            sentiment: sentiment,
            slice: '1d'
          });
          sentimentPromises.push(sentimentPromise);
        });
        Promise.all(sentimentPromises).then(function(responses) {
            keywordObj.sentiments = {};
            sentiments.forEach(function(sentiment, index) {
              keywordObj.sentiments[sentiment] = responses[index];
            });
            resolve(keywordObj.sentiments);
          })
          .catch(function(reason) {
            reject(reason);
          });
      } else {
        resolve(keywordObj.sentiments);
      }
    });
  };

  app.WatsonModel.prototype.fetchKeywords = function() {

    var keywordsPromise = this._sendRequest(this._getServiceURL('keywords'), {
      count: 10
    });
    var self = this;
    return new Promise(function(resolve, reject) {
      keywordsPromise.then(function(results) {
          var keywordCountPromises = [];
          results.forEach(function(result) {
            keywordCountPromises.push(self._sendRequest(self._getServiceURL('keywords'), {
              keyword: result.keyword
            }));
          });
          Promise.all(keywordCountPromises).then(function(countResponses) {
            results.forEach(function(result, index) {
              result.count = countResponses[index].count;
              result.label = result.keyword.replace(/(?!IBM\b)\b\w+/g,
                function(text) {
                  return text.charAt(0).toUpperCase() + text.substring(1).toLowerCase();
                });
              console.log(result.label);
            });
            results.sort(function(item1, item2) {
              return item2.count - item1.count;
            });
            self.data.keywords = results;
            resolve(self.data.keywords);
          }).catch(function(reason) {
            reject(reason);
          });
        })
        .catch(function(reason) {
          reject(reason);
        });
    });

  };

  app.WatsonModel.prototype._fetchActualCount = function(sourceObj) {
    var actualCountPromise = this._sendRequest(this._getServiceURL('sources'), {
      source: sourceObj.sourceId
    });
    return new Promise(function(resolve, reject) {
      actualCountPromise.then(function(actualCountObj) {
        sourceObj.count = actualCountObj.count;
        resolve(sourceObj);
      }).catch(function(reason) {
        reject(reason);
      });
    });
  };

  app.WatsonModel.prototype.fetchTopSources = function() {

    var topSourcePromise = this._sendRequest(this._getServiceURL('sources'), {
      count: 3
    });
    var self = this;
    return new Promise(function(resolve, reject) {
      topSourcePromise.then(function(responses) {
          self.data.topSources = responses;
          var childPromises = [];
          responses.forEach(function(responseSource) {
            responseSource.sourceId = self._getSourceId(responseSource.source);
            childPromises.push(self._fetchActualCount(responseSource));
            childPromises.push(self.fetchSourceSentiment(responseSource));
          });
          Promise.all(childPromises).then(function() {
            resolve(self.data.topSources);
          }).catch(function(reason) {
            reject(reason);
          });
        })
        .catch(function(reason) {
          reject(reason);
        });
    });

  };

  app.WatsonModel.prototype.fetchCoreInfo = function() {
    var self = this;
    return new Promise(function(resolve, reject) {
      Promise.all([
          self.fetchSentiment(),
          self.fetchTopSources()
        ]).then(function() {
          resolve(self);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  app.WatsonModel.prototype.fetchSentiment = function() {
    var sentiments = ['positive', 'negative', 'neutral'];
    var promises = [];
    sentiments.forEach(function(sentiment) {
      promises.push(this._sendRequest(this._getServiceURL('sentiment'), {
        sentiment: sentiment
      }));
    }, this);
    var self = this;
    return new Promise(function(resolve, reject) {
      Promise.all(promises).then(function(responses) {
          self.data.sentiments = {};
          sentiments.forEach(function(sentiment, index) {
            self.data.sentiments[sentiment] = responses[index];
          }, this);
          resolve(self.data.sentiments);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  //TODO: merge this with fetchSentiment
  app.WatsonModel.prototype.fetchSourceSentiment = function(sourceObj) {
    var sentiments = ['positive', 'negative', 'neutral'];
    var promises = [];
    sentiments.forEach(function(sentiment) {
      promises.push(this._sendRequest(this._getServiceURL('sources'), {
        sentiment: sentiment,
        source: sourceObj.sourceId
      }));
    }, this);
    return new Promise(function(resolve, reject) {
      Promise.all(promises).then(function(responses) {
          sourceObj.sentiments = {};
          sentiments.forEach(function(sentiment, index) {
            sourceObj.sentiments[sentiment] = responses[index];
          }, this);
          resolve(sourceObj.sentiments);
        })
        .catch(function(reason) {
          reject(reason);
        });
    });
  };

  app.WatsonModel.prototype._getServiceURL = function(path) {
    return '/' + window.globalProperties.serviceEndpoint + '/' + path;
  };

  app.WatsonModel.prototype.configureModel = function(defaultOptions) {
    var date = new Date();
    date.setHours(0, 0, 0, 0);
    this.updateDate = date.getTime();
    this.entity = defaultOptions.entity;
    this.start = defaultOptions.start;
    this.end = defaultOptions.end;
    this.data = {};

  };

})(window.app || (window.app = {}));
<|endoftext|>


<commit_before>var gulp       = require('gulp'),
    coffee     = require('gulp-coffee'),
    gutil      = require('gulp-util'),
    watch      = require('gulp-watch'),
    es         = require('event-stream'),
    coffeelint = require('gulp-coffeelint');

var srcFiles  = 'components/*.coffee';
var specFiles = 'spec/*.coffee';

gulp.task('default', function() {
  watch([srcFiles, specFiles], function(files) {
    gulp.start('coffee');
  });
});

gulp.task('coffee', function() {
  var components = gulp.src(srcFiles)
    .pipe( coffee({ bare: true }).on('error', gutil.log) )
    .pipe( gulp.dest('components/js/') );

  var tests = gulp.src(specFiles)
    .pipe( coffee({ bare: true }).on('error', gutil.log) )
    .pipe( gulp.dest('spec/javascripts/') );

  return es.concat(components, tests);
});

gulp.task('lint', function () {
    gulp.src(srcFiles)
        .pipe(coffeelint())
        .pipe(coffeelint.reporter())
});
<commit_msg>Overhaul Gulpfile.js<commit_after>// *************************************
//
//   Gulpfile
//
// *************************************

// -------------------------------------
//   Modules
// -------------------------------------

var gulp       = require( 'gulp' );
var coffee     = require( 'gulp-coffee' );
var coffeelint = require( 'gulp-coffeelint' );
var es         = require( 'event-stream' );
var gutil      = require( 'gulp-util' );
var watch      = require( 'gulp-watch' );

// -------------------------------------
//   Options
// -------------------------------------

var options = {

  coffee : {
    files       : [ 'components/*.coffee', 'spec/*.coffee' ],
    destination : [ 'components/js/', 'spec/javascripts/' ]
  },

  watch : function() {
    return this.coffee.files;
  }

};

// -------------------------------------
//   Task: Default
// -------------------------------------

gulp.task( 'default', function() {

  watch( options.watch(), function( files ) {

    gulp.start( 'coffee' );

  } );

} );

// -------------------------------------
//   Task: Coffee
// -------------------------------------

gulp.task( 'coffee', function() {

  var components = gulp.src( options.coffee.files[0] )
    .pipe(  coffee( { bare: true } ).on( 'error', gutil.log ) )
    .pipe(  gulp.dest( options.coffee.destination[0] ) );

  var tests = gulp.src( options.coffee.files[1] )
    .pipe(  coffee( { bare: true } ).on( 'error', gutil.log ) )
    .pipe(  gulp.dest( options.coffee.destination[1] ) );

  return es.concat(components, tests);

} );

// -------------------------------------
//   Task: Lint
// -------------------------------------

gulp.task( 'lint', function () {

  gulp.src( options.coffee.files[0] )
      .pipe( coffeelint() )
      .on( 'error', function( error ) { console.log( error.message ); } )
      .pipe( coffeelint.reporter( ) )

} );
<|endoftext|>


<commit_before>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus',
	'goo/renderer/SimplePartitioner',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/renderer/shaders/ShaderFragment',
	'goo/math/Matrix3x3',
	'goo/math/Matrix4x4',
	'goo/renderer/MeshData',
	'goo/renderer/Shader',
	'goo/util/gizmopack/Gizmo',
	'goo/util/gizmopack/TranslationGizmo',
	'goo/util/gizmopack/RotationGizmo',
	'goo/util/gizmopack/GlobalRotationGizmo',
	'goo/util/gizmopack/ScaleGizmo'
], function (
	System,
	SystemBus,
	SimplePartitioner,
	Material,
	ShaderLib,
	ShaderFragment,
	Matrix3x3,
	Matrix4x4,
	MeshData,
	Shader,
	Gizmo,
	TranslationGizmo,
	RotationGizmo,
	GlobalRotationGizmo,
	ScaleGizmo
) {
	'use strict';

	/**
	 * Renders transform gizmos

	 * @example-link http://code.gooengine.com/latest/visual-test/goo/util/TransformGizmos/TransformGizmos-vtest.html Working example
	 * @property {boolean} doRender Only render if set to true
	 * @extends System
	 */
	function GizmoRenderSystem(callbacks) {
		System.call(this, 'GizmoRenderSystem', null);

		this.renderables = [];
		this.camera = null;

		this.gizmos = [
			new TranslationGizmo(this),
			new RotationGizmo(this),
			new GlobalRotationGizmo(this),
			new ScaleGizmo(this)
		];
		this.active = false;
		this.nextGizmo = null;
		this.setupCallbacks(callbacks);
		//this.boundEntity = null; //unused
		this.activeGizmo = null;
		this.viewportWidth = 0;
		this.viewportHeight = 0;
		this.domElement = null;
		this.global = false;
		this.pickingMaterial = Material.createEmptyMaterial(customPickingShader, 'pickingMaterial');
		this.pickingMaterial.blendState = {
			blending: 'NoBlending',
			blendEquation: 'AddEquation',
			blendSrc: 'SrcAlphaFactor',
			blendDst: 'OneMinusSrcAlphaFactor'
		};
		this._devicePixelRatio = 1;

		this.mouseMove = function (evt) {
			if (!this.activeGizmo) {
				return;
			}
			var x = (evt.offsetX !== undefined) ? evt.offsetX : evt.layerX;
			var y = (evt.offsetY !== undefined) ? evt.offsetY : evt.layerY;

			var mousePos = [
				x / (this.viewportWidth / this._devicePixelRatio),
				y / (this.viewportHeight / this._devicePixelRatio)
			];

			/*
			var camera = this.camera;
			if (camera && camera.projectionMode === Camera.Parallel){
				mousePos[0] = x / (this.viewportWidth  / this._devicePixelRatio) / (camera._frustumRight - camera._frustumLeft);
				mousePos[1] = y / (this.viewportHeight / this._devicePixelRatio) / (camera._frustumTop  - camera._frustumBottom);
			}

			console.log(mousePos[0],mousePos[1])
			*/

			this.activeGizmo.update(mousePos);

		}.bind(this);

		// no more that!
		var that = this;
		SystemBus.addListener('goo.setCurrentCamera', function (newCam) {
			that.camera = newCam.camera;
		});
	}

	GizmoRenderSystem.prototype = Object.create(System.prototype);
	GizmoRenderSystem.prototype.constructor = GizmoRenderSystem;

	GizmoRenderSystem.prototype.activate = function (id, x, y) {
		this.active = true;
		var handle = Gizmo.getHandle(id);
		if (handle && this.activeGizmo) {
			this.activeGizmo.activate({
				id: id,
				data: handle,
				x: x / (this.viewportWidth / this._devicePixelRatio),
				y: y / (this.viewportHeight / this._devicePixelRatio)
			});
			this.domElement.addEventListener('mousemove', this.mouseMove);
		}
	};

	GizmoRenderSystem.prototype.deactivate = function () {
		this.activeGizmo.deactivate();

		this.active = false;
		this.domElement.removeEventListener('mousemove', this.mouseMove);
		if (this.nextGizmo !== null) {
			this.setActiveGizmo(this.nextGizmo);
			this.nextGizmo = null;
		}
	};

	GizmoRenderSystem.prototype.getGizmo = function (id) {
		return this.gizmos[id];
	};

	GizmoRenderSystem.prototype.show = function (entity) {
		this.entity = entity;
		if (this.activeGizmo) {
			if (this.entity) {
				this.showGizmo(this.activeGizmo);
			} else {
				this.hideGizmo(this.activeGizmo);
			}
		}
	};

	GizmoRenderSystem.prototype.showGizmo = function (gizmo) {
		gizmo.copyTransform(this.entity.transformComponent.worldTransform, this.global);
		if (!gizmo.visible) {
			this.renderables = gizmo.renderables;
			gizmo.visible = true;
		}
	};

	GizmoRenderSystem.prototype.hideGizmo = function (gizmo) {
		if (gizmo.visible) {
			this.renderables = [];
			gizmo.visible = false;
		}
	};

	GizmoRenderSystem.prototype.setActiveGizmo = function (id) {
		if (this.active) {
			this.nextGizmo = id;
			return;
		}
		if (this.activeGizmo) {
			this.hideGizmo(this.activeGizmo);
		}
		this.activeGizmo = this.gizmos[id] || null;
		if (this.activeGizmo && this.entity) {
			this.showGizmo(this.activeGizmo);
		}
	};

	GizmoRenderSystem.prototype.setGlobal = function (global) {
		if (this.global !== global) {
			this.global = !!global;
			if (this.entity && this.activeGizmo) {
				this.showGizmo(this.activeGizmo);
			}
		}
	};

	GizmoRenderSystem.prototype.setupCallbacks = function (callbacks) {
		if (callbacks && callbacks.length === 4) {
			this.gizmos[0].onChange = callbacks[0];
			this.gizmos[1].onChange = callbacks[1];
			this.gizmos[2].onChange = callbacks[2];
			this.gizmos[3].onChange = callbacks[3];
			return;
		}

		var inverseRotation = new Matrix3x3();
		var inverseTransformation = new Matrix4x4();

		// Set bound entities translation
		this.gizmos[0].onChange = function (change) {
			if (this.entity) {
				var translation = this.entity.transformComponent.transform.translation;
				translation.setVector(change);
				if (this.entity.transformComponent.parent) {
					inverseTransformation.copy(this.entity.transformComponent.parent.worldTransform.matrix);
					inverseTransformation.invert();
					inverseTransformation.applyPostPoint(translation);
				}
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);

		// Set bound entities rotation
		this.gizmos[1].onChange = function (change) {
			if (this.entity) {
				this.entity.transformComponent.transform.rotation.copy(change);
				if (this.entity.transformComponent.parent) {
					inverseRotation.copy(this.entity.transformComponent.parent.worldTransform.rotation);
					inverseRotation.invert();
				}
				Matrix3x3.combine(
					inverseRotation,
					this.entity.transformComponent.transform.rotation,
					this.entity.transformComponent.transform.rotation
				);
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);

		// Set bound entities rotation
		this.gizmos[2].onChange = function (change) {
			if (this.entity) {
				this.entity.transformComponent.transform.rotation.copy(change);
				if (this.entity.transformComponent.parent) {
					inverseRotation.copy(this.entity.transformComponent.parent.worldTransform.rotation);
					inverseRotation.invert();
				}
				Matrix3x3.combine(
					inverseRotation,
					this.entity.transformComponent.transform.rotation,
					this.entity.transformComponent.transform.rotation
				);
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);

		// Set bound entities scale
		this.gizmos[3].onChange = function (change) {
			if (this.entity) {
				var scale = this.entity.transformComponent.transform.scale;
				scale.setVector(change);
				if (this.entity.transformComponent.parent) {
					scale.div(this.entity.transformComponent.parent.worldTransform.scale);
				}
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);
	};

	GizmoRenderSystem.prototype.inserted = function (/*entity*/) {};

	GizmoRenderSystem.prototype.deleted = function (/*entity*/) {};

	GizmoRenderSystem.prototype.process = function (/*entities, tpf*/) {
		if (this.activeGizmo) {
			if (this.activeGizmo.dirty) {
				this.activeGizmo.process();
			} else if (this.entity && this.entity.transformComponent._updated && !this.active) {
				this.activeGizmo.copyTransform(this.entity.transformComponent.worldTransform, this.global);
			}
			this.activeGizmo.updateTransforms();
		}
	};

	GizmoRenderSystem.prototype.render = function (renderer) {
		renderer.checkResize(this.camera);
		this._devicePixelRatio = renderer._useDevicePixelRatio && window.devicePixelRatio ? window.devicePixelRatio / renderer.svg.currentScale : 1;

		if (!this.domElement) {
			this.domElement = renderer.domElement;
		}
		this.viewportHeight = renderer.viewportHeight;
		this.viewportWidth = renderer.viewportWidth;

		if (this.camera) {
			renderer.render(this.renderables, this.camera, this.lights, null, { color: false, stencil: true, depth: true }, this.overrideMaterials);
		}
	};

	GizmoRenderSystem.prototype.invalidateHandles = function (renderer) {
		renderer.invalidateMaterial(this.pickingMaterial);

		this.gizmos.forEach(function (gizmo) {
			gizmo.renderables.forEach(function (renderable) {
				renderable.materials.forEach(function (material) {
					renderer.invalidateMaterial(material);
				});

				renderer.invalidateMeshData(renderable.meshData);
			});
		});
	};

	GizmoRenderSystem.prototype.renderToPick = function (renderer, skipUpdateBuffer) {
		for (var i = 0; i < this.renderables.length; i++) {
			var renderable = this.renderables[i];
			if (renderable.thickness !== undefined) {
				renderable.materials[0].uniforms.thickness = renderable.thickness;
			}
		}
		renderer.renderToPick(this.renderables, this.camera, { color: false, stencil: true, depth: true }, skipUpdateBuffer, undefined, undefined, undefined, this.pickingMaterial);
		for (var i = 0; i < this.renderables.length; i++) {
			var renderable = this.renderables[i];
			if (renderable.thickness) {
				renderable.materials[0].uniforms.thickness = 0;
			}
		}
	};

	var customPickingShader = {
		attributes : {
			vertexPosition : MeshData.POSITION,
			vertexNormal : MeshData.NORMAL
		},
		processors: [
			function (shader, shaderInfo) {
				var attributeMap = shaderInfo.meshData.attributeMap;

				shader.defines = shader.defines || {};

				for (var attribute in attributeMap) {
					shader.setDefine(attribute, true);
				}
			}
		],
		uniforms : {
			viewMatrix : Shader.VIEW_MATRIX,
			projectionMatrix : Shader.PROJECTION_MATRIX,
			worldMatrix : Shader.WORLD_MATRIX,
			cameraFar : Shader.FAR_PLANE,
			thickness: 0.0,
			id : function (shaderInfo) {
				return shaderInfo.renderable.id + 1;
			}
		},
		vshader : [
		'attribute vec3 vertexPosition;',
		'#ifdef NORMAL',
			'attribute vec3 vertexNormal;',
		'#endif',

		'uniform mat4 viewMatrix;',
		'uniform mat4 projectionMatrix;',
		'uniform mat4 worldMatrix;',
		'uniform float cameraFar;',
		'uniform float thickness;',

		'varying float depth;',

		'void main() {',
			'#ifdef NORMAL',
				'vec4 mvPosition = viewMatrix * worldMatrix * vec4( vertexPosition + vertexNormal * thickness, 1.0 );',
			'#else',
				'vec4 mvPosition = viewMatrix * worldMatrix * vec4( vertexPosition, 1.0 );',
			'#endif',

			'depth = length(mvPosition.xyz) / cameraFar;',
			'gl_Position = projectionMatrix * mvPosition;',
		'}'
		].join("\n"),
		fshader : [
		'uniform float id;',

		'varying float depth;',

		ShaderFragment.methods.packDepth16,

		'void main() {',
			'vec2 packedId = vec2(floor(id/255.0), mod(id, 255.0)) * vec2(1.0/255.0);',
			'vec2 packedDepth = packDepth16(depth);',
			'gl_FragColor = vec4(packedId, packedDepth);',
		'}'
		].join("\n")
	};

	return GizmoRenderSystem;
});<commit_msg>Reduced common code<commit_after>define([
	'goo/entities/systems/System',
	'goo/entities/SystemBus',
	'goo/renderer/SimplePartitioner',
	'goo/renderer/Material',
	'goo/renderer/shaders/ShaderLib',
	'goo/renderer/shaders/ShaderFragment',
	'goo/math/Matrix3x3',
	'goo/math/Matrix4x4',
	'goo/renderer/MeshData',
	'goo/renderer/Shader',
	'goo/util/gizmopack/Gizmo',
	'goo/util/gizmopack/TranslationGizmo',
	'goo/util/gizmopack/RotationGizmo',
	'goo/util/gizmopack/GlobalRotationGizmo',
	'goo/util/gizmopack/ScaleGizmo'
], function (
	System,
	SystemBus,
	SimplePartitioner,
	Material,
	ShaderLib,
	ShaderFragment,
	Matrix3x3,
	Matrix4x4,
	MeshData,
	Shader,
	Gizmo,
	TranslationGizmo,
	RotationGizmo,
	GlobalRotationGizmo,
	ScaleGizmo
) {
	'use strict';

	/**
	 * Renders transform gizmos

	 * @example-link http://code.gooengine.com/latest/visual-test/goo/util/TransformGizmos/TransformGizmos-vtest.html Working example
	 * @property {boolean} doRender Only render if set to true
	 * @extends System
	 */
	function GizmoRenderSystem(callbacks) {
		System.call(this, 'GizmoRenderSystem', null);

		this.renderables = [];
		this.camera = null;

		this.gizmos = [
			new TranslationGizmo(this),
			new RotationGizmo(this),
			new GlobalRotationGizmo(this),
			new ScaleGizmo(this)
		];
		this.active = false;
		this.nextGizmo = null;
		this.setupCallbacks(callbacks);
		//this.boundEntity = null; //unused
		this.activeGizmo = null;
		this.viewportWidth = 0;
		this.viewportHeight = 0;
		this.domElement = null;
		this.global = false;
		this.pickingMaterial = Material.createEmptyMaterial(customPickingShader, 'pickingMaterial');
		this.pickingMaterial.blendState = {
			blending: 'NoBlending',
			blendEquation: 'AddEquation',
			blendSrc: 'SrcAlphaFactor',
			blendDst: 'OneMinusSrcAlphaFactor'
		};
		this._devicePixelRatio = 1;

		this.mouseMove = function (evt) {
			if (!this.activeGizmo) {
				return;
			}
			var x = (evt.offsetX !== undefined) ? evt.offsetX : evt.layerX;
			var y = (evt.offsetY !== undefined) ? evt.offsetY : evt.layerY;

			var mousePos = [
				x / (this.viewportWidth / this._devicePixelRatio),
				y / (this.viewportHeight / this._devicePixelRatio)
			];

			/*
			var camera = this.camera;
			if (camera && camera.projectionMode === Camera.Parallel){
				mousePos[0] = x / (this.viewportWidth  / this._devicePixelRatio) / (camera._frustumRight - camera._frustumLeft);
				mousePos[1] = y / (this.viewportHeight / this._devicePixelRatio) / (camera._frustumTop  - camera._frustumBottom);
			}

			console.log(mousePos[0],mousePos[1])
			*/

			this.activeGizmo.update(mousePos);

		}.bind(this);

		// no more that!
		var that = this;
		SystemBus.addListener('goo.setCurrentCamera', function (newCam) {
			that.camera = newCam.camera;
		});
	}

	GizmoRenderSystem.prototype = Object.create(System.prototype);
	GizmoRenderSystem.prototype.constructor = GizmoRenderSystem;

	GizmoRenderSystem.prototype.activate = function (id, x, y) {
		this.active = true;
		var handle = Gizmo.getHandle(id);
		if (handle && this.activeGizmo) {
			this.activeGizmo.activate({
				id: id,
				data: handle,
				x: x / (this.viewportWidth / this._devicePixelRatio),
				y: y / (this.viewportHeight / this._devicePixelRatio)
			});
			this.domElement.addEventListener('mousemove', this.mouseMove);
		}
	};

	GizmoRenderSystem.prototype.deactivate = function () {
		this.activeGizmo.deactivate();

		this.active = false;
		this.domElement.removeEventListener('mousemove', this.mouseMove);
		if (this.nextGizmo !== null) {
			this.setActiveGizmo(this.nextGizmo);
			this.nextGizmo = null;
		}
	};

	GizmoRenderSystem.prototype.getGizmo = function (id) {
		return this.gizmos[id];
	};

	GizmoRenderSystem.prototype.show = function (entity) {
		this.entity = entity;
		if (this.activeGizmo) {
			if (this.entity) {
				this.showGizmo(this.activeGizmo);
			} else {
				this.hideGizmo(this.activeGizmo);
			}
		}
	};

	GizmoRenderSystem.prototype.showGizmo = function (gizmo) {
		gizmo.copyTransform(this.entity.transformComponent.worldTransform, this.global);
		if (!gizmo.visible) {
			this.renderables = gizmo.renderables;
			gizmo.visible = true;
		}
	};

	GizmoRenderSystem.prototype.hideGizmo = function (gizmo) {
		if (gizmo.visible) {
			this.renderables = [];
			gizmo.visible = false;
		}
	};

	GizmoRenderSystem.prototype.setActiveGizmo = function (id) {
		if (this.active) {
			this.nextGizmo = id;
			return;
		}
		if (this.activeGizmo) {
			this.hideGizmo(this.activeGizmo);
		}
		this.activeGizmo = this.gizmos[id] || null;
		if (this.activeGizmo && this.entity) {
			this.showGizmo(this.activeGizmo);
		}
	};

	GizmoRenderSystem.prototype.setGlobal = function (global) {
		if (this.global !== global) {
			this.global = !!global;
			if (this.entity && this.activeGizmo) {
				this.showGizmo(this.activeGizmo);
			}
		}
	};

	GizmoRenderSystem.prototype.setupCallbacks = function (callbacks) {
		if (callbacks && callbacks.length === 4) {
			this.gizmos[0].onChange = callbacks[0];
			this.gizmos[1].onChange = callbacks[1];
			this.gizmos[2].onChange = callbacks[2];
			this.gizmos[3].onChange = callbacks[3];
			return;
		}

		var inverseRotation = new Matrix3x3();
		var inverseTransformation = new Matrix4x4();

		// Set bound entities translation
		this.gizmos[0].onChange = function (change) {
			if (this.entity) {
				var translation = this.entity.transformComponent.transform.translation;
				translation.setVector(change);
				if (this.entity.transformComponent.parent) {
					inverseTransformation.copy(this.entity.transformComponent.parent.worldTransform.matrix);
					inverseTransformation.invert();
					inverseTransformation.applyPostPoint(translation);
				}
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);

		var onRotationChange = function (change) {
			if (this.entity) {
				this.entity.transformComponent.transform.rotation.copy(change);
				if (this.entity.transformComponent.parent) {
					inverseRotation.copy(this.entity.transformComponent.parent.worldTransform.rotation);
					inverseRotation.invert();
				}
				Matrix3x3.combine(
					inverseRotation,
					this.entity.transformComponent.transform.rotation,
					this.entity.transformComponent.transform.rotation
				);
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);

		// Set bound entities rotation
		this.gizmos[1].onChange = onRotationChange;

		// Set bound entities rotation
		this.gizmos[2].onChange = onRotationChange;

		// Set bound entities scale
		this.gizmos[3].onChange = function (change) {
			if (this.entity) {
				var scale = this.entity.transformComponent.transform.scale;
				scale.setVector(change);
				if (this.entity.transformComponent.parent) {
					scale.div(this.entity.transformComponent.parent.worldTransform.scale);
				}
				this.entity.transformComponent.setUpdated();
			}
		}.bind(this);
	};

	GizmoRenderSystem.prototype.inserted = function (/*entity*/) {};

	GizmoRenderSystem.prototype.deleted = function (/*entity*/) {};

	GizmoRenderSystem.prototype.process = function (/*entities, tpf*/) {
		if (this.activeGizmo) {
			if (this.activeGizmo.dirty) {
				this.activeGizmo.process();
			} else if (this.entity && this.entity.transformComponent._updated && !this.active) {
				this.activeGizmo.copyTransform(this.entity.transformComponent.worldTransform, this.global);
			}
			this.activeGizmo.updateTransforms();
		}
	};

	GizmoRenderSystem.prototype.render = function (renderer) {
		renderer.checkResize(this.camera);
		this._devicePixelRatio = renderer._useDevicePixelRatio && window.devicePixelRatio ? window.devicePixelRatio / renderer.svg.currentScale : 1;

		if (!this.domElement) {
			this.domElement = renderer.domElement;
		}
		this.viewportHeight = renderer.viewportHeight;
		this.viewportWidth = renderer.viewportWidth;

		if (this.camera) {
			renderer.render(this.renderables, this.camera, this.lights, null, { color: false, stencil: true, depth: true }, this.overrideMaterials);
		}
	};

	GizmoRenderSystem.prototype.invalidateHandles = function (renderer) {
		renderer.invalidateMaterial(this.pickingMaterial);

		this.gizmos.forEach(function (gizmo) {
			gizmo.renderables.forEach(function (renderable) {
				renderable.materials.forEach(function (material) {
					renderer.invalidateMaterial(material);
				});

				renderer.invalidateMeshData(renderable.meshData);
			});
		});
	};

	GizmoRenderSystem.prototype.renderToPick = function (renderer, skipUpdateBuffer) {
		for (var i = 0; i < this.renderables.length; i++) {
			var renderable = this.renderables[i];
			if (renderable.thickness !== undefined) {
				renderable.materials[0].uniforms.thickness = renderable.thickness;
			}
		}
		renderer.renderToPick(this.renderables, this.camera, { color: false, stencil: true, depth: true }, skipUpdateBuffer, undefined, undefined, undefined, this.pickingMaterial);
		for (var i = 0; i < this.renderables.length; i++) {
			var renderable = this.renderables[i];
			if (renderable.thickness) {
				renderable.materials[0].uniforms.thickness = 0;
			}
		}
	};

	var customPickingShader = {
		attributes : {
			vertexPosition : MeshData.POSITION,
			vertexNormal : MeshData.NORMAL
		},
		processors: [
			function (shader, shaderInfo) {
				var attributeMap = shaderInfo.meshData.attributeMap;

				shader.defines = shader.defines || {};

				for (var attribute in attributeMap) {
					shader.setDefine(attribute, true);
				}
			}
		],
		uniforms : {
			viewMatrix : Shader.VIEW_MATRIX,
			projectionMatrix : Shader.PROJECTION_MATRIX,
			worldMatrix : Shader.WORLD_MATRIX,
			cameraFar : Shader.FAR_PLANE,
			thickness: 0.0,
			id : function (shaderInfo) {
				return shaderInfo.renderable.id + 1;
			}
		},
		vshader : [
		'attribute vec3 vertexPosition;',
		'#ifdef NORMAL',
			'attribute vec3 vertexNormal;',
		'#endif',

		'uniform mat4 viewMatrix;',
		'uniform mat4 projectionMatrix;',
		'uniform mat4 worldMatrix;',
		'uniform float cameraFar;',
		'uniform float thickness;',

		'varying float depth;',

		'void main() {',
			'#ifdef NORMAL',
				'vec4 mvPosition = viewMatrix * worldMatrix * vec4( vertexPosition + vertexNormal * thickness, 1.0 );',
			'#else',
				'vec4 mvPosition = viewMatrix * worldMatrix * vec4( vertexPosition, 1.0 );',
			'#endif',

			'depth = length(mvPosition.xyz) / cameraFar;',
			'gl_Position = projectionMatrix * mvPosition;',
		'}'
		].join("\n"),
		fshader : [
		'uniform float id;',

		'varying float depth;',

		ShaderFragment.methods.packDepth16,

		'void main() {',
			'vec2 packedId = vec2(floor(id/255.0), mod(id, 255.0)) * vec2(1.0/255.0);',
			'vec2 packedDepth = packDepth16(depth);',
			'gl_FragColor = vec4(packedId, packedDepth);',
		'}'
		].join("\n")
	};

	return GizmoRenderSystem;
});<|endoftext|>


<commit_before>import { Navigation } from 'react-native-navigation';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import Theme from 'config/theme';
import { registerScreens } from 'screens';

import * as reducers from 'redux-modules';
import offline from 'offline';

import Reactotron, { trackGlobalErrors, networking, openInEditor, asyncStorage } from 'reactotron-react-native'; // eslint-disable-line
import { reactotronRedux } from 'reactotron-redux'; // eslint-disable-line

// Disable ios warnings
// console.disableYellowBox = true;

// Show request in chrome network tool
// GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;

export default () => {
  function startApp() {
    Navigation.startSingleScreenApp({
      screen: {
        screen: 'ForestWatcher.Home',
        navigatorStyle: Theme.navigator.styles
      }
    });
  }

  const authMiddleware = ({ getState }) => next => action => next({ ...action, auth: getState().user.token });

  const reducer = combineReducers(reducers);
  const middleware = applyMiddleware(thunk, authMiddleware);

  let store = null;
  if (__DEV__) {
    Reactotron
      .configure()
      .use(reactotronRedux())
      .use(trackGlobalErrors())
      .use(networking())
      .use(openInEditor())
      .use(asyncStorage())
      .connect()
      .clear();
    window.tron = Reactotron; // eslint-disable-line
    store = offline({ persistCallback: startApp })(Reactotron.createStore)(reducer, undefined, middleware);
  } else {
    store = offline({ persistCallback: startApp })(createStore)(reducer, undefined, middleware);
  }

  registerScreens(store, Provider);
};
<commit_msg>feat: includes js error logging to analytics tracker<commit_after>import { Navigation } from 'react-native-navigation';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import Theme from 'config/theme';
import { registerScreens } from 'screens';

import * as reducers from 'redux-modules';
import offline from 'offline';

import Reactotron, { trackGlobalErrors, networking, openInEditor, asyncStorage } from 'reactotron-react-native'; // eslint-disable-line
import { reactotronRedux } from 'reactotron-redux'; // eslint-disable-line
import tracker from 'helpers/googleAnalytics';

// Disable ios warnings
// console.disableYellowBox = true;

// Show request in chrome network tool
// GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;

export default () => {
  function startApp() {
    Navigation.startSingleScreenApp({
      screen: {
        screen: 'ForestWatcher.Home',
        navigatorStyle: Theme.navigator.styles
      }
    });
  }

  const authMiddleware = ({ getState }) => next => action => next({ ...action, auth: getState().user.token });

  const reducer = combineReducers(reducers);
  const middleware = applyMiddleware(thunk, authMiddleware);

  let store = null;
  if (__DEV__) {
    Reactotron
      .configure()
      .use(reactotronRedux())
      .use(trackGlobalErrors())
      .use(networking())
      .use(openInEditor())
      .use(asyncStorage())
      .connect()
      .clear();
    window.tron = Reactotron; // eslint-disable-line
    store = offline({ persistCallback: startApp })(Reactotron.createStore)(reducer, undefined, middleware);
    global.ErrorUtils.setGlobalHandler((error, isFatal) => tron.display({ error, isFatal }));
  } else {
    global.ErrorUtils.setGlobalHandler(tracker.trackException);
    store = offline({ persistCallback: startApp })(createStore)(reducer, undefined, middleware);
  }

  registerScreens(store, Provider);
};
<|endoftext|>


<commit_before>const { DebuggerClient } = require("devtools-sham/shared/client/main");
const { DebuggerTransport } = require("devtools-sham/transport/transport");
const WebSocketDebuggerTransport = require("devtools/shared/transport/websocket-transport");
const { TargetFactory } = require("devtools-sham/client/framework/target");
const defer = require("../utils/defer");
const { getValue } = require("../feature");
const { Tab } = require("../types");
const { setupCommands, clientCommands } = require("./firefox/commands");
const { setupEvents, clientEvents } = require("./firefox/events");

let debuggerClient = null;
let threadClient = null;
let tabTarget = null;

function getThreadClient() {
  return threadClient;
}

function setThreadClient(client) {
  threadClient = client;
}

function getTabTarget() {
  return tabTarget;
}

function setTabTarget(target) {
  tabTarget = target;
}

function lookupTabTarget(tab) {
  const options = { client: debuggerClient, form: tab, chrome: false };
  return TargetFactory.forRemoteTab(options);
}

function createTabs(tabs) {
  return tabs.map(tab => {
    return Tab({
      title: tab.title,
      url: tab.url,
      id: tab.actor,
      tab,
      browser: "firefox"
    });
  });
}

function connectClient() {
  const deferred = defer();
  let isConnected = false;
  const useProxy = !getValue("firefox.webSocketConnection");
  const portPref = useProxy ? "firefox.proxyPort" : "firefox.webSocketPort";
  const webSocketPort = getValue(portPref);

  const socket = new WebSocket(`ws://${document.location.hostname}:${webSocketPort}`);
  const transport = useProxy ?
    new DebuggerTransport(socket) : new WebSocketDebuggerTransport(socket);
  debuggerClient = new DebuggerClient(transport);

  // TODO: the timeout logic should be moved to DebuggerClient.connect.
  setTimeout(() => {
    if (isConnected) {
      return;
    }

    deferred.resolve([]);
  }, 1000);

  debuggerClient.connect().then(() => {
    isConnected = true;
    return debuggerClient.listTabs().then(response => {
      deferred.resolve(createTabs(response.tabs));
    });
  }).catch(err => {
    console.log(err);
    deferred.reject();
  });

  return deferred.promise;
}

function connectTab(tab) {
  return new Promise((resolve, reject) => {
    window.addEventListener("beforeunload", () => {
      getTabTarget() && getTabTarget().destroy();
    });

    lookupTabTarget(tab).then(target => {
      tabTarget = target;
      target.activeTab.attachThread({}, (res, _threadClient) => {
        threadClient = _threadClient;
        threadClient.resume();
        resolve();
      });
    });
  });
}

function initPage(actions) {
  tabTarget = getTabTarget();
  threadClient = getThreadClient();

  setupCommands({ threadClient, tabTarget });

  tabTarget.on("will-navigate", actions.willNavigate);
  tabTarget.on("navigate", actions.navigate);

  // Listen to all the requested events.
  setupEvents({ threadClient, actions });
  Object.keys(clientEvents).forEach(eventName => {
    threadClient.addListener(eventName, clientEvents[eventName]);
  });

  threadClient.reconfigure({
    "useSourceMaps": false,
    "autoBlackBox": false
  });

  // In Firefox, we need to initially request all of the sources which
  // makes the server iterate over them and fire individual
  // `newSource` notifications. We don't need to do anything with the
  // response since `newSource` notifications are fired.
  threadClient.getSources();
}

module.exports = {
  connectClient,
  connectTab,
  clientCommands,
  getThreadClient,
  setThreadClient,
  getTabTarget,
  setTabTarget,
  initPage
};
<commit_msg>increase Firefox timeout (avoids false positives) (#509)<commit_after>const { DebuggerClient } = require("devtools-sham/shared/client/main");
const { DebuggerTransport } = require("devtools-sham/transport/transport");
const WebSocketDebuggerTransport = require("devtools/shared/transport/websocket-transport");
const { TargetFactory } = require("devtools-sham/client/framework/target");
const defer = require("../utils/defer");
const { getValue } = require("../feature");
const { Tab } = require("../types");
const { setupCommands, clientCommands } = require("./firefox/commands");
const { setupEvents, clientEvents } = require("./firefox/events");

let debuggerClient = null;
let threadClient = null;
let tabTarget = null;

function getThreadClient() {
  return threadClient;
}

function setThreadClient(client) {
  threadClient = client;
}

function getTabTarget() {
  return tabTarget;
}

function setTabTarget(target) {
  tabTarget = target;
}

function lookupTabTarget(tab) {
  const options = { client: debuggerClient, form: tab, chrome: false };
  return TargetFactory.forRemoteTab(options);
}

function createTabs(tabs) {
  return tabs.map(tab => {
    return Tab({
      title: tab.title,
      url: tab.url,
      id: tab.actor,
      tab,
      browser: "firefox"
    });
  });
}

function connectClient() {
  const deferred = defer();
  let isConnected = false;
  const useProxy = !getValue("firefox.webSocketConnection");
  const portPref = useProxy ? "firefox.proxyPort" : "firefox.webSocketPort";
  const webSocketPort = getValue(portPref);

  const socket = new WebSocket(`ws://${document.location.hostname}:${webSocketPort}`);
  const transport = useProxy ?
    new DebuggerTransport(socket) : new WebSocketDebuggerTransport(socket);
  debuggerClient = new DebuggerClient(transport);

  // TODO: the timeout logic should be moved to DebuggerClient.connect.
  setTimeout(() => {
    if (isConnected) {
      return;
    }

    deferred.resolve([]);
  }, 6000);

  debuggerClient.connect().then(() => {
    isConnected = true;
    return debuggerClient.listTabs().then(response => {
      deferred.resolve(createTabs(response.tabs));
    });
  }).catch(err => {
    console.log(err);
    deferred.reject();
  });

  return deferred.promise;
}

function connectTab(tab) {
  return new Promise((resolve, reject) => {
    window.addEventListener("beforeunload", () => {
      getTabTarget() && getTabTarget().destroy();
    });

    lookupTabTarget(tab).then(target => {
      tabTarget = target;
      target.activeTab.attachThread({}, (res, _threadClient) => {
        threadClient = _threadClient;
        threadClient.resume();
        resolve();
      });
    });
  });
}

function initPage(actions) {
  tabTarget = getTabTarget();
  threadClient = getThreadClient();

  setupCommands({ threadClient, tabTarget });

  tabTarget.on("will-navigate", actions.willNavigate);
  tabTarget.on("navigate", actions.navigate);

  // Listen to all the requested events.
  setupEvents({ threadClient, actions });
  Object.keys(clientEvents).forEach(eventName => {
    threadClient.addListener(eventName, clientEvents[eventName]);
  });

  threadClient.reconfigure({
    "useSourceMaps": false,
    "autoBlackBox": false
  });

  // In Firefox, we need to initially request all of the sources which
  // makes the server iterate over them and fire individual
  // `newSource` notifications. We don't need to do anything with the
  // response since `newSource` notifications are fired.
  threadClient.getSources();
}

module.exports = {
  connectClient,
  connectTab,
  clientCommands,
  getThreadClient,
  setThreadClient,
  getTabTarget,
  setTabTarget,
  initPage
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
  Command-lne app to convert Rimu source to HTML.
  Run 'node rimu.js --help' for details.
*/

var path = require('path');
var fs = require('fs');
var Rimu = require('./rimu-commonjs2.js');

var MANPAGE = 'NAME\n' +
    '  rimuc - convert Rimu source to HTML\n' +
    '\n' +
    'SYNOPSIS\n' +
    '  rimuc [OPTIONS...] [FILES...]\n' +
    '\n' +
    'DESCRIPTION\n' +
    '  Reads Rimu source markup from stdin, converts them to HTML\n' +
    '  then writes the HTML to stdout. If FILES are specified\n' +
    '  the Rimu source is read from FILES.\n' +
    '\n' +
    '  If a file named .rimurc exists in the user\'s home directory\n' +
    '  then its contents is processed (with safeMode 0) after\n' +
    '  --prepend sources but before any other inputs.\n' +
    '  This behavior can be disabled with the --no-rimurc option.\n' +
    '\n' +
    'OPTIONS\n' +
    '  -h, --help\n' +
    '    Display help message.\n' +
    '\n' +
    '  -o, --output OUTFILE\n' +
    '    Write output to file OUTFILE instead of stdout.\n' +
    '\n' +
    '  -p, --prepend SOURCE\n' +
    '    Process the SOURCE text before other inputs.\n' +
    '    Rendered with safeMode 0.\n' +
    '\n' +
    '  --no-rimurc\n' +
    '    Do not process .rimurc from the user\'s home directory.\n' +
    '\n' +
    '  -s, --styled\n' +
    '    Include HTML header and footer and Bootstrap CSS styling in\n' +
    '    output. If only one source file is specified and the --output option\n' +
    '    is not used then the output is written to a same-named file with\n' +
    '    an .html extension.\n' +
    '\n' +
    '  --safeMode NUMBER\n' +
    '    Specifies how to process inline and block HTML elements.\n' +
    '    --safeMode 0 renders raw HTML (default).\n' +
    '    --safeMode 1 drops raw HTML.\n' +
    '    --safeMode 2 replaces raw HTML with htmlReplacement option text.\n' +
    '    --safeMode 3 renders raw HTML as text.\n' +
    '\n' +
    '  --macroMode NUMBER\n' +
    '    Specifies which Rimu macro invocations are processed.\n' +
    '    --macroMode 0 None.\n' +
    '    --macroMode 1 All (legacy version 4 default behavior).\n' +
    '    --macroMode 2 Only Defined macros.\n' +
    '    --macroMode 3 Only Reserved macros.\n' +
    '    --macroMode 4 Defined or Reserved macros (default behavior).\n' +
    '\n' +
    '  --htmlReplacement\n' +
    '    A string that replaces embedded HTML when safeMode is set to 2.\n' +
    '    Defaults to `<mark>replaced HTML</mark>`.\n' +
    '\n' +
    '  --title TITLE, --highlightjs, --mathjax, --toc, --section-numbers\n' +
    '    Shortcuts for prepended styling macro definitions:\n' +
    '    --prepend "{--title}=\'TITLE\'"\n' +
    '    --prepend "{--highlightjs}=\'true\'"\n' +
    '    --prepend "{--mathjax}=\'true\'"\n' +
    '    --prepend "{--toc}=\'true\'"\n' +
    '    --prepend "{--section-numbers}=\'true\'"\n' +
    '\n' +
    'STYLING MACROS AND CLASSES\n' +
    '  The following macros and CSS classes are available when the\n' +
    '  --styled option is used:\n' +
    '\n' +
    '  Macro name         Description\n' +
    '  ______________________________________________________________\n' +
    '  --title            HTML document title (1).\n' +
    '  --highlightjs      Set to non-blank value to enable syntax\n' +
    '                     highlighting with Highlight.js.\n' +
    '  --mathjax          Set to a non-blank value to enable MathJax.\n' +
    '  --toc              Set to a non-blank value to generate a\n' +
    '                     table of contents (1).\n' +
    '  --section-numbers  Apply h2 and h3 section numbering (1).\n' +
    '  ______________________________________________________________\n' +
    '  (1) Must be defined prior to header (--prepend or .rimurc).\n' +
    '\n' +
    '  CSS class        Description\n' +
    '  ______________________________________________________________\n' +
    '  verse            Verse format (paragraphs, division blocks).\n' +
    '  sidebar          Sidebar format (paragraphs, division blocks).\n' +
    '  dl-numbered      Number labeled list items.\n' +
    '  dl-counter       Prepend dl item counter to element content.\n' +
    '  ol-counter       Prepend ol item counter to element content.\n' +
    '  ul-counter       Prepend ul item counter to element content.\n' +
    '  ______________________________________________________________\n';

// Helpers.
function die(message) {
  console.error(message);
  process.exit(1);
}

var safeMode = 0;
var macroMode = 4;
var htmlReplacement = null;
var styled = false;
var no_rimurc = false;

// Skip executable and script paths.
process.argv.shift(); // Skip executable path.
process.argv.shift(); // Skip rimuc script path.

// Parse command-line options.
var source = '';
var outfile;
outer:
    while (!!(arg = process.argv.shift())) {
      switch (arg) {
        case '--help':
        case '-h':
          console.log('\n' + MANPAGE);
          process.exit();
          break;
        case '--output':
        case '-o':
          outfile = process.argv.shift();
          if (!outfile) {
            die('missing --output file name');
          }
          break;
        case '--prepend':
        case '-p':
          source += process.argv.shift() + '\n';
          break;
        case '--no-rimurc':
          no_rimurc = true;
          break;
        case '--safeMode':
        case '--safe-mode': // Deprecated in Rimu 5.0.0.
          safeMode = parseInt(process.argv.shift() || 99, 10);
          if (safeMode < 0 || safeMode > 3) {
            die('illegal --safeMode option value');
          }
          break;
        case '--macroMode':
          macroMode = parseInt(process.argv.shift() || 99, 10);
          if (macroMode < 0 || macroMode > 4) {
            die('illegal --macroMode option value');
          }
          break;
        case '--htmlReplacement':
          htmlReplacement = process.argv.shift();
          break;
        case '--styled':
        case '-s':
          styled = true;
          break;
        // Styling macro definitions shortcut options.
        case '--highlightjs':
        case '--mathjax':
        case '--section-numbers':
        case '--title':
        case '--toc':
          var macroValue = arg === '--title' ? process.argv.shift() : 'true';
          source += '{' + arg + "}='" + macroValue + "'\n";
          break;
        default:
          if (arg[0] === '-') {
            die('illegal option: ' + arg);
          }
          process.argv.unshift(arg); // List of source files.
          break outer;
      }
    }

// process.argv contains the list of source files.
var files = process.argv;
if (files.length === 0) {
  files.push('/dev/stdin');
}
else if (styled && !outfile && files.length === 1) {
  // Use the source file name with .html extension for the output file.
  outfile = files[0].substr(0, files[0].lastIndexOf('.')) + '.html';
}

if (styled) {
  // Envelope source files with header and footer.
  files.unshift(path.resolve(__dirname, 'header.rmu'));
  files.push(path.resolve(__dirname, 'footer.rmu'));
}

// Prepend $HOME/.rimurc file if it exists.
var homeDir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var rimurc =  path.resolve(homeDir, '.rimurc');
if (!no_rimurc && fs.existsSync(rimurc)) {
  files.unshift(rimurc);
}

// Convert Rimu source files to HTML.
var html = '';
if (source !== '') {
  html += Rimu.render(source) + '\n'; // --prepend option source.
}
files.forEach(function (infile) {
  if (!fs.existsSync(infile)) {
    die('source file does not exist: ' + infile);
  }
  try {
    source = fs.readFileSync(infile).toString();
  } catch (e) {
    die('source file permission denied: ' + infile);
  }
  var options = {
      // rimurc processed with default safeMode and macroMode.
      safeMode: infile === rimurc ? 0 : safeMode,
      macroMode: infile === rimurc ? 4 : macroMode
    };
  if (htmlReplacement !== null) {
    options.htmlReplacement = htmlReplacement;
  }
  html += Rimu.render(source, options) + '\n';
});
html = html.trim() + '\n';
if (outfile) {
  fs.writeFileSync(outfile, html);
}
else {
  console.log(html);
}
<commit_msg>feature: rimuc: The contents of input files with an .html extension are passed directly to the output.<commit_after>#!/usr/bin/env node
/*
  Command-lne app to convert Rimu source to HTML.
  Run 'node rimu.js --help' for details.
*/

var path = require('path');
var fs = require('fs');
var Rimu = require('./rimu-commonjs2.js');

var MANPAGE = 'NAME\n' +
    '  rimuc - convert Rimu source to HTML\n' +
    '\n' +
    'SYNOPSIS\n' +
    '  rimuc [OPTIONS...] [FILES...]\n' +
    '\n' +
    'DESCRIPTION\n' +
    '  Reads Rimu source markup from stdin, converts them to HTML\n' +
    '  then writes the HTML to stdout. If FILES are specified\n' +
    '  the Rimu source is read from FILES. The contents of files\n' +
    '  with an .html extension are passed directly to the output.\n' +
    '\n' +
    '  If a file named .rimurc exists in the user\'s home directory\n' +
    '  then its contents is processed (with safeMode 0) after\n' +
    '  --prepend sources but before any other inputs.\n' +
    '  This behavior can be disabled with the --no-rimurc option.\n' +
    '\n' +
    'OPTIONS\n' +
    '  -h, --help\n' +
    '    Display help message.\n' +
    '\n' +
    '  -o, --output OUTFILE\n' +
    '    Write output to file OUTFILE instead of stdout.\n' +
    '\n' +
    '  -p, --prepend SOURCE\n' +
    '    Process the SOURCE text before other inputs.\n' +
    '    Rendered with safeMode 0.\n' +
    '\n' +
    '  --no-rimurc\n' +
    '    Do not process .rimurc from the user\'s home directory.\n' +
    '\n' +
    '  -s, --styled\n' +
    '    Include HTML header and footer and Bootstrap CSS styling in\n' +
    '    output. If only one source file is specified and the --output option\n' +
    '    is not used then the output is written to a same-named file with\n' +
    '    an .html extension.\n' +
    '\n' +
    '  --safeMode NUMBER\n' +
    '    Specifies how to process inline and block HTML elements.\n' +
    '    --safeMode 0 renders raw HTML (default).\n' +
    '    --safeMode 1 drops raw HTML.\n' +
    '    --safeMode 2 replaces raw HTML with htmlReplacement option text.\n' +
    '    --safeMode 3 renders raw HTML as text.\n' +
    '\n' +
    '  --macroMode NUMBER\n' +
    '    Specifies which Rimu macro invocations are processed.\n' +
    '    --macroMode 0 None.\n' +
    '    --macroMode 1 All (legacy version 4 default behavior).\n' +
    '    --macroMode 2 Only Defined macros.\n' +
    '    --macroMode 3 Only Reserved macros.\n' +
    '    --macroMode 4 Defined or Reserved macros (default behavior).\n' +
    '\n' +
    '  --htmlReplacement\n' +
    '    A string that replaces embedded HTML when safeMode is set to 2.\n' +
    '    Defaults to `<mark>replaced HTML</mark>`.\n' +
    '\n' +
    '  --title TITLE, --highlightjs, --mathjax, --toc, --section-numbers\n' +
    '    Shortcuts for prepended styling macro definitions:\n' +
    '    --prepend "{--title}=\'TITLE\'"\n' +
    '    --prepend "{--highlightjs}=\'true\'"\n' +
    '    --prepend "{--mathjax}=\'true\'"\n' +
    '    --prepend "{--toc}=\'true\'"\n' +
    '    --prepend "{--section-numbers}=\'true\'"\n' +
    '\n' +
    'STYLING MACROS AND CLASSES\n' +
    '  The following macros and CSS classes are available when the\n' +
    '  --styled option is used:\n' +
    '\n' +
    '  Macro name         Description\n' +
    '  ______________________________________________________________\n' +
    '  --title            HTML document title (1).\n' +
    '  --highlightjs      Set to non-blank value to enable syntax\n' +
    '                     highlighting with Highlight.js.\n' +
    '  --mathjax          Set to a non-blank value to enable MathJax.\n' +
    '  --toc              Set to a non-blank value to generate a\n' +
    '                     table of contents (1).\n' +
    '  --section-numbers  Apply h2 and h3 section numbering (1).\n' +
    '  ______________________________________________________________\n' +
    '  (1) Must be defined prior to header (--prepend or .rimurc).\n' +
    '\n' +
    '  CSS class        Description\n' +
    '  ______________________________________________________________\n' +
    '  verse            Verse format (paragraphs, division blocks).\n' +
    '  sidebar          Sidebar format (paragraphs, division blocks).\n' +
    '  dl-numbered      Number labeled list items.\n' +
    '  dl-counter       Prepend dl item counter to element content.\n' +
    '  ol-counter       Prepend ol item counter to element content.\n' +
    '  ul-counter       Prepend ul item counter to element content.\n' +
    '  ______________________________________________________________\n';

// Helpers.
function die(message) {
  console.error(message);
  process.exit(1);
}

var safeMode = 0;
var macroMode = 4;
var htmlReplacement = null;
var styled = false;
var no_rimurc = false;

// Skip executable and script paths.
process.argv.shift(); // Skip executable path.
process.argv.shift(); // Skip rimuc script path.

// Parse command-line options.
var source = '';
var outfile;
outer:
    while (!!(arg = process.argv.shift())) {
      switch (arg) {
        case '--help':
        case '-h':
          console.log('\n' + MANPAGE);
          process.exit();
          break;
        case '--output':
        case '-o':
          outfile = process.argv.shift();
          if (!outfile) {
            die('missing --output file name');
          }
          break;
        case '--prepend':
        case '-p':
          source += process.argv.shift() + '\n';
          break;
        case '--no-rimurc':
          no_rimurc = true;
          break;
        case '--safeMode':
        case '--safe-mode': // Deprecated in Rimu 5.0.0.
          safeMode = parseInt(process.argv.shift() || 99, 10);
          if (safeMode < 0 || safeMode > 3) {
            die('illegal --safeMode option value');
          }
          break;
        case '--macroMode':
          macroMode = parseInt(process.argv.shift() || 99, 10);
          if (macroMode < 0 || macroMode > 4) {
            die('illegal --macroMode option value');
          }
          break;
        case '--htmlReplacement':
          htmlReplacement = process.argv.shift();
          break;
        case '--styled':
        case '-s':
          styled = true;
          break;
        // Styling macro definitions shortcut options.
        case '--highlightjs':
        case '--mathjax':
        case '--section-numbers':
        case '--title':
        case '--toc':
          var macroValue = arg === '--title' ? process.argv.shift() : 'true';
          source += '{' + arg + "}='" + macroValue + "'\n";
          break;
        default:
          if (arg[0] === '-') {
            die('illegal option: ' + arg);
          }
          process.argv.unshift(arg); // List of source files.
          break outer;
      }
    }

// process.argv contains the list of source files.
var files = process.argv;
if (files.length === 0) {
  files.push('/dev/stdin');
}
else if (styled && !outfile && files.length === 1) {
  // Use the source file name with .html extension for the output file.
  outfile = files[0].substr(0, files[0].lastIndexOf('.')) + '.html';
}

if (styled) {
  // Envelope source files with header and footer.
  files.unshift(path.resolve(__dirname, 'header.rmu'));
  files.push(path.resolve(__dirname, 'footer.rmu'));
}

// Prepend $HOME/.rimurc file if it exists.
var homeDir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var rimurc =  path.resolve(homeDir, '.rimurc');
if (!no_rimurc && fs.existsSync(rimurc)) {
  files.unshift(rimurc);
}

// Convert Rimu source files to HTML.
var html = '';
if (source !== '') {
  html += Rimu.render(source) + '\n'; // --prepend option source.
}
files.forEach(function (infile) {
  if (!fs.existsSync(infile)) {
    die('source file does not exist: ' + infile);
  }
  try {
    source = fs.readFileSync(infile).toString();
  } catch (e) {
    die('source file permission denied: ' + infile);
  }
  var ext = infile.split('.').pop();
  if (ext === 'html') {
    html += source;
    return;
  }
  var options = {
      // rimurc processed with default safeMode and macroMode.
      safeMode: infile === rimurc ? 0 : safeMode,
      macroMode: infile === rimurc ? 4 : macroMode
    };
  if (htmlReplacement !== null) {
    options.htmlReplacement = htmlReplacement;
  }
  html += Rimu.render(source, options) + '\n';
});
html = html.trim() + '\n';
if (outfile) {
  fs.writeFileSync(outfile, html);
}
else {
  console.log(html);
}
<|endoftext|>


<commit_before>app.service('Action', ['$state', 'Screen', 'Model', 'ngDialog', '$http', function($state, Screen, Model, ngDialog, $http){
  var Action = this;

  Action.call = function (action) {
    Action.list[action.type](action.payload)
  }

  Action.list = {
    NEXT_SCREEN: function () {
      Action.animation_class = 'slide-left'

      Screen.next({id: $state.params.id}, function (res) {
        if (res)
          $state.go('screen_path', {id: res.id})
      })
    },
    PREV_SCREEN: function () {
      Action.animation_class = 'slide-right'

      Screen.prev({id: $state.params.id}, function (res) {
        if (res)
          $state.go('screen_path', {id: res.id})
      })

    },
    GO_TO_SCREEN_BY_ID: function (payload) {
      Action.animation_class = 'slide-fade'
      $state.go('screen_path', {id: payload.screen_id})
    },
    OPEN_FLOW: function (payload) {
      Action.animation_class = 'slide-fade'
      Screen.flow(payload, function (res) {
        $state.go('screen_path', {id: res.id})
      })
    },
    EXIT: function () {
      Action.animation_class = 'slide-down'
      Screen.main_flow(function (res) {
        Model.data = {}
        $state.go('screen_path', {id: res.id})
      })
    },
    SUBMIT_ON_SERVER: function (payload) {
      $http.post('/v1/endpoints', _.extend({data: Model.data}, payload))
        .then(function (res) {
          Action.call(payload.after_submit_action);
        })
    },
    OPEN_MODAL: function (payload) {
      ngDialog.open({
        template: 'mobile-modal.html',
        className: 'ngdialog-mobile-modal',
        controller: ['$scope', function (scope) {
          $('.app-layout').css({filter: "blur(10px)"})
          scope.settings = payload
        }],
        preCloseCallback: function (value) {
          $('.app-layout').css({filter: "none"})
        }
      })
    },
    OPEN_IFRAME: function (payload) {
      ngDialog.open({
        template: "",
        plain: true,
        className: 'ngdialog-mobile-modal',
        controller: ['$scope', '$interval', '$timeout', function (scope, $interval, $timeout) {
          $timeout(function () {
            $("#open_iframe").load(function () {
              $interval(function () {
                if ($('#open_iframe')[0].contentWindow.$('iframe').length === 0) {
                  scope.closeThisDialog();
                }
              },300)
              scope.$apply();
            })
          }, 100)
        }],
      })
    }
  }
}])<commit_msg>manage actions from server<commit_after>app.service('Action', ['$state', 'Screen', 'Model', 'ngDialog', '$http', function($state, Screen, Model, ngDialog, $http){
  var Action = this;

  Action.call = function (action) {
    Action.list[action.type](action.payload)
  }

  Action.list = {
    NEXT_SCREEN: function () {
      Action.animation_class = 'slide-left'

      Screen.next({id: $state.params.id}, function (res) {
        if (res)
          $state.go('screen_path', {id: res.id})
      })
    },
    PREV_SCREEN: function () {
      Action.animation_class = 'slide-right'

      Screen.prev({id: $state.params.id}, function (res) {
        if (res)
          $state.go('screen_path', {id: res.id})
      })

    },
    GO_TO_SCREEN_BY_ID: function (payload) {
      Action.animation_class = 'slide-fade'
      $state.go('screen_path', {id: payload.screen_id})
    },
    OPEN_FLOW: function (payload) {
      Action.animation_class = 'slide-fade'
      Screen.flow(payload, function (res) {
        $state.go('screen_path', {id: res.id})
      })
    },
    EXIT: function () {
      Action.animation_class = 'slide-down'
      Screen.main_flow(function (res) {
        Model.data = {}
        $state.go('screen_path', {id: res.id})
      })
    },
    SUBMIT_ON_SERVER: function (payload) {
      $http.post('/v1/endpoints', _.extend({data: Model.data}, payload))
        .then(function (res) {
          Action.call(payload.after_submit_action);
          if (res.data.action) {
            Action.call(res.data.action)
          }
        })
    },
    OPEN_MODAL: function (payload) {
      ngDialog.open({
        template: 'mobile-modal.html',
        className: 'ngdialog-mobile-modal',
        controller: ['$scope', function (scope) {
          $('.app-layout').css({filter: "blur(10px)"})
          scope.settings = payload
        }],
        preCloseCallback: function (value) {
          $('.app-layout').css({filter: "none"})
        }
      })
    },
    OPEN_IFRAME: function (payload) {
      ngDialog.open({
        template: "",
        plain: true,
        className: 'ngdialog-mobile-modal',
        controller: ['$scope', '$interval', '$timeout', function (scope, $interval, $timeout) {
          $timeout(function () {
            $("#open_iframe").load(function () {
              $interval(function () {
                if ($('#open_iframe')[0].contentWindow.$('iframe').length === 0) {
                  scope.closeThisDialog();
                }
              },300)
              scope.$apply();
            })
          }, 100)
        }],
      })
    }
  }
}])<|endoftext|>