Bug 1246034: Part 1 - [webext] Add a helper function to trigger a browserAction. r?jaws,kmag draft
authorKris Maglione <maglione.k@gmail.com>
Wed, 07 Sep 2016 11:05:11 +0100
changeset 422570 76bab3177db2432347164850b953c3bea269bb08
parent 422569 5ddd619ca0c5410faca3fc1e0ae52ad14de898a2
child 422571 d865b0822584cf7aebf8f89c0649ad82ac168f65
push id31744
push usermwein@mozilla.com
push dateFri, 07 Oct 2016 21:14:49 +0000
reviewersjaws, kmag
bugs1246034
milestone52.0a1
Bug 1246034: Part 1 - [webext] Add a helper function to trigger a browserAction. r?jaws,kmag MozReview-Commit-ID: JUW6oUpWiN4
browser/components/extensions/ext-browserAction.js
browser/components/extensions/ext-utils.js
browser/components/extensions/test/browser/browser_ext_browserAction_popup.js
toolkit/components/extensions/ExtensionUtils.jsm
--- a/browser/components/extensions/ext-browserAction.js
+++ b/browser/components/extensions/ext-browserAction.js
@@ -9,18 +9,19 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
                                   "resource://gre/modules/Timer.jsm");
 
 XPCOMUtils.defineLazyGetter(this, "colorUtils", () => {
   return require("devtools/shared/css/color").colorUtils;
 });
 
 Cu.import("resource://devtools/shared/event-emitter.js");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
 
-Cu.import("resource://gre/modules/ExtensionUtils.jsm");
 var {
   EventManager,
   IconDetails,
 } = ExtensionUtils;
 
 const POPUP_PRELOAD_TIMEOUT_MS = 200;
 
 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
@@ -103,20 +104,19 @@ BrowserAction.prototype = {
       onViewShowing: event => {
         let document = event.target.ownerDocument;
         let tabbrowser = document.defaultView.gBrowser;
 
         let tab = tabbrowser.selectedTab;
         let popupURL = this.getProperty(tab, "popup");
         this.tabManager.addActiveTabPermission(tab);
 
-        // If the widget has a popup URL defined, we open a popup, but do not
-        // dispatch a click event to the extension.
-        // If it has no popup URL defined, we dispatch a click event, but do not
-        // open a popup.
+        // Popups are shown only if a popup URL is defined; otherwise
+        // a "click" event is dispatched. This is done for compatibility with the
+        // Google Chrome onClicked extension API.
         if (popupURL) {
           try {
             let popup = this.getPopup(document.defaultView, popupURL);
             event.detail.addBlocker(popup.attach(event.target));
           } catch (e) {
             Cu.reportError(e);
             event.preventDefault();
           }
@@ -130,16 +130,52 @@ BrowserAction.prototype = {
     });
 
     this.tabContext.on("tab-select", // eslint-disable-line mozilla/balanced-listeners
                        (evt, tab) => { this.updateWindow(tab.ownerGlobal); });
 
     this.widget = widget;
   },
 
+  /**
+   * Triggers this browser action for the given window, with the same effects as
+   * if it were clicked by a user.
+   *
+   * This has no effect if the browser action is disabled for, or not
+   * present in, the given window.
+   */
+  triggerAction: Task.async(function* (window) {
+    let popup = ViewPopup.for(this.extension, window);
+    if (popup) {
+      popup.closePopup();
+      return;
+    }
+
+    let widget = this.widget.forWindow(window);
+    let tab = window.gBrowser.selectedTab;
+
+    if (!widget || !this.getProperty(tab, "enabled")) {
+      return;
+    }
+
+    // Popups are shown only if a popup URL is defined; otherwise
+    // a "click" event is dispatched. This is done for compatibility with the
+    // Google Chrome onClicked extension API.
+    if (this.getProperty(tab, "popup")) {
+      if (this.widget.areaType == CustomizableUI.TYPE_MENU_PANEL) {
+        yield window.PanelUI.show();
+      }
+
+      let event = new window.CustomEvent("command", {bubbles: true, cancelable: true});
+      widget.node.dispatchEvent(event);
+    } else {
+      this.emit("click");
+    }
+  }),
+
   handleEvent(event) {
     let button = event.target;
     let window = button.ownerDocument.defaultView;
 
     switch (event.type) {
       case "mousedown":
         if (event.button == 0) {
           // Begin pre-loading the browser for the popup, so it's more likely to
--- a/browser/components/extensions/ext-utils.js
+++ b/browser/components/extensions/ext-utils.js
@@ -27,16 +27,17 @@ Cu.import("resource://gre/modules/AppCon
 const POPUP_LOAD_TIMEOUT_MS = 200;
 
 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 
 // Minimum time between two resizes.
 const RESIZE_TIMEOUT = 100;
 
 var {
+  DefaultWeakMap,
   EventManager,
 } = ExtensionUtils;
 
 // This file provides some useful code for the |tabs| and |windows|
 // modules. All of the code is installed on |global|, which is a scope
 // shared among the different ext-*.js scripts.
 
 global.makeWidgetId = id => {
@@ -120,16 +121,22 @@ class BasePopup {
     let arrowContent = doc.getAnonymousElementByAttribute(this.panel, "class", "panel-arrowcontent");
     this.borderColor = doc.defaultView.getComputedStyle(arrowContent).borderTopColor;
 
     this.browser = null;
     this.browserLoaded = new Promise((resolve, reject) => {
       this.browserLoadedDeferred = {resolve, reject};
     });
     this.browserReady = this.createBrowser(viewNode, popupURL);
+
+    BasePopup.instances.get(this.window).set(extension, this);
+  }
+
+  static for(extension, window) {
+    return BasePopup.instances.get(window).get(extension);
   }
 
   destroy() {
     this.destroyed = true;
     this.browserLoadedDeferred.reject(new Error("Popup destroyed"));
     return this.browserReady.then(() => {
       this.destroyBrowser(this.browser);
       this.browser.remove();
@@ -137,16 +144,18 @@ class BasePopup {
       this.viewNode.removeEventListener(this.DESTROY_EVENT, this);
       this.viewNode.style.maxHeight = "";
 
       if (this.panel) {
         this.panel.style.removeProperty("--arrowpanel-background");
         this.panel.style.removeProperty("--panel-arrow-image-vertical");
       }
 
+      BasePopup.instances.get(this.window).delete(this.extension);
+
       this.browser = null;
       this.viewNode = null;
     });
   }
 
   destroyBrowser(browser) {
     browser.removeEventListener("DOMWindowCreated", this, true);
     browser.removeEventListener("load", this, true);
@@ -417,16 +426,23 @@ class BasePopup {
 
     let event = new this.window.CustomEvent("WebExtPopupResized");
     this.browser.dispatchEvent(event);
 
     this._resolveContentReady();
   }
 }
 
+/**
+ * A map of active popups for a given browser window.
+ *
+ * WeakMap[window -> WeakMap[Extension -> BasePopup]]
+ */
+BasePopup.instances = new DefaultWeakMap(() => new WeakMap());
+
 global.PanelPopup = class PanelPopup extends BasePopup {
   constructor(extension, imageNode, popupURL, browserStyle) {
     let document = imageNode.ownerDocument;
 
     let panel = document.createElement("panel");
     panel.setAttribute("id", makeWidgetId(extension.id) + "-panel");
     panel.setAttribute("class", "browser-extension-panel");
     panel.setAttribute("tabspecific", "true");
--- a/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js
+++ b/browser/components/extensions/test/browser/browser_ext_browserAction_popup.js
@@ -1,12 +1,19 @@
 /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
 /* vim: set sts=2 sw=2 et tw=80: */
 "use strict";
 
+function getBrowserAction(extension) {
+  const {GlobalManager, Management: {global: {browserActionFor}}} = Cu.import("resource://gre/modules/Extension.jsm", {});
+
+  let ext = GlobalManager.extensionMap.get(extension.id);
+  return browserActionFor(ext);
+}
+
 function* testInArea(area) {
   let scriptPage = url => `<html><head><meta charset="utf-8"><script src="${url}"></script></head><body>${url}</body></html>`;
 
   let extension = ExtensionTestUtils.loadExtension({
     manifest: {
       "background": {
         "page": "data/background.html",
       },
@@ -20,17 +27,17 @@ function* testInArea(area) {
       "popup-a.html": scriptPage("popup-a.js"),
       "popup-a.js": function() {
         window.onload = () => {
           let color = window.getComputedStyle(document.body).color;
           browser.test.assertEq("rgb(34, 36, 38)", color);
           browser.runtime.sendMessage("from-popup-a");
         };
         browser.runtime.onMessage.addListener(msg => {
-          if (msg == "close-popup") {
+          if (msg == "close-popup-using-window.close") {
             window.close();
           }
         });
       },
 
       "data/popup-b.html": scriptPage("popup-b.js"),
       "data/popup-b.js": function() {
         window.onload = () => {
@@ -47,96 +54,112 @@ function* testInArea(area) {
       },
 
       "data/background.html": scriptPage("background.js"),
 
       "data/background.js": function() {
         let sendClick;
         let tests = [
           () => {
-            browser.test.log("Open popup a");
+            browser.test.log(`Click browser action, expect popup "a".`);
+            sendClick({expectEvent: false, expectPopup: "a"});
+          },
+          () => {
+            browser.test.log(`Click browser action again, expect popup "a".`);
             sendClick({expectEvent: false, expectPopup: "a"});
           },
           () => {
-            browser.test.log("Open popup a again");
-            sendClick({expectEvent: false, expectPopup: "a"});
+            browser.test.log(`Call triggerAction, expect popup "a" again. Leave popup open.`);
+            sendClick({expectEvent: false, expectPopup: "a", closePopup: false}, "trigger-action");
           },
           () => {
-            browser.test.log("Open popup c");
+            browser.test.log(`Call triggerAction again. Expect remaining popup closed.`);
+            sendClick({expectEvent: false, expectPopup: null}, "trigger-action");
+            browser.test.sendMessage("next-test", {waitUntilClosed: true});
+          },
+          () => {
+            browser.test.log(`Call triggerAction again. Expect popup "a" again.`);
+            sendClick({expectEvent: false, expectPopup: "a"}, "trigger-action");
+          },
+          () => {
+            browser.test.log(`Set popup to "c" and click browser action. Expect popup "c".`);
             browser.browserAction.setPopup({popup: "popup-c.html"});
             sendClick({expectEvent: false, expectPopup: "c", closePopup: false});
           },
           () => {
-            browser.test.log("Open popup b");
+            browser.test.log(`Set popup to "b" and click browser action. Expect popup "b".`);
             browser.browserAction.setPopup({popup: "popup-b.html"});
             sendClick({expectEvent: false, expectPopup: "b"});
           },
           () => {
-            browser.test.log("Open popup b again");
+            browser.test.log(`Click browser action again, expect popup "b".`);
             sendClick({expectEvent: false, expectPopup: "b"});
           },
           () => {
+            browser.test.log(`Clear popup URL. Click browser action. Expect click event.`);
             browser.browserAction.setPopup({popup: ""});
             sendClick({expectEvent: true, expectPopup: null});
           },
           () => {
+            browser.test.log(`Click browser action again. Expect another click event.`);
             sendClick({expectEvent: true, expectPopup: null});
           },
           () => {
-            browser.browserAction.setPopup({popup: "/popup-a.html"});
-            sendClick({expectEvent: false, expectPopup: "a", runNextTest: true});
+            browser.test.log(`Call triggerAction. Expect click event.`);
+            sendClick({expectEvent: true, expectPopup: null}, "trigger-action");
           },
           () => {
-            browser.test.sendMessage("next-test", {expectClosed: true});
+            browser.test.log(`Set popup to "a" and click browser action. Expect popup "a", and leave open.`);
+            browser.browserAction.setPopup({popup: "/popup-a.html"});
+            sendClick({expectEvent: false, expectPopup: "a", closePopup: false});
+          },
+          () => {
+            browser.test.log(`Tell popup "a" to call window.close(). Expect popup closed.`);
+            browser.test.sendMessage("next-test", {closePopupUsingWindow: true});
           },
         ];
 
         let expect = {};
-        sendClick = ({expectEvent, expectPopup, runNextTest, closePopup}) => {
+        sendClick = ({expectEvent, expectPopup, runNextTest, waitUntilClosed, closePopup}, message = "send-click") => {
           if (closePopup == undefined) {
             closePopup = true;
           }
 
-          expect = {event: expectEvent, popup: expectPopup, runNextTest, closePopup};
-          browser.test.sendMessage("send-click");
+          expect = {event: expectEvent, popup: expectPopup, runNextTest, waitUntilClosed, closePopup};
+          browser.test.sendMessage(message);
         };
 
         browser.runtime.onMessage.addListener(msg => {
-          if (msg == "close-popup") {
+          if (msg == "close-popup-using-window.close") {
             return;
           } else if (expect.popup) {
             browser.test.assertEq(msg, `from-popup-${expect.popup}`,
                                   "expected popup opened");
           } else {
             browser.test.fail(`unexpected popup: ${msg}`);
           }
 
           expect.popup = null;
-          if (expect.runNextTest) {
-            expect.runNextTest = false;
-            tests.shift()();
-          } else {
-            browser.test.sendMessage("next-test", {closePopup: expect.closePopup});
-          }
+          browser.test.sendMessage("next-test", expect);
         });
 
         browser.browserAction.onClicked.addListener(() => {
           if (expect.event) {
             browser.test.succeed("expected click event received");
           } else {
             browser.test.fail("unexpected click event");
           }
 
           expect.event = false;
-          browser.test.sendMessage("next-test");
+          browser.test.sendMessage("next-test", expect);
         });
 
         browser.test.onMessage.addListener((msg) => {
-          if (msg == "close-popup") {
-            browser.runtime.sendMessage("close-popup");
+          if (msg == "close-popup-using-window.close") {
+            browser.runtime.sendMessage("close-popup-using-window.close");
             return;
           }
 
           if (msg != "next-test") {
             browser.test.fail("Expecting 'next-test' message");
           }
 
           if (tests.length) {
@@ -151,28 +174,38 @@ function* testInArea(area) {
       },
     },
   });
 
   extension.onMessage("send-click", () => {
     clickBrowserAction(extension);
   });
 
+  extension.onMessage("trigger-action", () => {
+    getBrowserAction(extension).triggerAction(window);
+  });
+
   let widget;
   extension.onMessage("next-test", Task.async(function* (expecting = {}) {
     if (!widget) {
       widget = getBrowserActionWidget(extension);
       CustomizableUI.addWidgetToArea(widget.id, area);
     }
-    if (expecting.expectClosed) {
+    if (expecting.waitUntilClosed) {
+      dump(`L0G HERE`);
+      let panel = getBrowserActionPopup(extension);
+      if (panel && panel.state != "closed") {
+        yield promisePopupHidden(panel);
+      }
+    } else if (expecting.closePopupUsingWindow) {
       let panel = getBrowserActionPopup(extension);
       ok(panel, "Expect panel to exist");
       yield promisePopupShown(panel);
 
-      extension.sendMessage("close-popup");
+      extension.sendMessage("close-popup-using-window.close");
 
       yield promisePopupHidden(panel);
       ok(true, "Panel is closed");
     } else if (expecting.closePopup) {
       yield closeBrowserAction(extension);
     }
 
     extension.sendMessage("next-test");
--- a/toolkit/components/extensions/ExtensionUtils.jsm
+++ b/toolkit/components/extensions/ExtensionUtils.jsm
@@ -125,39 +125,33 @@ function extend(obj, ...args) {
       let descriptor = Object.getOwnPropertyDescriptor(arg, prop);
       Object.defineProperty(obj, prop, descriptor);
     }
   }
 
   return obj;
 }
 
-// Similar to a WeakMap, but returns a particular default value for
-// |get| if a key is not present.
-function DefaultWeakMap(defaultValue) {
-  this.defaultValue = defaultValue;
-  this.weakmap = new WeakMap();
-}
+/**
+ * Similar to a WeakMap, but creates a new key with the given
+ * constructor if one is not present.
+ */
+class DefaultWeakMap extends WeakMap {
+  constructor(defaultConstructor, init) {
+    super(init);
+    this.defaultConstructor = defaultConstructor;
+  }
 
-DefaultWeakMap.prototype = {
   get(key) {
-    if (this.weakmap.has(key)) {
-      return this.weakmap.get(key);
+    if (!this.has(key)) {
+      this.set(key, this.defaultConstructor());
     }
-    return this.defaultValue;
-  },
-
-  set(key, value) {
-    if (key) {
-      this.weakmap.set(key, value);
-    } else {
-      this.defaultValue = value;
-    }
-  },
-};
+    return super.get(key);
+  }
+}
 
 class SpreadArgs extends Array {
   constructor(args) {
     super();
     this.push(...args);
   }
 }