]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/main.jsm
Import 1.0 supporting Firefox up to 14.*
[dactyl.git] / common / modules / main.jsm
1 // Copyright (c) 2009-2011 by Kris Maglione <maglione.k@gmail.com>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 /* use strict */
6
7 try {
8
9 Components.utils.import("resource://dactyl/bootstrap.jsm");
10 defineModule("main", {
11     exports: ["ModuleBase"],
12     require: ["config", "overlay", "services", "util"]
13 }, this);
14
15 var BASE = "resource://dactyl-content/";
16
17 /**
18  * @class ModuleBase
19  * The base class for all modules.
20  */
21 var ModuleBase = Class("ModuleBase", {
22     /**
23      * @property {[string]} A list of module prerequisites which
24      * must be initialized before this module is loaded.
25      */
26     requires: [],
27
28     toString: function () "[module " + this.constructor.className + "]"
29 });
30
31 var _id = 0;
32
33 var Modules = function Modules(window) {
34     /**
35      * @constructor Module
36      *
37      * Constructs a new ModuleBase class and makes arrangements for its
38      * initialization. Arguments marked as optional must be either
39      * entirely elided, or they must have the exact type specified.
40      * Loading semantics are as follows:
41      *
42      *  - A module is guaranteed not to be initialized before any of its
43      *    prerequisites as listed in its {@see ModuleBase#requires} member.
44      *  - A module is considered initialized once it's been instantiated,
45      *    its {@see Class#init} method has been called, and its
46      *    instance has been installed into the top-level {@see modules}
47      *    object.
48      *  - Once the module has been initialized, its module-dependent
49      *    initialization functions will be called as described hereafter.
50      * @param {string} name The module's name as it will appear in the
51      *     top-level {@see modules} object.
52      * @param {ModuleBase} base The base class for this module.
53      *     @optional
54      * @param {Object} prototype The prototype for instances of this
55      *     object. The object itself is copied and not used as a prototype
56      *     directly.
57      * @param {Object} classProperties The class properties for the new
58      *     module constructor.
59      *     @optional
60      * @param {Object} moduleInit The module initialization functions
61      *     for the new module. Each function is called as soon as the
62      *     named module has been initialized. The constructors are
63      *     guaranteed to be called in the same order that the dependent
64      *     modules were initialized.
65      *     @optional
66      *
67      * @returns {function} The constructor for the resulting module.
68      */
69     function Module(name) {
70         let args = Array.slice(arguments);
71
72         var base = ModuleBase;
73         if (callable(args[1]))
74             base = args.splice(1, 1)[0];
75
76         let [, prototype, classProperties, moduleInit] = args;
77         prototype._metaInit_ = function () {
78             delete module.prototype._metaInit_;
79             Class.replaceProperty(modules, module.className, this);
80         };
81         const module = Class(name, base, prototype, classProperties);
82
83         module.INIT = moduleInit || {};
84         module.modules = modules;
85         module.prototype.INIT = module.INIT;
86         module.requires = prototype.requires || [];
87         Module.list.push(module);
88         Module.constructors[name] = module;
89         return module;
90     }
91     Module.list = [];
92     Module.constructors = {};
93
94     const create = window.Object.create || (function () {
95         window.__dactyl_eval_string = "(function (proto) ({ __proto__: proto }))";
96         JSMLoader.loadSubScript(BASE + "eval.js", window);
97
98         let res = window.__dactyl_eval_result;
99         delete window.__dactyl_eval_string;
100         delete window.__dactyl_eval_result;
101         return res;
102     })();
103
104
105     const BASES = [BASE, "resource://dactyl-local-content/"];
106
107     const jsmodules = { NAME: "jsmodules" };
108     const modules = update(create(jsmodules), {
109         yes_i_know_i_should_not_report_errors_in_these_branches_thanks: [],
110
111         jsmodules: jsmodules,
112
113         get content() this.config.browser.contentWindow || window.content,
114
115         window: window,
116
117         Module: Module,
118
119         load: function load(script) {
120             for (let [i, base] in Iterator(BASES)) {
121                 try {
122                     JSMLoader.loadSubScript(base + script + ".js", modules, "UTF-8");
123                     return;
124                 }
125                 catch (e) {
126                     if (typeof e !== "string") {
127                         util.dump("Trying: " + (base + script + ".js") + ":");
128                         util.reportError(e);
129                     }
130                 }
131             }
132             try {
133                 require(jsmodules, script);
134             }
135             catch (e) {
136                 util.dump("Loading script " + script + ":");
137                 util.reportError(e);
138             }
139         },
140
141         newContext: function newContext(proto, normal, name) {
142             if (normal)
143                 return create(proto);
144
145             if (services.has("dactyl") && services.dactyl.createGlobal)
146                 var sandbox = services.dactyl.createGlobal();
147             else
148                 sandbox = Components.utils.Sandbox(window, { sandboxPrototype: proto || modules,
149                                                              sandboxName: name || ("Dactyl Sandbox " + ++_id),
150                                                              wantXrays: false });
151
152             // Hack:
153             sandbox.Object = jsmodules.Object;
154             sandbox.File = jsmodules.File;
155             sandbox.Math = jsmodules.Math;
156             sandbox.__proto__ = proto || modules;
157             return sandbox;
158         },
159
160         get ownPropertyValues() array.compact(
161                 Object.getOwnPropertyNames(this)
162                       .map(function (name) Object.getOwnPropertyDescriptor(this, name).value, this)),
163
164         get moduleList() this.ownPropertyValues.filter(function (mod) mod instanceof this.ModuleBase || mod.isLocalModule, this)
165     });
166
167     modules.plugins = create(modules);
168     modules.modules = modules;
169     return modules;
170 }
171
172 config.loadStyles();
173
174 overlay.overlayWindow(Object.keys(config.overlays), function _overlay(window) ({
175     ready: function onInit(document) {
176         const modules = Modules(window);
177         modules.moduleManager = this;
178         this.modules = modules;
179
180         window.dactyl = { modules: modules };
181
182         defineModule.time("load", null, function _load() {
183             config.modules.global
184                   .forEach(function (name) defineModule.time("load", name, require, null, modules.jsmodules, name));
185
186             config.modules.window
187                   .forEach(function (name) defineModule.time("load", name, modules.load, modules, name));
188         }, this);
189     },
190
191     load: function onLoad(document) {
192         let self = this;
193
194         var { modules, Module } = this.modules;
195         delete window.dactyl;
196
197         this.startTime = Date.now();
198         this.deferredInit = { load: {} };
199         this.seen = {};
200         this.loaded = {};
201         modules.loaded = this.loaded;
202
203         this.modules = modules;
204
205         this.scanModules();
206         this.initDependencies("init");
207
208         modules.config.scripts.forEach(modules.load);
209
210         this.scanModules();
211
212         defineModule.modules.forEach(function defModule({ lazyInit, constructor: { className } }) {
213             if (!lazyInit) {
214                 Class.replaceProperty(modules, className, modules[className]);
215                 this.initDependencies(className);
216             }
217             else
218                 modules.__defineGetter__(className, function () {
219                     let module = modules.jsmodules[className];
220                     Class.replaceProperty(modules, className, module);
221                     if (module.reallyInit)
222                         module.reallyInit(); // :(
223
224                     if (!module.lazyDepends)
225                         self.initDependencies(className);
226                     return module;
227                 });
228         }, this);
229     },
230
231     cleanup: function cleanup(window) {
232         overlay.windows = overlay.windows.filter(function (w) w != window);
233     },
234
235     unload: function unload(window) {
236         for each (let mod in this.modules.moduleList.reverse()) {
237             mod.stale = true;
238
239             if ("destroy" in mod)
240                 util.trapErrors("destroy", mod);
241         }
242     },
243
244     visible: function visible(window) {
245         // Module.list.forEach(load);
246         this.initDependencies("load");
247         this.modules.times = update({}, defineModule.times);
248
249         defineModule.loadLog.push("Loaded in " + (Date.now() - this.startTime) + "ms");
250
251         overlay.windows = array.uniq(overlay.windows.concat(window), true);
252     },
253
254     loadModule: function loadModule(module, prereq, frame) {
255         let { loaded, seen } = this;
256         let { Module, modules } = this.modules;
257
258         if (isString(module)) {
259             if (!Module.constructors.hasOwnProperty(module))
260                 modules.load(module);
261             module = Module.constructors[module];
262         }
263
264         try {
265             if (Set.has(loaded, module.className))
266                 return;
267
268             if (Set.add(seen, module.className))
269                 throw Error("Module dependency loop.");
270
271             for (let dep in values(module.requires))
272                 this.loadModule(Module.constructors[dep], module.className);
273
274             defineModule.loadLog.push(
275                 "Load" + (isString(prereq) ? " " + prereq + " dependency: " : ": ")
276                     + module.className);
277
278             if (frame && frame.filename)
279                 defineModule.loadLog.push("  from: " + util.fixURI(frame.filename) + ":" + frame.lineNumber);
280
281             let obj = defineModule.time(module.className, "init", module);
282             Class.replaceProperty(modules, module.className, obj);
283
284             Set.add(loaded, module.className);
285
286             if (loaded.dactyl && obj.signals)
287                 modules.dactyl.registerObservers(obj);
288
289             if (!module.lazyDepends)
290                 this.initDependencies(module.className);
291         }
292         catch (e) {
293             util.dump("Loading " + (module && module.className) + ":");
294             util.reportError(e);
295         }
296         return modules[module.className];
297     },
298
299     deferInit: function deferInit(name, INIT, mod) {
300         let { modules } = this.modules;
301
302         let init = this.deferredInit[name] || {};
303         this.deferredInit[name] = init;
304
305         let className = mod.className || mod.constructor.className;
306
307         if (!Set.has(init, className)) {
308             init[className] = function callee() {
309                 function finish() {
310                     this.currentDependency = className;
311                     defineModule.time(className, name, INIT[name], mod,
312                                       modules.dactyl, modules, window);
313                 }
314                 if (!callee.frobbed) {
315                     callee.frobbed = true;
316                     if (modules[name] instanceof Class)
317                         modules[name].withSavedValues(["currentDependency"], finish);
318                     else
319                         finish.call({});
320                 }
321             };
322
323             INIT[name].require = function (name) { init[name](); };
324         }
325     },
326
327     scanModules: function scanModules() {
328         let self = this;
329         let { Module, modules } = this.modules;
330
331         defineModule.modules.forEach(function defModule(mod) {
332             let names = Set(Object.keys(mod.INIT));
333             if ("init" in mod.INIT)
334                 Set.add(names, "init");
335
336             keys(names).forEach(function (name) { self.deferInit(name, mod.INIT, mod); });
337         });
338
339         Module.list.forEach(function frobModule(mod) {
340             if (!mod.frobbed) {
341                 modules.__defineGetter__(mod.className, function () {
342                     delete modules[mod.className];
343                     return self.loadModule(mod.className, null, Components.stack.caller);
344                 });
345                 Object.keys(mod.prototype.INIT)
346                       .forEach(function (name) { self.deferInit(name, mod.prototype.INIT, mod); });
347             }
348             mod.frobbed = true;
349         });
350     },
351
352     initDependencies: function initDependencies(name, parents) {
353         for (let [k, v] in Iterator(this.deferredInit[name] || {}))
354             if (!parents || ~parents.indexOf(k))
355                 util.trapErrors(v);
356     }
357 }));
358
359 endModule();
360
361 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
362
363 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: