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