summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/extensions/parent/ext-browserAction.js
blob: de07f9e3a2a2713adf489c204a5b469c22b4be3d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

ChromeUtils.defineESModuleGetters(this, {
  storeState: "resource:///modules/CustomizationState.mjs",
  getState: "resource:///modules/CustomizationState.mjs",
  registerExtension: "resource:///modules/CustomizableItems.sys.mjs",
  unregisterExtension: "resource:///modules/CustomizableItems.sys.mjs",
  EXTENSION_PREFIX: "resource:///modules/CustomizableItems.sys.mjs",
});
var { ExtensionCommon } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionCommon.sys.mjs"
);
var { XPCOMUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/XPCOMUtils.sys.mjs"
);
XPCOMUtils.defineLazyModuleGetters(this, {
  ToolbarButtonAPI: "resource:///modules/ExtensionToolbarButtons.jsm",
  getCachedAllowedSpaces: "resource:///modules/ExtensionToolbarButtons.jsm",
  setCachedAllowedSpaces: "resource:///modules/ExtensionToolbarButtons.jsm",
});

var { makeWidgetId } = ExtensionCommon;

const browserActionMap = new WeakMap();

this.browserAction = class extends ToolbarButtonAPI {
  static for(extension) {
    return browserActionMap.get(extension);
  }

  /**
   * A browser_action can be placed in the unified toolbar of the main window and
   * in the XUL toolbar of the message window. We conditionally bypass XUL toolbar
   * behavior by using the following custom method implementations.
   */

  paint(window) {
    // Ignore XUL toolbar paint requests for the main window.
    if (window.location.href != MAIN_WINDOW_URI) {
      super.paint(window);
    }
  }

  unpaint(window) {
    // Ignore XUL toolbar unpaint requests for the main window.
    if (window.location.href != MAIN_WINDOW_URI) {
      super.unpaint(window);
    }
  }

  /**
   * Return the toolbar button if it is currently visible in the given window.
   *
   * @param window
   * @returns {DOMElement} the toolbar button element, or null
   */
  getToolbarButton(window) {
    // Return the visible button from the unified toolbar, if this is the main window.
    if (window.location.href == MAIN_WINDOW_URI) {
      let buttonItem = window.document.querySelector(
        `#unifiedToolbarContent [item-id="ext-${this.extension.id}"]`
      );
      return (
        buttonItem &&
        !buttonItem.hidden &&
        window.document.querySelector(
          `#unifiedToolbarContent [extension="${this.extension.id}"]`
        )
      );
    }
    return super.getToolbarButton(window);
  }

  updateButton(button, tabData) {
    if (button.applyTabData) {
      // This is an extension-action-button customElement and therefore a button
      // in the unified toolbar and needs special handling.
      button.applyTabData(tabData);
    } else {
      super.updateButton(button, tabData);
    }
  }

  async onManifestEntry(entryName) {
    await super.onManifestEntry(entryName);
    browserActionMap.set(this.extension, this);

    // Check if a browser_action was added to the unified toolbar.
    if (this.windowURLs.includes(MAIN_WINDOW_URI)) {
      await registerExtension(this.extension.id, this.allowedSpaces);
      const currentToolbarState = getState();
      const unifiedToolbarButtonId = `${EXTENSION_PREFIX}${this.extension.id}`;

      // Load the cached allowed spaces. Make sure there are no awaited promises
      // before storing the updated allowed spaces, as it could have been changed
      // elsewhere.
      let cachedAllowedSpaces = getCachedAllowedSpaces();
      let priorAllowedSpaces = cachedAllowedSpaces.get(this.extension.id);

      // If the extension has set allowedSpaces to an empty array, the button needs
      // to be added to all available spaces.
      let allowedSpaces =
        this.allowedSpaces.length == 0
          ? [
              "mail",
              "addressbook",
              "calendar",
              "tasks",
              "chat",
              "settings",
              "default",
            ]
          : this.allowedSpaces;

      // Manually add the button to all customized spaces, where it has not been
      // allowed in the prior version of this add-on (if any). This automatically
      // covers the install and the update case, including staged updates.
      // Spaces which have not been customized will receive the button from
      // getDefaultItemIdsForSpace() in CustomizableItems.sys.mjs.
      let missingSpacesInState = allowedSpaces.filter(
        space =>
          (!priorAllowedSpaces || !priorAllowedSpaces.includes(space)) &&
          space !== "default" &&
          currentToolbarState.hasOwnProperty(space) &&
          !currentToolbarState[space].includes(unifiedToolbarButtonId)
      );
      for (const space of missingSpacesInState) {
        currentToolbarState[space].push(unifiedToolbarButtonId);
      }

      // Manually remove button from all customized spaces, if it is no longer
      // allowed. This will remove its stored customized positioning information.
      // If a space becomes allowed again later, the button will be added to the
      // end of the space and not at its former customized location.
      let invalidSpacesInState = [];
      if (priorAllowedSpaces) {
        invalidSpacesInState = priorAllowedSpaces.filter(
          space =>
            space !== "default" &&
            !allowedSpaces.includes(space) &&
            currentToolbarState.hasOwnProperty(space) &&
            currentToolbarState[space].includes(unifiedToolbarButtonId)
        );
        for (const space of invalidSpacesInState) {
          currentToolbarState[space] = currentToolbarState[space].filter(
            id => id != unifiedToolbarButtonId
          );
        }
      }

      // Update the cached values for the allowed spaces.
      cachedAllowedSpaces.set(this.extension.id, allowedSpaces);
      setCachedAllowedSpaces(cachedAllowedSpaces);

      if (missingSpacesInState.length || invalidSpacesInState.length) {
        storeState(currentToolbarState);
      } else {
        Services.obs.notifyObservers(null, "unified-toolbar-state-change");
      }
    }
  }

  close() {
    super.close();
    browserActionMap.delete(this.extension);
    windowTracker.removeListener("TabSelect", this);
    // Unregister the extension from the unified toolbar.
    if (this.windowURLs.includes(MAIN_WINDOW_URI)) {
      unregisterExtension(this.extension.id);
      Services.obs.notifyObservers(null, "unified-toolbar-state-change");
    }
  }

  constructor(extension) {
    super(extension, global);
    this.manifest_name =
      extension.manifestVersion < 3 ? "browser_action" : "action";
    this.manifestName =
      extension.manifestVersion < 3 ? "browserAction" : "action";
    this.manifest = extension.manifest[this.manifest_name];
    // browserAction was renamed to action in MV3, but its module name is
    // still "browserAction" because that is the name used in ext-mail.json,
    // independently from the manifest version.
    this.moduleName = "browserAction";

    this.windowURLs = [];
    if (this.manifest.default_windows.includes("normal")) {
      this.windowURLs.push(MAIN_WINDOW_URI);
    }
    if (this.manifest.default_windows.includes("messageDisplay")) {
      this.windowURLs.push(MESSAGE_WINDOW_URI);
    }

    this.toolboxId = "mail-toolbox";
    this.toolbarId = "mail-bar3";

    this.allowedSpaces =
      this.extension.manifest[this.manifest_name].allowed_spaces;

    windowTracker.addListener("TabSelect", this);
  }

  static onUpdate(extensionId, manifest) {
    // These manifest entries can exist and be null.
    if (!manifest.browser_action && !manifest.action) {
      this.#removeFromUnifiedToolbar(extensionId);
    }
  }

  static onUninstall(extensionId) {
    let widgetId = makeWidgetId(extensionId);
    let id = `${widgetId}-browserAction-toolbarbutton`;

    // Check all possible XUL toolbars and remove the toolbarbutton if found.
    // Sadly we have to hardcode these values here, as the add-on is already
    // shutdown when onUninstall is called.
    let toolbars = ["mail-bar3", "toolbar-menubar"];
    for (let toolbar of toolbars) {
      for (let setName of ["currentset", "extensionset"]) {
        let set = Services.xulStore
          .getValue(MESSAGE_WINDOW_URI, toolbar, setName)
          .split(",");
        let newSet = set.filter(e => e != id);
        if (newSet.length < set.length) {
          Services.xulStore.setValue(
            MESSAGE_WINDOW_URI,
            toolbar,
            setName,
            newSet.join(",")
          );
        }
      }
    }

    this.#removeFromUnifiedToolbar(extensionId);
  }

  static #removeFromUnifiedToolbar(extensionId) {
    const currentToolbarState = getState();
    const unifiedToolbarButtonId = `${EXTENSION_PREFIX}${extensionId}`;
    let modifiedState = false;
    for (const space of Object.keys(currentToolbarState)) {
      if (currentToolbarState[space].includes(unifiedToolbarButtonId)) {
        currentToolbarState[space].splice(
          currentToolbarState[space].indexOf(unifiedToolbarButtonId),
          1
        );
        modifiedState = true;
      }
    }
    if (modifiedState) {
      storeState(currentToolbarState);
    }

    // Update cachedAllowedSpaces for the unified toolbar.
    let cachedAllowedSpaces = getCachedAllowedSpaces();
    if (cachedAllowedSpaces.has(extensionId)) {
      cachedAllowedSpaces.delete(extensionId);
      setCachedAllowedSpaces(cachedAllowedSpaces);
    }
  }

  handleEvent(event) {
    super.handleEvent(event);
    let window = event.target.ownerGlobal;

    switch (event.type) {
      case "popupshowing":
        const menu = event.target;
        if (menu.tagName != "menupopup") {
          return;
        }

        // This needs to work in normal window and message window.
        let tab = tabTracker.activeTab;
        let browser = tab.linkedBrowser || tab.getBrowser?.();

        const trigger = menu.triggerNode;
        const node =
          window.document.getElementById(this.id) ||
          (this.windowURLs.includes(MAIN_WINDOW_URI) &&
            window.document.querySelector(
              `#unifiedToolbarContent [item-id="${EXTENSION_PREFIX}${this.extension.id}"]`
            ));
        const contexts = [
          "toolbar-context-menu",
          "customizationPanelItemContextMenu",
          "unifiedToolbarMenu",
        ];
        if (contexts.includes(menu.id) && node && node.contains(trigger)) {
          const action =
            this.extension.manifestVersion < 3 ? "onBrowserAction" : "onAction";
          global.actionContextMenu({
            tab,
            pageUrl: browser?.currentURI?.spec,
            extension: this.extension,
            [action]: true,
            menu,
          });
        }

        if (
          menu.dataset.actionMenu == this.manifestName &&
          this.extension.id == menu.dataset.extensionId
        ) {
          const action =
            this.extension.manifestVersion < 3
              ? "inBrowserActionMenu"
              : "inActionMenu";
          global.actionContextMenu({
            tab,
            pageUrl: browser?.currentURI?.spec,
            extension: this.extension,
            [action]: true,
            menu,
          });
        }
        break;
    }
  }
};

global.browserActionFor = this.browserAction.for;