1 // Copyright (c) 2010-2014 by Kris Maglione <maglione.k@gmail.com>
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
6 // See https://wiki.mozilla.org/Extension_Manager:Bootstrapped_Extensions
12 var { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
14 function module(uri) Cu.import(uri, {});
18 __defineGetter__("BOOTSTRAP", () => "resource://" + moduleName + "/bootstrap.jsm");
20 var { AddonManager } = module("resource://gre/modules/AddonManager.jsm");
21 var { XPCOMUtils } = module("resource://gre/modules/XPCOMUtils.jsm");
22 var { Services } = module("resource://gre/modules/Services.jsm");
24 var Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer", "initWithCallback");
26 const resourceProto = Services.io.getProtocolHandler("resource")
27 .QueryInterface(Ci.nsIResProtocolHandler);
28 const categoryManager = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
29 const manager = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
31 const BOOTSTRAP_CONTRACT = "@dactyl.googlecode.com/base/bootstrap";
35 function reportError(e) {
36 let stack = e.stack || Error().stack;
37 dump("\n" + name + ": bootstrap: " + e + "\n" + stack + "\n");
39 Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService)
40 .logStringMessage(stack);
42 function debug(...args) {
44 dump(name + ": " + args.join(", ") + "\n");
47 function httpGet(uri) {
48 let xmlhttp = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
49 xmlhttp.overrideMimeType("text/plain");
50 xmlhttp.open("GET", uri.spec || uri, false);
56 let initialized = false;
66 SANDBOX: Cu.nukeSandbox,
76 get module() moduleName,
83 add: function add(major, minor, delta) {
86 this[major] = (this[major] || 0) + delta;
89 this[minor] = (this[minor] || 0) + delta;
90 this[major + minor] = (this[major + minor] || 0) + delta;
93 clear: function clear() {
95 if (typeof this[key] !== "number")
100 getTarget: function getTarget(url) {
101 let uri = Services.io.newURI(url, null, null);
102 if (uri.schemeIs("resource"))
103 return resourceProto.resolveURI(uri);
105 let chan = Services.io.newChannelFromURI(uri);
106 try { chan.cancel(Cr.NS_BINDING_ABORTED); } catch (e) {}
112 atexit: function atexit(arg, self) {
113 if (typeof arg !== "string")
114 this._atexit.push(arguments);
116 for each (let [fn, self] in this._atexit)
125 _load: function _load(name, target) {
127 if (name.indexOf(":") === -1)
128 urls = this.config["module-paths"].map(path => path + name + ".jsm");
130 for each (let url in urls)
132 var uri = this.getTarget(url);
133 if (uri in this.globals)
134 return this.modules[name] = this.globals[uri];
136 this.globals[uri] = this.modules[name];
137 bootstrap_jsm.loadSubScript(url, this.modules[name], "UTF-8");
141 debug("Loading " + name + ": " + e);
142 delete this.globals[uri];
144 if (typeof e != "string")
148 throw Error("No such module: " + name);
151 load: function load(name, target) {
152 if (!this.modules.hasOwnProperty(name)) {
153 this.modules[name] = this.modules.base ? bootstrap.create(this.modules.base)
154 : bootstrap.import({ JSMLoader: this, module: global.module });
156 let currentModule = this.currentModule;
157 this.currentModule = this.modules[name];
160 this._load(name, this.modules[name]);
163 delete this.modules[name];
168 this.currentModule = currentModule;
172 let module = this.modules[name];
174 for each (let symbol in module.EXPORTED_SYMBOLS)
176 Object.defineProperty(target, symbol, {
180 value: module[symbol]
184 target[symbol] = module[symbol];
190 // Cuts down on stupid, fscking url mangling.
191 get loadSubScript() bootstrap_jsm.loadSubScript,
193 cleanup: function cleanup() {
194 for (let factory of this.factories.splice(0))
195 manager.unregisterFactory(factory.classID, factory);
198 Factory: function Factory(class_) ({
199 __proto__: class_.prototype,
201 createInstance: function (outer, iid) {
204 throw Cr.NS_ERROR_NO_AGGREGATION;
205 if (!class_.instance)
206 class_.instance = new class_();
207 return class_.instance.QueryInterface(iid);
216 registerFactory: function registerFactory(factory) {
217 manager.registerFactory(factory.classID,
218 String(factory.classID),
221 this.factories.push(factory);
226 debug("bootstrap: init");
228 let manifest = JSON.parse(httpGet(getURI("config.json"))
231 if (!manifest.categories)
232 manifest.categories = [];
234 for (let [classID, { contract, path, categories }] of Iterator(manifest.components || {})) {
235 components[classID] = new FactoryProxy(getURI(path).spec, classID, contract);
237 for (let [category, id] in Iterator(categories))
238 manifest.categories.push([category, id, contract]);
241 for (let [category, id, value] of manifest.categories)
242 categoryManager.addCategoryEntry(category, id, value,
245 for (let [pkg, path] in Iterator(manifest.resources || {})) {
246 moduleName = moduleName || pkg;
247 resourceProto.setSubstitution(pkg, getURI(path));
250 JSMLoader.config = manifest;
252 bootstrap_jsm = module(BOOTSTRAP);
253 if (!JSMLoader.SANDBOX)
254 bootstrap = bootstrap_jsm;
256 bootstrap = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance(),
257 { sandboxName: BOOTSTRAP });
258 Services.scriptloader.loadSubScript(BOOTSTRAP, bootstrap);
260 bootstrap.require = JSMLoader.load("base").require;
262 let pref = "extensions.dactyl.cacheFlushCheck";
263 let val = addon.version;
264 if (!Services.prefs.prefHasUserValue(pref) || Services.prefs.getCharPref(pref) != val) {
265 var cacheFlush = true;
266 Services.prefs.setCharPref(pref, val);
269 Services.obs.notifyObservers(null, "dactyl-rehash", null);
271 JSMLoader.bootstrap = global;
273 JSMLoader.load("config", global);
274 JSMLoader.load("main", global);
276 JSMLoader.cacheFlush = cacheFlush;
277 JSMLoader.load("base", global);
279 if (!(BOOTSTRAP_CONTRACT in Cc)) {
280 // Use Sandbox to prevent closures over this scope
281 let sandbox = Cu.Sandbox(Cc["@mozilla.org/systemprincipal;1"].createInstance());
282 let factory = Cu.evalInSandbox("({ createInstance: function () this })", sandbox);
284 factory.classID = Components.ID("{f541c8b0-fe26-4621-a30b-e77d21721fb5}");
285 factory.contractID = BOOTSTRAP_CONTRACT;
286 factory.QueryInterface = XPCOMUtils.generateQI([Ci.nsIFactory]);
287 factory.wrappedJSObject = factory;
289 manager.registerFactory(factory.classID, String(factory.classID),
290 BOOTSTRAP_CONTRACT, factory);
293 Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject.loader = !Cu.unload && JSMLoader;
295 for each (let component in components)
296 component.register();
300 if (addon !== addonData)
301 require("main", global);
305 * Performs necessary migrations after a version change.
307 function updateVersion() {
308 function isDev(ver) /^hg|pre$/.test(ver);
310 if (typeof require === "undefined" || addon === addonData)
313 JSMLoader.load("prefs", global);
314 config.lastVersion = localPrefs.get("lastVersion", null);
316 localPrefs.set("lastVersion", addon.version);
318 // We're switching from a nightly version to a stable or
319 // semi-stable version or vice versa.
321 // Disable automatic updates when switching to nightlies,
322 // restore the default action when switching to stable.
323 if (!config.lastVersion || isDev(config.lastVersion) != isDev(addon.version))
324 addon.applyBackgroundUpdates =
325 AddonManager[isDev(addon.version) ? "AUTOUPDATE_DISABLE"
326 : "AUTOUPDATE_DEFAULT"];
333 function startup(data, reason) {
334 debug("bootstrap: startup " + reasonToString(reason));
335 basePath = data.installPath;
340 debug("bootstrap: init " + data.id);
344 name = data.id.replace(/@.*/, "");
345 AddonManager.getAddonByID(addon.id, function (a) {
349 if (typeof require !== "undefined")
350 require("main", global);
353 if (basePath.isDirectory())
354 getURI = function getURI(path) {
355 let uri = Services.io.newFileURI(basePath);
357 return Services.io.newFileURI(uri.QueryInterface(Ci.nsIFileURL).file);
360 getURI = function getURI(path)
361 Services.io.newURI("jar:" + Services.io.newFileURI(basePath).spec.replace(/!/g, "%21") + "!" +
362 "/" + path, null, null);
374 * An XPCOM class factory proxy. Loads the JavaScript module at *url*
375 * when an instance is to be created and calls its NSGetFactory method
376 * to obtain the actual factory.
378 * @param {string} url The URL of the module housing the real factory.
379 * @param {string} classID The CID of the class this factory represents.
381 function FactoryProxy(url, classID, contractID) {
383 this.classID = Components.ID(classID);
384 this.contractID = contractID;
386 FactoryProxy.prototype = {
387 QueryInterface: XPCOMUtils.generateQI(Ci.nsIFactory),
388 register: function () {
389 debug("bootstrap: register: " + this.classID + " " + this.contractID);
391 JSMLoader.registerFactory(this);
394 debug("bootstrap: create module: " + this.contractID);
396 Object.defineProperty(this, "module", { value: {}, enumerable: true });
397 JSMLoader.load(this.url, this.module);
400 createInstance: function (iids) {
401 return let (factory = this.module.NSGetFactory(this.classID))
402 factory.createInstance.apply(factory, arguments);
407 function shutdown(data, reason) {
408 let strReason = reasonToString(reason);
409 debug("bootstrap: shutdown " + strReason);
411 if (reason != APP_SHUTDOWN) {
412 if (~[ADDON_UPGRADE, ADDON_DOWNGRADE, ADDON_UNINSTALL].indexOf(reason))
413 Services.obs.notifyObservers(null, "dactyl-purge", null);
415 Services.obs.notifyObservers(null, "dactyl-cleanup", strReason);
416 Services.obs.notifyObservers(null, "dactyl-cleanup-modules", reasonToString(reason));
418 JSMLoader.atexit(strReason);
419 JSMLoader.cleanup(strReason);
421 for each (let [category, entry] in JSMLoader.config.categories)
422 categoryManager.deleteCategoryEntry(category, entry, false);
423 for (let resource in JSMLoader.config.resources)
424 resourceProto.setSubstitution(resource, null);
426 timer = Timer(() => {
427 bootstrap_jsm.require = null;
428 if (JSMLoader.SANDBOX)
429 Cu.nukeSandbox(bootstrap);
431 Cu.unload(BOOTSTRAP);
433 bootstrap_jsm = null;
434 }, 5000, Ci.nsITimer.TYPE_ONE_SHOT);
438 function uninstall(data, reason) {
439 debug("bootstrap: uninstall " + reasonToString(reason));
440 if (reason == ADDON_UNINSTALL) {
441 Services.prefs.deleteBranch("extensions.dactyl.");
443 if (BOOTSTRAP_CONTRACT in Cc) {
444 let service = Cc[BOOTSTRAP_CONTRACT].getService().wrappedJSObject;
445 manager.unregisterFactory(service.classID, service);
450 function reasonToString(reason) {
451 for each (let name in ["disable", "downgrade", "enable",
452 "install", "shutdown", "startup",
453 "uninstall", "upgrade"])
454 if (reason == global["ADDON_" + name.toUpperCase()] ||
455 reason == global["APP_" + name.toUpperCase()])
459 function install(data, reason) { debug("bootstrap: install " + reasonToString(reason)); }
461 // vim: set fdm=marker sw=4 ts=4 et: