]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/overlay.jsm
0ccf502c00984159200124271c2ff193df84b416
[dactyl.git] / common / modules / overlay.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("overlay", {
11     exports: ["overlay"],
12     require: ["util"]
13 }, this);
14
15 var getAttr = function getAttr(elem, ns, name)
16     elem.hasAttributeNS(ns, name) ? elem.getAttributeNS(ns, name) : null;
17 var setAttr = function setAttr(elem, ns, name, val) {
18     if (val == null)
19         elem.removeAttributeNS(ns, name);
20     else
21         elem.setAttributeNS(ns, name, val);
22 }
23
24 var Overlay = Class("Overlay", {
25     init: function init(window) {
26         this.window = window;
27     },
28
29     cleanups: Class.Memoize(function () []),
30     objects: Class.Memoize(function () ({})),
31
32     get doc() this.window.document,
33
34     get win() this.window,
35
36     $: function $(sel, node) DOM(sel, node || this.doc),
37
38     cleanup: function cleanup(window, reason) {
39         for (let fn in values(this.cleanups))
40             util.trapErrors(fn, this, window, reason);
41     }
42 });
43
44
45 var Overlay = Module("Overlay", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
46     init: function init() {
47         util.addObserver(this);
48         this.overlays = {};
49
50         this.onWindowVisible = [];
51     },
52
53     id: Class.Memoize(function () config.addon.id),
54
55     /**
56      * Adds an event listener for this session and removes it on
57      * dactyl shutdown.
58      *
59      * @param {Element} target The element on which to listen.
60      * @param {string} event The event to listen for.
61      * @param {function} callback The function to call when the event is received.
62      * @param {boolean} capture When true, listen during the capture
63      *      phase, otherwise during the bubbling phase.
64      * @param {boolean} allowUntrusted When true, allow capturing of
65      *      untrusted events.
66      */
67     listen: function (target, event, callback, capture, allowUntrusted) {
68         let doc = target.ownerDocument || target.document || target;
69         let listeners = this.getData(doc, "listeners");
70
71         if (!isObject(event))
72             var [self, events] = [null, array.toObject([[event, callback]])];
73         else
74             [self, events] = [event, event[callback || "events"]];
75
76         for (let [event, callback] in Iterator(events)) {
77             let args = [util.weakReference(target),
78                         event,
79                         util.wrapCallback(callback, self),
80                         capture,
81                         allowUntrusted];
82
83             target.addEventListener.apply(target, args.slice(1));
84             listeners.push(args);
85         }
86     },
87
88     /**
89      * Remove an event listener.
90      *
91      * @param {Element} target The element on which to listen.
92      * @param {string} event The event to listen for.
93      * @param {function} callback The function to call when the event is received.
94      * @param {boolean} capture When true, listen during the capture
95      *      phase, otherwise during the bubbling phase.
96      */
97     unlisten: function (target, event, callback, capture) {
98         let doc = target.ownerDocument || target.document || target;
99         let listeners = this.getData(doc, "listeners");
100         if (event === true)
101             target = null;
102
103         this.setData(doc, "listeners", listeners.filter(function (args) {
104             if (target == null || args[0].get() == target && args[1] == event && args[2].wrapped == callback && args[3] == capture) {
105                 args[0].get().removeEventListener.apply(args[0].get(), args.slice(1));
106                 return false;
107             }
108             return !args[0].get();
109         }));
110     },
111
112     cleanup: function cleanup(reason) {
113         for (let doc in util.iterDocuments()) {
114             for (let elem in values(this.getData(doc, "overlayElements")))
115                 if (elem.parentNode)
116                     elem.parentNode.removeChild(elem);
117
118             for (let [elem, ns, name, orig, value] in values(this.getData(doc, "overlayAttributes")))
119                 if (getAttr(elem, ns, name) === value)
120                     setAttr(elem, ns, name, orig);
121
122             for (let callback in values(this.getData(doc, "cleanup")))
123                 util.trapErrors(callback, doc, reason);
124
125             this.unlisten(doc, true);
126
127             delete doc[this.id];
128             delete doc.defaultView[this.id];
129         }
130     },
131
132     observers: {
133         "toplevel-window-ready": function (window, data) {
134             let listener = util.wrapCallback(function listener(event) {
135                 if (event.originalTarget === window.document) {
136                     window.removeEventListener("DOMContentLoaded", listener.wrapper, true);
137                     window.removeEventListener("load", listener.wrapper, true);
138                     overlay._loadOverlays(window);
139                 }
140             });
141
142             window.addEventListener("DOMContentLoaded", listener, true);
143             window.addEventListener("load", listener, true);
144         },
145         "chrome-document-global-created": function (window, uri) { this.observe(window, "toplevel-window-ready", null); },
146         "content-document-global-created": function (window, uri) { this.observe(window, "toplevel-window-ready", null); },
147         "xul-window-visible": function () {
148             if (this.onWindowVisible)
149                 this.onWindowVisible.forEach(function (f) f.call(this), this);
150             this.onWindowVisible = null;
151         }
152     },
153
154     getData: function getData(obj, key, constructor) {
155         let { id } = this;
156
157         if (!(id in obj && obj[id]))
158             obj[id] = {};
159
160         if (arguments.length == 1)
161             return obj[id];
162
163         if (obj[id][key] === undefined)
164             if (constructor === undefined || callable(constructor))
165                 obj[id][key] = (constructor || Array)();
166             else
167                 obj[id][key] = constructor;
168
169         return obj[id][key];
170     },
171
172     setData: function setData(obj, key, val) {
173         let { id } = this;
174
175         if (!(id in obj))
176             obj[id] = {};
177
178         return obj[id][key] = val;
179     },
180
181     overlayWindow: function (url, fn) {
182         if (url instanceof Ci.nsIDOMWindow)
183             overlay._loadOverlay(url, fn);
184         else {
185             Array.concat(url).forEach(function (url) {
186                 if (!this.overlays[url])
187                     this.overlays[url] = [];
188                 this.overlays[url].push(fn);
189             }, this);
190
191             for (let doc in util.iterDocuments())
192                 if (~["interactive", "complete"].indexOf(doc.readyState)) {
193                     this.observe(doc.defaultView, "xul-window-visible");
194                     this._loadOverlays(doc.defaultView);
195                 }
196                 else {
197                     if (!this.onWindowVisible)
198                         this.onWindowVisible = [];
199                     this.observe(doc.defaultView, "toplevel-window-ready");
200                 }
201         }
202     },
203
204     _loadOverlays: function _loadOverlays(window) {
205         let overlays = this.getData(window, "overlays");
206
207         for each (let obj in overlay.overlays[window.document.documentURI] || []) {
208             if (~overlays.indexOf(obj))
209                 continue;
210             overlays.push(obj);
211             this._loadOverlay(window, obj(window));
212         }
213     },
214
215     _loadOverlay: function _loadOverlay(window, obj) {
216         let doc = window.document;
217         let elems = this.getData(doc, "overlayElements");
218         let attrs = this.getData(doc, "overlayAttributes");
219
220         function insert(key, fn) {
221             if (obj[key]) {
222                 let iterator = Iterator(obj[key]);
223                 if (!isObject(obj[key]))
224                     iterator = ([elem.@id, elem.elements(), elem.@*::*.(function::name() != "id")] for each (elem in obj[key]));
225
226                 for (let [elem, xml, attr] in iterator) {
227                     if (elem = doc.getElementById(elem)) {
228                         let node = DOM.fromXML(xml, doc, obj.objects);
229                         if (!(node instanceof Ci.nsIDOMDocumentFragment))
230                             elems.push(node);
231                         else
232                             for (let n in array.iterValues(node.childNodes))
233                                 elems.push(n);
234
235                         fn(elem, node);
236                         for each (let attr in attr || []) {
237                             let ns = attr.namespace(), name = attr.localName();
238                             attrs.push([elem, ns, name, getAttr(elem, ns, name), String(attr)]);
239                             if (attr.name() != "highlight")
240                                 elem.setAttributeNS(ns, name, String(attr));
241                             else
242                                 highlight.highlightNode(elem, String(attr));
243                         }
244                     }
245                 }
246             }
247         }
248
249         insert("before", function (elem, dom) elem.parentNode.insertBefore(dom, elem));
250         insert("after", function (elem, dom) elem.parentNode.insertBefore(dom, elem.nextSibling));
251         insert("append", function (elem, dom) elem.appendChild(dom));
252         insert("prepend", function (elem, dom) elem.insertBefore(dom, elem.firstChild));
253         if (obj.ready)
254             util.trapErrors("ready", obj, window);
255
256         function load(event) {
257             util.trapErrors("load", obj, window, event);
258             if (obj.visible)
259                 if (!event || !overlay.onWindowVisible || window != util.topWindow(window))
260                     util.trapErrors("visible", obj, window);
261                 else
262                     overlay.onWindowVisible.push(function () { obj.visible(window) });
263         }
264
265         if (obj.load)
266             if (doc.readyState === "complete")
267                 load();
268             else
269                 window.addEventListener("load", util.wrapCallback(function onLoad(event) {
270                     if (event.originalTarget === doc) {
271                         window.removeEventListener("load", onLoad.wrapper, true);
272                         load(event);
273                     }
274                 }), true);
275
276         if (obj.unload || obj.cleanup)
277             this.listen(window, "unload", function unload(event) {
278                 if (event.originalTarget === doc) {
279                     overlay.unlisten(window, "unload", unload);
280                     if (obj.unload)
281                         util.trapErrors("unload", obj, window, event);
282
283                     if (obj.cleanup)
284                         util.trapErrors("cleanup", obj, window, "unload", event);
285                 }
286             });
287
288         if (obj.cleanup)
289             this.getData(doc, "cleanup").push(bind("cleanup", obj, window));
290     },
291
292     /**
293      * Overlays an object with the given property overrides. Each
294      * property in *overrides* is added to *object*, replacing any
295      * original value. Functions in *overrides* are augmented with the
296      * new properties *super*, *supercall*, and *superapply*, in the
297      * same manner as class methods, so that they may call their
298      * overridden counterparts.
299      *
300      * @param {object} object The object to overlay.
301      * @param {object} overrides An object containing properties to
302      *      override.
303      * @returns {function} A function which, when called, will remove
304      *      the overlay.
305      */
306     overlayObject: function (object, overrides) {
307         let original = Object.create(object);
308         overrides = update(Object.create(original), overrides);
309
310         Object.getOwnPropertyNames(overrides).forEach(function (k) {
311             let orig, desc = Object.getOwnPropertyDescriptor(overrides, k);
312             if (desc.value instanceof Class.Property)
313                 desc = desc.value.init(k) || desc.value;
314
315             if (k in object) {
316                 for (let obj = object; obj && !orig; obj = Object.getPrototypeOf(obj))
317                     if (orig = Object.getOwnPropertyDescriptor(obj, k))
318                         Object.defineProperty(original, k, orig);
319
320                 if (!orig)
321                     if (orig = Object.getPropertyDescriptor(object, k))
322                         Object.defineProperty(original, k, orig);
323             }
324
325             // Guard against horrible add-ons that use eval-based monkey
326             // patching.
327             let value = desc.value;
328             if (callable(desc.value)) {
329
330                 delete desc.value;
331                 delete desc.writable;
332                 desc.get = function get() value;
333                 desc.set = function set(val) {
334                     if (!callable(val) || Function.prototype.toString(val).indexOf(sentinel) < 0)
335                         Class.replaceProperty(this, k, val);
336                     else {
337                         let package_ = util.newURI(Components.stack.caller.filename).host;
338                         util.reportError(Error(_("error.monkeyPatchOverlay", package_)));
339                         util.dactyl.echoerr(_("error.monkeyPatchOverlay", package_));
340                     }
341                 };
342             }
343
344             try {
345                 Object.defineProperty(object, k, desc);
346
347                 if (callable(value)) {
348                     var sentinel = "(function DactylOverlay() {}())"
349                     value.toString = function toString() toString.toString.call(this).replace(/\}?$/, sentinel + "; $&");
350                     value.toSource = function toSource() toSource.toSource.call(this).replace(/\}?$/, sentinel + "; $&");
351                 }
352             }
353             catch (e) {
354                 try {
355                     if (value) {
356                         object[k] = value;
357                         return;
358                     }
359                 }
360                 catch (f) {}
361                 util.reportError(e);
362             }
363         }, this);
364
365         return function unwrap() {
366             for each (let k in Object.getOwnPropertyNames(original))
367                 if (Object.getOwnPropertyDescriptor(object, k).configurable)
368                     Object.defineProperty(object, k, Object.getOwnPropertyDescriptor(original, k));
369                 else {
370                     try {
371                         object[k] = original[k];
372                     }
373                     catch (e) {}
374                 }
375         };
376     },
377
378     get activeModules() this.activeWindow && this.activeWindow.dactyl.modules,
379
380     get modules() this.windows.map(function (w) w.dactyl.modules),
381
382     /**
383      * The most recently active dactyl window.
384      */
385     get activeWindow() this.windows[0],
386
387     set activeWindow(win) this.windows = [win].concat(this.windows.filter(function (w) w != win)),
388
389     /**
390      * A list of extant dactyl windows.
391      */
392     windows: Class.Memoize(function () [])
393 });
394
395 endModule();
396
397 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
398
399 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: