<commit_before> 'use strict';

  var heartbeat = {};
  var options = {};
  var internalConsoleError = 'HeartBeat';

  heartbeat.start = function(opt) {
    options.url = opt.url;
    options.methods = typeof opt.methods !== 'undefined' ? opt.methods : ["log", "info", "warn", "error", "assert", "dir", "clear", "profile", "profileEnd"];
    options.logConsole = typeof opt.logConsole !== 'undefined' ? opt.logConsole : true;
    options.logError = typeof opt.logError !== 'undefined' ? opt.logError : true;
    options.callback = typeof opt.callback !== 'undefined' ? opt.callback : function(){};

    if (options.logConsole){
      this.initConsole();
    }
    if (options.logError){
      this.initErrorlog();
    }

  };

  heartbeat.initErrorlog = function(){

    window.onerror = (function(message, url, line, col, error) {
      if (message !== internalConsoleError){
        var data = {
          message: message,
          url: url,
          line: line,
          col: col
        };

        this.sendMessage(data, 'error');
      }

    }).bind(this);

  };

  heartbeat.sendMessage = function(data, event) {
    options.callback(data, event);
    if (options.url) {
      var id = prepareId();

      var content = JSON.stringify({
        id: id,
        timestamp: (new Date()).getTime(),
        data: data,
        event: event,
        useragent: window.navigator.userAgent
      });

        xdr(options.url, 'POST', content);
    }
  };

  heartbeat.initConsole = function() {
    var regexp = /at (.*)\:([0-9]{1,})\:([0-9]{1,})/;

    options.methods.forEach((function(method) {

      var cLog = console[method];
      console[method] = (function(message) {
        var stack = (new Error()).stack.split(/\n/);
         if (stack[0].indexOf('Error') === 0) {
           stack = stack.slice(1);
         }

        var matches = regexp.exec(stack[1].trim());
        var content = {
          message: message,
          url: matches[1],
          line: matches[2],
          col: matches[3]
        };

        this.sendMessage(content, 'console.' + method);
        cLog.apply(console, arguments);
      }).bind(this);
    }).bind(this));
  };

/**
 * Makes a request
 * @param  {String}   url      URL
 * @param  {String}   method   Method type (GET/POST)
 * @param  {String}   data     Content
 */
  var xdr = function(url, method, data) {
    var promise = function(resolve, reject) {
          var xhr = new XMLHttpRequest();

          if ("withCredentials" in xhr) {
            // XHR for Chrome/Firefox/Opera/Safari.
            xhr.open(method, url, true);
          } else if (typeof XDomainRequest !== "undefined") {
            xhr = new XDomainRequest();
            xhr.open(method, url);
          } else {
            reject('CORS not supported')
          }

          xhr.onload = function() {
            resolve(xhr.responseText);
          };

          xhr.onerror = function() {
            reject('Failed to load');
          };

          //do it, wrapped in timeout to fix ie9
          setTimeout(function() {
            xhr.send();
          }, 0);

        }

        return new Promise(promise);
  };

  var makeHash = function(input) {
    var hash = 0;
    if (input.length === 0) {
      return hash;
    }

    for (var i = 0; i < input.length; i++) {
     hash = hash * 31 + input.charCodeAt(i);
     hash &= hash;
    }

    return hash;
  };

  var prepareId = function() {
    var idString = readProperties(window.navigator) + readProperties(window.screen) + readProperties(window.history);
    return makeHash(idString);
  };

  var readProperties = function(obj, depth, result, info) {
    depth = depth || 1;
    result = result || '';
    info = info || {};
    if (depth < 3) {
      for (var property in obj) {
        if (obj[property] !== undefined) {
          result += property;
          switch (typeof obj[property]) {
            case 'object':
              result += readProperties(obj[property], ++depth, '', info);
              break;
            case 'number':
            case 'string':
            case 'boolean':
              result += obj[property].toString();
              break;
          }
        }
      }
    }
    return result;

  };

  window.heartbeat = heartbeat;
<commit_msg>Add post data<commit_after> 'use strict';

  var heartbeat = {};
  var options = {};
  var internalConsoleError = 'HeartBeat';

  heartbeat.start = function(opt) {
    options.url = opt.url;
    options.methods = typeof opt.methods !== 'undefined' ? opt.methods : ["log", "info", "warn", "error", "assert", "dir", "clear", "profile", "profileEnd"];
    options.logConsole = typeof opt.logConsole !== 'undefined' ? opt.logConsole : true;
    options.logError = typeof opt.logError !== 'undefined' ? opt.logError : true;
    options.callback = typeof opt.callback !== 'undefined' ? opt.callback : function(){};

    if (options.logConsole){
      this.initConsole();
    }
    if (options.logError){
      this.initErrorlog();
    }

  };

  heartbeat.initErrorlog = function(){

    window.onerror = (function(message, url, line, col, error) {
      if (message !== internalConsoleError){
        var data = {
          message: message,
          url: url,
          line: line,
          col: col
        };

        this.sendMessage(data, 'error');
      }

    }).bind(this);

  };

  heartbeat.sendMessage = function(data, event) {
    options.callback(data, event);
    if (options.url) {
      var id = prepareId();

      var content = JSON.stringify({
        id: id,
        timestamp: (new Date()).getTime(),
        data: data,
        event: event,
        useragent: window.navigator.userAgent
      });

        xdr(options.url, 'POST', content);
    }
  };

  heartbeat.initConsole = function() {
    var regexp = /at (.*)\:([0-9]{1,})\:([0-9]{1,})/;

    options.methods.forEach((function(method) {

      var cLog = console[method];
      console[method] = (function(message) {
        var stack = (new Error()).stack.split(/\n/);
         if (stack[0].indexOf('Error') === 0) {
           stack = stack.slice(1);
         }

        var matches = regexp.exec(stack[1].trim());
        var content = {
          message: message,
          url: matches[1],
          line: matches[2],
          col: matches[3]
        };

        this.sendMessage(content, 'console.' + method);
        cLog.apply(console, arguments);
      }).bind(this);
    }).bind(this));
  };

/**
 * Makes a request
 * @param  {String}   url      URL
 * @param  {String}   method   Method type (GET/POST)
 * @param  {String}   data     Content
 */
  var xdr = function(url, method, data) {
    var promise = function(resolve, reject) {
          var xhr = new XMLHttpRequest();

          if ("withCredentials" in xhr) {
            xhr.open(method, url, true);
          } else if (typeof XDomainRequest !== "undefined") {
            xhr = new XDomainRequest();
            xhr.open(method, url);
          } else {
            reject('CORS not supported')
          }

          xhr.onload = function() {
            resolve(xhr.responseText);
          };

          xhr.onerror = function() {
            reject('Failed to load');
          };

          //do it, wrapped in timeout to fix ie9
          setTimeout(function() {
            xhr.send(data);
          }, 0);

        }

        return new Promise(promise);
  };

  var makeHash = function(input) {
    var hash = 0;
    if (input.length === 0) {
      return hash;
    }

    for (var i = 0; i < input.length; i++) {
     hash = hash * 31 + input.charCodeAt(i);
     hash &= hash;
    }

    return hash;
  };

  var prepareId = function() {
    var idString = readProperties(window.navigator) + readProperties(window.screen) + readProperties(window.history);
    return makeHash(idString);
  };

  var readProperties = function(obj, depth, result, info) {
    depth = depth || 1;
    result = result || '';
    info = info || {};
    if (depth < 3) {
      for (var property in obj) {
        if (obj[property] !== undefined) {
          result += property;
          switch (typeof obj[property]) {
            case 'object':
              result += readProperties(obj[property], ++depth, '', info);
              break;
            case 'number':
            case 'string':
            case 'boolean':
              result += obj[property].toString();
              break;
          }
        }
      }
    }
    return result;

  };

  window.heartbeat = heartbeat;
<|endoftext|>


<commit_before>import BaseImageResource from './BaseImageResource';

/**
 * Resource type for HTMLCanvasElement.
 * @class
 * @extends PIXI.resources.BaseImageResource
 * @memberof PIXI.resources
 * @param {HTMLCanvasElement} source - Canvas element to use
 */
export default class CanvasResource extends BaseImageResource
{
    /**
     * Used to auto-detect the type of resource.
     *
     * @static
     * @param {HTMLCanvasElement|OffscreenCanvas} source - The source object
     * @return {boolean} `true` if <canvas>
     */
    static test(source)
    {
        const { OffscreenCanvas } = window;

        // Check for browsers that don't yet support OffscreenCanvas
        if (OffscreenCanvas && source instanceof OffscreenCanvas)
        {
            return true;
        }

        return source instanceof HTMLCanvasElement;
    }
}
<commit_msg>Compatibility with older typescript OffscreenCanvas type (#5813)<commit_after>import BaseImageResource from './BaseImageResource';

/**
 * @interface OffscreenCanvas
 */

/**
 * Resource type for HTMLCanvasElement.
 * @class
 * @extends PIXI.resources.BaseImageResource
 * @memberof PIXI.resources
 * @param {HTMLCanvasElement} source - Canvas element to use
 */
export default class CanvasResource extends BaseImageResource
{
    /**
     * Used to auto-detect the type of resource.
     *
     * @static
     * @param {HTMLCanvasElement|OffscreenCanvas} source - The source object
     * @return {boolean} `true` if <canvas>
     */
    static test(source)
    {
        const { OffscreenCanvas } = window;

        // Check for browsers that don't yet support OffscreenCanvas
        if (OffscreenCanvas && source instanceof OffscreenCanvas)
        {
            return true;
        }

        return source instanceof HTMLCanvasElement;
    }
}
<|endoftext|>


<commit_before>var application, view,
    ActionHelper = Ember.Handlebars.ActionHelper,
    originalRegisterAction = ActionHelper.registerAction;

var appendView = function() {
  Ember.run(function() { view.appendTo('#qunit-fixture'); });
};

module("Ember.Handlebars - action helper", {
  setup: function() {
    application = Ember.Application.create();
  },

  teardown: function() {
    Ember.run(function() {
      view.destroy();
      application.destroy();
    });
  }
});

test("should output a data attribute with a guid", function() {
  view = Ember.View.create({
    template: Ember.Handlebars.compile('')
  });

  appendView();

  ok(view.$('a').attr('data-ember-action').match(/\d+/), "A data-ember-action attribute with a guid was added");
});

test("should by default register a click event", function() {
  var registeredEventName;

  ActionHelper.registerAction = function(_, eventName) {
    registeredEventName = eventName;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('')
  });

  appendView();

  equals(registeredEventName, 'click', "The click event was properly registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should allow alternative events to be handled", function() {
  var registeredEventName;

  ActionHelper.registerAction = function(_, eventName) {
    registeredEventName = eventName;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('')
  });

  appendView();

  equals(registeredEventName, 'mouseUp', "The alternative mouseUp event was properly registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should by default target the parent view", function() {
  var registeredTarget;

  ActionHelper.registerAction = function(_, _, target) {
    registeredTarget = target;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('')
  });

  appendView();

  equals(registeredTarget, view, "The parent view was registered as the target");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should allow a target to be specified", function() {
  var registeredTarget;

  ActionHelper.registerAction = function(_, _, target) {
    registeredTarget = target;
  };

  var anotherTarget = Ember.View.create();

  view = Ember.View.create({
    template: Ember.Handlebars.compile(''),
    anotherTarget: anotherTarget
  });

  appendView();

  equals(registeredTarget, anotherTarget, "The specified target was registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should attach an event handler on the parent view", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "An event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should wrap an existing event handler on the parent view", function() {
  var eventHandlerWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { eventHandlerWasCalled = true; return false; }
  });

  appendView();

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
  ok(!originalEventHandlerWasCalled, "The parent view's event handler wasn't called");

  eventHandlerWasCalled = originalEventHandlerWasCalled = false;

  view.$().trigger('click');

  ok(!eventHandlerWasCalled, "The event handler wasn't called");
  ok(originalEventHandlerWasCalled, "The parent view's event handler was called");
});

test("should be able to use action more than once for the same event within a view", function() {
  var editWasCalled = false,
      deleteWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile(
      'editdelete'
    ),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { editWasCalled = true; return false; },
    "delete": function() { deleteWasCalled = true; return false; }
  });

  appendView();

  view.$('#edit').trigger('click');

  ok(editWasCalled && !deleteWasCalled && !originalEventHandlerWasCalled, "Only the edit action was called");

  editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;

  view.$('#delete').trigger('click');

  ok(!editWasCalled && deleteWasCalled && !originalEventHandlerWasCalled, "Only the delete action was called");

  editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;

  view.$().trigger('click');

  ok(!editWasCalled && !deleteWasCalled && originalEventHandlerWasCalled, "Only the original event handler was called");
});

test("should work properly in an #each block", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    items: Ember.A([1, 2, 3, 4]),
    template: Ember.Handlebars.compile('{{#each items}}click me{{/each}}'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should work properly in a #with block", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    something: {ohai: 'there'},
    template: Ember.Handlebars.compile('{{#with something}}click me{{/with}}'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should unwrap parent view event handlers on rerender", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.rerender();

  ok(view.click === null, "On rerender, the event handler was removed");

  Ember.run.end();

  ok('function' === typeof view.click, "After rerender completes, a new event handler was added");
});

test("should properly capture events on child elements of a container with an action", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('
<button>click me</button>
'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  view.$('button').trigger('click');

  ok(eventHandlerWasCalled, "Event on a child element triggered the action of it's parent")
});

test("should allow bubbling of events from action helper to original parent event", function() {
  var eventHandlerWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { eventHandlerWasCalled = true; return true; }
  });

  appendView();

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled && originalEventHandlerWasCalled, "Both event handlers were called");
});
<commit_msg>Fix action helper test for IE<commit_after>var application, view,
    ActionHelper = Ember.Handlebars.ActionHelper,
    originalRegisterAction = ActionHelper.registerAction;

var appendView = function() {
  Ember.run(function() { view.appendTo('#qunit-fixture'); });
};

module("Ember.Handlebars - action helper", {
  setup: function() {
    application = Ember.Application.create();
  },

  teardown: function() {
    Ember.run(function() {
      view.destroy();
      application.destroy();
    });
  }
});

test("should output a data attribute with a guid", function() {
  view = Ember.View.create({
    template: Ember.Handlebars.compile('edit')
  });

  appendView();

  ok(view.$('a').attr('data-ember-action').match(/\d+/), "A data-ember-action attribute with a guid was added");
});

test("should by default register a click event", function() {
  var registeredEventName;

  ActionHelper.registerAction = function(_, eventName) {
    registeredEventName = eventName;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('edit')
  });

  appendView();

  equals(registeredEventName, 'click', "The click event was properly registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should allow alternative events to be handled", function() {
  var registeredEventName;

  ActionHelper.registerAction = function(_, eventName) {
    registeredEventName = eventName;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('edit')
  });

  appendView();

  equals(registeredEventName, 'mouseUp', "The alternative mouseUp event was properly registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should by default target the parent view", function() {
  var registeredTarget;

  ActionHelper.registerAction = function(_, _, target) {
    registeredTarget = target;
  };

  view = Ember.View.create({
    template: Ember.Handlebars.compile('edit')
  });

  appendView();

  equals(registeredTarget, view, "The parent view was registered as the target");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should allow a target to be specified", function() {
  var registeredTarget;

  ActionHelper.registerAction = function(_, _, target) {
    registeredTarget = target;
  };

  var anotherTarget = Ember.View.create();

  view = Ember.View.create({
    template: Ember.Handlebars.compile('edit'),
    anotherTarget: anotherTarget
  });

  appendView();

  equals(registeredTarget, anotherTarget, "The specified target was registered");

  ActionHelper.registerAction = originalRegisterAction;
});

test("should attach an event handler on the parent view", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "An event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should wrap an existing event handler on the parent view", function() {
  var eventHandlerWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { eventHandlerWasCalled = true; return false; }
  });

  appendView();

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
  ok(!originalEventHandlerWasCalled, "The parent view's event handler wasn't called");

  eventHandlerWasCalled = originalEventHandlerWasCalled = false;

  view.$().trigger('click');

  ok(!eventHandlerWasCalled, "The event handler wasn't called");
  ok(originalEventHandlerWasCalled, "The parent view's event handler was called");
});

test("should be able to use action more than once for the same event within a view", function() {
  var editWasCalled = false,
      deleteWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile(
      'editdelete'
    ),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { editWasCalled = true; return false; },
    "delete": function() { deleteWasCalled = true; return false; }
  });

  appendView();

  view.$('#edit').trigger('click');

  ok(editWasCalled && !deleteWasCalled && !originalEventHandlerWasCalled, "Only the edit action was called");

  editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;

  view.$('#delete').trigger('click');

  ok(!editWasCalled && deleteWasCalled && !originalEventHandlerWasCalled, "Only the delete action was called");

  editWasCalled = deleteWasCalled = originalEventHandlerWasCalled = false;

  view.$().trigger('click');

  ok(!editWasCalled && !deleteWasCalled && originalEventHandlerWasCalled, "Only the original event handler was called");
});

test("should work properly in an #each block", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    items: Ember.A([1, 2, 3, 4]),
    template: Ember.Handlebars.compile('{{#each items}}click me{{/each}}'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should work properly in a #with block", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    something: {ohai: 'there'},
    template: Ember.Handlebars.compile('{{#with something}}click me{{/with}}'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled, "The event handler was called");
});

test("should unwrap parent view event handlers on rerender", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  ok('function' === typeof view.click, "The event handler was added to the parent view");

  view.rerender();

  ok(view.click === null, "On rerender, the event handler was removed");

  Ember.run.end();

  ok('function' === typeof view.click, "After rerender completes, a new event handler was added");
});

test("should properly capture events on child elements of a container with an action", function() {
  var eventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('
<button>click me</button>
'),
    edit: function() { eventHandlerWasCalled = true; }
  });

  appendView();

  view.$('button').trigger('click');

  ok(eventHandlerWasCalled, "Event on a child element triggered the action of it's parent")
});

test("should allow bubbling of events from action helper to original parent event", function() {
  var eventHandlerWasCalled = false,
      originalEventHandlerWasCalled = false;

  view = Ember.View.create({
    template: Ember.Handlebars.compile('click me'),
    click: function() { originalEventHandlerWasCalled = true; },
    edit: function() { eventHandlerWasCalled = true; return true; }
  });

  appendView();

  view.$('a').trigger('click');

  ok(eventHandlerWasCalled && originalEventHandlerWasCalled, "Both event handlers were called");
});
<|endoftext|>


<commit_before>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import browser from "webextension-polyfill";

browser.runtime.sendMessage(process.env.SIDE_ID, {
  uri: "/register",
  verb: "post",
  payload: {
    name: "Selenium IDE plugin",
    version: "1.0.0",
    commands: [
      {
        id: "successfulCommand",
        name: "successful command"
      },
      {
        id: "failCommand",
        name: "failed command"
      }
    ]
  }
}).catch(console.error);

browser.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
  if (message.action === "execute") {
    switch (event.data.command) {
      case "successfulCommand":
        sendResponse(true);
        break;
      case "failCommand":
        sendResponse({ error: "Some failure has occurred" });
        break;
    }
  }
});
<commit_msg>switch the command id<commit_after>// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

import browser from "webextension-polyfill";

browser.runtime.sendMessage(process.env.SIDE_ID, {
  uri: "/register",
  verb: "post",
  payload: {
    name: "Selenium IDE plugin",
    version: "1.0.0",
    commands: [
      {
        id: "successfulCommand",
        name: "successful command"
      },
      {
        id: "failCommand",
        name: "failed command"
      }
    ]
  }
}).catch(console.error);

browser.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
  if (message.action === "execute") {
    switch (message.command.command) {
      case "successfulCommand":
        sendResponse(true);
        break;
      case "failCommand":
        sendResponse({ error: "Some failure has occurred" });
        break;
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    cypto = require('crypto'),
    async = require('async'),
    fs = require('node-fs'),
    AssetPacker = require('../lib/AssetPacker'),
    UglifyJS = require("uglify-js");

function generateSha(content) {
    var shasum = cypto.createHash('sha1');

    shasum.update(content);

    return shasum.digest('hex');
}

var fileHandlers = {
    js: function(contents, pack, outputDir) {
        var fileSha = generateSha(contents.content),
            filename = pack.compiler.name + '-' + fileSha,
            metaFiles = contents.meta.files,
            baseName = pack.compiler.name,
            compressTransform = UglifyJS.Compressor({ warnings: false }),
            sourceMap = UglifyJS.SourceMap({
                file: filename + '.js.map'
            }),
            toplevel;

        function parseAST(raw, filename) {
            toplevel = UglifyJS.parse(raw, {
                filename: filename,
                toplevel: toplevel
            });

            // Embed content in source map
            sourceMap.get().setSourceContent(filename, raw);
        }

        // Generate AST
        parseAST(contents.meta.header, baseName + '/_header.js');
        for(var i = 0, list = Object.keys(metaFiles); i < list.length; i++) {
            parseAST(metaFiles[list[i]], baseName + '/' + list[i]);
        }
        parseAST(contents.meta.footer, baseName + '/_footer.js');

        // Wrap AST in anonymous function
        if(contents.meta.params.length) {
            toplevel = toplevel.wrap_enclose(contents.meta.params);
        }

        // Compress AST.
        toplevel.figure_out_scope();
        toplevel = toplevel.transform(compressTransform);

        // Mangle vars in AST
        toplevel.figure_out_scope();
        toplevel.compute_char_frequency();
        toplevel.mangle_names();

        var compressContent = toplevel.print_to_string({
            source_map: sourceMap
        });

        fs.writeFile(path.resolve(outputDir, filename + '.js'), contents.content);
        fs.writeFile(path.resolve(outputDir, filename + '.min.js'), compressContent + '\n//# sourceMappingURL=' + filename + '.js.map');
        fs.writeFile(path.resolve(outputDir, filename + '.js.map'), sourceMap);

        return filename + '.min.js';
    }
}

module.exports = function(grunt) {
    grunt.registerMultiTask('packs', 'Grunt Plugin for writing packs to disk', function() {
        var outputDir = path.resolve(this.data.dest),
            done = this.async(),
            packs = [],
            manifest = {};

        if(!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, 511 /* 0777 */, true);
        }

        for(var list = this.filesSrc, i = 0; i < list.length; i++) {
            packs.push(new AssetPacker({
                pack: path.resolve(list[i]),
                base: path.dirname(list[i]),
                autoWatch: false
            }));
        }

        async.each(packs, function(pack, done) {
            pack.getAllContent(function(content) {
                var filename, p;

                for(p in content) {
                    filename = fileHandlers[p](content[p], pack, outputDir);

                    if(!manifest[pack.compiler.base]) {
                        manifest[pack.compiler.base] = {};
                    }

                    manifest[pack.compiler.base][p] = filename;
                }

                done();
            });
        }, function() {
            fs.writeFile(path.resolve(outputDir, 'manifest.json'), JSON.stringify(manifest), done);
        });
    });
};<commit_msg>Adding options to configure minifying.<commit_after>'use strict';

var path = require('path'),
    cypto = require('crypto'),
    async = require('async'),
    fs = require('node-fs'),
    AssetPacker = require('../lib/AssetPacker'),
    UglifyJS = require("uglify-js");

function generateSha(content) {
    var shasum = cypto.createHash('sha1');

    shasum.update(content);

    return shasum.digest('hex');
}

var fileHandlers = {
    js: function(contents, pack, outputDir) {
        var fileSha = generateSha(contents.content),
            filename = pack.compiler.name + '-' + fileSha,
            metaFiles = contents.meta.files,
            baseName = pack.compiler.name,
            buildOpts = pack.pack.build || {},
            compressTransform = UglifyJS.Compressor({ warnings: false }),
            sourceMap = UglifyJS.SourceMap({
                file: filename + '.js.map'
            }),
            toplevel;

        function parseAST(raw, filename) {
            toplevel = UglifyJS.parse(raw, {
                filename: filename,
                toplevel: toplevel
            });

            // Embed content in source map
            sourceMap.get().setSourceContent(filename, raw);
        }

        // Generate AST
        parseAST(contents.meta.header, baseName + '/_header.js');
        for(var i = 0, list = Object.keys(metaFiles); i < list.length; i++) {
            parseAST(metaFiles[list[i]], baseName + '/' + list[i]);
        }
        parseAST(contents.meta.footer, baseName + '/_footer.js');

        // Wrap AST in anonymous function
        if(contents.meta.params.length) {
            toplevel = toplevel.wrap_enclose(contents.meta.params);
        }

        // Compress AST.
        if(!buildOpts.skipCompression) {
            toplevel.figure_out_scope();
            toplevel = toplevel.transform(compressTransform);
        }

        // Mangle vars in AST
        if(!buildOpts.skipMangle) {
            toplevel.figure_out_scope();
            toplevel.compute_char_frequency();
            toplevel.mangle_names();
        }

        var compressContent = toplevel.print_to_string({
            source_map: sourceMap
        });

        fs.writeFile(path.resolve(outputDir, filename + '.js'), contents.content);
        fs.writeFile(path.resolve(outputDir, filename + '.min.js'), compressContent + '\n//# sourceMappingURL=' + filename + '.js.map');
        fs.writeFile(path.resolve(outputDir, filename + '.js.map'), sourceMap);

        return filename + '.min.js';
    }
}

module.exports = function(grunt) {
    grunt.registerMultiTask('packs', 'Grunt Plugin for writing packs to disk', function() {
        var outputDir = path.resolve(this.data.dest),
            done = this.async(),
            packs = [],
            manifest = {};

        if(!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, 511 /* 0777 */, true);
        }

        for(var list = this.filesSrc, i = 0; i < list.length; i++) {
            packs.push(new AssetPacker({
                pack: path.resolve(list[i]),
                base: path.dirname(list[i]),
                autoWatch: false
            }));
        }

        async.each(packs, function(pack, done) {
            pack.getAllContent(function(content) {
                var filename, p;

                for(p in content) {
                    filename = fileHandlers[p](content[p], pack, outputDir);

                    if(!manifest[pack.compiler.base]) {
                        manifest[pack.compiler.base] = {};
                    }

                    manifest[pack.compiler.base][p] = filename;
                }

                done();
            });
        }, function() {
            fs.writeFile(path.resolve(outputDir, 'manifest.json'), JSON.stringify(manifest), done);
        });
    });
};<|endoftext|>


<commit_before>/*
 * grunt-bitbundler
 * https://github.com/MiguelCastillo/bit-bundler
 *
 * Copyright (c) 2016 Miguel Castillo
 * Licensed under the MIT license.
 */

var Bitbundler = require("bit-bundler");

module.exports = function(grunt) {
  function logError(err) {
    var errStr = err && err.stack || err;
    grunt.log.error(errStr);
    return err;
  }

  grunt.task.registerMultiTask("bitbundler", "bit bundler grunt plugin", function() {
    var settings = this.data || {};
    var done = this.async();

    if (settings.Bitbundler) {
      Bitbundler = settings.Bitbundler;
    }

    try {
      this.files.forEach(function(file) {
        Bitbundler.bundle({
          src: file.src,
          dest: file.dest
        }, settings).then(function() {
          done();
        }, function(err) {
          done(err);
        });
      });
    }
    catch(err) {
      logError(err);
    }
  });
};
<commit_msg>added ability to read the watch flag to determine if we should quit grunt when the build is done<commit_after>/*
 * grunt-bitbundler
 * https://github.com/MiguelCastillo/bit-bundler
 *
 * Copyright (c) 2016 Miguel Castillo
 * Licensed under the MIT license.
 */

var Bitbundler = require("bit-bundler");

module.exports = function(grunt) {
  function logError(err) {
    var errStr = err && err.stack || err;
    grunt.log.error(errStr);
    return err;
  }

  grunt.task.registerMultiTask("bitbundler", "bit bundler grunt plugin", function() {
    var settings = this.data || {};
    var done = this.async();

    if (settings.Bitbundler) {
      Bitbundler = settings.Bitbundler;
    }

    try {
      this.files.forEach(function(file) {
        var bundler = Bitbundler.bundle({
          src: file.src,
          dest: file.dest
        }, settings);

        if (!settings.watch) {
          bundler.then(function() {
            done();
          }, function(err) {
            done(err);
          });
        }
      });
    }
    catch(err) {
      logError(err);
    }
  });
};
<|endoftext|>


<commit_before>var task = function(gulp, config) {
  'use strict';
  gulp.task('browserSync', function() {

    var path = require('path');
    var fs = require('fs');
    var browserSync = require('browser-sync').create();
    var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');

    browserSync.init({
      server: {
        // Serve both project root and dist to enable sourcemaps
        baseDir: [process.cwd(), config.dist.root],
        middleware: function (req, res, next) {
          var location;
          // Enable CORS
          res.setHeader('Access-Control-Allow-Origin', '*');
          // Rewrite html5 urls
          var matches = html5Regex.exec(req.url);
          //console.log('req', req.url);
          var file = path.join(config.dist.root, req.url);
          //console.log('file', file);
          if (req.method === 'GET' && matches && !fs.existsSync(file)) {
            //console.log('no file -> hashbang!');
            location = '/'+config.name+'/#!'+matches[1];
            res.writeHead(302, {'Location': location});
            res.end();
          } else {
            //console.log('serve file');
            next();
          }
        },
        directory: config.dirListings || false
      },
      // Watch for updates in dist
      files: [config.dist.root+'/**/*'],
      // Disable input mirroring between connected browsers
      ghostMode: false,
      open: false
    });

  });
};

module.exports = task;
<commit_msg>Fix bug in serving partial css files<commit_after>var task = function(gulp, config) {
  'use strict';
  gulp.task('browserSync', function() {

    var path = require('path');
    var fs = require('fs');
    var browserSync = require('browser-sync').create();
    var html5Regex = new RegExp('\/'+config.name+'\/(.*)$');

    browserSync.init({
      server: {
        // Serve both project root and dist to enable sourcemaps
        baseDir: [process.cwd(), config.dist.root],
        middleware: function (req, res, next) {
          var location;
          // Enable CORS
          res.setHeader('Access-Control-Allow-Origin', '*');
          // Rewrite html5 urls
          var matches = html5Regex.exec(req.url);
          //console.log('req', req.url);
          var file = path.join(config.dist.root, req.url.split('?')[0]);
          //console.log('file', file);
          if (req.method === 'GET' && matches && !fs.existsSync(file)) {
            console.log('no file -> hashbang!', file);
            location = '/'+config.name+'/#!'+matches[1];
            res.writeHead(302, {'Location': location});
            res.end();
          } else {
            console.log('serve file', file);
            next();
          }
        },
        directory: config.dirListings || false
      },
      // Watch for updates in dist
      files: [config.dist.root+'/**/*'],
      // Disable input mirroring between connected browsers
      ghostMode: false,
      open: false
    });

  });
};

module.exports = task;
<|endoftext|>


<commit_before>"use strict";

module.exports = function (config, helpers) {
  var grunt = this;

  grunt.registerTask("compilation_step", "Runs iterative all compilation steps from config", function () {
    var moduleData = grunt.config.get("modules.active");
    if (moduleData == null) {
      return grunt.fail.fatal("set_active_module must be run first");
    }
    var steps = grunt.config.get("compilation.stack");
    var step = steps.shift();
    grunt.config.set("compilation.stack", steps);
    var compiler = helpers.loadCompiler(step.compiler);
    var result = compiler.process.call(grunt, moduleData, step, helpers);
    if (result instanceof Array || typeof result === "string") {
      grunt.task.run(result);
    }
    if (steps.length) {
      grunt.task.run("compilation_step");
    }
  });

  grunt.registerTask("compilation", "Runs compilation of module as defined within config", function () {
    var moduleData = grunt.config.get("modules.active");
    if (moduleData == null) {
      return grunt.fail.fatal("set_active_module must be run first");
    }
    var dev = grunt.config.get("development");
    var compilationId = config.types[moduleData.meta.type.id].compilation;

    grunt.task.run("increment_module_build");
    grunt.config.set("compilation.stack", helpers.getCompilation(compilationId, dev));
    if (grunt.config.get("compilation.stack").length) {
      grunt.task.run("compilation_step");
    }
  });

  return {};
};
<commit_msg>Fix cwd while compilation<commit_after>"use strict";

module.exports = function (config, helpers) {
  var grunt = this;

  grunt.registerTask("compilation_step", "Runs iterative all compilation steps from config", function () {
    var moduleData = grunt.config.get("modules.active");
    if (moduleData == null) {
      return grunt.fail.fatal("set_active_module must be run first");
    }
    var steps = grunt.config.get("compilation.stack");
    var step = steps.shift();
    grunt.config.set("compilation.stack", steps);
    var compiler = helpers.loadCompiler(step.compiler);
    grunt.file.setBase(moduleData.paths.tmp);
    var result = compiler.process.call(grunt, moduleData, step, helpers);
    if (result instanceof Array || typeof result === "string") {
      grunt.task.run(result);
    }
    grunt.task.run("compilation_step_done");
    if (steps.length) {
      grunt.task.run("compilation_step");
    }
  });

  grunt.registerTask("compilation", "Runs compilation of module as defined within config", function () {
    var moduleData = grunt.config.get("modules.active");
    if (moduleData == null) {
      return grunt.fail.fatal("set_active_module must be run first");
    }
    var dev = grunt.config.get("development");
    var compilationId = config.types[moduleData.meta.type.id].compilation;

    grunt.task.run("increment_module_build");
    grunt.config.set("compilation.stack", helpers.getCompilation(compilationId, dev));
    if (grunt.config.get("compilation.stack").length) {
      grunt.task.run("compilation_step");
    }
  });

  grunt.registerTask("compilation_step_done", "Resets the cwd", function () { grunt.file.setBase(config.cwd); });

  return {};
};
<|endoftext|>


<commit_before>/*
 * grunt-imagemagick
 * https://github.com/icagstrout/grunt-imagemagick
 *
 * Copyright (c) 2012 Arne Strout
 * Licensed under the MIT license.
 */

var grunt=require('grunt');
var fs=require('fs');
var path=require('path');
/** Quick Proxy methods **/
var proxy=function(f,c){
  var fn=f;
  var cn=c;
  return function(){
    fn.apply(cn,Array.prototype.slice.call(arguments));
  };
};
// True if the file path exists.
var fileExists = function() {
  var filepath = path.join.apply(path, arguments);
  return fs.existsSync(filepath);
};
/****
* HisrcCommand - Command which asynchronously generates all sizes for a large image for use with HiSRC.js
* This command assumes that suffix is an array of suffixes in the order [{FULL}, {1/2}, {1/4}].
* for example, a typical use is suffix:['-2x','-1x','-low'] with files: '{PATH}*-2x.jpg'. The actual file
* provided should always be the retina image (eg: 2X) but you can use whatever suffixes you wish.
**/
var HisrcCommand={
  path:'',
  name:'',
  ext:'',
  file:'',
  callback:undefined,
  context:undefined,
  im:undefined,
  init:function (fpath,fsuffix,fcallback,context){
    try{
      this.file=fpath;
      this.suffix=fsuffix;
      var lslash=fpath.lastIndexOf('/');
      var ldot=fpath.lastIndexOf('.');
      this.path=fpath.substr(0,lslash+1);
      this.ext=fpath.substr(ldot+1);
      this.name=fpath.substr(lslash+1,ldot-lslash-1);
      this.im=require('node-imagemagick');
      this.callback=fcallback;

      this.im.identify(['-format','%wx%h',this.file],proxy(this.resize,this));
    }catch(e){
      grunt.log.write('error '+e+"\n");
    }
  },
  resize: function(err,output){
    try{
    grunt.log.write("Resizing image: "+output+"\n");
    this.baseWidth=Number(output.split('x')[0]);
    this.baseHeight=Number(output.split('x')[1]);
    grunt.log.write("To size: "+Math.round(this.baseWidth/2)+"x"+Math.round(this.baseHeight/2)+"\n");
    this.im.resize({
      width:Math.round(this.baseWidth/2),
      height:Math.round(this.baseHeight/2),
      srcPath: this.file,
      dstPath: this.path + this.name.split(this.suffix[0]).join(this.suffix[1]) +'.'+this.ext
    },proxy(this.resize2,this));
    } catch (e){
      grunt.log.write('error '+e+"\n");
    }
  },
  resize2: function(err){
    try{
    grunt.log.write("Resizing lowrez\n");
    grunt.log.write("To size: "+Math.round(this.baseWidth/4)+"x"+Math.round(this.baseHeight/4)+"\n");
    this.im.resize({
      width:Math.round(this.baseWidth/4),
      height:Math.round(this.baseHeight/4),
      srcPath: this.file,
      dstPath: this.path + this.name.split(this.suffix[0]).join(this.suffix[2]) +'.'+this.ext
    },proxy(this.complete,this));
    } catch (e){
      grunt.log.write('error '+e+"\n");
    }
  },
  complete:function(){
    grunt.log.write(" - created responsive for "+this.path + this.name +"."+this.ext+"\n");
    this.callback.apply(this.context,[this,true]);
  },
};

/**
* ResizeCommand
* resizes the specified images or groups of images using the specified parameters
* currently uses the same properties as node-imagemagick
**/
var ResizeCommand={
  props:undefined,
  callback:undefined,
  context:undefined,
  im:undefined,
  init:function(pfrom,pto,pprops,pcallback,pcontext){

    this.props=Object.create(pprops);
    this.props.srcPath=pfrom;
    this.props.dstPath=pto;
    this.callback=pcallback;
    this.context=pcontext;
    this.im=require('node-imagemagick');

    grunt.log.write('resizing:'+this.props.srcPath+"...\n");
    this.im.resize(this.props,proxy(this.complete,this));
  },
  complete:function(err){
    grunt.log.write('created '+this.props.dstPath+'--'+err+"\n");
    if (err !== undefined && err !== null) {
      if (this.context.data.fatals === true) {
        grunt.warn(err);
	  } else {
	    grunt.log.write('error: '+err+"\n");
	  }
	}
    this.callback.apply(this.context,[this,true]);
  }
};

/**
* ConvertCommand
* raw interface to the convert command in imagemagick
* accepts an array of command line arguments
**/
var ConvertCommand={
  args: undefined,
  callback: undefined,
  context: undefined,
  im: undefined,
  init:function(pArgs,pCallback,pContext){
    this.args=pArgs;
    this.callback=pCallback;
    this.context=pContext;
    this.im=require('node-imagemagick');

    grunt.log.write('convert: '+this.args+"...\n");
    this.im.convert(this.args,proxy(this.complete,this));
  },
  complete:function(err){
    grunt.log.write('convert complete...'+"\n"+err+"\n");
    if (err !== undefined && err !== null) {
      if (this.context.data.fatals === true) {
        grunt.warn(err);
	  } else {
	    grunt.log.write('error: '+err+"\n");
	  }
	}
    this.callback.apply(this.context,[this,true]);
  }
};

module.exports = function(grunt) {
  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================
  /*
   * imagemagick-hisrc TASK
   * takes a file identification expression (usually with wildcards) to create a list of files
   * iterates over the files to generate 1/2 and 1/4 size alternatives for mobile.
   * uses the filename pattern specified in the "suffix" property to save the files.
   */
  grunt.registerMultiTask('imagemagick-hisrc', 'Performs a number of configured tasks', function() {
    var done = this.async();
    grunt.log.write("Beginning ImageMagick processing for HiSRC\n");

    var fls=grunt.file.expand(this.data.files);
    var i=0;
    var count=fls.length;
    var suffix=this.data.suffix;
    var cmds=[];
    var cmd;

    grunt.log.write("CWD:"+process.cwd()+"\n-files:"+fls.length+"\n-pattern:"+this.data.files+"\n");

    function onCmdComplete(cmd,success){
      grunt.log.write("completed : "+cmd.file+"\n");
      cmds.splice(cmds.indexOf(cmd),1);
      if(cmds.length<1){
        done();
      }
    }

    for(i=0;i<fls.length;i++){
      cmd = Object.create(HisrcCommand);
      cmds.push(cmd);
      cmd.init(fls[i],suffix,onCmdComplete,this);
    }
    if(fls.length<1){
      grunt.log.write("Nothing to do\n");
      done();
    }else{
      grunt.log.write("all queued\n");
    }
  });

  /*
  * imagemagick-resize TASK
  * takes a from folder, a to folder, a file pattern, and properties, and resizes the matching
  * files, outputting the resized images to the "to" folder.
  * {from:"folder",to:"folder",files:"*.ext",props{width:100}} etc.
  */
  grunt.registerMultiTask('imagemagick-resize','Resizes images using imagemagick',function(){
    var done= this.async();
    grunt.log.write("Beginning ImageMagick resizing process\n");
    var cmds=[],cmd;
    var i=0;
    var fls=grunt.file.expand(this.data.from+this.data.files);

    function onCmdComplete(cmd,success){
      grunt.log.write("completed:"+cmd.props.dstPath+"\n");
      cmds.splice(cmds.indexOf(cmd),1);
      if(cmds.length<1){
        done();
      }
    }

    if(!fileExists(this.data.to)){
      grunt.file.mkdir(this.data.to);
    }

    for(i=0;i<fls.length;i++){
      cmd=Object.create(ResizeCommand);
      cmds.push(cmd);
      cmd.init(
        fls[i],
        this.data.to+fls[i].substr(this.data.from.length), // replace folder
        this.data.props,
        onCmdComplete,
        this
      );
    }

    if(fls.length<1){
      grunt.log.write("Nothing to do\n");
      done();
    }else{
      grunt.log.write("all queued\n");
    }
  });

  grunt.registerMultiTask('imagemagick-convert','Converts images using imagemagick',function(){
    var done=this.async();
    grunt.log.write("Beginning convert operation\n");
    var cmd=Object.create(ConvertCommand);
    function onCmdComplete(cmd,success){
      grunt.log.write("completed:"+cmd.args+"\n");
      done();
    }
    cmd.init(this.data.args,onCmdComplete,this);
  });
};
<commit_msg>chore(task): remove unneccessary error output<commit_after>/*
 * grunt-imagemagick
 * https://github.com/icagstrout/grunt-imagemagick
 *
 * Copyright (c) 2012 Arne Strout
 * Licensed under the MIT license.
 */

var grunt=require('grunt');
var fs=require('fs');
var path=require('path');
/** Quick Proxy methods **/
var proxy=function(f,c){
  var fn=f;
  var cn=c;
  return function(){
    fn.apply(cn,Array.prototype.slice.call(arguments));
  };
};
// True if the file path exists.
var fileExists = function() {
  var filepath = path.join.apply(path, arguments);
  return fs.existsSync(filepath);
};
/****
* HisrcCommand - Command which asynchronously generates all sizes for a large image for use with HiSRC.js
* This command assumes that suffix is an array of suffixes in the order [{FULL}, {1/2}, {1/4}].
* for example, a typical use is suffix:['-2x','-1x','-low'] with files: '{PATH}*-2x.jpg'. The actual file
* provided should always be the retina image (eg: 2X) but you can use whatever suffixes you wish.
**/
var HisrcCommand={
  path:'',
  name:'',
  ext:'',
  file:'',
  callback:undefined,
  context:undefined,
  im:undefined,
  init:function (fpath,fsuffix,fcallback,context){
    try{
      this.file=fpath;
      this.suffix=fsuffix;
      var lslash=fpath.lastIndexOf('/');
      var ldot=fpath.lastIndexOf('.');
      this.path=fpath.substr(0,lslash+1);
      this.ext=fpath.substr(ldot+1);
      this.name=fpath.substr(lslash+1,ldot-lslash-1);
      this.im=require('node-imagemagick');
      this.callback=fcallback;

      this.im.identify(['-format','%wx%h',this.file],proxy(this.resize,this));
    }catch(e){
      grunt.log.write('error '+e+"\n");
    }
  },
  resize: function(err,output){
    try{
    grunt.log.write("Resizing image: "+output+"\n");
    this.baseWidth=Number(output.split('x')[0]);
    this.baseHeight=Number(output.split('x')[1]);
    grunt.log.write("To size: "+Math.round(this.baseWidth/2)+"x"+Math.round(this.baseHeight/2)+"\n");
    this.im.resize({
      width:Math.round(this.baseWidth/2),
      height:Math.round(this.baseHeight/2),
      srcPath: this.file,
      dstPath: this.path + this.name.split(this.suffix[0]).join(this.suffix[1]) +'.'+this.ext
    },proxy(this.resize2,this));
    } catch (e){
      grunt.log.write('error '+e+"\n");
    }
  },
  resize2: function(err){
    try{
    grunt.log.write("Resizing lowrez\n");
    grunt.log.write("To size: "+Math.round(this.baseWidth/4)+"x"+Math.round(this.baseHeight/4)+"\n");
    this.im.resize({
      width:Math.round(this.baseWidth/4),
      height:Math.round(this.baseHeight/4),
      srcPath: this.file,
      dstPath: this.path + this.name.split(this.suffix[0]).join(this.suffix[2]) +'.'+this.ext
    },proxy(this.complete,this));
    } catch (e){
      grunt.log.write('error '+e+"\n");
    }
  },
  complete:function(){
    grunt.log.write(" - created responsive for "+this.path + this.name +"."+this.ext+"\n");
    this.callback.apply(this.context,[this,true]);
  },
};

/**
* ResizeCommand
* resizes the specified images or groups of images using the specified parameters
* currently uses the same properties as node-imagemagick
**/
var ResizeCommand={
  props:undefined,
  callback:undefined,
  context:undefined,
  im:undefined,
  init:function(pfrom,pto,pprops,pcallback,pcontext){

    this.props=Object.create(pprops);
    this.props.srcPath=pfrom;
    this.props.dstPath=pto;
    this.callback=pcallback;
    this.context=pcontext;
    this.im=require('node-imagemagick');

    grunt.log.write('resizing:'+this.props.srcPath+"...\n");
    this.im.resize(this.props,proxy(this.complete,this));
  },
  complete:function(err){
    grunt.log.write('created '+this.props.dstPath+"\n");
    if (err !== undefined && err !== null) {
      if (this.context.data.fatals === true) {
        grunt.warn(err);
	  } else {
	    grunt.log.write('error: '+err+"\n");
	  }
	}
    this.callback.apply(this.context,[this,true]);
  }
};

/**
* ConvertCommand
* raw interface to the convert command in imagemagick
* accepts an array of command line arguments
**/
var ConvertCommand={
  args: undefined,
  callback: undefined,
  context: undefined,
  im: undefined,
  init:function(pArgs,pCallback,pContext){
    this.args=pArgs;
    this.callback=pCallback;
    this.context=pContext;
    this.im=require('node-imagemagick');

    grunt.log.write('convert: '+this.args+"...\n");
    this.im.convert(this.args,proxy(this.complete,this));
  },
  complete:function(err){
    grunt.log.write('convert complete...'+"\n");
    if (err !== undefined && err !== null) {
      if (this.context.data.fatals === true) {
        grunt.warn(err);
	  } else {
	    grunt.log.write('error: '+err+"\n");
	  }
	}
    this.callback.apply(this.context,[this,true]);
  }
};

module.exports = function(grunt) {
  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================
  /*
   * imagemagick-hisrc TASK
   * takes a file identification expression (usually with wildcards) to create a list of files
   * iterates over the files to generate 1/2 and 1/4 size alternatives for mobile.
   * uses the filename pattern specified in the "suffix" property to save the files.
   */
  grunt.registerMultiTask('imagemagick-hisrc', 'Performs a number of configured tasks', function() {
    var done = this.async();
    grunt.log.write("Beginning ImageMagick processing for HiSRC\n");

    var fls=grunt.file.expand(this.data.files);
    var i=0;
    var count=fls.length;
    var suffix=this.data.suffix;
    var cmds=[];
    var cmd;

    grunt.log.write("CWD:"+process.cwd()+"\n-files:"+fls.length+"\n-pattern:"+this.data.files+"\n");

    function onCmdComplete(cmd,success){
      grunt.log.write("completed : "+cmd.file+"\n");
      cmds.splice(cmds.indexOf(cmd),1);
      if(cmds.length<1){
        done();
      }
    }

    for(i=0;i<fls.length;i++){
      cmd = Object.create(HisrcCommand);
      cmds.push(cmd);
      cmd.init(fls[i],suffix,onCmdComplete,this);
    }
    if(fls.length<1){
      grunt.log.write("Nothing to do\n");
      done();
    }else{
      grunt.log.write("all queued\n");
    }
  });

  /*
  * imagemagick-resize TASK
  * takes a from folder, a to folder, a file pattern, and properties, and resizes the matching
  * files, outputting the resized images to the "to" folder.
  * {from:"folder",to:"folder",files:"*.ext",props{width:100}} etc.
  */
  grunt.registerMultiTask('imagemagick-resize','Resizes images using imagemagick',function(){
    var done= this.async();
    grunt.log.write("Beginning ImageMagick resizing process\n");
    var cmds=[],cmd;
    var i=0;
    var fls=grunt.file.expand(this.data.from+this.data.files);

    function onCmdComplete(cmd,success){
      grunt.log.write("completed:"+cmd.props.dstPath+"\n");
      cmds.splice(cmds.indexOf(cmd),1);
      if(cmds.length<1){
        done();
      }
    }

    if(!fileExists(this.data.to)){
      grunt.file.mkdir(this.data.to);
    }

    for(i=0;i<fls.length;i++){
      cmd=Object.create(ResizeCommand);
      cmds.push(cmd);
      cmd.init(
        fls[i],
        this.data.to+fls[i].substr(this.data.from.length), // replace folder
        this.data.props,
        onCmdComplete,
        this
      );
    }

    if(fls.length<1){
      grunt.log.write("Nothing to do\n");
      done();
    }else{
      grunt.log.write("all queued\n");
    }
  });

  grunt.registerMultiTask('imagemagick-convert','Converts images using imagemagick',function(){
    var done=this.async();
    grunt.log.write("Beginning convert operation\n");
    var cmd=Object.create(ConvertCommand);
    function onCmdComplete(cmd,success){
      grunt.log.write("completed:"+cmd.args+"\n");
      done();
    }
    cmd.init(this.data.args,onCmdComplete,this);
  });
};
<|endoftext|>


<commit_before>var eslint = require('eslint');
var constants = require('./util/constants');
var EXIT_CODE = 0;

var partialBundlePaths = constants.partialBundleNames.map(constants.makePartialBundleOpts);

assertES5();

// Ensure no ES6 has snuck through into the build:
function assertES5() {
    var CLIEngine = eslint.CLIEngine;

    var cli = new CLIEngine({
        allowInlineConfig: false,
        useEslintrc: false,
        ignore: false,
        parserOptions: {
            ecmaVersion: 5
        }
    });

    var files = partialBundlePaths.map(function(f) { return f.dist; });
    files.unshift(constants.pathToPlotlyDist);

    var report = cli.executeOnFiles(files);
    var formatter = cli.getFormatter();

    var errors = [];
    if(report.errorCount > 0) {
        console.log(formatter(report.results));

        // It doesn't work well to pass formatted logs into this,
        // so instead pass the empty string in a way that causes
        // the test to fail
        errors.push('');
    }

    log('es5-only syntax', errors);
}

function log(name, logs) {
    if(logs.length) {
        console.error('test-syntax error [' + name + ']');
        console.error(logs.join('\n'));
        EXIT_CODE = 1;
    } else {
        console.log('ok ' + name);
    }
}

process.on('exit', function() {
    if(EXIT_CODE) {
        throw new Error('test syntax failed.');
    }
});
<commit_msg>adapt no_es6_dist to eslint v7<commit_after>var eslint = require('eslint');
var constants = require('./util/constants');
var EXIT_CODE = 0;

var partialBundlePaths = constants.partialBundleNames.map(constants.makePartialBundleOpts);

assertES5();

// Ensure no ES6 has snuck through into the build:
function assertES5() {
    var ESLint = eslint.ESLint;

    var cli = new ESLint({
        allowInlineConfig: false,
        useEslintrc: false,
        ignore: false,
        overrideConfig: {
            parserOptions: {
                ecmaVersion: 5
            }
        }
    });

    var files = partialBundlePaths.map(function(f) { return f.dist; });
    files.unshift(constants.pathToPlotlyDist);

    var report = cli.lintFiles(files);
    var formatter = cli.loadFormatter();

    var errors = [];
    if(report.errorCount > 0) {
        console.log(formatter(report.results));

        // It doesn't work well to pass formatted logs into this,
        // so instead pass the empty string in a way that causes
        // the test to fail
        errors.push('');
    }

    log('es5-only syntax', errors);
}

function log(name, logs) {
    if(logs.length) {
        console.error('test-syntax error [' + name + ']');
        console.error(logs.join('\n'));
        EXIT_CODE = 1;
    } else {
        console.log('ok ' + name);
    }
}

process.on('exit', function() {
    if(EXIT_CODE) {
        throw new Error('test syntax failed.');
    }
});
<|endoftext|>


<commit_before>import {
  getNewContext,
  resetCanvasContextTransform,
  transformCanvasContext,
} from '../drawing/index.js';

import BaseBrushTool from './../tools/base/BaseBrushTool.js';
import external from '../externalModules.js';
import getActiveToolsForElement from '../store/getActiveToolsForElement.js';
import { getToolState } from '../stateManagement/toolState.js';
import store from '../store/index.js';

/* Safari and Edge polyfill for createImageBitmap
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap
 */

// TODO: Do we still need this? I've yanked the package for now
// It should be covered by @babel/runtime and plugin-transform-runtime:
// https://babeljs.io/docs/en/babel-plugin-transform-runtime
// @James, I think Babel should take care of this for us
// Import regeneratorRuntime from "regenerator-runtime";

if (!('createImageBitmap' in window)) {
  window.createImageBitmap = function(imageData) {
    return new Promise(resolve => {
      const img = document.createElement('img');

      img.addEventListener('load', function() {
        resolve(this);
      });

      const conversionCanvas = document.createElement('canvas');

      conversionCanvas.width = imageData.width;
      conversionCanvas.height = imageData.height;

      const conversionCanvasContext = conversionCanvas.getContext('2d');

      conversionCanvasContext.putImageData(
        imageData,
        0,
        0,
        0,
        0,
        conversionCanvas.width,
        conversionCanvas.height
      );
      img.src = conversionCanvas.toDataURL();
    });
  };
}

const { state, getters, setters } = store.modules.brush;

/**
 * Used to redraw the brush label map data per render.
 *
 * @private
 * @param {Object} evt - The event.
 * @returns {void}
 */
export default function(evt) {
  const eventData = evt.detail;
  const element = eventData.element;
  const maxSegmentations = BaseBrushTool.getNumberOfColors();

  const toolData = getToolState(
    element,
    BaseBrushTool.getReferencedToolDataName()
  );

  if (!toolData) {
    return;
  }

  const enabledElement = external.cornerstone.getEnabledElement(element);
  const enabledElementUID = enabledElement.uuid;

  const segData = {
    visibleSegmentations: getters.visibleSegmentationsForElement(
      enabledElementUID
    ),
    imageBitmapCache: getters.imageBitmapCacheForElement(enabledElementUID),
    toolData,
  };

  for (let segIndex = 0; segIndex < maxSegmentations; segIndex++) {
    if (shouldRenderSegmentation(evt, segIndex, segData)) {
      renderSegmentation(evt, segIndex, segData);
    }
  }
}

function shouldRenderSegmentation(evt, segIndex, segData) {
  const element = evt.detail.element;
  const toolData = segData.toolData;
  const visibleSegmentations = segData.visibleSegmentations;

  if (!toolData.data[segIndex] || !toolData.data[segIndex].pixelData) {
    // No data, no render.
    return false;
  }

  if (visibleSegmentations[segIndex]) {
    // Has data and marked as visible, render!
    return true;
  }

  const currentColor = state.drawColorId;

  if (currentColor !== segIndex) {
    // Hidden and not current color, don't render.
    return false;
  }

  // Check that a brush tool is active.
  const activeTools = getActiveToolsForElement(element, store.state.tools);
  const brushTools = activeTools.filter(tool => tool instanceof BaseBrushTool);

  if (brushTools.length > 0) {
    // Active brush tool with same color, render!
    return true;
  }

  return false;
}

function renderSegmentation(evt, segIndex, segData) {
  const toolData = segData.toolData;
  const imageBitmapCache = segData.imageBitmapCache;
  const visibleSegmentations = segData.visibleSegmentations;

  // Draw previous image if cached.
  if (imageBitmapCache && imageBitmapCache[segIndex]) {
    _drawImageBitmap(
      evt,
      imageBitmapCache[segIndex],
      visibleSegmentations[segIndex]
    );
  }

  if (toolData.data[segIndex].invalidated) {
    createNewBitmapAndQueueRenderOfSegmentation(evt, toolData, segIndex);
  }
}

function createNewBitmapAndQueueRenderOfSegmentation(evt, toolData, segIndex) {
  const eventData = evt.detail;
  const element = eventData.element;
  const enabledElement = external.cornerstone.getEnabledElement(element);

  const pixelData = toolData.data[segIndex].pixelData;
  const imageSpecificSegmentationAlpha = toolData.data[segIndex].alpha;

  if (!pixelData) {
    return;
  }

  const colormapId = state.colorMapId;
  const colormap = external.cornerstone.colors.getColormap(colormapId);
  const colorLutTable = [[0, 0, 0, 0], colormap.getColor(segIndex)];

  const imageData = new ImageData(
    eventData.image.width,
    eventData.image.height
  );
  const image = {
    stats: {},
    minPixelValue: 0,
    getPixelData: () => pixelData,
  };

  const hasImageSpecificSegmentationAlpha =
    imageSpecificSegmentationAlpha !== undefined;

  if (hasImageSpecificSegmentationAlpha) {
    colorLutTable[1][3] = imageSpecificSegmentationAlpha;
  }

  external.cornerstone.storedPixelDataToCanvasImageDataColorLUT(
    image,
    colorLutTable,
    imageData.data
  );

  window.createImageBitmap(imageData).then(newImageBitmap => {
    setters.imageBitmapCacheForElement(
      enabledElement.uuid,
      segIndex,
      newImageBitmap
    );
    toolData.data[segIndex].invalidated = false;

    external.cornerstone.updateImage(eventData.element);
  });
}

/**
 * Draws the ImageBitmap the canvas.
 *
 * @private
 * @param  {Object} evt description
 * @param {ImageBitmap} imageBitmap
 * @param {Boolean} alwaysVisible
 * @returns {void}
 */
function _drawImageBitmap(evt, imageBitmap, alwaysVisible) {
  const eventData = evt.detail;
  const context = getNewContext(eventData.canvasContext.canvas);

  const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, {
    x: 0,
    y: 0,
  });

  const canvasTopRight = external.cornerstone.pixelToCanvas(eventData.element, {
    x: eventData.image.width,
    y: 0,
  });

  const canvasBottomRight = external.cornerstone.pixelToCanvas(
    eventData.element,
    {
      x: eventData.image.width,
      y: eventData.image.height,
    }
  );

  const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance(
    canvasTopLeft,
    canvasTopRight
  );
  const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance(
    canvasTopRight,
    canvasBottomRight
  );

  const canvas = eventData.canvasContext.canvas;
  const viewport = eventData.viewport;

  context.imageSmoothingEnabled = false;
  context.globalAlpha = getLayerAlpha(alwaysVisible);

  transformCanvasContext(context, canvas, viewport);

  const canvasViewportTranslation = {
    x: viewport.translation.x * viewport.scale,
    y: viewport.translation.y * viewport.scale,
  };

  context.drawImage(
    imageBitmap,
    canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x,
    canvas.height / 2 -
      cornerstoneCanvasHeight / 2 +
      canvasViewportTranslation.y,
    cornerstoneCanvasWidth,
    cornerstoneCanvasHeight
  );

  context.globalAlpha = 1.0;

  resetCanvasContextTransform(context);
}

function getLayerAlpha(alwaysVisible) {
  if (alwaysVisible) {
    return state.alpha;
  }

  return state.hiddenButActiveAlpha;
}
<commit_msg>feat(RenderedBrushEventHandler): Force bitmap refresh if elementUID is in our list of invalidatedEnabledElements<commit_after>import {
  getNewContext,
  resetCanvasContextTransform,
  transformCanvasContext,
} from '../drawing/index.js';

import BaseBrushTool from './../tools/base/BaseBrushTool.js';
import external from '../externalModules.js';
import getActiveToolsForElement from '../store/getActiveToolsForElement.js';
import { getToolState } from '../stateManagement/toolState.js';
import store from '../store/index.js';

/* Safari and Edge polyfill for createImageBitmap
 * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/createImageBitmap
 */

// TODO: Do we still need this? I've yanked the package for now
// It should be covered by @babel/runtime and plugin-transform-runtime:
// https://babeljs.io/docs/en/babel-plugin-transform-runtime
// @James, I think Babel should take care of this for us
// Import regeneratorRuntime from "regenerator-runtime";

if (!('createImageBitmap' in window)) {
  window.createImageBitmap = function(imageData) {
    return new Promise(resolve => {
      const img = document.createElement('img');

      img.addEventListener('load', function() {
        resolve(this);
      });

      const conversionCanvas = document.createElement('canvas');

      conversionCanvas.width = imageData.width;
      conversionCanvas.height = imageData.height;

      const conversionCanvasContext = conversionCanvas.getContext('2d');

      conversionCanvasContext.putImageData(
        imageData,
        0,
        0,
        0,
        0,
        conversionCanvas.width,
        conversionCanvas.height
      );
      img.src = conversionCanvas.toDataURL();
    });
  };
}

const { state, getters, setters } = store.modules.brush;

/**
 * Used to redraw the brush label map data per render.
 *
 * @private
 * @param {Object} evt - The event.
 * @returns {void}
 */
export default function(evt) {
  const eventData = evt.detail;
  const element = eventData.element;
  const maxSegmentations = BaseBrushTool.getNumberOfColors();

  const toolData = getToolState(
    element,
    BaseBrushTool.getReferencedToolDataName()
  );

  if (!toolData) {
    return;
  }

  const enabledElement = external.cornerstone.getEnabledElement(element);
  const enabledElementUID = enabledElement.uuid;

  const segData = {
    visibleSegmentations: getters.visibleSegmentationsForElement(
      enabledElementUID
    ),
    imageBitmapCache: getters.imageBitmapCacheForElement(enabledElementUID),
    toolData,
  };

  for (let segIndex = 0; segIndex < maxSegmentations; segIndex++) {
    if (shouldRenderSegmentation(evt, segIndex, segData)) {
      renderSegmentation(evt, segIndex, segData);
    }
  }
}

function shouldRenderSegmentation(evt, segIndex, segData) {
  const element = evt.detail.element;
  const toolData = segData.toolData;
  const visibleSegmentations = segData.visibleSegmentations;

  if (!toolData.data[segIndex] || !toolData.data[segIndex].pixelData) {
    // No data, no render.
    return false;
  }

  if (visibleSegmentations[segIndex]) {
    // Has data and marked as visible, render!
    return true;
  }

  const currentColor = state.drawColorId;

  if (currentColor !== segIndex) {
    // Hidden and not current color, don't render.
    return false;
  }

  // Check that a brush tool is active.
  const activeTools = getActiveToolsForElement(element, store.state.tools);
  const brushTools = activeTools.filter(tool => tool instanceof BaseBrushTool);

  if (brushTools.length > 0) {
    // Active brush tool with same color, render!
    return true;
  }

  return false;
}

function renderSegmentation(evt, segIndex, segData) {
  const toolData = segData.toolData;
  const imageBitmapCache = segData.imageBitmapCache;
  const visibleSegmentations = segData.visibleSegmentations;

  // Draw previous image if cached.
  if (imageBitmapCache && imageBitmapCache[segIndex]) {
    _drawImageBitmap(
      evt,
      imageBitmapCache[segIndex],
      visibleSegmentations[segIndex]
    );
  }

  const eventData = evt.detail;
  const element = eventData.element;
  const enabledElement = external.cornerstone.getEnabledElement(element);

  if (
    toolData.data[segIndex].invalidated ||
    state.invalidatedEnabledElements.includes(enabledElement.uuid)
  ) {
    createNewBitmapAndQueueRenderOfSegmentation(
      eventData,
      enabledElement.uuid,
      toolData,
      segIndex
    );
  }
}

function createNewBitmapAndQueueRenderOfSegmentation(
  { image: eventImage, element },
  enabledElementUID,
  toolData,
  segIndex
) {
  const pixelData = toolData.data[segIndex].pixelData;
  const imageSpecificSegmentationAlpha = toolData.data[segIndex].alpha;

  if (!pixelData) {
    return;
  }

  const colormapId = state.colorMapId;
  const colormap = external.cornerstone.colors.getColormap(colormapId);
  const colorLutTable = [[0, 0, 0, 0], colormap.getColor(segIndex)];

  const imageData = new ImageData(eventImage.width, eventImage.height);
  const image = {
    stats: {},
    minPixelValue: 0,
    getPixelData: () => pixelData,
  };

  const hasImageSpecificSegmentationAlpha =
    imageSpecificSegmentationAlpha !== undefined;

  if (hasImageSpecificSegmentationAlpha) {
    colorLutTable[1][3] = imageSpecificSegmentationAlpha;
  }

  external.cornerstone.storedPixelDataToCanvasImageDataColorLUT(
    image,
    colorLutTable,
    imageData.data
  );

  window.createImageBitmap(imageData).then(newImageBitmap => {
    setters.imageBitmapCacheForElement(
      enabledElementUID,
      segIndex,
      newImageBitmap
    );
    toolData.data[segIndex].invalidated = false;
    state.invalidatedEnabledElements = state.invalidatedEnabledElements.filter(
      iee => iee !== enabledElementUID
    );

    external.cornerstone.updateImage(element);
  });
}

/**
 * Draws the ImageBitmap the canvas.
 *
 * @private
 * @param  {Object} evt description
 * @param {ImageBitmap} imageBitmap
 * @param {Boolean} alwaysVisible
 * @returns {void}
 */
function _drawImageBitmap(evt, imageBitmap, alwaysVisible) {
  const eventData = evt.detail;
  const context = getNewContext(eventData.canvasContext.canvas);

  const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, {
    x: 0,
    y: 0,
  });

  const canvasTopRight = external.cornerstone.pixelToCanvas(eventData.element, {
    x: eventData.image.width,
    y: 0,
  });

  const canvasBottomRight = external.cornerstone.pixelToCanvas(
    eventData.element,
    {
      x: eventData.image.width,
      y: eventData.image.height,
    }
  );

  const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance(
    canvasTopLeft,
    canvasTopRight
  );
  const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance(
    canvasTopRight,
    canvasBottomRight
  );

  const canvas = eventData.canvasContext.canvas;
  const viewport = eventData.viewport;

  context.imageSmoothingEnabled = false;
  context.globalAlpha = getLayerAlpha(alwaysVisible);

  transformCanvasContext(context, canvas, viewport);

  const canvasViewportTranslation = {
    x: viewport.translation.x * viewport.scale,
    y: viewport.translation.y * viewport.scale,
  };

  context.drawImage(
    imageBitmap,
    canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x,
    canvas.height / 2 -
      cornerstoneCanvasHeight / 2 +
      canvasViewportTranslation.y,
    cornerstoneCanvasWidth,
    cornerstoneCanvasHeight
  );

  context.globalAlpha = 1.0;

  resetCanvasContextTransform(context);
}

function getLayerAlpha(alwaysVisible) {
  if (alwaysVisible) {
    return state.alpha;
  }

  return state.hiddenButActiveAlpha;
}
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { compose, withHandlers, withProps } from 'recompose';
import { withTranslation } from 'react-i18next';
import { SearchBox } from '@nuclear/ui';

import * as SearchActions from '../../actions/search';
import * as PluginActions from '../../actions/plugins';
import { pluginsSelectors } from '../../selectors/plugins';

const MIN_SEARCH_LENGTH = 3;
const SearchBoxContainer = ({
  handleSearch,
  unifiedSearchStarted,
  searchProvidersOptions,
  searchHistory,
  handleClearSearchHistory,
  selectedSearchProviderOption,
  handleSelectSearchProvider,
  isConnected,
  t,
  isFocused,
  handleFocus
}) => (
  <SearchBox
    loading={unifiedSearchStarted}
    disabled={!isConnected}
    placeholder={t('placeholder')}
    lastSearchesLabel={t('last-searches')}
    clearHistoryLabel={t('clear-history')}
    footerLabel={t('you-can-search-for')}
    onChange={_.debounce(handleSearch, 500)}
    onSearch={handleSearch}
    searchProviders={searchProvidersOptions}
    searchHistory={searchHistory}
    onClearHistory={handleClearSearchHistory}
    selectedSearchProvider={selectedSearchProviderOption}
    onSearchProviderSelect={handleSelectSearchProvider}
    isFocused={isFocused}
    handleFocus={handleFocus}
  />
);

const mapStateToProps = state => ({
  unifiedSearchStarted: state.search.unifiedSearchStarted,
  searchHistory: state.search.searchHistory,
  isConnected: state.connectivity,
  searchProviders: _.get(pluginsSelectors.plugins(state), 'metaProviders'),
  selectedSearchProvider: _.get(pluginsSelectors.selected(state), 'metaProviders'),
  isFocused: state.search.isFocused
});

const mapDispatchToProps = dispatch => ({
  searchActions: bindActionCreators({
    ...SearchActions,
    ...SearchActions.SearchActions
  }, dispatch),
  pluginActions: bindActionCreators(PluginActions, dispatch)
});

const providerToOption = provider => ({
  key: _.lowerCase(_.get(provider, 'sourceName')),
  text: _.get(provider, 'searchName'),
  value: _.get(provider, 'sourceName')
});

export default compose(
  withRouter,
  connect(mapStateToProps, mapDispatchToProps),
  withTranslation('search'),
  withHandlers({
    handleSearch:
      ({ searchActions, history }) => value =>
        value.length >= MIN_SEARCH_LENGTH ? searchActions.unifiedSearch(value, history) : null,
    handleSelectSearchProvider:
      ({ pluginActions }) => provider =>
        pluginActions.selectMetaProvider(provider.value),
    handleFocus: ({ searchActions }) => bool => searchActions.setSearchDropdownVisibility(bool),
    handleClearSearchHistory: ({ searchActions }) => () => searchActions.updateSearchHistory([])
  }),
  withProps(({ searchProviders, selectedSearchProvider }) => ({
    searchProvidersOptions: _.map(searchProviders, providerToOption),
    selectedSearchProviderOption: providerToOption(
      _.find(searchProviders, { sourceName: selectedSearchProvider })
    )
  }))
)(SearchBoxContainer);
<commit_msg>Set minimum search length to 2, closes #807<commit_after>import React from 'react';
import _ from 'lodash';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { compose, withHandlers, withProps } from 'recompose';
import { withTranslation } from 'react-i18next';
import { SearchBox } from '@nuclear/ui';

import * as SearchActions from '../../actions/search';
import * as PluginActions from '../../actions/plugins';
import { pluginsSelectors } from '../../selectors/plugins';

const MIN_SEARCH_LENGTH = 2;
const SearchBoxContainer = ({
  handleSearch,
  unifiedSearchStarted,
  searchProvidersOptions,
  searchHistory,
  handleClearSearchHistory,
  selectedSearchProviderOption,
  handleSelectSearchProvider,
  isConnected,
  t,
  isFocused,
  handleFocus
}) => (
  <SearchBox
    loading={unifiedSearchStarted}
    disabled={!isConnected}
    placeholder={t('placeholder')}
    lastSearchesLabel={t('last-searches')}
    clearHistoryLabel={t('clear-history')}
    footerLabel={t('you-can-search-for')}
    onChange={_.debounce(handleSearch, 500)}
    onSearch={handleSearch}
    searchProviders={searchProvidersOptions}
    searchHistory={searchHistory}
    onClearHistory={handleClearSearchHistory}
    selectedSearchProvider={selectedSearchProviderOption}
    onSearchProviderSelect={handleSelectSearchProvider}
    isFocused={isFocused}
    handleFocus={handleFocus}
  />
);

const mapStateToProps = state => ({
  unifiedSearchStarted: state.search.unifiedSearchStarted,
  searchHistory: state.search.searchHistory,
  isConnected: state.connectivity,
  searchProviders: _.get(pluginsSelectors.plugins(state), 'metaProviders'),
  selectedSearchProvider: _.get(pluginsSelectors.selected(state), 'metaProviders'),
  isFocused: state.search.isFocused
});

const mapDispatchToProps = dispatch => ({
  searchActions: bindActionCreators({
    ...SearchActions,
    ...SearchActions.SearchActions
  }, dispatch),
  pluginActions: bindActionCreators(PluginActions, dispatch)
});

const providerToOption = provider => ({
  key: _.lowerCase(_.get(provider, 'sourceName')),
  text: _.get(provider, 'searchName'),
  value: _.get(provider, 'sourceName')
});

export default compose(
  withRouter,
  connect(mapStateToProps, mapDispatchToProps),
  withTranslation('search'),
  withHandlers({
    handleSearch:
      ({ searchActions, history }) => value =>
        value.length >= MIN_SEARCH_LENGTH ? searchActions.unifiedSearch(value, history) : null,
    handleSelectSearchProvider:
      ({ pluginActions }) => provider =>
        pluginActions.selectMetaProvider(provider.value),
    handleFocus: ({ searchActions }) => bool => searchActions.setSearchDropdownVisibility(bool),
    handleClearSearchHistory: ({ searchActions }) => () => searchActions.updateSearchHistory([])
  }),
  withProps(({ searchProviders, selectedSearchProvider }) => ({
    searchProvidersOptions: _.map(searchProviders, providerToOption),
    selectedSearchProviderOption: providerToOption(
      _.find(searchProviders, { sourceName: selectedSearchProvider })
    )
  }))
)(SearchBoxContainer);
<|endoftext|>


<commit_before>export default function populatePath (context, strings, values) {
  return strings.reduce((currentPath, string, idx) => {
    const valueTemplate = values[idx]
    if (valueTemplate && valueTemplate.getValue) {
      return currentPath + string + context.state.compute(valueTemplate)
    }

    return currentPath + string + (valueTemplate ? valueTemplate(context).toValue() : '')
  }, '')
}
<commit_msg>fix(Operators): populatePaths   (#411)<commit_after>export default function populatePath (context, strings, values) {
  return strings.reduce((currentPath, string, idx) => {
    const valueTemplate = values[idx]
    if (valueTemplate && valueTemplate.getValue) {
      return currentPath + string + context.state.compute(valueTemplate)
    }

    if (valueTemplate && typeof valueTemplate === 'function') {
      return currentPath + string + valueTemplate(context).toValue()
    }

    return currentPath + string + (valueTemplate || '')
  }, '')
}
<|endoftext|>


<commit_before>'use strict';

// get command from index.js
let cmd = commands.find(c => c.topic === 'maintenance');

describe('maintenance', () => {
  // prevent stdout/stderr from displaying
  // redirects to cli.stdout/cli.stderr instead
  beforeEach(() => cli.mockConsole());

  it('shows the maintenance is on', () => {
    // mock out API
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp')
      .reply(200, {maintenance: true});

    // run the command
    return cmd.run({app: 'myapp'})
    // check stdout
    .then(() => expect(cli.stdout).to.equal('on\n'))
    // check stderr
    .then(() => expect(cli.stderr).to.equal(''))
    // ensure all nock HTTP expectations are met
    .then(() => api.done());
  });

  it('shows the maintenance is off', () => {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp')
      .reply(200, {maintenance: false});
    return cmd.run({app: 'myapp'})
    .then(() => expect(cli.stdout).to.equal('off\n'))
    .then(() => api.done());
  });
});
<commit_msg>minor testing doc update<commit_after>'use strict';

// get command from index.js
let cmd = commands.find(c => c.topic === 'maintenance');

describe('maintenance', () => {
  // prevent stdout/stderr from displaying
  // redirects to cli.stdout/cli.stderr instead
  beforeEach(() => cli.mockConsole());

  it('shows that maintenance is on', () => {
    // mock out API
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp')
      .reply(200, {maintenance: true});

    // run the command
    return cmd.run({app: 'myapp'})
    // check stdout
    .then(() => expect(cli.stdout).to.equal('on\n'))
    // check stderr
    .then(() => expect(cli.stderr).to.equal(''))
    // ensure all nock HTTP expectations are met
    .then(() => api.done());
  });

  it('shows that maintenance is off', () => {
    let api = nock('https://api.heroku.com:443')
      .get('/apps/myapp')
      .reply(200, {maintenance: false});
    return cmd.run({app: 'myapp'})
    .then(() => expect(cli.stdout).to.equal('off\n'))
    .then(() => api.done());
  });
});
<|endoftext|>