<commit_before>goog.provide('annotorious.mediatypes.openlayers.OpenLayersAnnotator');

goog.require('annotorious.mediatypes.Annotator');
goog.require('annotorious.templates.openlayers');
goog.require('annotorious.mediatypes.openlayers.Viewer');

/**
 * The OpenLayersAnnotator is responsible for handling annotation functionality
 * on one OpenLayers map in the page.
 * @param {OpenLayers.Map} map the OpenLayers map
 * @constructor
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator = function(map) {
  annotorious.mediatypes.Annotator.call();

  /** @private **/
  this._map = map;

  /** @private **/
  this.element = map.div;

  // We need to constrain the dimension of the canvas by the size of the map.
  // Therefore the map enclosing DIV needs to have position 'absolute' or
  // 'relative' set!
  var pos = goog.style.getStyle(this.element, 'position');
  if (pos != 'absolute' && pos != 'relative')
    goog.style.setStyle(this.element, 'position', 'relative');

  /** @private **/
  this._eventBroker = new annotorious.events.EventBroker();

  /** @private **/
  this._secondaryHint = goog.soy.renderAsElement(annotorious.templates.openlayers.secondaryHint, {msg: 'Click and Drag'});
  goog.style.setStyle(this._secondaryHint, 'z-index', 9998);
  goog.style.setOpacity(this._secondaryHint, 0);
  goog.dom.appendChild(this.element, this._secondaryHint);

  /** @private **/
  this.popup = new annotorious.Popup(this);

  /** @private **/
  this._viewer = new annotorious.mediatypes.openlayers.Viewer(map, this);

  /** @private **/
  this._editCanvas = goog.soy.renderAsElement(annotorious.templates.image.canvas,
    { width:'0', height:'0' });
  goog.style.showElement(this._editCanvas, false);
  goog.style.setStyle(this._editCanvas, 'position', 'absolute');
  goog.style.setStyle(this._editCanvas, 'top', '0px');
  goog.style.setStyle(this._editCanvas, 'z-index', 9999);

  goog.dom.appendChild(this.element, this._editCanvas);

  var self = this,
      updateCanvasSize = function() {
        var width = parseInt(goog.style.getComputedStyle(self.element, 'width'), 10),
            height = parseInt(goog.style.getComputedStyle(self.element, 'height'), 10);

        goog.style.setSize(self._editCanvas, width, height);
        self._editCanvas.width = width;
        self._editCanvas.height = height;
      };

  updateCanvasSize();

  /** @private **/
  this._selector = new annotorious.plugins.selection.RectDragSelector();
  this._selector.init(this, this._editCanvas);

  /** @private **/
  this._stop_selection_callback = undefined;

  /** @private **/
  this.editor = new annotorious.Editor(this);
  goog.style.setStyle(this.editor.element, 'z-index', 10000);

  if (window.addEventListener)
    window.addEventListener('resize', updateCanvasSize, false);
  else if (window.attachEvent)
    window.attachEvent('onresize', updateCanvasSize);

  goog.events.listen(this.element, goog.events.EventType.MOUSEOVER, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(self.element, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OVER_ANNOTATABLE_ITEM);
  });

  goog.events.listen(this.element, goog.events.EventType.MOUSEOUT, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(self.element, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OUT_OF_ANNOTATABLE_ITEM);
  });

  goog.events.listen(this._editCanvas, goog.events.EventType.MOUSEDOWN, function(event) {
    var offset = goog.style.getClientPosition(self.element);
    self._selector.startSelection(event.clientX - offset.x, event.clientY - offset.y);
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_COMPLETED, function(event) {
    goog.style.setStyle(self._editCanvas, 'pointer-events', 'none');

    var bounds = event.viewportBounds;
    self.editor.setPosition(new annotorious.shape.geom.Point(bounds.left /* + self.element.offsetLeft */,
                                                             bounds.bottom + 4 /* + self.element.offsetTop */));
    self.editor.open();
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_CANCELED, function(event) {
    self.stopSelection();
  });
}
goog.inherits(annotorious.mediatypes.openlayers.OpenLayersAnnotator, annotorious.mediatypes.Annotator);

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.showSelectionWidget = function() {
  // Does not have any effect at the moment
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.hideSelectionWidget = function() {
  // Does not have any effect at the moment
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.activateSelector = function(callback) {
  goog.style.setStyle(this._editCanvas, 'pointer-events', 'auto');

  var self = this;
  goog.style.showElement(this._editCanvas, true);
  goog.style.setOpacity(this._secondaryHint, 0.8);
  window.setTimeout(function() {
    goog.style.setOpacity(self._secondaryHint, 0);
  }, 2000);

  if (callback)
    this._stop_selection_callback = callback;
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.destroy = function() {
  this._viewer.destroy();
  goog.dom.removeNode(this._secondaryHint);
  goog.dom.removeNode(this._editCanvas);
}

/**
 * Standard Annotator method: editAnnotation
 * @suppress {checkTypes}
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.editAnnotation = function(annotation) {
  // Step 1 - remove from viewer
  this._viewer.removeAnnotation(annotation);

  // Step 2 - TODO find a suitable selector for the shape
  var selector = this._selector;

  // Step 3 - open annotation in editor
  var self = this;
  if (selector) {
    goog.style.showElement(this._editCanvas, true);
    this._viewer.highlightAnnotation(undefined);

    // TODO make editable - not just draw (selector implementation required)
    var g2d = this._editCanvas.getContext('2d');
    var shape = annotation.shapes[0];
    var viewportShape = annotorious.shape.transform(shape, function(xy) { return self.fromItemCoordinates(xy); });
    selector.drawShape(g2d, viewportShape);

    var viewportBounds = annotorious.shape.getBoundingRect(viewportShape).geometry;
    this.editor.setPosition(new annotorious.shape.geom.Point(viewportBounds.x + this.element.offsetLeft,
                                                             viewportBounds.y + viewportBounds.height + 4 + this.element.offsetTop));
    this.editor.open(annotation);
  }
}

/**
 * Standard Annotator method: addSelector
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.addSelector = function(selector) {

}

/**
 * Standard Annotator method: fromItemCoordinates
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.fromItemCoordinates = function(itemCoords) {
  var pxCoords = this._map.getViewPortPxFromLonLat(new OpenLayers.LonLat(itemCoords.x, itemCoords.y));
  return { x: pxCoords.x, y: pxCoords.y };
}

/**
 * Standard Annotator method: getAnnotations
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getAnnotations = function() {

}

/**
 * Standard Annotator method: getAvailableSelectors
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getAvailableSelectors = function() {

}

/**
 * Standard Annotator method: getItem
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getItem = function() {
  // TODO implement something decent!
  return {src: "map://openlayers/something"};
}

/**
 * Standard Annotator method: setActiveSelector
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.setActiveSelector = function(selector) {

}

/**
 * Standard Annotator method: toItemCoordinates
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.toItemCoordinates = function(xy) {
  var itemCoords = this._map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x, xy.y));
  return { x: itemCoords.lon, y: itemCoords.lat };
}
<commit_msg>Bugfix: updated OpenLayers itemCoordinate conversion after API change<commit_after>goog.provide('annotorious.mediatypes.openlayers.OpenLayersAnnotator');

goog.require('annotorious.mediatypes.Annotator');
goog.require('annotorious.templates.openlayers');
goog.require('annotorious.mediatypes.openlayers.Viewer');

/**
 * The OpenLayersAnnotator is responsible for handling annotation functionality
 * on one OpenLayers map in the page.
 * @param {OpenLayers.Map} map the OpenLayers map
 * @constructor
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator = function(map) {
  annotorious.mediatypes.Annotator.call();

  /** @private **/
  this._map = map;

  /** @private **/
  this.element = map.div;

  // We need to constrain the dimension of the canvas by the size of the map.
  // Therefore the map enclosing DIV needs to have position 'absolute' or
  // 'relative' set!
  var pos = goog.style.getStyle(this.element, 'position');
  if (pos != 'absolute' && pos != 'relative')
    goog.style.setStyle(this.element, 'position', 'relative');

  /** @private **/
  this._eventBroker = new annotorious.events.EventBroker();

  /** @private **/
  this._secondaryHint = goog.soy.renderAsElement(annotorious.templates.openlayers.secondaryHint, {msg: 'Click and Drag'});
  goog.style.setStyle(this._secondaryHint, 'z-index', 9998);
  goog.style.setOpacity(this._secondaryHint, 0);
  goog.dom.appendChild(this.element, this._secondaryHint);

  /** @private **/
  this.popup = new annotorious.Popup(this);

  /** @private **/
  this._viewer = new annotorious.mediatypes.openlayers.Viewer(map, this);

  /** @private **/
  this._editCanvas = goog.soy.renderAsElement(annotorious.templates.image.canvas,
    { width:'0', height:'0' });
  goog.style.showElement(this._editCanvas, false);
  goog.style.setStyle(this._editCanvas, 'position', 'absolute');
  goog.style.setStyle(this._editCanvas, 'top', '0px');
  goog.style.setStyle(this._editCanvas, 'z-index', 9999);

  goog.dom.appendChild(this.element, this._editCanvas);

  var self = this,
      updateCanvasSize = function() {
        var width = parseInt(goog.style.getComputedStyle(self.element, 'width'), 10),
            height = parseInt(goog.style.getComputedStyle(self.element, 'height'), 10);

        goog.style.setSize(self._editCanvas, width, height);
        self._editCanvas.width = width;
        self._editCanvas.height = height;
      };

  updateCanvasSize();

  /** @private **/
  this._selector = new annotorious.plugins.selection.RectDragSelector();
  this._selector.init(this, this._editCanvas);

  /** @private **/
  this._stop_selection_callback = undefined;

  /** @private **/
  this.editor = new annotorious.Editor(this);
  goog.style.setStyle(this.editor.element, 'z-index', 10000);

  if (window.addEventListener)
    window.addEventListener('resize', updateCanvasSize, false);
  else if (window.attachEvent)
    window.attachEvent('onresize', updateCanvasSize);

  goog.events.listen(this.element, goog.events.EventType.MOUSEOVER, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(self.element, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OVER_ANNOTATABLE_ITEM);
  });

  goog.events.listen(this.element, goog.events.EventType.MOUSEOUT, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(self.element, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OUT_OF_ANNOTATABLE_ITEM);
  });

  goog.events.listen(this._editCanvas, goog.events.EventType.MOUSEDOWN, function(event) {
    var offset = goog.style.getClientPosition(self.element);
    self._selector.startSelection(event.clientX - offset.x, event.clientY - offset.y);
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_COMPLETED, function(event) {
    goog.style.setStyle(self._editCanvas, 'pointer-events', 'none');

    var bounds = event.viewportBounds;
    self.editor.setPosition(new annotorious.shape.geom.Point(bounds.left /* + self.element.offsetLeft */,
                                                             bounds.bottom + 4 /* + self.element.offsetTop */));
    self.editor.open();
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_CANCELED, function(event) {
    self.stopSelection();
  });
}
goog.inherits(annotorious.mediatypes.openlayers.OpenLayersAnnotator, annotorious.mediatypes.Annotator);

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.showSelectionWidget = function() {
  // Does not have any effect at the moment
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.hideSelectionWidget = function() {
  // Does not have any effect at the moment
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.activateSelector = function(callback) {
  goog.style.setStyle(this._editCanvas, 'pointer-events', 'auto');

  var self = this;
  goog.style.showElement(this._editCanvas, true);
  goog.style.setOpacity(this._secondaryHint, 0.8);
  window.setTimeout(function() {
    goog.style.setOpacity(self._secondaryHint, 0);
  }, 2000);

  if (callback)
    this._stop_selection_callback = callback;
}

annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.destroy = function() {
  this._viewer.destroy();
  goog.dom.removeNode(this._secondaryHint);
  goog.dom.removeNode(this._editCanvas);
}

/**
 * Standard Annotator method: editAnnotation
 * @suppress {checkTypes}
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.editAnnotation = function(annotation) {
  // Step 1 - remove from viewer
  this._viewer.removeAnnotation(annotation);

  // Step 2 - TODO find a suitable selector for the shape
  var selector = this._selector;

  // Step 3 - open annotation in editor
  var self = this;
  if (selector) {
    goog.style.showElement(this._editCanvas, true);
    this._viewer.highlightAnnotation(undefined);

    // TODO make editable - not just draw (selector implementation required)
    var g2d = this._editCanvas.getContext('2d');
    var shape = annotation.shapes[0];
    var viewportShape = annotorious.shape.transform(shape, function(xy) { return self.fromItemCoordinates(xy); });
    selector.drawShape(g2d, viewportShape);

    var viewportBounds = annotorious.shape.getBoundingRect(viewportShape).geometry;
    this.editor.setPosition(new annotorious.shape.geom.Point(viewportBounds.x + this.element.offsetLeft,
                                                             viewportBounds.y + viewportBounds.height + 4 + this.element.offsetTop));
    this.editor.open(annotation);
  }
}

/**
 * Standard Annotator method: addSelector
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.addSelector = function(selector) {

}

/**
 * Standard Annotator method: fromItemCoordinates
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.fromItemCoordinates = function(itemCoords) {
  var pxCoords = this._map.getViewPortPxFromLonLat(new OpenLayers.LonLat(itemCoords.x, itemCoords.y));
  return { x: pxCoords.x, y: pxCoords.y };
}

/**
 * Standard Annotator method: getAnnotations
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getAnnotations = function() {

}

/**
 * Standard Annotator method: getAvailableSelectors
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getAvailableSelectors = function() {

}

/**
 * Standard Annotator method: getItem
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.getItem = function() {
  // TODO implement something decent!
  return {src: "map://openlayers/something"};
}

/**
 * Standard Annotator method: setActiveSelector
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.setActiveSelector = function(selector) {

}

/**
 * Standard Annotator method: toItemCoordinates
 */
annotorious.mediatypes.openlayers.OpenLayersAnnotator.prototype.toItemCoordinates = function(xy) {
  var itemCoords = this._map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x, xy.y));
  var opposite = (xy.width) ? new OpenLayers.Pixel(xy.x + xy.width - 2, xy.y + xy.height - 2) : false;

  if (opposite) {
	var itemOpposite = this._map.getLonLatFromPixel(opposite);
	return { x: itemCoords.lon, y: itemOpposite.lat,
	          width: itemOpposite.lon - itemCoords.lon,
	          height: itemCoords.lat - itemOpposite.lat };
  } else {
    return { x: itemCoords.lon, y: itemCoords.lat };
  }
}
<|endoftext|>


<commit_before>define(function(require) {
  'use strict';

  var states = require('states');
  var modules = require('modules');
  var plugins = require('plugins');
  var _ = require('lodash');
  var angular = require('angular');

  require('angular-cookies');
  require('angular-resource');
  require('angular-sanitize');
  require('angular-bootstrap');
  require('angular-ui-router');
  require('angular-translate');
  require('angular-xeditable');
  require('scripts/layout/layout');

  var alien4cloud = modules.get('alien4cloud', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.bootstrap',
    'ui.router',
    'pascalprecht.translate',
    'xeditable'
  ]);

  // bootstrap angular js application
  states.state('home', {
    url: '/',
    templateUrl: 'views/main.html',
    controller: ['$scope', 'authService', 'hopscotchService', '$state', function($scope, authService, hopscotchService, $state) {
      $scope.isAdmin = false;
      var isAdmin = authService.hasRole('ADMIN');
      if(_.defined(isAdmin.then)) {
        authService.hasRole('ADMIN').then(function(result) {
          $scope.isAdmin = result;
        });
      } else {
        $scope.isAdmin = isAdmin;
      }
      $scope.adminTour = function() {
        $state.go('admin');
        hopscotchService.startTour('admin.home');
      };
    }]
  });
  states.state('restricted', {
    url: '/restricted',
    templateUrl: 'views/authentication/restricted.html'
  });

  require('scripts/common/services/rest_technical_error_interceptor');

  alien4cloud.startup = function() {
    // add requirements to alien4cloud
    modules.link(alien4cloud);

    alien4cloud.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
      function($stateProvider, $urlRouterProvider, $httpProvider) {
        $httpProvider.interceptors.push('restTechnicalErrorInterceptor');
        $httpProvider.defaults.headers.common['A4C-Agent'] = 'AngularJS_UI';
        $urlRouterProvider.otherwise('/');
        states.config($stateProvider);
      }
    ]);

    // TODO load more modules
    alien4cloud.config(['$translateProvider',
      function($translateProvider) {
        $translateProvider.translations({CODE: 'en-us'});
        // Default language to load
        $translateProvider.preferredLanguage('en-us');

        var options = {
          files: [{
            prefix: 'data/languages/locale-',
            suffix: '.json'
          }]
        };

        // load translations provided by plugins
        if(!_.isEmpty(plugins.registeredTranlations)){
          _.each(plugins.registeredTranlations, function(trans){
            options.files.push({
              prefix: trans.prefix,
              suffix: trans.suffix
            });
          });
        }

        // Static file loader
        $translateProvider.useStaticFilesLoader(options);
      }
    ]);

    alien4cloud.run(['$rootScope', '$state', 'editableOptions', 'editableThemes', 'authService',
      function($rootScope, $state, editableOptions, editableThemes, authService) {
        // check when the state is about to change
        $rootScope.$on('$stateChangeStart', function(event, toState) {
          authService.getStatus().$promise.then(function() {
            // check all the menu array & permissions
            authService.menu.forEach(function(menuItem) {
              var menuType = menuItem.id.split('.')[1];
              var foundMenuIndex = toState.name.indexOf(menuType);
              if (foundMenuIndex === 0 && menuItem.hasRole === false) {
                $state.go('restricted');
              }
            });
          });
        });

        // state routing
        $rootScope.$on('$stateChangeSuccess', function(event, toState) {
          var forward = states.stateForward[toState.name];
          if (_.defined(forward)) {
            $state.go(forward);
          }
        });

        /* angular-xeditable config */
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableThemes.bs3.submitTpl = '<button type="button" class="btn btn-primary"' +
          ' confirm="{{\'CONFIRM_MESSAGE\' | translate}}"' +
          ' confirm-title="{{\'CONFIRM\' | translate }}"' +
          ' confirm-placement="left"' +
          ' cancel-handler="$form.$cancel()"' +
          ' ng-click="$event.stopPropagation();">' +
          '' +
          '</button>';
        editableThemes.bs3.cancelTpl = '<button type="button" class="btn btn-default" ng-click="$form.$cancel()">' +
          '' +
          '</button>';
        editableOptions.theme = 'bs3';
      }
    ]);

    angular.bootstrap(document, ['alien4cloud']);
  };

  return alien4cloud;
});
<commit_msg>ALIEN-1585: Fix plugin loading<commit_after>define(function(require) {
  'use strict';

  var states = require('states');
  var modules = require('modules');
  var plugins = require('plugins');
  var _ = require('lodash');
  var angular = require('angular');

  require('angular-cookies');
  require('angular-resource');
  require('angular-sanitize');
  require('angular-bootstrap');
  require('moment');
  require('angular-bootstrap-datetimepicker');
  require('angular-ui-router');
  require('angular-translate');
  require('angular-xeditable');
  require('scripts/layout/layout');

  var alien4cloud = modules.get('alien4cloud', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.bootstrap',
    'ui.router',
    'pascalprecht.translate',
    'xeditable'
  ]);

  // bootstrap angular js application
  states.state('home', {
    url: '/',
    templateUrl: 'views/main.html',
    controller: ['$scope', 'authService', 'hopscotchService', '$state', function($scope, authService, hopscotchService, $state) {
      $scope.isAdmin = false;
      var isAdmin = authService.hasRole('ADMIN');
      if(_.defined(isAdmin.then)) {
        authService.hasRole('ADMIN').then(function(result) {
          $scope.isAdmin = result;
        });
      } else {
        $scope.isAdmin = isAdmin;
      }
      $scope.adminTour = function() {
        $state.go('admin');
        hopscotchService.startTour('admin.home');
      };
    }]
  });
  states.state('restricted', {
    url: '/restricted',
    templateUrl: 'views/authentication/restricted.html'
  });

  require('scripts/common/services/rest_technical_error_interceptor');

  alien4cloud.startup = function() {
    // add requirements to alien4cloud
    modules.link(alien4cloud);

    alien4cloud.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
      function($stateProvider, $urlRouterProvider, $httpProvider) {
        $httpProvider.interceptors.push('restTechnicalErrorInterceptor');
        $httpProvider.defaults.headers.common['A4C-Agent'] = 'AngularJS_UI';
        $urlRouterProvider.otherwise('/');
        states.config($stateProvider);
      }
    ]);

    // TODO load more modules
    alien4cloud.config(['$translateProvider',
      function($translateProvider) {
        $translateProvider.translations({CODE: 'en-us'});
        // Default language to load
        $translateProvider.preferredLanguage('en-us');

        var options = {
          files: [{
            prefix: 'data/languages/locale-',
            suffix: '.json'
          }]
        };

        // load translations provided by plugins
        if(!_.isEmpty(plugins.registeredTranlations)){
          _.each(plugins.registeredTranlations, function(trans){
            options.files.push({
              prefix: trans.prefix,
              suffix: trans.suffix
            });
          });
        }

        // Static file loader
        $translateProvider.useStaticFilesLoader(options);
      }
    ]);

    alien4cloud.run(['$rootScope', '$state', 'editableOptions', 'editableThemes', 'authService',
      function($rootScope, $state, editableOptions, editableThemes, authService) {
        // check when the state is about to change
        $rootScope.$on('$stateChangeStart', function(event, toState) {
          authService.getStatus().$promise.then(function() {
            // check all the menu array & permissions
            authService.menu.forEach(function(menuItem) {
              var menuType = menuItem.id.split('.')[1];
              var foundMenuIndex = toState.name.indexOf(menuType);
              if (foundMenuIndex === 0 && menuItem.hasRole === false) {
                $state.go('restricted');
              }
            });
          });
        });

        // state routing
        $rootScope.$on('$stateChangeSuccess', function(event, toState) {
          var forward = states.stateForward[toState.name];
          if (_.defined(forward)) {
            $state.go(forward);
          }
        });

        /* angular-xeditable config */
        editableThemes.bs3.inputClass = 'input-sm';
        editableThemes.bs3.buttonsClass = 'btn-sm';
        editableThemes.bs3.submitTpl = '<button type="button" class="btn btn-primary"' +
          ' confirm="{{\'CONFIRM_MESSAGE\' | translate}}"' +
          ' confirm-title="{{\'CONFIRM\' | translate }}"' +
          ' confirm-placement="left"' +
          ' cancel-handler="$form.$cancel()"' +
          ' ng-click="$event.stopPropagation();">' +
          '' +
          '</button>';
        editableThemes.bs3.cancelTpl = '<button type="button" class="btn btn-default" ng-click="$form.$cancel()">' +
          '' +
          '</button>';
        editableOptions.theme = 'bs3';
      }
    ]);

    angular.bootstrap(document, ['alien4cloud']);
  };

  return alien4cloud;
});
<|endoftext|>


<commit_before>$(document).ready(function () {
	oTable = $('#reports_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"bStateSave": true,
		"sAjaxSource": $('#reports_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 7, 8 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 5, 6, 7, 8] },
			{ "fnRender": function (oObj) {
					return '' + oObj.aData[1] + '';
				},
				"aTargets": [ 1 ]
			}
		],
		"aoColumns": [
			{ "sWidth": "1%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "40%" },
			{ "sWidth": "5%" },
			{ "sWidth": "15%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "5%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#reports_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#reports_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function (event) {
				if (event.ctrlKey || event.which == 2) {
					event.stopPropagation();
				} else {
					// extract the href from the anchor string
					var url = $($.parseHTML(aData[1])).attr('href');
					document.location.href = url;
				}
			});
		},
		"fnInitComplete": function(oSettings) {
			$(this.find("select")).each( function(index) {
				if (index == 0 && oSettings.aoPreSearchCols[index+2].sSearch.length>0) {
					// Exception Name selector
					$(this).val(oSettings.aoPreSearchCols[index+2].sSearch);
				} else if (oSettings.aoPreSearchCols[index+3].sSearch.length>0) {
					//Other selectors
					$(this).val(oSettings.aoPreSearchCols[index+3].sSearch);
				}
			});
		}
	});

	$('#notifications_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": $('#notifications_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 6 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 2, 3, 4, 5 ] }
		],
		"aoColumns": [
			{ "sWidth": "5%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "30%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#notifications_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#notifications_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');

			});
		}
	});

	oTable.find("input").on('keyup', function (e) {
		// only search when enter is pressed
		if (e.keyCode == 13) {
			oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
		}
	});

	oTable.find("select").on('change', function (e) {
		oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
	});

	$('#toggle-stacktrace').click(function (e) {
		if ($('#stacktrace').hasClass('shown')) {
			$('#toggle-stacktrace').html('Show stacktrace');

			$('#stacktrace').slideUp(function () {
				$(this).removeClass('shown');
			});
		} else {
			$('#toggle-stacktrace').html('Hide stacktrace');

			$('#stacktrace').slideDown(function () {
				$(this).addClass('shown');
			});
		}
		return false;
	});

	$('#resultsForm_checkall').click(function () {
		if($(this).attr('checked') == 'checked') {
			$('#reports_table td input').attr('checked', 'checked');
		} else {
			$('#reports_table td input').removeAttr('checked');
		}
	});

	$('#notificationsForm_checkall').click(function () {
		if($(this).attr('checked') == 'checked') {
			$('#notifications_table td input').attr('checked', 'checked');
		} else {
			$('#notifications_table td input').removeAttr('checked');
		}
	});

	$('#mark_all_btn').click(function (e) {
        if (
            !confirm(
				'This would mark all your notifications as '
				+ '\'read\'. These notifications would NOT be recoverable. '
				+ 'Are you sure to continue?'
            )
        ) {
            e.preventDefault();
        }
    });

	// display notifications count
	if (notifications_count > 0)
	{
		$('#nav_notifications a').html($('#nav_notifications a').html() + '(' + notifications_count + ')');
	}

	setTimeout(
		function () {
			$(".alert.alert-success").slideUp();
		},
		2000
	);

	SyntaxHighlighter.defaults.toolbar = false;
	SyntaxHighlighter.all();
});

function showStateForm() {
	$('#state-form').slideToggle();
}
<commit_msg>Add lengthMenu to dataTables config to enable more values<commit_after>$(document).ready(function () {
	oTable = $('#reports_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
        "bStateSave": true,
        "lengthMenu": [10, 25, 50, 100, 200, 300, 400, 500, 1000],
		"sAjaxSource": $('#reports_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 7, 8 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 5, 6, 7, 8] },
			{ "fnRender": function (oObj) {
					return '' + oObj.aData[1] + '';
				},
				"aTargets": [ 1 ]
			}
		],
		"aoColumns": [
			{ "sWidth": "1%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "40%" },
			{ "sWidth": "5%" },
			{ "sWidth": "15%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "5%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#reports_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#reports_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function (event) {
				if (event.ctrlKey || event.which == 2) {
					event.stopPropagation();
				} else {
					// extract the href from the anchor string
					var url = $($.parseHTML(aData[1])).attr('href');
					document.location.href = url;
				}
			});
		},
		"fnInitComplete": function(oSettings) {
			$(this.find("select")).each( function(index) {
				if (index == 0 && oSettings.aoPreSearchCols[index+2].sSearch.length>0) {
					// Exception Name selector
					$(this).val(oSettings.aoPreSearchCols[index+2].sSearch);
				} else if (oSettings.aoPreSearchCols[index+3].sSearch.length>0) {
					//Other selectors
					$(this).val(oSettings.aoPreSearchCols[index+3].sSearch);
				}
			});
		}
	});

	$('#notifications_table').dataTable({
		"bSortCellsTop": true,
		"bProcessing": true,
		"bServerSide": true,
		"sAjaxSource": $('#notifications_table').data('ajax-url'),
		"aoColumnDefs": [
			{ "bSearchable": false, "aTargets": [ 1, 6 ] },
			{ "sClass": "center", "aTargets": [ 0, 1, 2, 3, 4, 5 ] }
		],
		"aoColumns": [
			{ "sWidth": "5%" },
			{ "sWidth": "10%" },
			{ "sWidth": "15%" },
			{ "sWidth": "30%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" },
			{ "sWidth": "10%" }
		],
		"fnServerData": function (sSource, aoData, fnCallback) {
			$.getJSON(sSource, aoData, function (json) {
				fnCallback(json);
				// setup necessary CSS for linkable rows.
				$('#notifications_table tbody tr').hover(function() {
					$(this).css('cursor', 'pointer');
				}, function() {
					$(this).css('cursor', 'auto');
				});
				// Stop Redirecting upon checkbox click event
				$('#notifications_table td input').click(function (e) {
					e.stopPropagation();
				});
			});
		},
		"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
			// click on the row anywhere to go to the report.
			$(nRow).click(function () {
				// extract the href from the anchor string
				document.location.href = $($.parseHTML(aData[1])).attr('href');

			});
		}
	});

	oTable.find("input").on('keyup', function (e) {
		// only search when enter is pressed
		if (e.keyCode == 13) {
			oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
		}
	});

	oTable.find("select").on('change', function (e) {
		oTable.fnFilter($(this).val(), oTable.find("tr:last-child th").index($(this).parent()));
	});

	$('#toggle-stacktrace').click(function (e) {
		if ($('#stacktrace').hasClass('shown')) {
			$('#toggle-stacktrace').html('Show stacktrace');

			$('#stacktrace').slideUp(function () {
				$(this).removeClass('shown');
			});
		} else {
			$('#toggle-stacktrace').html('Hide stacktrace');

			$('#stacktrace').slideDown(function () {
				$(this).addClass('shown');
			});
		}
		return false;
	});

	$('#resultsForm_checkall').click(function () {
		if($(this).attr('checked') == 'checked') {
			$('#reports_table td input').attr('checked', 'checked');
		} else {
			$('#reports_table td input').removeAttr('checked');
		}
	});

	$('#notificationsForm_checkall').click(function () {
		if($(this).attr('checked') == 'checked') {
			$('#notifications_table td input').attr('checked', 'checked');
		} else {
			$('#notifications_table td input').removeAttr('checked');
		}
	});

	$('#mark_all_btn').click(function (e) {
        if (
            !confirm(
				'This would mark all your notifications as '
				+ '\'read\'. These notifications would NOT be recoverable. '
				+ 'Are you sure to continue?'
            )
        ) {
            e.preventDefault();
        }
    });

	// display notifications count
	if (notifications_count > 0)
	{
		$('#nav_notifications a').html($('#nav_notifications a').html() + '(' + notifications_count + ')');
	}

	setTimeout(
		function () {
			$(".alert.alert-success").slideUp();
		},
		2000
	);

	SyntaxHighlighter.defaults.toolbar = false;
	SyntaxHighlighter.all();
});

function showStateForm() {
	$('#state-form').slideToggle();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  WebInspector.InspectorControllerStub.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('copyNode');
  this.installInspectorControllerDelegate_('deleteCookie');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('disableTimeline');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('getCookies');
  this.installInspectorControllerDelegate_('getDatabaseTableNames');
  this.installInspectorControllerDelegate_('getDOMStorageEntries');
  this.installInspectorControllerDelegate_('getEventListenersForNode');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('releaseWrapperObjectGroup');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('removeDOMStorageItem');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('setDOMStorageItem');
  this.installInspectorControllerDelegate_('setSetting');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('setting');
  this.installInspectorControllerDelegate_('startTimelineProfiler');
  this.installInspectorControllerDelegate_('stopTimelineProfiler');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
};
goog.inherits(devtools.InspectorControllerImpl,
    WebInspector.InspectorControllerStub);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return DevToolsHost.hiddenPanels();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  WebInspector.InspectorControllerStub.prototype.toggleNodeSearch.call(this);
  this.callInspectorController_.call(this, 'toggleNodeSearch');
  if (!this.searchingForNode()) {
    // This is called from ElementsPanel treeOutline's focusNodeChanged().
    DevToolsHost.activateWindow();
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }

  // Temporary fix for http://crbug/23260.
  var mimeType = resource.mimeType;
  if (!mimeType && resource.url) {
    if (resource.url.search('\.js$') != -1) {
      mimeType = 'application/x-javascript';
    } else if (resource.url.search('\.html$') != -1) {
      mimeType = 'text/html';
    }
  }

  DevToolsHost.addResourceSourceToFrame(identifier, mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.profilerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfileHeaders = function(callId) {
  WebInspector.didGetProfileHeaders(callId, []);
};

/**
 * Emulate WebKit InspectorController behavior. It stores profiles on renderer side,
 * and is able to retrieve them by uid using 'getProfile'.
 */
devtools.InspectorControllerImpl.prototype.addFullProfile = function(profile) {
  WebInspector.__fullProfiles = WebInspector.__fullProfiles || {};
  WebInspector.__fullProfiles[profile.uid] = profile;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfile = function(callId, uid) {
  if (WebInspector.__fullProfiles && (uid in WebInspector.__fullProfiles)) {
    WebInspector.didGetProfile(callId, WebInspector.__fullProfiles[uid]);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.takeHeapSnapshot = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_SNAPSHOT
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_STATS
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_JS_CONSTRUCTORS);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString, async) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId, result, isException);
  };
  RemoteToolsAgent.DispatchOnInjectedScript(
      WebInspector.Callback.wrap(callback),
      async ? methodName + "_async" : methodName,
      argsString);
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments, 1);
  RemoteToolsAgent.DispatchOnInspectorController(
      WebInspector.Callback.wrap(function(){}),
      methodName,
      JSON.stringify(args));
};

InspectorController = new devtools.InspectorControllerImpl();
<commit_msg>DevTools: Add support for removeNode from elements panel implemented upstream. TBR=yurys<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview DevTools' implementation of the InspectorController API.
 */

goog.provide('devtools.InspectorControllerImpl');

devtools.InspectorControllerImpl = function() {
  WebInspector.InspectorControllerStub.call(this);
  this.frame_element_id_ = 1;

  this.installInspectorControllerDelegate_('clearMessages');
  this.installInspectorControllerDelegate_('copyNode');
  this.installInspectorControllerDelegate_('deleteCookie');
  this.installInspectorControllerDelegate_('disableResourceTracking');
  this.installInspectorControllerDelegate_('disableTimeline');
  this.installInspectorControllerDelegate_('enableResourceTracking');
  this.installInspectorControllerDelegate_('enableTimeline');
  this.installInspectorControllerDelegate_('getChildNodes');
  this.installInspectorControllerDelegate_('getCookies');
  this.installInspectorControllerDelegate_('getDatabaseTableNames');
  this.installInspectorControllerDelegate_('getDOMStorageEntries');
  this.installInspectorControllerDelegate_('getEventListenersForNode');
  this.installInspectorControllerDelegate_('highlightDOMNode');
  this.installInspectorControllerDelegate_('hideDOMNodeHighlight');
  this.installInspectorControllerDelegate_('releaseWrapperObjectGroup');
  this.installInspectorControllerDelegate_('removeAttribute');
  this.installInspectorControllerDelegate_('removeDOMStorageItem');
  this.installInspectorControllerDelegate_('removeNode');
  this.installInspectorControllerDelegate_('setAttribute');
  this.installInspectorControllerDelegate_('setDOMStorageItem');
  this.installInspectorControllerDelegate_('setSetting');
  this.installInspectorControllerDelegate_('setTextNodeValue');
  this.installInspectorControllerDelegate_('setting');
  this.installInspectorControllerDelegate_('startTimelineProfiler');
  this.installInspectorControllerDelegate_('stopTimelineProfiler');
  this.installInspectorControllerDelegate_('storeLastActivePanel');
};
goog.inherits(devtools.InspectorControllerImpl,
    WebInspector.InspectorControllerStub);

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.platform = function() {
  return DevToolsHost.getPlatform();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.closeWindow = function() {
  DevToolsHost.closeWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.attach = function() {
  DevToolsHost.dockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.detach = function() {
  DevToolsHost.undockWindow();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.hiddenPanels = function() {
  return DevToolsHost.hiddenPanels();
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.search = function(sourceRow, query) {
  return DevToolsHost.search(sourceRow, query);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.toggleNodeSearch = function() {
  WebInspector.InspectorControllerStub.prototype.toggleNodeSearch.call(this);
  this.callInspectorController_.call(this, 'toggleNodeSearch');
  if (!this.searchingForNode()) {
    // This is called from ElementsPanel treeOutline's focusNodeChanged().
    DevToolsHost.activateWindow();
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.localizedStringsURL =
    function(opt_prefix) {
  // l10n is turned off in test mode because delayed loading of strings
  // causes test failures.
  if (false) {
    var locale = DevToolsHost.getApplicationLocale();
    locale = locale.replace('_', '-');
    return 'l10n/localizedStrings_' + locale + '.js';
  } else {
    return undefined;
  }
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addSourceToFrame =
    function(mimeType, source, element) {
  return DevToolsHost.addSourceToFrame(mimeType, source, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.addResourceSourceToFrame =
    function(identifier, element) {
  var resource = WebInspector.resources[identifier];
  if (!resource) {
    return;
  }

  // Temporary fix for http://crbug/23260.
  var mimeType = resource.mimeType;
  if (!mimeType && resource.url) {
    if (resource.url.search('\.js$') != -1) {
      mimeType = 'application/x-javascript';
    } else if (resource.url.search('\.html$') != -1) {
      mimeType = 'text/html';
    }
  }

  DevToolsHost.addResourceSourceToFrame(identifier, mimeType, element);
};

/**
 * {@inheritDoc}.
 */
devtools.InspectorControllerImpl.prototype.inspectedWindow = function() {
  return null;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.debuggerEnabled = function() {
  return true;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.profilerEnabled = function() {
  return true;
};

devtools.InspectorControllerImpl.prototype.addBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().addBreakpoint(sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.removeBreakpoint = function(
    sourceID, line) {
  devtools.tools.getDebuggerAgent().removeBreakpoint(sourceID, line);
};

devtools.InspectorControllerImpl.prototype.updateBreakpoint = function(
    sourceID, line, condition) {
  devtools.tools.getDebuggerAgent().updateBreakpoint(
      sourceID, line, condition);
};

devtools.InspectorControllerImpl.prototype.pauseInDebugger = function() {
  devtools.tools.getDebuggerAgent().pauseExecution();
};

devtools.InspectorControllerImpl.prototype.resumeDebugger = function() {
  devtools.tools.getDebuggerAgent().resumeExecution();
};

devtools.InspectorControllerImpl.prototype.stepIntoStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepIntoStatement();
};

devtools.InspectorControllerImpl.prototype.stepOutOfFunctionInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOutOfFunction();
};

devtools.InspectorControllerImpl.prototype.stepOverStatementInDebugger =
    function() {
  devtools.tools.getDebuggerAgent().stepOverStatement();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.pauseOnExceptions = function() {
  return devtools.tools.getDebuggerAgent().pauseOnExceptions();
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.setPauseOnExceptions = function(
    value) {
  return devtools.tools.getDebuggerAgent().setPauseOnExceptions(value);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.startProfiling = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.stopProfiling = function() {
  devtools.tools.getDebuggerAgent().stopProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_CPU);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfileHeaders = function(callId) {
  WebInspector.didGetProfileHeaders(callId, []);
};

/**
 * Emulate WebKit InspectorController behavior. It stores profiles on renderer side,
 * and is able to retrieve them by uid using 'getProfile'.
 */
devtools.InspectorControllerImpl.prototype.addFullProfile = function(profile) {
  WebInspector.__fullProfiles = WebInspector.__fullProfiles || {};
  WebInspector.__fullProfiles[profile.uid] = profile;
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.getProfile = function(callId, uid) {
  if (WebInspector.__fullProfiles && (uid in WebInspector.__fullProfiles)) {
    WebInspector.didGetProfile(callId, WebInspector.__fullProfiles[uid]);
  }
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.takeHeapSnapshot = function() {
  devtools.tools.getDebuggerAgent().startProfiling(
      devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_SNAPSHOT
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_HEAP_STATS
      | devtools.DebuggerAgent.ProfilerModules.PROFILER_MODULE_JS_CONSTRUCTORS);
};

/**
 * @override
 */
devtools.InspectorControllerImpl.prototype.dispatchOnInjectedScript = function(
    callId, methodName, argsString, async) {
  var callback = function(result, isException) {
    WebInspector.didDispatchOnInjectedScript(callId, result, isException);
  };
  RemoteToolsAgent.DispatchOnInjectedScript(
      WebInspector.Callback.wrap(callback),
      async ? methodName + "_async" : methodName,
      argsString);
};

/**
 * Installs delegating handler into the inspector controller.
 * @param {string} methodName Method to install delegating handler for.
 */
devtools.InspectorControllerImpl.prototype.installInspectorControllerDelegate_
    = function(methodName) {
  this[methodName] = goog.bind(this.callInspectorController_, this,
      methodName);
};

/**
 * Bound function with the installInjectedScriptDelegate_ actual
 * implementation.
 */
devtools.InspectorControllerImpl.prototype.callInspectorController_ =
    function(methodName, var_arg) {
  var args = Array.prototype.slice.call(arguments, 1);
  RemoteToolsAgent.DispatchOnInspectorController(
      WebInspector.Callback.wrap(function(){}),
      methodName,
      JSON.stringify(args));
};

InspectorController = new devtools.InspectorControllerImpl();
<|endoftext|>


<commit_before>import moment from 'moment';
import DayPicker from 'react-day-picker';
import React from 'react';
import Popout from '../../admin/client/App/shared/Popout';
import { FormInput } from 'elemental';

let lastId = 0;

module.exports = React.createClass({
	displayName: 'DateInput',
	propTypes: {
		format: React.PropTypes.string,
		name: React.PropTypes.string,
		onChange: React.PropTypes.func.isRequired,
		path: React.PropTypes.string,
		value: React.PropTypes.string.isRequired,
	},
	getDefaultProps () {
		return {
			format: 'YYYY-MM-DD',
		};
	},
	getInitialState () {
		const id = ++lastId;
		let month = new Date();
		const { format, value } = this.props;
		if (moment(value, format, true).isValid()) {
			month = moment(value, format).toDate();
		}
		return {
			id: `_DateInput_${id}`,
			month: month,
			pickerIsOpen: false,
			inputValue: value,
		};
	},
	componentDidMount () {
		this.showCurrentMonth();
	},
	componentWillReceiveProps: function (newProps) {
		if (newProps.value === this.props.value) return;
		this.setState({
			month: moment(newProps.value, this.props.format).toDate(),
			inputValue: newProps.value,
		}, this.showCurrentMonth);
	},
	focus () {
		if (!this.refs.input) return;
		this.refs.input.focus();
	},
	handleInputChange (e) {
		const { value } = e.target;
		this.setState({ inputValue: value }, this.showCurrentMonth);
	},
	handleKeyPress (e) {
		if (e.key === 'Enter') {
			e.preventDefault();
			// If the date is strictly equal to the format string, dispatch onChange
			if (moment(this.state.inputValue, this.props.format, true).isValid()) {
				this.props.onChange({ value: this.state.inputValue });
			// If the date is not strictly equal, only change the tab that is displayed
			} else if (moment(this.state.inputValue, this.props.format).isValid()) {
				this.setState({
					month: moment(this.state.inputValue, this.props.format).toDate(),
				}, this.showCurrentMonth);
			}
		}
	},
	handleDaySelect (e, date, modifiers) {
		if (modifiers && modifiers.disabled) return;

		var value = moment(date).format(this.props.format);

		this.props.onChange({ value });
		this.setState({
			pickerIsOpen: false,
			month: date,
			inputValue: value,
		});
	},
	showPicker () {
		this.setState({ pickerIsOpen: true }, this.showCurrentMonth);
	},
	showCurrentMonth () {
		if (!this.refs.picker) return;
		this.refs.picker.showMonth(this.state.month);
	},
	handleFocus (e) {
		if (this.state.pickerIsOpen) return;
		this.showPicker();
	},
	handleBlur (e) {
		let rt = e.relatedTarget || e.nativeEvent.explicitOriginalTarget;
		const popout = this.refs.popout.getPortalDOMNode();
		while (rt) {
			if (rt === popout) return;
			rt = rt.parentNode;
		}
		this.setState({
			pickerIsOpen: false,
		});
	},
	render () {
		const selectedDay = this.props.value;
		// react-day-picker adds a class to the selected day based on this
		const modifiers = {
			selected: (day) => moment(day).format(this.props.format) === selectedDay,
		};

		return (

				<FormInput
					autoComplete="off"
					id={this.state.id}
					name={this.props.name}
					onBlur={this.handleBlur}
					onFocus={this.handleFocus}
					onChange={this.handleInputChange}
					placeholder={this.props.format}
					ref="input"
					onKeyPress={this.handleKeyPress}
					value={this.state.inputValue} />
				<Popout
					ref="popout"
					isOpen={this.state.pickerIsOpen}
					onCancel={() => this.setState({ pickerIsOpen: false })}
					relativeToID={this.state.id}
					width={260}>
					<DayPicker
						ref="picker"
						modifiers={modifiers}
						onDayClick={this.handleDaySelect}
						tabIndex={-1} />
				</Popout>

		);
	},
});
<commit_msg>quick tidy DateInput<commit_after>import moment from 'moment';
import DayPicker from 'react-day-picker';
import React from 'react';
import Popout from '../../admin/client/App/shared/Popout';
import { FormInput } from 'elemental';

let lastId = 0;

module.exports = React.createClass({
	displayName: 'DateInput',
	propTypes: {
		format: React.PropTypes.string,
		name: React.PropTypes.string,
		onChange: React.PropTypes.func.isRequired,
		path: React.PropTypes.string,
		value: React.PropTypes.string.isRequired,
	},
	getDefaultProps () {
		return {
			format: 'YYYY-MM-DD',
		};
	},
	getInitialState () {
		const id = ++lastId;
		let month = new Date();
		const { format, value } = this.props;
		if (moment(value, format, true).isValid()) {
			month = moment(value, format).toDate();
		}
		return {
			id: `_DateInput_${id}`,
			month: month,
			pickerIsOpen: false,
			inputValue: value,
		};
	},
	componentDidMount () {
		this.showCurrentMonth();
	},
	componentWillReceiveProps: function (newProps) {
		if (newProps.value === this.props.value) return;
		this.setState({
			month: moment(newProps.value, this.props.format).toDate(),
			inputValue: newProps.value,
		}, this.showCurrentMonth);
	},
	focus () {
		if (!this.refs.input) return;
		this.refs.input.focus();
	},
	handleInputChange (e) {
		const { value } = e.target;
		this.setState({ inputValue: value }, this.showCurrentMonth);
	},
	handleKeyPress (e) {
		if (e.key === 'Enter') {
			e.preventDefault();
			// If the date is strictly equal to the format string, dispatch onChange
			if (moment(this.state.inputValue, this.props.format, true).isValid()) {
				this.props.onChange({ value: this.state.inputValue });
			// If the date is not strictly equal, only change the tab that is displayed
			} else if (moment(this.state.inputValue, this.props.format).isValid()) {
				this.setState({
					month: moment(this.state.inputValue, this.props.format).toDate(),
				}, this.showCurrentMonth);
			}
		}
	},
	handleDaySelect (e, date, modifiers) {
		if (modifiers && modifiers.disabled) return;

		var value = moment(date).format(this.props.format);

		this.props.onChange({ value });
		this.setState({
			pickerIsOpen: false,
			month: date,
			inputValue: value,
		});
	},
	showPicker () {
		this.setState({ pickerIsOpen: true }, this.showCurrentMonth);
	},
	showCurrentMonth () {
		if (!this.refs.picker) return;
		this.refs.picker.showMonth(this.state.month);
	},
	handleFocus (e) {
		if (this.state.pickerIsOpen) return;
		this.showPicker();
	},
	handleCancel () {
		this.setState({ pickerIsOpen: false });
	},
	handleBlur (e) {
		let rt = e.relatedTarget || e.nativeEvent.explicitOriginalTarget;
		const popout = this.refs.popout.getPortalDOMNode();
		while (rt) {
			if (rt === popout) return;
			rt = rt.parentNode;
		}
		this.setState({
			pickerIsOpen: false,
		});
	},
	render () {
		const selectedDay = this.props.value;
		// react-day-picker adds a class to the selected day based on this
		const modifiers = {
			selected: (day) => moment(day).format(this.props.format) === selectedDay,
		};

		return (

				<FormInput
					autoComplete="off"
					id={this.state.id}
					name={this.props.name}
					onBlur={this.handleBlur}
					onChange={this.handleInputChange}
					onFocus={this.handleFocus}
					onKeyPress={this.handleKeyPress}
					placeholder={this.props.format}
					ref="input"
					value={this.state.inputValue}
				/>
				<Popout
					isOpen={this.state.pickerIsOpen}
					onCancel={this.handleCancel}
					ref="popout"
					relativeToID={this.state.id}
					width={260}
					>
					<DayPicker
						modifiers={modifiers}
						onDayClick={this.handleDaySelect}
						ref="picker"
						tabIndex={-1}
					/>
				</Popout>

		);
	},
});
<|endoftext|>


<commit_before>'use strict';
var chalk = require('chalk');
var _ = require('lodash');
var utils = require('keystone-utils');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var TestGenerator = yeoman.generators.Base.extend({

  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    var done = this.async();

    this.log(yosay('Welcome to the ' + chalk.green('Keystone-React') + ' generator!'));

    var prompts = [{
      type: 'input',
      name: 'projectName',
      message: 'What is the name of your project?',
      default: 'My Site'
    }, {
      type: 'confirm',
      name: 'createDirectory',
      message: 'Would you like to create a new directory for your project?',
      default: true
    }];

    this.prompt(prompts, function(props) {
      this.log('\n');
      _.extend(this, props);
      this.projectKey = utils.slug(this.projectName);
      if (props.createDirectory) {
        this.destinationRoot(this.projectKey);
      }
      done();
    }.bind(this));
  },

  keys: function keys() {
    var cookieSecretChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!@#$%^&*()-=_+[]{}|;:",./<>?`~';
    this.cookieSecret = utils.randomString(64, cookieSecretChars);
  },

  writing: {
    project: function() {
      this.copy('keystone.js', 'keystone.js');
      this.copy('editorconfig', '.editorconfig');
      this.copy('gitignore', '.gitignore');
      this.copy('jshintrc', '.jshintrc');
      this.copy('Procfile', 'Procfile');
      this.template('_package.json', 'package.json');
    },

    clientfiles: function() {
      this.copy('client/scripts/application.js', 'client/scripts/application.js');
    },

    libfiles: function() {
      this.copy('lib/modelToJSON.js', 'lib/modelToJSON.js');
    },

    modelfiles: function() {
      this.copy('models/User.js', 'models/User.js');
    },

    publicfiles: function() {
      this.copy('public/favicon.ico', 'public/favicon.ico');
      this.directory('public/styles', 'public/styles');
    },

    routesfiles: function() {
      this.directory('routes/api', 'routes/api');
      this.copy('routes/index.js', 'routes/index.js');
    },

    templatefiles: function() {
      this.copy('templates/views/index.jade', 'templates/views/index.jade');
    },

    updatefiles: function() {
      this.copy('updates/0.0.1-admins.js', 'updates/0.0.1-admins.js');
    }

  },

  install: function() {
    this.log('\n' + chalk.green('Running an npm install...') +
    '\n'
    );
    this.npmInstall();
  },

  end: function() {
    var cmd = (this.newDirectory ? '"cd ' + utils.slug(this.projectName) + '" then ' : '') + '"node keystone"';
    this.log(
      '\n' + chalk.green.underline('Your new project is ready!') +
      '\n' +
      '\n\nTo start your new website, run ' + cmd + '.' +
      '\n'
    );
  }
});

module.exports = TestGenerator;
<commit_msg>Fixing new directory instructions<commit_after>'use strict';
var chalk = require('chalk');
var _ = require('lodash');
var utils = require('keystone-utils');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var TestGenerator = yeoman.generators.Base.extend({

  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    var done = this.async();

    this.log(yosay('Welcome to the ' + chalk.green('Keystone-React') + ' generator!'));

    var prompts = [{
      type: 'input',
      name: 'projectName',
      message: 'What is the name of your project?',
      default: 'My Site'
    }, {
      type: 'confirm',
      name: 'createDirectory',
      message: 'Would you like to create a new directory for your project?',
      default: true
    }];

    this.prompt(prompts, function(props) {
      this.log('\n');
      _.extend(this, props);
      this.projectKey = utils.slug(this.projectName);
      if (props.createDirectory) {
        this.destinationRoot(this.projectKey);
      }
      done();
    }.bind(this));
  },

  keys: function keys() {
    var cookieSecretChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!@#$%^&*()-=_+[]{}|;:",./<>?`~';
    this.cookieSecret = utils.randomString(64, cookieSecretChars);
  },

  writing: {
    project: function() {
      this.copy('keystone.js', 'keystone.js');
      this.copy('editorconfig', '.editorconfig');
      this.copy('gitignore', '.gitignore');
      this.copy('jshintrc', '.jshintrc');
      this.copy('Procfile', 'Procfile');
      this.template('_package.json', 'package.json');
    },

    clientfiles: function() {
      this.copy('client/scripts/application.js', 'client/scripts/application.js');
    },

    libfiles: function() {
      this.copy('lib/modelToJSON.js', 'lib/modelToJSON.js');
    },

    modelfiles: function() {
      this.copy('models/User.js', 'models/User.js');
    },

    publicfiles: function() {
      this.copy('public/favicon.ico', 'public/favicon.ico');
      this.directory('public/styles', 'public/styles');
    },

    routesfiles: function() {
      this.directory('routes/api', 'routes/api');
      this.copy('routes/index.js', 'routes/index.js');
    },

    templatefiles: function() {
      this.copy('templates/views/index.jade', 'templates/views/index.jade');
    },

    updatefiles: function() {
      this.copy('updates/0.0.1-admins.js', 'updates/0.0.1-admins.js');
    }

  },

  install: function() {
    this.log('\n' + chalk.green('Running an npm install...') +
    '\n'
    );
    this.npmInstall();
  },

  end: function() {
    var cmd = (this.createDirectory ? '"cd ' + utils.slug(this.projectName) + '" then ' : '') + '"node keystone"';
    this.log(
      '\n' + chalk.green.underline('Your new project is ready!') +
      '\n' +
      '\n\nTo start your new website, run ' + cmd + '.' +
      '\n'
    );
  }
});

module.exports = TestGenerator;
<|endoftext|>


<commit_before>/*jslint bitwise:false */
/*globals getUrl picker bind Picker Shape pointsFromEv */
// GOGGLES
function Goggles(ajaxroot) {
  // Here is our goggles object.

  this.canvas = $("<canvas>").css({
    position: "fixed",
    "z-index": "100000",
    top: "0",
    left: "0"
  }).appendTo(document.body)[0];

  this.url = getUrl();
  this.serverUrl = ajaxroot;//+"?callback=?";

  this.ctx = this.canvas.getContext('2d');

  this.shapes = null;
  // the list of shapes to draw.

  // used to find out whether we've stopped or not
  this.active = true;

  this.historyStream = null;

  // Center coordinate
  // Guess at where the text probably is
  this.centerCoord = 0;

  // Color picker
  this.curColor = {r:0,g:0,b:0};
  this.picker = new Picker(bind(this,function(color){
      this.curColor = color;
    }));

  // Events
  this.canvas.oncontextmenu = function(){ return false; };
  this.canvas.onmousedown = bind(this, function(ev) {
      if (ev.button & 2) {
        this.beginErasing(ev);
      } else {
        this.beginDrawing(ev);
      }
      return false;
    });

  // Window resize and scroll handlers
  this.resizeTimer = null;
  window.onresize = bind(this, function() {
    // Resize later
    clearTimeout(this.resizeTimer);
    this.resizeTimer = setTimeout(bind(this, this.resizeCanvas), 100);
  });
  window.onscroll = bind(this, this.redraw);
  this.resizeCanvas();

  // And connect
  this.connect(bind(this, function(){
      this.picker.show();
    }));
}
Goggles.prototype.stop = function() {
  // Destroy a goggles object with optional callback
  this.active = false;
  this.picker.del();
  $(this.canvas).fadeOut('fast', bind(this, function() {
      window.onresize = null;
      window.onscroll = null;
      if (this.historyStream) {
        this.historyStream.stop();
      }
      clearTimeout(this.resizeTimer);
      $(this.canvas).remove();
    }));
};
Goggles.prototype.transform = function(p) {
  // Point transformation functions
  // Establish a new coordinate system. (0, 0) is at the top MIDDLE of
  // the page, +x is right and -x is left.
  // This accomodates pages that have fixed-width or centered layouts.
  // todo: actually I would really like this to be relative to either
  // the left of the content or the middle of the page.
  //
  // Given an absolute point in our new coordinate system, return the
  // point's position on the screen
  return [
    p[0]-window.scrollX + this.centerCoord,
    p[1]-window.scrollY
  ];
};
Goggles.prototype.untransform = function(p) {
  // Given an point wrt the screen, return the point's absolute position
  // wrt our coordinate system
  return [
    p[0]+window.scrollX - this.centerCoord,
    p[1]+window.scrollY
  ];
};
Goggles.prototype.recalculateCenter = function() {
  // this calculates what X-coordinate will be the 'focus' of our web
  // page.
  //
  // essentially, we want our x=0 coordinate to be the left edge of the
  // content. this works reasonably well in practice except for
  // dynamically generated things and line wrapping.

  this.centerCoord = (
    ($("#header").offset() || {left:0}).left ||
    ($(".header").offset() || {left:0}).left ||
    ($(".inner").offset()  || {left:0}).left ||
    ($(".content").offset()|| {left:0}).left ||
    ($("#content").offset()|| {left:0}).left ||

    // hackernews
    ($("body>center>table").offset()||{left: 0}).left ||
    // table-based layouts
    ($("body>table").offset()||{left: 0}).left ||

    // gogole results pages
    ($("#center_col").offset()||{left:0}).left ||

    (this.canvas.width/2)
  );
};
Goggles.prototype.beginErasing = function(ev) {
  var mdhandler = this.canvas.onmousedown;
  if (this.shapes !== null) {
    // Erase
    var curpoint = this.untransform(pointsFromEv(ev));
    this.canvas.onmousedown = null;
    this.canvas.onmouseup = bind(this, function(ev) {
        this.canvas.onmousemove = null;
        this.canvas.onmouseup = null;
        this.canvas.onmousedown = bind(this, mdhandler);
    });
    this.canvas.onmousemove = bind(this, function(ev) {
        var newpoint = this.untransform(pointsFromEv(ev));
        var shapeToRemove = null;
        this.shapes.map(function(shape){
            if (shape.lineIntersects(curpoint, newpoint)) {
              shapeToRemove = shape;
            }
          });
        if (shapeToRemove) {
          this.sendDeleteShape(shapeToRemove);
          this.shapes.splice(this.shapes.indexOf(shapeToRemove), 1);
          this.redraw();
        }
        curpoint = newpoint;
    });
  }
};
Goggles.prototype.beginDrawing = function(ev){
  var mdhandler = this.canvas.onmousedown;
  if (this.shapes !== null) {
    var curshape = new Shape(5, this.curColor.r,this.curColor.g,this.curColor.b,1);
    this.canvas.onmousedown = null;
    this.canvas.onmouseup = bind(this, function(ev) {
        if (curshape.p.length>=2) {
          this.sendShape(curshape);
        }
        this.canvas.onmousemove = null;
        this.canvas.onmouseup = null;
        this.canvas.onmousedown = bind(this, mdhandler);
    });
    this.canvas.onmousemove = bind(this, function(ev) {
        curshape.appendPoint(this.untransform(pointsFromEv(ev)));
        curshape.drawLast(this.ctx);
    });
  }
};
Goggles.prototype.deleteShape = function(shape) {
  // Delete the shape given by 'shape'
  // Note that the shapes are not referentially identical
  for (var i=0,l=this.shapes.length; i<l; i++) {
    if (shape.equalTo(this.shapes[i])) {
      this.shapes.splice(i, 1);
      break;
    }
  }
};
<commit_msg>begin drawing right at mousedown<commit_after>/*jslint bitwise:false */
/*globals getUrl picker bind Picker Shape pointsFromEv */
// GOGGLES
function Goggles(ajaxroot) {
  // Here is our goggles object.

  this.canvas = $("<canvas>").css({
    position: "fixed",
    "z-index": "100000",
    top: "0",
    left: "0"
  }).appendTo(document.body)[0];

  this.url = getUrl();
  this.serverUrl = ajaxroot;//+"?callback=?";

  this.ctx = this.canvas.getContext('2d');

  this.shapes = null;
  // the list of shapes to draw.

  // used to find out whether we've stopped or not
  this.active = true;

  this.historyStream = null;

  // Center coordinate
  // Guess at where the text probably is
  this.centerCoord = 0;

  // Color picker
  this.curColor = {r:0,g:0,b:0};
  this.picker = new Picker(bind(this,function(color){
      this.curColor = color;
    }));

  // Events
  this.canvas.oncontextmenu = function(){ return false; };
  this.canvas.onmousedown = bind(this, function(ev) {
      if (ev.button & 2) {
        this.beginErasing(ev);
      } else {
        this.beginDrawing(ev);
      }
      return false;
    });

  // Window resize and scroll handlers
  this.resizeTimer = null;
  window.onresize = bind(this, function() {
    // Resize later
    clearTimeout(this.resizeTimer);
    this.resizeTimer = setTimeout(bind(this, this.resizeCanvas), 100);
  });
  window.onscroll = bind(this, this.redraw);
  this.resizeCanvas();

  // And connect
  this.connect(bind(this, function(){
      this.picker.show();
    }));
}
Goggles.prototype.stop = function() {
  // Destroy a goggles object with optional callback
  this.active = false;
  this.picker.del();
  $(this.canvas).fadeOut('fast', bind(this, function() {
      window.onresize = null;
      window.onscroll = null;
      if (this.historyStream) {
        this.historyStream.stop();
      }
      clearTimeout(this.resizeTimer);
      $(this.canvas).remove();
    }));
};
Goggles.prototype.transform = function(p) {
  // Point transformation functions
  // Establish a new coordinate system. (0, 0) is at the top MIDDLE of
  // the page, +x is right and -x is left.
  // This accomodates pages that have fixed-width or centered layouts.
  // todo: actually I would really like this to be relative to either
  // the left of the content or the middle of the page.
  //
  // Given an absolute point in our new coordinate system, return the
  // point's position on the screen
  return [
    p[0]-window.scrollX + this.centerCoord,
    p[1]-window.scrollY
  ];
};
Goggles.prototype.untransform = function(p) {
  // Given an point wrt the screen, return the point's absolute position
  // wrt our coordinate system
  return [
    p[0]+window.scrollX - this.centerCoord,
    p[1]+window.scrollY
  ];
};
Goggles.prototype.recalculateCenter = function() {
  // this calculates what X-coordinate will be the 'focus' of our web
  // page.
  //
  // essentially, we want our x=0 coordinate to be the left edge of the
  // content. this works reasonably well in practice except for
  // dynamically generated things and line wrapping.

  this.centerCoord = (
    ($("#header").offset() || {left:0}).left ||
    ($(".header").offset() || {left:0}).left ||
    ($(".inner").offset()  || {left:0}).left ||
    ($(".content").offset()|| {left:0}).left ||
    ($("#content").offset()|| {left:0}).left ||

    // hackernews
    ($("body>center>table").offset()||{left: 0}).left ||
    // table-based layouts
    ($("body>table").offset()||{left: 0}).left ||

    // gogole results pages
    ($("#center_col").offset()||{left:0}).left ||

    (this.canvas.width/2)
  );
};
Goggles.prototype.beginErasing = function(ev) {
  var mdhandler = this.canvas.onmousedown;
  if (this.shapes !== null) {
    // Erase
    var curpoint = this.untransform(pointsFromEv(ev));
    this.canvas.onmousedown = null;
    this.canvas.onmouseup = bind(this, function(ev) {
        this.canvas.onmousemove = null;
        this.canvas.onmouseup = null;
        this.canvas.onmousedown = bind(this, mdhandler);
    });
    this.canvas.onmousemove = bind(this, function(ev) {
        var newpoint = this.untransform(pointsFromEv(ev));
        var shapeToRemove = null;
        this.shapes.map(function(shape){
            if (shape.lineIntersects(curpoint, newpoint)) {
              shapeToRemove = shape;
            }
          });
        if (shapeToRemove) {
          this.sendDeleteShape(shapeToRemove);
          this.shapes.splice(this.shapes.indexOf(shapeToRemove), 1);
          this.redraw();
        }
        curpoint = newpoint;
    });
  }
};
Goggles.prototype.beginDrawing = function(ev){
  if (this.shapes !== null) {
    var mdhandler = this.canvas.onmousedown,
        curshape = new Shape(5, this.curColor.r,this.curColor.g,this.curColor.b,1);
    curshape.appendPoint(this.untransform(pointsFromEv(ev)));
    this.canvas.onmousedown = null;
    this.canvas.onmouseup = bind(this, function(ev) {
        if (curshape.p.length>=2) {
          this.sendShape(curshape);
        }
        this.canvas.onmousemove = null;
        this.canvas.onmouseup = null;
        this.canvas.onmousedown = bind(this, mdhandler);
    });
    this.canvas.onmousemove = bind(this, function(ev) {
        curshape.appendPoint(this.untransform(pointsFromEv(ev)));
        curshape.drawLast(this.ctx);
    });
  }
};
Goggles.prototype.deleteShape = function(shape) {
  // Delete the shape given by 'shape'
  // Note that the shapes are not referentially identical
  for (var i=0,l=this.shapes.length; i<l; i++) {
    if (shape.equalTo(this.shapes[i])) {
      this.shapes.splice(i, 1);
      break;
    }
  }
};
<|endoftext|>


<commit_before>import { deprecate } from '@ember/debug';

/*
  Configures a registry for use with an Ember-Data
  store.

  @method initializeStoreService
  @param {Ember.ApplicationInstance} applicationOrRegistry
*/
export default function initializeStoreService(application) {
  const container = application.lookup ? application : application.container;

  // Eagerly generate the store so defaultStore is populated.
  container.lookup('service:store');

  deprecateOldEmberDataInitializers(application.application.constructor.initializers);
}

const DEPRECATED_INITIALIZER_NAMES = ['data-adapter', 'injectStore', 'transforms', 'store'];

function matchesDeprecatedInititalizer(name) {
  return DEPRECATED_INITIALIZER_NAMES.indexOf(name) !== -1;
}

function deprecateOldEmberDataInitializers(initializers) {
  // collect all of the initializers
  let keys = Object.keys(initializers);

  for (let i = 0; i < keys.length; i++) {
    let name = keys[i];

    // filter out all of the Ember Data initializer. We have some
    // deprecated initializers that depend on other deprecated
    // initializers which may trigger the deprecation warning
    // unintentionally.
    if (!matchesDeprecatedInititalizer(name)) {
      warnForDeprecatedInitializers(initializers[name]);
    }
  }
}

function warnForDeprecatedInitializers(initializer) {
  let deprecatedBeforeInitializer = matchesDeprecatedInititalizer(initializer.before);
  let deprecatedAfterInitializer = matchesDeprecatedInititalizer(initializer.after);
  let deprecatedProp = deprecatedBeforeInitializer ? 'before' : 'after';

  deprecate(
    `The initializer \`${initializer[deprecatedProp]}\` has been deprecated. Please update your \`${initializer.name}\` initializer to use use \`${deprecatedProp}: \'ember-data\'\` instead.`,
    !(deprecatedBeforeInitializer || deprecatedAfterInitializer),
    {
      id: 'ds.deprecated-initializers',
      until: '3.0.0'
    })
}
<commit_msg>[BUGFIX beta] Ensure Engines can boot without error.<commit_after>import { deprecate } from '@ember/debug';

/*
  Configures a registry for use with an Ember-Data
  store.

  @method initializeStoreService
  @param {Ember.ApplicationInstance | Ember.EngineInstance} instance
*/
export default function initializeStoreService(instance) {
  // instance.lookup supports Ember 2.1 and higher
  // instance.container supports Ember 1.11 - 2.0
  const container = instance.lookup ? instance : instance.container;

  // Eagerly generate the store so defaultStore is populated.
  container.lookup('service:store');

  // In Ember 2.4+ instance.base is the `Ember.Application` or `Ember.Engine` instance
  // In Ember 1.11 - 2.3 we fallback to `instance.application`
  let base = instance.base || instance.application;
  deprecateOldEmberDataInitializers(base.constructor.initializers);
}

const DEPRECATED_INITIALIZER_NAMES = ['data-adapter', 'injectStore', 'transforms', 'store'];

function matchesDeprecatedInititalizer(name) {
  return DEPRECATED_INITIALIZER_NAMES.indexOf(name) !== -1;
}

function deprecateOldEmberDataInitializers(initializers) {
  // collect all of the initializers
  let keys = Object.keys(initializers);

  for (let i = 0; i < keys.length; i++) {
    let name = keys[i];

    // filter out all of the Ember Data initializer. We have some
    // deprecated initializers that depend on other deprecated
    // initializers which may trigger the deprecation warning
    // unintentionally.
    if (!matchesDeprecatedInititalizer(name)) {
      warnForDeprecatedInitializers(initializers[name]);
    }
  }
}

function warnForDeprecatedInitializers(initializer) {
  let deprecatedBeforeInitializer = matchesDeprecatedInititalizer(initializer.before);
  let deprecatedAfterInitializer = matchesDeprecatedInititalizer(initializer.after);
  let deprecatedProp = deprecatedBeforeInitializer ? 'before' : 'after';

  deprecate(
    `The initializer \`${initializer[deprecatedProp]}\` has been deprecated. Please update your \`${initializer.name}\` initializer to use use \`${deprecatedProp}: \'ember-data\'\` instead.`,
    !(deprecatedBeforeInitializer || deprecatedAfterInitializer),
    {
      id: 'ds.deprecated-initializers',
      until: '3.0.0'
    })
}
<|endoftext|>