forked from Quicksaver/Tab-Groups
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bootstrap.js
362 lines (307 loc) · 13.4 KB
/
bootstrap.js
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
/* 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/. */
// VERSION 1.8.10
// This looks for file defaults.js in resource folder, expects:
// objName - (string) main object name for the add-on, to be added to window element
// objPathString - (string) add-on path name to use in URIs
// addonUUID = (string) used to register the add-on's about: uri; must be unique for each add-on! See http://www.famkruithof.net/uuid/uuidgen for generating one
// prefList - (object) { prefName: defaultValue } - add-on preferences
// paneList - (iterable) of array with a panes arguments to apply to PrefPanes.setList(); see PrefPanes.jsm
// addonUris - (object) containing any of the following string properties
// homepage: add-on homepage
// support: add-on support page
// fullchangelog: add-on detailed changelog (usually github commits page)
// email: developer e-mail
// profile: developer profile or homepage
// api: address from where it should fetch the data for the About pane's current development state
// development: where the follow ongoing add-on development
// startConditions(aData, aReason) - (optional) (method) should return false if any requirements the add-on needs aren't met,
// otherwise return true or call continueStartup(aData, aReason)
// onStartup/onShutdown/onInstall/onUninstall(aData, aReason) - (optional) (methods) to be called appropriately as their name suggest
// handleDeadObject(ex) - expects [nsIScriptError object] ex. Shows dead object notices as warnings only in the console.
// If the code can handle them accordingly and firefox does its thing, they shouldn't cause any problems.
// prepareObject(window, aName) - initializes a window-dependent add-on object with utils loaded into it, returns the newly created object
// window - (xul object) the window object to be initialized
// (optional) aName - (string) the object name, defaults to objName
// removeObject(window, aName) - closes and removes the object initialized by prepareObject()
// see prepareObject()
// preparePreferences(window, aName) - loads the preferencesUtils module into that window's object initialized by prepareObject() (if it hasn't yet, it will be initialized)
// see prepareObject()
// listenOnce(aSubject, type, handler, capture) - adds handler to window listening to event type that will be removed after one execution.
// aSubject - (xul object) to add the handler to
// type - (string) event type to listen to
// handler - (function(event, aSubject)) - method to be called when event is triggered
// (optional) capture - (bool) capture mode
// callOnLoad(aSubject, aCallback, beforeComplete) - calls aCallback immediately if aWindow is already loaded, otherwise waits for the load event to be fired on that window.
// aSubject - (xul object) to execute aCallback on
// aCallback - (function(aSubject)) to be called on aSubject
// (optional) beforeComplete - (bool) if true, aCallback will be called on aSubject immediately, regardless of its readyState value; defaults to false.
// disable() - disables the add-on, in general the add-on disabling itself is a bad idea so I shouldn't use it
var UNLOADED = false;
var STARTED = false;
var Addon = {};
var AddonData = null;
var onceListeners = [];
var alwaysRunOnShutdown = [];
var MessengerLoaded = false;
var isChrome = true;
var isContent = false;
// Globals - lets me use objects that I can share through all the windows
var Globals = {};
// actual add-on data, to be overriden by defaults.js
var objName = null;
var objPathString = null;
var prefList = null;
var paneList = null;
var addonUUID = null;
// add-on relevant links, to be overriden by defaults.js
var addonUris = {
homepage: '',
support: '',
fullchangelog: '',
email: '',
profile: '',
api: '',
development: ''
};
var {classes: Cc, interfaces: Ci, utils: Cu, manager: Cm, results: Cr} = Components;
var {XPCOMUtils} = ChromeUtils.importESModule("resource://gre/modules/XPCOMUtils.sys.mjs");
ChromeUtils.defineESModuleGetters(this, {AddonManager: "resource://gre/modules/AddonManager.sys.mjs",
PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs",
// easy and useful helpers for when I'm debugging
console: "resource://gre/modules/Console.sys.mjs"});
function LOG(str) {
if(!str) { str = typeof(str)+': '+str; }
console.log(objName+' :: CHROME :: '+str);
}
function STEPLOGGER(name) {
this.name = name;
this.steps = [];
this.initTime = new Date().getTime();
this.lastTime = this.initTime;
}
STEPLOGGER.prototype = {
step: function(name) {
let time = new Date().getTime();
this.steps.push({ name, time: time - this.lastTime});
this.lastTime = time;
},
end: function() {
this.step('end');
let endTime = new Date().getTime();
let report = { name: this.name, total: endTime - this.initTime };
for(let x of this.steps) {
report[x.name] = x.time;
}
console.log(report);
}
};
XPCOMUtils.defineLazyServiceGetter(Services, "navigator", "@mozilla.org/network/protocol;1?name=http", "nsIHttpProtocolHandler");
XPCOMUtils.defineLazyServiceGetter(Services, "stylesheet", "@mozilla.org/content/style-sheet-service;1", "nsIStyleSheetService");
// I check these pretty much everywhere, so might as well keep a single reference to them
var WINNT = Services.appinfo.OS == 'WINNT';
var DARWIN = Services.appinfo.OS == 'Darwin';
var LINUX = !WINNT && !DARWIN;
function handleDeadObject(ex) {
if(ex.message == "can't access dead object") {
let scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
scriptError.init("Can't access dead object. This shouldn't cause any problems.", ex.sourceName || ex.fileName || null, ex.sourceLine || null, ex.lineNumber || null, ex.columnNumber || null, scriptError.warningFlag, 'XPConnect JavaScript');
Services.console.logMessage(scriptError);
return true;
} else {
Cu.reportError(ex);
return false;
}
}
function prepareObject(window, aName) {
// I can override the object name if I want
let objectName = aName || objName;
if(window[objectName]) { return; }
var rtl = getComputedStyle(window.document.documentElement).direction == 'rtl';
window[objectName] = {
objName: objectName,
objPathString: objPathString,
_UUID: new Date().getTime(),
RTL: rtl,
LTR: !rtl,
// every supposedly global variable is inaccessible because bootstraped means sandboxed, so I have to reference all these;
// it's easier to reference more specific objects from within the modules for better control, only setting these two here because they're more generalized
window: window,
get document () { return window.document; },
$: function(id) { return window.document.getElementById(id); },
$$: function(sel, parent = window.document) { return parent.querySelectorAll(sel); },
$ª: function(parent, anonid, anonattr = 'id') { return [...window.document.getElementsByAttribute(anonattr,anonid)].filter(i => i.parentElement == parent)[0]; }
};
Services.scriptloader.loadSubScript("chrome://"+objPathString+"-resource/content/modules/utils/Modules.jsm", window[objectName]);
Services.scriptloader.loadSubScript("chrome://"+objPathString+"-resource/content/modules/utils/windowUtilsPreload.jsm", window[objectName]);
window[objectName].Modules.load("utils/windowUtils");
setAttribute(window.document.documentElement, objectName+'_UUID', window[objectName]._UUID);
setAttribute(window.document.documentElement, objectName+'_Version', AddonData.version);
}
function removeObject(window, aName) {
let objectName = aName || objName;
if(window[objectName]) {
removeAttribute(window.document.documentElement, objectName+'_UUID');
removeAttribute(window.document.documentElement, objectName+'_Version');
window[objectName].Modules.unload("utils/windowUtils");
delete window[objectName];
}
}
function preparePreferences(window, aName) {
let objectName = aName || objName;
if(!window[objectName]) {
prepareObject(window, objectName);
}
window[objectName].Modules.load("utils/preferencesUtils");
}
function removeOnceListener(oncer) {
for(var i=0; i<onceListeners.length; i++) {
let unwrapped = onceListeners[i].get();
// clean up dead weak ref
if(!unwrapped) {
onceListeners.splice(i, 1);
i--;
continue;
}
if(!oncer) {
unwrapped();
continue;
}
if(unwrapped == oncer) {
onceListeners.splice(i, 1);
return;
}
}
if(!oncer) {
onceListeners = [];
}
}
function listenOnce(aSubject, type, handler, capture) {
if(UNLOADED || !aSubject || !aSubject.addEventListener) { return; }
var runOnce = function(event) {
try { aSubject.removeEventListener(type, runOnce, capture); }
catch(ex) { handleDeadObject(ex); } // Prevents some can't access dead object errors
if(!UNLOADED && event !== undefined) {
removeOnceListener(runOnce);
try { handler(event, aSubject); }
catch(ex) { Cu.reportError(ex); }
}
};
aSubject.addEventListener(type, runOnce, capture);
let weak = Cu.getWeakReference(runOnce);
onceListeners.push(weak);
}
function callOnLoad(aSubject, aCallback, beforeComplete) {
if(aSubject.document.readyState == 'complete' || beforeComplete) {
try { aCallback(aSubject); }
catch(ex) { Cu.reportError(ex); }
return;
}
// don't wait for the load event if we're terminating
if(UNLOADED) { return; }
listenOnce(aSubject, "load", function() {
if(UNLOADED) { return; }
try { aCallback(aSubject); }
catch(ex) { Cu.reportError(ex); }
}, false);
}
function disable() {
AddonManager.getAddonByID(AddonData.id, function(addon) {
addon.userDisabled = true;
});
}
function continueStartup(aReason) {
STARTED = aReason;
// append actual preferences panes into the preferences tab
if(paneList) {
PrefPanes.setList(paneList);
}
if(typeof(onStartup) == 'function') {
onStartup(AddonData, aReason);
}
}
async function startup(aData, aReason) {
UNLOADED = false;
AddonData = aData;
// to make sure we get always the most recent files when updating the add-on, see:
// https://bugzilla.mozilla.org/show_bug.cgi?id=918033
// https://bugzilla.mozilla.org/show_bug.cgi?id=1051238
AddonData.initTime = new Date().getTime();
// This includes the optionsURL property
AddonManager.getAddonByID(AddonData.id, function(addon) {
if(typeof(UNLOADED) == 'undefined' || UNLOADED) { return; }
Addon = addon;
});
// Set the default strings for the add-on
let defaultsURI = AddonData.resourceURI.spec+'resource/defaults.js';
Services.scriptloader.loadSubScript(defaultsURI, this);
// Get the utils.jsm module into our sandbox
ChromeUtils.defineESModuleGetters(this, {PluralForm: "chrome://"+objPathString+"-resource/content/modules/utils/PluralForm.sys.mjs"});
Services.scriptloader.loadSubScript("chrome://"+objPathString+"-resource/content/modules/utils/Modules.jsm", this);
Services.scriptloader.loadSubScript("chrome://"+objPathString+"-resource/content/modules/utils/sandboxUtilsPreload.jsm", this);
Modules.load("utils/sandboxUtils");
if(typeof(startConditions) != 'function' || startConditions(aReason)) {
if(aReason == APP_STARTUP) {
let promise = new Promise(resolve => {
Services.obs.addObserver(function obs(subject, topic) {
if (subject.createXULElement) {
Services.obs.removeObserver(obs, topic);
resolve();
}
}, "chrome-document-loaded");
});
await promise;
continueStartup(aReason);
}
// In non-e10s, loadFrameScript from this startup can run load content script even before the previous sandboxed content module had a chance to shutdown.
// Case: enable add-on (instance A). Disable add-on. Re-enable add-on (instance B).
// This has to happen in immediate succession, i.e. when updating add-on, but not only.
// Sandbox content B tries to load before sandbox A received the shutdown message, so sandbox B never loads (because A is still loaded).
// Then A receives the shutdown message, it shuts down, and we are left with nothing initialized in the child process.
// Here's hoping that a delay of 500ms covers the vast majority of cases, edge-cases (ultra-busy CPU during add-on update?) may still suffer from this.
// This doesn't seem to happen in e10s, but I'm leaving the delay there as well because why not. Maybe when e10s is norm this can be removed.
else {
aSync(function() {
continueStartup(aReason);
}, 500);
}
}
}
function shutdown(aData, aReason) {
UNLOADED = aReason;
if(aReason == APP_SHUTDOWN) {
// List of methods that must always be run on shutdown, such as restoring some native prefs
while(alwaysRunOnShutdown.length > 0) {
alwaysRunOnShutdown.pop()();
}
removeOnceListener();
return;
}
if(STARTED) {
// content scripts should know as soon as possible that we're disabling the add-on, before any of them starts unloading,
// otherwise they could try to load modules after the resource:// uri was gone
if(MessengerLoaded) {
Services.ppmm.broadcastAsyncMessage(Messenger.messageName('disable'));
}
if(typeof(onShutdown) == 'function') {
onShutdown(aData, aReason);
}
}
Modules.unload("utils/sandboxUtils");
removeOnceListener();
}
function install(aData, aReason) {
// Set the default strings for the add-on
let defaultsURI = aData.resourceURI.spec+'resource/defaults.js';
Services.scriptloader.loadSubScript(defaultsURI, this);
if(typeof(onInstall) == 'function') {
onInstall(aData, aReason);
}
}
function uninstall(aData, aReason) {
if(typeof(onUninstall) == 'function') {
onUninstall(aData, aReason);
}
}