summaryrefslogtreecommitdiffstats
path: root/mobile/android/modules/geckoview/GeckoViewTab.sys.mjs
blob: 53f43f153ce05f39c88999aae3c88479dadd9e46 (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
/* 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/. */

import { GeckoViewModule } from "resource://gre/modules/GeckoViewModule.sys.mjs";

import { ExtensionUtils } from "resource://gre/modules/ExtensionUtils.sys.mjs";

const { ExtensionError } = ExtensionUtils;

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  EventDispatcher: "resource://gre/modules/Messaging.sys.mjs",
  mobileWindowTracker: "resource://gre/modules/GeckoViewWebExtension.sys.mjs",
});

class Tab {
  constructor(window) {
    this.id = GeckoViewTabBridge.windowIdToTabId(window.docShell.outerWindowID);
    this.browser = window.browser;
    this.active = false;
  }

  get linkedBrowser() {
    return this.browser;
  }

  getActive() {
    return this.active;
  }

  get userContextId() {
    return this.browser.ownerGlobal.moduleManager.settings
      .unsafeSessionContextId;
  }
}

// Because of bug 1410749, we can't use 0, though, and just to be safe
// we choose a value that is unlikely to overlap with Fennec's tab IDs.
const TAB_ID_BASE = 10000;

export const GeckoViewTabBridge = {
  /**
   * Converts windowId to tabId as in GeckoView every browser window has exactly one tab.
   *
   * @param {number} windowId outerWindowId
   *
   * @returns {number} tabId
   */
  windowIdToTabId(windowId) {
    return TAB_ID_BASE + windowId;
  },

  /**
   * Converts tabId to windowId.
   *
   * @param {number} tabId
   *
   * @returns {number}
   *          outerWindowId of browser window to which the tab belongs.
   */
  tabIdToWindowId(tabId) {
    return tabId - TAB_ID_BASE;
  },

  /**
   * Delegates openOptionsPage handling to the app.
   *
   * @param {number} extensionId
   *        The ID of the extension requesting the options menu.
   *
   * @returns {Promise<Void>}
   *          A promise resolved after successful handling.
   */
  async openOptionsPage(extensionId) {
    debug`openOptionsPage for extensionId ${extensionId}`;

    try {
      await lazy.EventDispatcher.instance.sendRequestForResult({
        type: "GeckoView:WebExtension:OpenOptionsPage",
        extensionId,
      });
    } catch (errorMessage) {
      // The error message coming from GeckoView is about :OpenOptionsPage not
      // being registered so we need to have one that's extension friendly
      // here.
      throw new ExtensionError("runtime.openOptionsPage is not supported");
    }
  },

  /**
   * Request the GeckoView App to create a new tab (GeckoSession).
   *
   * @param {object} options
   * @param {string} options.extensionId
   *        The ID of the extension that requested a new tab.
   * @param {object} options.createProperties
   *        The properties for the new tab, see tabs.create reference for details.
   *
   * @returns {Promise<Tab>}
   *          A promise resolved to the newly created tab.
   * @throws {Error}
   *         Throws an error if the GeckoView app doesn't support tabs.create or fails to handle the request.
   */
  async createNewTab({ extensionId, createProperties } = {}) {
    debug`createNewTab`;

    const newSessionId = Services.uuid
      .generateUUID()
      .toString()
      .slice(1, -1)
      .replace(/-/g, "");

    // The window might already be open by the time we get the response, so we
    // need to start waiting before we send the message.
    const windowPromise = new Promise(resolve => {
      const handler = {
        observe(aSubject, aTopic, aData) {
          if (
            aTopic === "geckoview-window-created" &&
            aSubject.name === newSessionId
          ) {
            Services.obs.removeObserver(handler, "geckoview-window-created");
            resolve(aSubject);
          }
        },
      };
      Services.obs.addObserver(handler, "geckoview-window-created");
    });

    let didOpenSession = false;
    try {
      didOpenSession = await lazy.EventDispatcher.instance.sendRequestForResult(
        {
          type: "GeckoView:WebExtension:NewTab",
          extensionId,
          createProperties,
          newSessionId,
        }
      );
    } catch (errorMessage) {
      // The error message coming from GeckoView is about :NewTab not being
      // registered so we need to have one that's extension friendly here.
      throw new ExtensionError("tabs.create is not supported");
    }

    if (!didOpenSession) {
      throw new ExtensionError("Cannot create new tab");
    }

    const window = await windowPromise;
    if (!window.tab) {
      window.tab = new Tab(window);
    }
    return window.tab;
  },

  /**
   * Request the GeckoView App to close a tab (GeckoSession).
   *
   *
   * @param {object} options
   * @param {Window} options.window The window owning the tab to close
   * @param {string} options.extensionId
   *
   * @returns {Promise<Void>}
   *          A promise resolved after GeckoSession is closed.
   * @throws {Error}
   *         Throws an error if the GeckoView app doesn't allow extension to close tab.
   */
  async closeTab({ window, extensionId } = {}) {
    try {
      await window.WindowEventDispatcher.sendRequestForResult({
        type: "GeckoView:WebExtension:CloseTab",
        extensionId,
      });
    } catch (errorMessage) {
      throw new ExtensionError(errorMessage);
    }
  },

  async updateTab({ window, extensionId, updateProperties } = {}) {
    try {
      await window.WindowEventDispatcher.sendRequestForResult({
        type: "GeckoView:WebExtension:UpdateTab",
        extensionId,
        updateProperties,
      });
    } catch (errorMessage) {
      throw new ExtensionError(errorMessage);
    }
  },
};

export class GeckoViewTab extends GeckoViewModule {
  onInit() {
    const { window } = this;
    if (!window.tab) {
      window.tab = new Tab(window);
    }

    this.registerListener(["GeckoView:WebExtension:SetTabActive"]);
  }

  onEvent(aEvent, aData, aCallback) {
    debug`onEvent: event=${aEvent}, data=${aData}`;

    switch (aEvent) {
      case "GeckoView:WebExtension:SetTabActive": {
        const { active } = aData;
        lazy.mobileWindowTracker.setTabActive(this.window, active);
        break;
      }
    }
  }
}

const { debug, warn } = GeckoViewTab.initLogging("GeckoViewTab");