summaryrefslogtreecommitdiffstats
path: root/application/basilisk/components/webextensions/ext-windows.js
blob: 5956ae15bd25a40a2422900d0d7206a8cc398aa7 (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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";

XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
                                   "@mozilla.org/browser/aboutnewtab-service;1",
                                   "nsIAboutNewTabService");
XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
                                  "resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
                                  "resource://gre/modules/PrivateBrowsingUtils.jsm");

Cu.import("resource://gre/modules/ExtensionUtils.jsm");
var {
  EventManager,
  promiseObserved,
} = ExtensionUtils;

function onXULFrameLoaderCreated({target}) {
  target.messageManager.sendAsyncMessage("AllowScriptsToClose", {});
}

extensions.registerSchemaAPI("windows", "addon_parent", context => {
  let {extension} = context;
  return {
    windows: {
      onCreated:
      new WindowEventManager(context, "windows.onCreated", "domwindowopened", (fire, window) => {
        fire(WindowManager.convert(extension, window));
      }).api(),

      onRemoved:
      new WindowEventManager(context, "windows.onRemoved", "domwindowclosed", (fire, window) => {
        fire(WindowManager.getId(window));
      }).api(),

      onFocusChanged: new EventManager(context, "windows.onFocusChanged", fire => {
        // Keep track of the last windowId used to fire an onFocusChanged event
        let lastOnFocusChangedWindowId;

        let listener = event => {
          // Wait a tick to avoid firing a superfluous WINDOW_ID_NONE
          // event when switching focus between two Firefox windows.
          Promise.resolve().then(() => {
            let window = Services.focus.activeWindow;
            let windowId = window ? WindowManager.getId(window) : WindowManager.WINDOW_ID_NONE;
            if (windowId !== lastOnFocusChangedWindowId) {
              fire(windowId);
              lastOnFocusChangedWindowId = windowId;
            }
          });
        };
        AllWindowEvents.addListener("focus", listener);
        AllWindowEvents.addListener("blur", listener);
        return () => {
          AllWindowEvents.removeListener("focus", listener);
          AllWindowEvents.removeListener("blur", listener);
        };
      }).api(),

      get: function(windowId, getInfo) {
        let window = WindowManager.getWindow(windowId, context);
        return Promise.resolve(WindowManager.convert(extension, window, getInfo));
      },

      getCurrent: function(getInfo) {
        let window = currentWindow(context);
        return Promise.resolve(WindowManager.convert(extension, window, getInfo));
      },

      getLastFocused: function(getInfo) {
        let window = WindowManager.topWindow;
        return Promise.resolve(WindowManager.convert(extension, window, getInfo));
      },

      getAll: function(getInfo) {
        let windows = Array.from(WindowListManager.browserWindows(),
                                 window => WindowManager.convert(extension, window, getInfo));
        return Promise.resolve(windows);
      },

      create: function(createData) {
        let needResize = (createData.left !== null || createData.top !== null ||
                          createData.width !== null || createData.height !== null);

        if (needResize) {
          if (createData.state !== null && createData.state != "normal") {
            return Promise.reject({message: `"state": "${createData.state}" may not be combined with "left", "top", "width", or "height"`});
          }
          createData.state = "normal";
        }

        function mkstr(s) {
          let result = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
          result.data = s;
          return result;
        }

        let args = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);

        if (createData.tabId !== null) {
          if (createData.url !== null) {
            return Promise.reject({message: "`tabId` may not be used in conjunction with `url`"});
          }

          if (createData.allowScriptsToClose) {
            return Promise.reject({message: "`tabId` may not be used in conjunction with `allowScriptsToClose`"});
          }

          let tab = TabManager.getTab(createData.tabId, context);

          // Private browsing tabs can only be moved to private browsing
          // windows.
          let incognito = PrivateBrowsingUtils.isBrowserPrivate(tab.linkedBrowser);
          if (createData.incognito !== null && createData.incognito != incognito) {
            return Promise.reject({message: "`incognito` property must match the incognito state of tab"});
          }
          createData.incognito = incognito;

          args.appendElement(tab, /* weak = */ false);
        } else if (createData.url !== null) {
          if (Array.isArray(createData.url)) {
            let array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
            for (let url of createData.url) {
              array.appendElement(mkstr(url), /* weak = */ false);
            }
            args.appendElement(array, /* weak = */ false);
          } else {
            args.appendElement(mkstr(createData.url), /* weak = */ false);
          }
        } else {
          args.appendElement(mkstr(aboutNewTabService.newTabURL), /* weak = */ false);
        }

        let features = ["chrome"];

        if (createData.type === null || createData.type == "normal") {
          features.push("dialog=no", "all");
        } else {
          // All other types create "popup"-type windows by default.
          features.push("dialog", "resizable", "minimizable", "centerscreen", "titlebar", "close");
        }

        if (createData.incognito !== null) {
          if (createData.incognito) {
            features.push("private");
          } else {
            features.push("non-private");
          }
        }

        let {allowScriptsToClose, url} = createData;
        if (allowScriptsToClose === null) {
          allowScriptsToClose = typeof url === "string" && url.startsWith("moz-extension://");
        }

        let window = Services.ww.openWindow(null, "chrome://browser/content/browser.xul", "_blank",
                                            features.join(","), args);

        WindowManager.updateGeometry(window, createData);

        // TODO: focused, type

        return new Promise(resolve => {
          window.addEventListener("load", function listener() {
            window.removeEventListener("load", listener);
            if (["maximized", "normal"].includes(createData.state)) {
              window.document.documentElement.setAttribute("sizemode", createData.state);
            }
            resolve(promiseObserved("browser-delayed-startup-finished", win => win == window));
          });
        }).then(() => {
          // Some states only work after delayed-startup-finished
          if (["minimized", "fullscreen", "docked"].includes(createData.state)) {
            WindowManager.setState(window, createData.state);
          }
          if (allowScriptsToClose) {
            for (let {linkedBrowser} of window.gBrowser.tabs) {
              onXULFrameLoaderCreated({target: linkedBrowser});
              linkedBrowser.addEventListener( // eslint-disable-line mozilla/balanced-listeners
                                             "XULFrameLoaderCreated", onXULFrameLoaderCreated);
            }
          }
          return WindowManager.convert(extension, window, {populate: true});
        });
      },

      update: function(windowId, updateInfo) {
        if (updateInfo.state !== null && updateInfo.state != "normal") {
          if (updateInfo.left !== null || updateInfo.top !== null ||
              updateInfo.width !== null || updateInfo.height !== null) {
            return Promise.reject({message: `"state": "${updateInfo.state}" may not be combined with "left", "top", "width", or "height"`});
          }
        }

        let window = WindowManager.getWindow(windowId, context);
        if (updateInfo.focused) {
          Services.focus.activeWindow = window;
        }

        if (updateInfo.state !== null) {
          WindowManager.setState(window, updateInfo.state);
        }

        if (updateInfo.drawAttention) {
          // Bug 1257497 - Firefox can't cancel attention actions.
          window.getAttention();
        }

        WindowManager.updateGeometry(window, updateInfo);

        // TODO: All the other properties, focused=false...

        return Promise.resolve(WindowManager.convert(extension, window));
      },

      remove: function(windowId) {
        let window = WindowManager.getWindow(windowId, context);
        window.close();

        return new Promise(resolve => {
          let listener = () => {
            AllWindowEvents.removeListener("domwindowclosed", listener);
            resolve();
          };
          AllWindowEvents.addListener("domwindowclosed", listener);
        });
      },
    },
  };
});