summaryrefslogtreecommitdiffstats
path: root/comm/mail/components/extensions/ExtensionToolbarButtons.jsm
blob: 86e66e06e99882922adafcb47a2cfb2328a378c6 (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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
/* -*- 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";

const EXPORTED_SYMBOLS = [
  "ToolbarButtonAPI",
  "getIconData",
  "getCachedAllowedSpaces",
  "setCachedAllowedSpaces",
];

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  ViewPopup: "resource:///modules/ExtensionPopups.sys.mjs",
});
ChromeUtils.defineModuleGetter(
  lazy,
  "ExtensionSupport",
  "resource:///modules/ExtensionSupport.jsm"
);
const { ExtensionCommon } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionCommon.sys.mjs"
);
const { ExtensionUtils } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionUtils.sys.mjs"
);
const { ExtensionParent } = ChromeUtils.importESModule(
  "resource://gre/modules/ExtensionParent.sys.mjs"
);

var { EventManager, ExtensionAPIPersistent, makeWidgetId } = ExtensionCommon;

var { IconDetails, StartupCache } = ExtensionParent;

var { DefaultWeakMap, ExtensionError } = ExtensionUtils;

var DEFAULT_ICON = "chrome://messenger/content/extension.svg";

function getCachedAllowedSpaces() {
  let cache = {};
  if (
    Services.xulStore.hasValue(
      "chrome://messenger/content/messenger.xhtml",
      "unifiedToolbar",
      "allowedExtSpaces"
    )
  ) {
    let rawCache = Services.xulStore.getValue(
      "chrome://messenger/content/messenger.xhtml",
      "unifiedToolbar",
      "allowedExtSpaces"
    );
    cache = JSON.parse(rawCache);
  }
  return new Map(Object.entries(cache));
}

function setCachedAllowedSpaces(allowedSpacesMap) {
  Services.xulStore.setValue(
    "chrome://messenger/content/messenger.xhtml",
    "unifiedToolbar",
    "allowedExtSpaces",
    JSON.stringify(Object.fromEntries(allowedSpacesMap))
  );
}

/**
 * Get icon properties for updating the UI.
 *
 * @param {object} icons
 *        Contains the icon information, typically the extension manifest
 */
function getIconData(icons, extension) {
  let baseSize = 16;
  let { icon, size } = IconDetails.getPreferredIcon(icons, extension, baseSize);

  let legacy = false;

  // If the best available icon size is not divisible by 16, check if we have
  // an 18px icon to fall back to, and trim off the padding instead.
  if (size % 16 && typeof icon === "string" && !icon.endsWith(".svg")) {
    let result = IconDetails.getPreferredIcon(icons, extension, 18);

    if (result.size % 18 == 0) {
      baseSize = 18;
      icon = result.icon;
      legacy = true;
    }
  }

  let getIcon = (size, theme) => {
    let { icon } = IconDetails.getPreferredIcon(icons, extension, size);
    if (typeof icon === "object") {
      if (icon[theme] == IconDetails.DEFAULT_ICON) {
        icon[theme] = DEFAULT_ICON;
      }
      return IconDetails.escapeUrl(icon[theme]);
    }
    if (icon == IconDetails.DEFAULT_ICON) {
      return DEFAULT_ICON;
    }
    return IconDetails.escapeUrl(icon);
  };

  let style = [];
  let getStyle = (name, size) => {
    style.push([
      `--webextension-${name}`,
      `url("${getIcon(size, "default")}")`,
    ]);
    style.push([
      `--webextension-${name}-light`,
      `url("${getIcon(size, "light")}")`,
    ]);
    style.push([
      `--webextension-${name}-dark`,
      `url("${getIcon(size, "dark")}")`,
    ]);
  };

  getStyle("menupanel-image", 32);
  getStyle("menupanel-image-2x", 64);
  getStyle("toolbar-image", baseSize);
  getStyle("toolbar-image-2x", baseSize * 2);

  let realIcon = getIcon(size, "default");

  return { style, legacy, realIcon };
}

var ToolbarButtonAPI = class extends ExtensionAPIPersistent {
  constructor(extension, global) {
    super(extension);
    this.global = global;
    this.tabContext = new this.global.TabContext(target =>
      this.getContextData(null)
    );
  }

  /**
   * If this action is available in the unified toolbar.
   *
   * @type {boolean}
   */
  inUnifiedToolbar = false;

  /**
   * Called when the extension is enabled.
   *
   * @param {string} entryName
   *        The name of the property in the extension manifest
   */
  async onManifestEntry(entryName) {
    let { extension } = this;
    this.paint = this.paint.bind(this);
    this.unpaint = this.unpaint.bind(this);

    if (this.manifest?.type == "menu" && this.manifest.default_popup) {
      console.warn(
        `The "default_popup" manifest entry is not supported for action buttons with type "menu".`
      );
    }

    this.widgetId = makeWidgetId(extension.id);
    this.id = `${this.widgetId}-${this.moduleName}-toolbarbutton`;
    this.eventQueue = [];

    let options = extension.manifest[entryName];
    this.defaults = {
      enabled: true,
      label: options.default_label,
      title: options.default_title || extension.name,
      badgeText: "",
      badgeBackgroundColor: null,
      popup: options.default_popup || "",
      type: options.type,
    };
    this.globals = Object.create(this.defaults);

    this.browserStyle = options.browser_style;

    this.defaults.icon = await StartupCache.get(
      extension,
      [this.manifestName, "default_icon"],
      () =>
        IconDetails.normalize(
          {
            path: options.default_icon,
            iconType: this.manifestName,
            themeIcons: options.theme_icons,
          },
          extension
        )
    );

    this.iconData = new DefaultWeakMap(icons => getIconData(icons, extension));
    this.iconData.set(
      this.defaults.icon,
      await StartupCache.get(
        extension,
        [this.manifestName, "default_icon_data"],
        () => getIconData(this.defaults.icon, extension)
      )
    );

    lazy.ExtensionSupport.registerWindowListener(this.id, {
      chromeURLs: this.windowURLs,
      onLoadWindow: window => {
        this.paint(window);
      },
    });

    extension.callOnClose(this);
  }

  /**
   * Called when the extension is disabled or removed.
   */
  close() {
    lazy.ExtensionSupport.unregisterWindowListener(this.id);
    for (let window of lazy.ExtensionSupport.openWindows) {
      if (this.windowURLs.includes(window.location.href)) {
        this.unpaint(window);
      }
    }
  }

  /**
   * Creates a toolbar button.
   *
   * @param {Window} window
   */
  makeButton(window) {
    let { document } = window;
    let button;
    switch (this.globals.type) {
      case "menu":
        {
          button = document.createXULElement("toolbarbutton");
          button.setAttribute("type", "menu");
          button.setAttribute("wantdropmarker", "true");
          let menupopup = document.createXULElement("menupopup");
          menupopup.dataset.actionMenu = this.manifestName;
          menupopup.dataset.extensionId = this.extension.id;
          button.appendChild(menupopup);
        }
        break;
      case "button":
        button = document.createXULElement("toolbarbutton");
        break;
    }
    button.id = this.id;
    button.classList.add("toolbarbutton-1");
    button.classList.add("webextension-action");
    button.setAttribute("badged", "true");
    button.setAttribute("data-extensionid", this.extension.id);
    button.addEventListener("mousedown", this);
    this.updateButton(button, this.globals);
    return button;
  }

  /**
   * Returns an element in the toolbar, which is to be used as default insertion
   * point for new toolbar buttons in non-customizable toolbars.
   *
   * May return null to append new buttons to the end of the toolbar.
   *
   * @param {DOMElement} toolbar - a toolbar node
   * @returns {DOMElement} a node which is to be used as insertion point, or null
   */
  getNonCustomizableToolbarInsertionPoint(toolbar) {
    return null;
  }

  /**
   * Adds a toolbar button to a customizable toolbar in this window.
   *
   * @param {Window} window
   */
  customizableToolbarPaint(window) {
    let windowURL = window.location.href;
    let { document } = window;
    if (document.getElementById(this.id)) {
      return;
    }

    let toolbox = document.getElementById(this.toolboxId);
    if (!toolbox) {
      return;
    }

    // Get all toolbars which link to or are children of this.toolboxId and check
    // if the button has been moved to a non-default toolbar.
    let toolbars = window.document.querySelectorAll(
      `#${this.toolboxId} toolbar, toolbar[toolboxid="${this.toolboxId}"]`
    );
    for (let toolbar of toolbars) {
      let currentSet = Services.xulStore
        .getValue(windowURL, toolbar.id, "currentset")
        .split(",")
        .filter(Boolean);
      if (currentSet.includes(this.id)) {
        this.toolbarId = toolbar.id;
        break;
      }
    }

    let toolbar = document.getElementById(this.toolbarId);
    let button = this.makeButton(window);
    if (toolbox.palette) {
      toolbox.palette.appendChild(button);
    } else {
      toolbar.appendChild(button);
    }

    // Handle the special case where this toolbar does not yet have a currentset
    // defined.
    if (!Services.xulStore.hasValue(windowURL, this.toolbarId, "currentset")) {
      let defaultSet = toolbar
        .getAttribute("defaultset")
        .split(",")
        .filter(Boolean);
      Services.xulStore.setValue(
        windowURL,
        this.toolbarId,
        "currentset",
        defaultSet.join(",")
      );
    }

    // Add new buttons to currentset: If the extensionset does not include the
    // button, it is a new one which needs to be added.
    let extensionSet = Services.xulStore
      .getValue(windowURL, this.toolbarId, "extensionset")
      .split(",")
      .filter(Boolean);
    if (!extensionSet.includes(this.id)) {
      extensionSet.push(this.id);
      Services.xulStore.setValue(
        windowURL,
        this.toolbarId,
        "extensionset",
        extensionSet.join(",")
      );
      let currentSet = Services.xulStore
        .getValue(windowURL, this.toolbarId, "currentset")
        .split(",")
        .filter(Boolean);
      if (!currentSet.includes(this.id)) {
        currentSet.push(this.id);
        Services.xulStore.setValue(
          windowURL,
          this.toolbarId,
          "currentset",
          currentSet.join(",")
        );
      }
    }

    let currentSet = Services.xulStore.getValue(
      windowURL,
      this.toolbarId,
      "currentset"
    );

    toolbar.currentSet = currentSet;
    toolbar.setAttribute("currentset", toolbar.currentSet);

    if (this.extension.hasPermission("menus")) {
      document.addEventListener("popupshowing", this);
    }
  }

  /**
   * Adds a toolbar button to a non-customizable toolbar in this window.
   *
   * @param {Window} window
   */
  nonCustomizableToolbarPaint(window) {
    let { document } = window;
    let windowURL = window.location.href;
    if (document.getElementById(this.id)) {
      return;
    }
    let toolbar = document.getElementById(this.toolbarId);
    let before = this.getNonCustomizableToolbarInsertionPoint(toolbar);
    let button = this.makeButton(window);
    let currentSet = Services.xulStore
      .getValue(windowURL, toolbar.id, "currentset")
      .split(",")
      .filter(Boolean);
    if (!currentSet.includes(this.id)) {
      currentSet.push(this.id);
      Services.xulStore.setValue(
        windowURL,
        toolbar.id,
        "currentset",
        currentSet.join(",")
      );
    } else {
      for (let id of [...currentSet].reverse()) {
        if (!id.endsWith(`-${this.manifestName}-toolbarbutton`)) {
          continue;
        }
        if (id == this.id) {
          break;
        }
        let element = document.getElementById(id);
        if (element) {
          before = element;
        }
      }
    }
    toolbar.insertBefore(button, before);

    if (this.extension.hasPermission("menus")) {
      document.addEventListener("popupshowing", this);
    }
  }

  /**
   * Adds a toolbar button to a toolbar in this window.
   *
   * @param {Window} window
   */
  paint(window) {
    let toolbar = window.document.getElementById(this.toolbarId);
    if (toolbar.hasAttribute("customizable")) {
      return this.customizableToolbarPaint(window);
    }
    return this.nonCustomizableToolbarPaint(window);
  }

  /**
   * Removes the toolbar button from this window.
   *
   * @param {Window} window
   */
  unpaint(window) {
    let { document } = window;

    if (this.extension.hasPermission("menus")) {
      document.removeEventListener("popupshowing", this);
    }

    let button = document.getElementById(this.id);
    if (button) {
      button.remove();
    }
  }

  /**
   * 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) {
    let button = window.document.getElementById(this.id);
    let toolbar = button?.closest("toolbar");
    return button && !toolbar?.collapsed ? button : null;
  }

  /**
   * 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.
   *
   * @param {Window} window
   * @param {object} options
   * @param {boolean} options.requirePopupUrl - do not fall back to emitting an
   *                                            onClickedEvent, if no popupURL is
   *                                            set and consider this action fail
   *
   * @returns {boolean} status if action could be successfully triggered
   */
  async triggerAction(window, options = {}) {
    let button = this.getToolbarButton(window);
    let { popup: popupURL, enabled } = this.getContextData(
      this.getTargetFromWindow(window)
    );

    let success = false;
    if (button && enabled) {
      window.focus();

      if (popupURL) {
        success = true;
        let popup =
          lazy.ViewPopup.for(this.extension, window.top) ||
          this.getPopup(window.top, popupURL);
        popup.viewNode.openPopup(button, "bottomleft topleft", 0, 0);
      } else if (!options.requirePopupUrl) {
        if (!this.lastClickInfo) {
          this.lastClickInfo = { button: 0, modifiers: [] };
        }
        this.emit("click", window.top, this.lastClickInfo);
        success = true;
      }
    }

    delete this.lastClickInfo;
    return success;
  }

  /**
   * Event listener.
   *
   * @param {Event} event
   */
  handleEvent(event) {
    let window = event.target.ownerGlobal;
    switch (event.type) {
      case "click":
      case "mousedown":
        if (event.button == 0) {
          // Bail out, if this is a menu typed action button or any of its menu entries.
          if (
            event.target.tagName == "menu" ||
            event.target.tagName == "menuitem" ||
            event.target.getAttribute("type") == "menu"
          ) {
            return;
          }

          this.lastClickInfo = {
            button: 0,
            modifiers: this.global.clickModifiersFromEvent(event),
          };
          this.triggerAction(window);
        }
        break;
      case "TabSelect":
        this.updateWindow(window);
        break;
    }
  }

  /**
   * Returns a potentially pre-loaded popup for the given URL in the given
   * window. If a matching pre-load popup already exists, returns that.
   * Otherwise, initializes a new one.
   *
   * If a pre-load popup exists which does not match, it is destroyed before a
   * new one is created.
   *
   * @param {Window} window
   *        The browser window in which to create the popup.
   * @param {string} popupURL
   *        The URL to load into the popup.
   * @param {boolean} [blockParser = false]
   *        True if the HTML parser should initially be blocked.
   * @returns {ViewPopup}
   */
  getPopup(window, popupURL, blockParser = false) {
    let popup = new lazy.ViewPopup(
      this.extension,
      window,
      popupURL,
      this.browserStyle,
      false,
      blockParser
    );
    popup.ignoreResizes = false;
    return popup;
  }

  /**
   * Update the toolbar button |node| with the tab context data
   * in |tabData|.
   *
   * @param {XULElement} node
   *        XUL toolbarbutton to update
   * @param {object} tabData
   *        Properties to set
   * @param {boolean} sync
   *        Whether to perform the update immediately
   */
  updateButton(node, tabData, sync = false) {
    let title = tabData.title || this.extension.name;
    let label = tabData.label;
    let callback = () => {
      node.setAttribute("tooltiptext", title);
      node.setAttribute("label", label || title);
      node.setAttribute(
        "hideWebExtensionLabel",
        label === "" ? "true" : "false"
      );

      if (tabData.badgeText) {
        node.setAttribute("badge", tabData.badgeText);
      } else {
        node.removeAttribute("badge");
      }

      if (tabData.enabled) {
        node.removeAttribute("disabled");
      } else {
        node.setAttribute("disabled", "true");
      }

      let color = tabData.badgeBackgroundColor;
      if (color) {
        color = `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${
          color[3] / 255
        })`;
        node.setAttribute("badgeStyle", `background-color: ${color};`);
      } else {
        node.removeAttribute("badgeStyle");
      }

      let { style } = this.iconData.get(tabData.icon);

      for (let [name, value] of style) {
        node.style.setProperty(name, value);
      }
    };
    if (sync) {
      callback();
    } else {
      node.ownerGlobal.requestAnimationFrame(callback);
    }
  }

  /**
   * Update the toolbar button for a given window.
   *
   * @param {ChromeWindow} window
   *        Browser chrome window.
   */
  async updateWindow(window) {
    let button = this.getToolbarButton(window);
    if (button) {
      let tabData = this.getContextData(this.getTargetFromWindow(window));
      this.updateButton(button, tabData);
    }
    await new Promise(window.requestAnimationFrame);
  }

  /**
   * Update the toolbar button when the extension changes the icon, title, url, etc.
   * If it only changes a parameter for a single tab, `target` will be that tab.
   * If it only changes a parameter for a single window, `target` will be that window.
   * Otherwise `target` will be null.
   *
   * @param {XULElement|ChromeWindow|null} target
   *        Browser tab or browser chrome window, may be null.
   */
  async updateOnChange(target) {
    if (target) {
      let window = Cu.getGlobalForObject(target);
      if (target === window) {
        await this.updateWindow(window);
      } else {
        let tabmail = window.document.getElementById("tabmail");
        if (tabmail && target == tabmail.selectedTab) {
          await this.updateWindow(window);
        }
      }
    } else {
      let promises = [];
      for (let window of lazy.ExtensionSupport.openWindows) {
        if (this.windowURLs.includes(window.location.href)) {
          promises.push(this.updateWindow(window));
        }
      }
      await Promise.all(promises);
    }
  }

  /**
   * Gets the active tab of the passed window if the window has tabs, or the
   * window itself.
   *
   * @param {ChromeWindow} window
   * @returns {XULElement|ChromeWindow}
   */
  getTargetFromWindow(window) {
    let tabmail = window.top.document.getElementById("tabmail");
    if (!tabmail) {
      return window.top;
    }

    if (window == window.top) {
      return tabmail.currentTabInfo;
    }
    if (window.parent != window.top) {
      window = window.parent;
    }
    return tabmail.tabInfo.find(t => t.chromeBrowser?.contentWindow == window);
  }

  /**
   * Gets the target object corresponding to the `details` parameter of the various
   * get* and set* API methods.
   *
   * @param {object} details
   *        An object with optional `tabId` or `windowId` properties.
   * @throws if `windowId` is specified, this is not valid in Thunderbird.
   * @returns {XULElement|ChromeWindow|null}
   *        If a `tabId` was specified, the corresponding XULElement tab.
   *        If a `windowId` was specified, the corresponding ChromeWindow.
   *        Otherwise, `null`.
   */
  getTargetFromDetails({ tabId, windowId }) {
    if (windowId != null) {
      throw new ExtensionError("windowId is not allowed, use tabId instead.");
    }
    if (tabId != null) {
      return this.global.tabTracker.getTab(tabId);
    }
    return null;
  }

  /**
   * Gets the data associated with a tab, window, or the global one.
   *
   * @param {XULElement|ChromeWindow|null} target
   *        A XULElement tab, a ChromeWindow, or null for the global data.
   * @returns {object}
   *        The icon, title, badge, etc. associated with the target.
   */
  getContextData(target) {
    if (target) {
      return this.tabContext.get(target);
    }
    return this.globals;
  }

  /**
   * Set a global, window specific or tab specific property.
   *
   * @param {object} details
   *        An object with optional `tabId` or `windowId` properties.
   * @param {string} prop
   *        String property to set. Should should be one of "icon", "title", "label",
   *        "badgeText", "popup", "badgeBackgroundColor" or "enabled".
   * @param {string} value
   *        Value for prop.
   */
  async setProperty(details, prop, value) {
    let target = this.getTargetFromDetails(details);
    let values = this.getContextData(target);
    if (value === null) {
      delete values[prop];
    } else {
      values[prop] = value;
    }

    await this.updateOnChange(target);
  }

  /**
   * Retrieve the value of a global, window specific or tab specific property.
   *
   * @param {object} details
   *        An object with optional `tabId` or `windowId` properties.
   * @param {string} prop
   *        String property to retrieve. Should should be one of "icon", "title", "label",
   *        "badgeText", "popup", "badgeBackgroundColor" or "enabled".
   * @returns {string} value
   *          Value of prop.
   */
  getProperty(details, prop) {
    return this.getContextData(this.getTargetFromDetails(details))[prop];
  }

  PERSISTENT_EVENTS = {
    onClicked({ context, fire }) {
      const { extension } = this;
      const { tabManager, windowManager } = extension;

      async function listener(_event, window, clickInfo) {
        if (fire.wakeup) {
          await fire.wakeup();
        }

        // TODO: We should double-check if the tab is already being closed by the time
        // the background script got started and we converted the primed listener.

        let win = windowManager.wrapWindow(window);
        fire.sync(tabManager.convert(win.activeTab.nativeTab), clickInfo);
      }
      this.on("click", listener);
      return {
        unregister: () => {
          this.off("click", listener);
        },
        convert(newFire, extContext) {
          fire = newFire;
          context = extContext;
        },
      };
    },
  };

  /**
   * WebExtension API.
   *
   * @param {object} context
   */
  getAPI(context) {
    let { extension } = context;

    let action = this;

    return {
      [this.manifestName]: {
        onClicked: new EventManager({
          context,
          module: this.moduleName,
          event: "onClicked",
          inputHandling: true,
          extensionApi: this,
        }).api(),

        async enable(tabId) {
          await action.setProperty({ tabId }, "enabled", true);
        },

        async disable(tabId) {
          await action.setProperty({ tabId }, "enabled", false);
        },

        isEnabled(details) {
          return action.getProperty(details, "enabled");
        },

        async setTitle(details) {
          await action.setProperty(details, "title", details.title);
        },

        getTitle(details) {
          return action.getProperty(details, "title");
        },

        async setLabel(details) {
          await action.setProperty(details, "label", details.label);
        },

        getLabel(details) {
          return action.getProperty(details, "label");
        },

        async setIcon(details) {
          details.iconType = this.manifestName;

          let icon = IconDetails.normalize(details, extension, context);
          if (!Object.keys(icon).length) {
            icon = null;
          }
          await action.setProperty(details, "icon", icon);
        },

        async setBadgeText(details) {
          await action.setProperty(details, "badgeText", details.text);
        },

        getBadgeText(details) {
          return action.getProperty(details, "badgeText");
        },

        async setPopup(details) {
          if (this.manifest?.type == "menu") {
            console.warn(
              `Popups are not supported for action buttons with type "menu".`
            );
          }

          // Note: Chrome resolves arguments to setIcon relative to the calling
          // context, but resolves arguments to setPopup relative to the extension
          // root.
          // For internal consistency, we currently resolve both relative to the
          // calling context.
          let url = details.popup && context.uri.resolve(details.popup);
          if (url && !context.checkLoadURL(url)) {
            return Promise.reject({ message: `Access denied for URL ${url}` });
          }
          await action.setProperty(details, "popup", url);
          return Promise.resolve(null);
        },

        getPopup(details) {
          if (this.manifest?.type == "menu") {
            console.warn(
              `Popups are not supported for action buttons with type "menu".`
            );
          }

          return action.getProperty(details, "popup");
        },

        async setBadgeBackgroundColor(details) {
          let color = details.color;
          if (typeof color == "string") {
            let col = InspectorUtils.colorToRGBA(color);
            if (!col) {
              throw new ExtensionError(
                `Invalid badge background color: "${color}"`
              );
            }
            color = col && [col.r, col.g, col.b, Math.round(col.a * 255)];
          }
          await action.setProperty(details, "badgeBackgroundColor", color);
        },

        getBadgeBackgroundColor(details, callback) {
          let color = action.getProperty(details, "badgeBackgroundColor");
          return color || [0xd9, 0, 0, 255];
        },

        openPopup(options) {
          if (this.manifest?.type == "menu") {
            console.warn(
              `Popups are not supported for action buttons with type "menu".`
            );
            return false;
          }

          let window;
          if (options?.windowId) {
            window = action.global.windowTracker.getWindow(
              options.windowId,
              context
            );
            if (!window) {
              return Promise.reject({
                message: `Invalid window ID: ${options.windowId}`,
              });
            }
          } else {
            window = Services.wm.getMostRecentWindow("");
          }

          // When triggering the action here, we consider a missing popupUrl as a failure and will not
          // cause an onClickedEvent.
          return action.triggerAction(window, { requirePopupUrl: true });
        },
      },
    };
  }
};