]> git.donarmstrong.com Git - dactyl.git/blob - common/content/events.js
Import r6948 from upstream hg supporting Firefox up to 24.*
[dactyl.git] / common / content / events.js
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2012 Kris Maglione <maglione.k at Gmail>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /** @scope modules */
10
11 /**
12  * A hive used mainly for tracking event listeners and cleaning them up when a
13  * group is destroyed.
14  */
15 var EventHive = Class("EventHive", Contexts.Hive, {
16     init: function init(group) {
17         init.supercall(this, group);
18         this.sessionListeners = [];
19     },
20
21     cleanup: function cleanup() {
22         this.unlisten(null);
23     },
24
25     _events: function _events(event, callback) {
26         if (!isObject(event))
27             var [self, events] = [null, array.toObject([[event, callback]])];
28         else
29             [self, events] = [event, event[callback || "events"]];
30
31         if (Set.has(events, "input") && !Set.has(events, "dactyl-input"))
32             events["dactyl-input"] = events.input;
33
34         return [self, events];
35     },
36
37     /**
38      * Adds an event listener for this session and removes it on
39      * dactyl shutdown.
40      *
41      * @param {Element} target The element on which to listen.
42      * @param {string} event The event to listen for.
43      * @param {function} callback The function to call when the event is received.
44      * @param {boolean} capture When true, listen during the capture
45      *      phase, otherwise during the bubbling phase.
46      * @param {boolean} allowUntrusted When true, allow capturing of
47      *      untrusted events.
48      */
49     listen: function (target, event, callback, capture, allowUntrusted) {
50         var [self, events] = this._events(event, callback);
51
52         for (let [event, callback] in Iterator(events)) {
53             let args = [util.weakReference(target),
54                         util.weakReference(self),
55                         event,
56                         this.wrapListener(callback, self),
57                         capture,
58                         allowUntrusted];
59
60             target.addEventListener.apply(target, args.slice(2));
61             this.sessionListeners.push(args);
62         }
63     },
64
65     /**
66      * Remove an event listener.
67      *
68      * @param {Element} target The element on which to listen.
69      * @param {string} event The event to listen for.
70      * @param {function} callback The function to call when the event is received.
71      * @param {boolean} capture When true, listen during the capture
72      *      phase, otherwise during the bubbling phase.
73      */
74     unlisten: function (target, event, callback, capture) {
75         if (target != null)
76             var [self, events] = this._events(event, callback);
77
78         this.sessionListeners = this.sessionListeners.filter(function (args) {
79             let elem = args[0].get();
80             if (target == null || elem == target
81                                && self == args[1].get()
82                                && Set.has(events, args[2])
83                                && args[3].wrapped == events[args[2]]
84                                && args[4] == capture) {
85
86                 elem.removeEventListener.apply(elem, args.slice(2));
87                 return false;
88             }
89             return elem;
90         });
91     },
92
93     get wrapListener() events.closure.wrapListener
94 });
95
96 /**
97  * @instance events
98  */
99 var Events = Module("events", {
100     dbg: function () {},
101
102     init: function () {
103         this.keyEvents = [];
104
105         overlay.overlayWindow(window, {
106             append: [
107                 ["window", { id: document.documentElement.id, xmlns: "xul" },
108                     // http://developer.mozilla.org/en/docs/XUL_Tutorial:Updating_Commands
109                     ["commandset", { id: "dactyl-onfocus", commandupdater: "true", events: "focus",
110                                      commandupdate: this.closure.onFocusChange }],
111                     ["commandset", { id: "dactyl-onselect", commandupdater: "true", events: "select",
112                                      commandupdate: this.closure.onSelectionChange }]]]
113         });
114
115         this._fullscreen = window.fullScreen;
116         this._lastFocus = { get: function () null };
117         this._macroKeys = [];
118         this._lastMacro = "";
119
120         this._macros = storage.newMap("registers", { privateData: true, store: true });
121         if (storage.exists("macros")) {
122             for (let [k, m] in storage.newMap("macros", { store: true }))
123                 this._macros.set(k, { text: m.keys, timestamp: m.timeRecorded * 1000 });
124             storage.remove("macros");
125         }
126
127         this.popups = {
128             active: [],
129
130             activeMenubar: null,
131
132             update: function update(elem) {
133                 if (elem) {
134                     if (elem instanceof Ci.nsIAutoCompletePopup
135                             || elem.localName == "tooltip"
136                             || !elem.popupBoxObject)
137                         return;
138
139                     if (!~this.active.indexOf(elem))
140                         this.active.push(elem);
141                 }
142
143                 this.active = this.active.filter(function (e) e.popupBoxObject && e.popupBoxObject.popupState != "closed");
144
145                 if (!this.active.length && !this.activeMenubar)
146                     modes.remove(modes.MENU, true);
147                 else if (modes.main != modes.MENU)
148                     modes.push(modes.MENU);
149             },
150
151             events: {
152                 DOMMenuBarActive: function onDOMMenuBarActive(event) {
153                     this.activeMenubar = event.target;
154                     if (modes.main != modes.MENU)
155                         modes.push(modes.MENU);
156                 },
157
158                 DOMMenuBarInactive: function onDOMMenuBarInactive(event) {
159                     this.activeMenubar = null;
160                     modes.remove(modes.MENU, true);
161                 },
162
163                 popupshowing: function onPopupShowing(event) {
164                     this.update(event.originalTarget);
165                 },
166
167                 popupshown: function onPopupShown(event) {
168                     let elem = event.originalTarget;
169                     this.update(elem);
170
171                     if (elem instanceof Ci.nsIAutoCompletePopup) {
172                         if (modes.main != modes.AUTOCOMPLETE)
173                             modes.push(modes.AUTOCOMPLETE);
174                     }
175                     else if (elem.hidePopup && elem.localName !== "tooltip"
176                                 && Events.isHidden(elem)
177                                 && Events.isHidden(elem.parentNode)) {
178                         elem.hidePopup();
179                     }
180                 },
181
182                 popuphidden: function onPopupHidden(event) {
183                     this.update();
184                     modes.remove(modes.AUTOCOMPLETE);
185                 }
186             }
187         };
188
189         this.listen(window, this, "events", true);
190         this.listen(window, this.popups, "events", true);
191     },
192
193     cleanup: function cleanup() {
194         let elem = dactyl.focusedElement;
195         if (DOM(elem).isEditable)
196             util.trapErrors("removeEditActionListener",
197                             DOM(elem).editor, editor);
198     },
199
200     signals: {
201         "browser.locationChange": function (webProgress, request, uri) {
202             options.get("passkeys").flush();
203         },
204         "modes.change": function (oldMode, newMode) {
205             delete this.processor;
206         }
207     },
208
209     get listen() this.builtin.closure.listen,
210     addSessionListener: deprecated("events.listen", { get: function addSessionListener() this.listen }),
211
212     /**
213      * Wraps an event listener to ensure that errors are reported.
214      */
215     wrapListener: function wrapListener(method, self) {
216         self = self || this;
217         method.wrapper = wrappedListener;
218         wrappedListener.wrapped = method;
219         function wrappedListener(event) {
220             try {
221                 method.apply(self, arguments);
222             }
223             catch (e) {
224                 dactyl.reportError(e);
225                 if (e.message == "Interrupted")
226                     dactyl.echoerr(_("error.interrupted"), commandline.FORCE_SINGLELINE);
227                 else
228                     dactyl.echoerr(_("event.error", event.type, e.echoerr || e),
229                                    commandline.FORCE_SINGLELINE);
230             }
231         };
232         return wrappedListener;
233     },
234
235     /**
236      * @property {boolean} Whether synthetic key events are currently being
237      *     processed.
238      */
239     feedingKeys: false,
240
241     /**
242      * Initiates the recording of a key event macro.
243      *
244      * @param {string} macro The name for the macro.
245      */
246     _recording: null,
247     get recording() this._recording,
248
249     set recording(macro) {
250         dactyl.assert(macro == null || /[a-zA-Z0-9]/.test(macro),
251                       _("macro.invalid", macro));
252
253         modes.recording = macro;
254
255         if (/[A-Z]/.test(macro)) { // Append.
256             macro = macro.toLowerCase();
257             this._macroKeys = DOM.Event.iterKeys(editor.getRegister(macro))
258                                  .toArray();
259         }
260         else if (macro) { // Record afresh.
261             this._macroKeys = [];
262         }
263         else if (this.recording) { // Save.
264             editor.setRegister(this.recording, this._macroKeys.join(""));
265
266             dactyl.log(_("macro.recorded", this.recording, this._macroKeys.join("")), 9);
267             dactyl.echomsg(_("macro.recorded", this.recording));
268         }
269         this._recording = macro || null;
270     },
271
272     /**
273      * Replays a macro.
274      *
275      * @param {string} The name of the macro to replay.
276      * @returns {boolean}
277      */
278     playMacro: function (macro) {
279         dactyl.assert(/^[a-zA-Z0-9@]$/.test(macro),
280                       _("macro.invalid", macro));
281
282         if (macro == "@")
283             dactyl.assert(this._lastMacro, _("macro.noPrevious"));
284         else
285             this._lastMacro = macro.toLowerCase(); // XXX: sets last played macro, even if it does not yet exist
286
287         let keys = editor.getRegister(this._lastMacro);
288         if (keys)
289             return modes.withSavedValues(["replaying"], function () {
290                 this.replaying = true;
291                 return events.feedkeys(keys, { noremap: true });
292             });
293
294         // TODO: ignore this like Vim?
295         dactyl.echoerr(_("macro.noSuch", this._lastMacro));
296         return false;
297     },
298
299     /**
300      * Returns all macros matching *filter*.
301      *
302      * @param {string} filter A regular expression filter string. A null
303      *     filter selects all macros.
304      */
305     getMacros: function (filter) {
306         let re = RegExp(filter || "");
307         return ([k, m.text] for ([k, m] in editor.registers) if (re.test(k)));
308     },
309
310     /**
311      * Deletes all macros matching *filter*.
312      *
313      * @param {string} filter A regular expression filter string. A null
314      *     filter deletes all macros.
315      */
316     deleteMacros: function (filter) {
317         let re = RegExp(filter || "");
318         for (let [item, ] in editor.registers) {
319             if (!filter || re.test(item))
320                 editor.registers.remove(item);
321         }
322     },
323
324     /**
325      * Feeds a list of events to *target* or the originalTarget member
326      * of each event if *target* is null.
327      *
328      * @param {EventTarget} target The destination node for the events.
329      *      @optional
330      * @param {[Event]} list The events to dispatch.
331      * @param {object} extra Extra properties for processing by dactyl.
332      *      @optional
333      */
334     feedevents: function feedevents(target, list, extra) {
335         list.forEach(function _feedevent(event, i) {
336             let elem = target || event.originalTarget;
337             if (elem) {
338                 let doc = elem.ownerDocument || elem.document || elem;
339                 let evt = DOM.Event(doc, event.type, event);
340                 DOM.Event.dispatch(elem, evt, extra);
341             }
342             else if (i > 0 && event.type === "keypress")
343                 events.events.keypress.call(events, event);
344         });
345     },
346
347     /**
348      * Pushes keys onto the event queue from dactyl. It is similar to
349      * Vim's feedkeys() method, but cannot cope with 2 partially-fed
350      * strings, you have to feed one parseable string.
351      *
352      * @param {string} keys A string like "2<C-f>" to push onto the event
353      *     queue. If you want "<" to be taken literally, prepend it with a
354      *     "\\".
355      * @param {boolean} noremap Whether recursive mappings should be
356      *     disallowed.
357      * @param {boolean} silent Whether the command should be echoed to the
358      *     command line.
359      * @returns {boolean}
360      */
361     feedkeys: function (keys, noremap, quiet, mode) {
362         try {
363             var savedEvents = this._processor && this._processor.keyEvents;
364
365             var wasFeeding = this.feedingKeys;
366             this.feedingKeys = true;
367
368             var wasQuiet = commandline.quiet;
369             if (quiet)
370                 commandline.quiet = quiet;
371
372             for (let [, evt_obj] in Iterator(DOM.Event.parse(keys))) {
373                 let now = Date.now();
374                 let key = DOM.Event.stringify(evt_obj);
375                 for (let type in values(["keydown", "keypress", "keyup"])) {
376                     let evt = update({}, evt_obj, { type: type });
377                     if (type !== "keypress" && !evt.keyCode)
378                         evt.keyCode = evt._keyCode || 0;
379
380                     if (isObject(noremap))
381                         update(evt, noremap);
382                     else
383                         evt.noremap = !!noremap;
384                     evt.isMacro = true;
385                     evt.dactylMode = mode;
386                     evt.dactylSavedEvents = savedEvents;
387                     DOM.Event.feedingEvent = evt;
388
389                     let doc = document.commandDispatcher.focusedWindow.document;
390
391                     let target = dactyl.focusedElement
392                               || ["complete", "interactive"].indexOf(doc.readyState) >= 0 && doc.documentElement
393                               || doc.defaultView;
394
395                     if (target instanceof Element && !Events.isInputElement(target) &&
396                         ["<Return>", "<Space>"].indexOf(key) == -1)
397                         target = target.ownerDocument.documentElement;
398
399                     let event = DOM.Event(doc, type, evt);
400                     if (!evt_obj.dactylString && !mode)
401                         DOM.Event.dispatch(target, event, evt);
402                     else if (type === "keypress")
403                         events.events.keypress.call(events, event);
404                 }
405
406                 if (!this.feedingKeys)
407                     return false;
408             }
409         }
410         catch (e) {
411             util.reportError(e);
412         }
413         finally {
414             DOM.Event.feedingEvent = null;
415             this.feedingKeys = wasFeeding;
416             if (quiet)
417                 commandline.quiet = wasQuiet;
418             dactyl.triggerObserver("events.doneFeeding");
419         }
420         return true;
421     },
422
423     canonicalKeys: deprecated("DOM.Event.canonicalKeys", { get: function canonicalKeys() DOM.Event.closure.canonicalKeys }),
424     create:        deprecated("DOM.Event", function create() DOM.Event.apply(null, arguments)),
425     dispatch:      deprecated("DOM.Event.dispatch", function dispatch() DOM.Event.dispatch.apply(DOM.Event, arguments)),
426     fromString:    deprecated("DOM.Event.parse", { get: function fromString() DOM.Event.closure.parse }),
427     iterKeys:      deprecated("DOM.Event.iterKeys", { get: function iterKeys() DOM.Event.closure.iterKeys }),
428
429     toString: function toString() {
430         if (!arguments.length)
431             return toString.supercall(this);
432
433         deprecated.warn(toString, "toString", "DOM.Event.stringify");
434         return DOM.Event.stringify.apply(DOM.Event, arguments);
435     },
436
437     get defaultTarget() dactyl.focusedElement || content.document.body || document.documentElement,
438
439     /**
440      * Returns true if there's a known native key handler for the given
441      * event in the given mode.
442      *
443      * @param {Event} event A keypress event.
444      * @param {Modes.Mode} mode The main mode.
445      * @param {boolean} passUnknown Whether unknown keys should be passed.
446      */
447     hasNativeKey: function hasNativeKey(event, mode, passUnknown) {
448         if (mode.input && event.charCode && !(event.ctrlKey || event.metaKey))
449             return true;
450
451         if (!passUnknown)
452             return false;
453
454         var elements = document.getElementsByTagNameNS(XUL, "key");
455         var filters = [];
456
457         if (event.keyCode)
458             filters.push(["keycode", this._code_nativeKey[event.keyCode]]);
459         if (event.charCode) {
460             let key = String.fromCharCode(event.charCode);
461             filters.push(["key", key.toUpperCase()],
462                          ["key", key.toLowerCase()]);
463         }
464
465         let accel = config.OS.isMacOSX ? "metaKey" : "ctrlKey";
466
467         let access = iter({ 1: "shiftKey", 2: "ctrlKey", 4: "altKey", 8: "metaKey" })
468                         .filter(function ([k, v]) this & k, prefs.get("ui.key.chromeAccess"))
469                         .map(function ([k, v]) [v, true])
470                         .toObject();
471
472     outer:
473         for (let [, key] in iter(elements))
474             if (filters.some(function ([k, v]) key.getAttribute(k) == v)) {
475                 let keys = { ctrlKey: false, altKey: false, shiftKey: false, metaKey: false };
476                 let needed = { ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, metaKey: event.metaKey };
477
478                 let modifiers = (key.getAttribute("modifiers") || "").trim().split(/[\s,]+/);
479                 for (let modifier in values(modifiers))
480                     switch (modifier) {
481                         case "access": update(keys, access); break;
482                         case "accel":  keys[accel] = true; break;
483                         default:       keys[modifier + "Key"] = true; break;
484                         case "any":
485                             if (!iter.some(keys, function ([k, v]) v && needed[k]))
486                                 continue outer;
487                             for (let [k, v] in iter(keys)) {
488                                 if (v)
489                                     needed[k] = false;
490                                 keys[k] = false;
491                             }
492                             break;
493                     }
494
495                 if (iter(needed).every(function ([k, v]) v == keys[k]))
496                     return key;
497             }
498
499         return false;
500     },
501
502     /**
503      * Returns true if *key* is a key code defined to accept/execute input on
504      * the command line.
505      *
506      * @param {string} key The key code to test.
507      * @returns {boolean}
508      */
509     isAcceptKey: function (key) key == "<Return>" || key == "<C-j>" || key == "<C-m>",
510
511     /**
512      * Returns true if *key* is a key code defined to reject/cancel input on
513      * the command line.
514      *
515      * @param {string} key The key code to test.
516      * @returns {boolean}
517      */
518     isCancelKey: function (key) key == "<Esc>" || key == "<C-[>" || key == "<C-c>",
519
520     /**
521      * Returns true if *node* belongs to the current content document or any
522      * sub-frame thereof.
523      *
524      * @param {Node|Document|Window} node The node to test.
525      * @returns {boolean}
526      */
527     isContentNode: function isContentNode(node) {
528         let win = (node.ownerDocument || node).defaultView || node;
529         return XPCNativeWrapper(win).top == content;
530     },
531
532     /**
533      * Waits for the current buffer to successfully finish loading. Returns
534      * true for a successful page load otherwise false.
535      *
536      * @returns {boolean}
537      */
538     waitForPageLoad: function (time) {
539         if (buffer.loaded)
540             return true;
541
542         dactyl.echo(_("macro.loadWaiting"), commandline.FORCE_SINGLELINE);
543
544         const maxWaitTime = (time || 25);
545         util.waitFor(function () buffer.loaded, this, maxWaitTime * 1000, true);
546
547         dactyl.echo("", commandline.FORCE_SINGLELINE);
548         if (!buffer.loaded)
549             dactyl.echoerr(_("macro.loadFailed", maxWaitTime));
550
551         return buffer.loaded;
552     },
553
554     /**
555      * Ensures that the currently focused element is visible and blurs
556      * it if it's not.
557      */
558     checkFocus: function () {
559         if (dactyl.focusedElement) {
560             let rect = dactyl.focusedElement.getBoundingClientRect();
561             if (!rect.width || !rect.height) {
562                 services.focus.clearFocus(window);
563                 document.commandDispatcher.focusedWindow = content;
564                 // onFocusChange needs to die.
565                 this.onFocusChange();
566             }
567         }
568     },
569
570     events: {
571         blur: function onBlur(event) {
572             let elem = event.originalTarget;
573             if (DOM(elem).isEditable)
574                 util.trapErrors("removeEditActionListener",
575                                 DOM(elem).editor, editor);
576
577             if (elem instanceof Window && services.focus.activeWindow == null
578                 && document.commandDispatcher.focusedWindow !== window) {
579                 // Deals with circumstances where, after the main window
580                 // blurs while a collapsed frame has focus, re-activating
581                 // the main window does not restore focus and we lose key
582                 // input.
583                 services.focus.clearFocus(window);
584                 document.commandDispatcher.focusedWindow = Editor.getEditor(content) ? window : content;
585             }
586
587             let hold = modes.topOfStack.params.holdFocus;
588             if (elem == hold) {
589                 dactyl.focus(hold);
590                 this.timeout(function () { dactyl.focus(hold); });
591             }
592         },
593
594         // TODO: Merge with onFocusChange
595         focus: function onFocus(event) {
596             let elem = event.originalTarget;
597             if (DOM(elem).isEditable)
598                 util.trapErrors("addEditActionListener",
599                                 DOM(elem).editor, editor);
600
601             if (elem == window)
602                 overlay.activeWindow = window;
603
604             overlay.setData(elem, "had-focus", true);
605             if (event.target instanceof Ci.nsIDOMXULTextBoxElement)
606                 if (Events.isHidden(elem, true))
607                     elem.blur();
608
609             let win = (elem.ownerDocument || elem).defaultView || elem;
610
611             if (!(services.focus.getLastFocusMethod(win) & 0x3000)
612                 && events.isContentNode(elem)
613                 && !buffer.focusAllowed(elem)
614                 && isinstance(elem, [Ci.nsIDOMHTMLInputElement,
615                                      Ci.nsIDOMHTMLSelectElement,
616                                      Ci.nsIDOMHTMLTextAreaElement,
617                                      Ci.nsIDOMWindow])) {
618
619                 if (elem.frameElement)
620                     dactyl.focusContent(true);
621                 else if (!(elem instanceof Window) || Editor.getEditor(elem))
622                     dactyl.focus(window);
623             }
624
625             if (elem instanceof Element)
626                 delete overlay.getData(elem)["focus-allowed"];
627         },
628
629         /*
630         onFocus: function onFocus(event) {
631             let elem = event.originalTarget;
632             if (!(elem instanceof Element))
633                 return;
634             let win = elem.ownerDocument.defaultView;
635
636             try {
637                 util.dump(elem, services.focus.getLastFocusMethod(win) & (0x7000));
638                 if (buffer.focusAllowed(win))
639                     win.dactylLastFocus = elem;
640                 else if (isinstance(elem, [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement])) {
641                     if (win.dactylLastFocus)
642                         dactyl.focus(win.dactylLastFocus);
643                     else
644                         elem.blur();
645                 }
646             }
647             catch (e) {
648                 util.dump(win, String(elem.ownerDocument), String(elem.ownerDocument && elem.ownerDocument.defaultView));
649                 util.reportError(e);
650             }
651         },
652         */
653
654         input: function onInput(event) {
655             event.originalTarget.dactylKeyPress = undefined;
656         },
657
658         // this keypress handler gets always called first, even if e.g.
659         // the command-line has focus
660         // TODO: ...help me...please...
661         keypress: function onKeyPress(event) {
662             event.dactylDefaultPrevented = event.getPreventDefault();
663
664             let duringFeed = this.duringFeed || [];
665             this.duringFeed = [];
666             try {
667                 let ourEvent = DOM.Event.feedingEvent;
668                 DOM.Event.feedingEvent = null;
669                 if (ourEvent)
670                     for (let [k, v] in Iterator(ourEvent))
671                         if (!(k in event))
672                             event[k] = v;
673
674                 let key = DOM.Event.stringify(ourEvent || event);
675                 event.dactylString = key;
676
677                 // Hack to deal with <BS> and so forth not dispatching input
678                 // events
679                 if (key && event.originalTarget instanceof Ci.nsIDOMHTMLInputElement && !modes.main.passthrough) {
680                     let elem = event.originalTarget;
681                     elem.dactylKeyPress = elem.value;
682                     util.timeout(function () {
683                         if (elem.dactylKeyPress !== undefined && elem.value !== elem.dactylKeyPress)
684                             DOM(elem).dactylInput();
685                         elem.dactylKeyPress = undefined;
686                     });
687                 }
688
689                 if (!key)
690                      return null;
691
692                 if (modes.recording && !event.isReplay)
693                     events._macroKeys.push(key);
694
695                 // feedingKeys needs to be separate from interrupted so
696                 // we can differentiate between a recorded <C-c>
697                 // interrupting whatever it's started and a real <C-c>
698                 // interrupting our playback.
699                 if (events.feedingKeys && !event.isMacro) {
700                     if (key == "<C-c>") {
701                         events.feedingKeys = false;
702                         if (modes.replaying) {
703                             modes.replaying = false;
704                             this.timeout(function () { dactyl.echomsg(_("macro.canceled", this._lastMacro)); }, 100);
705                         }
706                     }
707                     else
708                         duringFeed.push(event);
709
710                     return Events.kill(event);
711                 }
712
713                 if (!this.processor) {
714                     let mode = modes.getStack(0);
715                     if (event.dactylMode)
716                         mode = Modes.StackElement(event.dactylMode);
717
718                     let ignore = false;
719
720                     if (mode.main == modes.PASS_THROUGH)
721                         ignore = !Events.isEscape(key) && key != "<C-v>";
722                     else if (mode.main == modes.QUOTE) {
723                         if (modes.getStack(1).main == modes.PASS_THROUGH) {
724                             mode = Modes.StackElement(modes.getStack(2).main);
725                             ignore = Events.isEscape(key);
726                         }
727                         else if (events.shouldPass(event))
728                             mode = Modes.StackElement(modes.getStack(1).main);
729                         else
730                             ignore = true;
731
732                         modes.pop();
733                     }
734                     else if (!event.isMacro && !event.noremap && events.shouldPass(event))
735                         ignore = true;
736
737                     events.dbg("\n\n");
738                     events.dbg("ON KEYPRESS " + key + " ignore: " + ignore,
739                                event.originalTarget instanceof Element ? event.originalTarget : String(event.originalTarget));
740
741                     if (ignore)
742                         return null;
743
744                     // FIXME: Why is this hard coded? --Kris
745                     if (key == "<C-c>")
746                         util.interrupted = true;
747
748                     this.processor = ProcessorStack(mode, mappings.hives.array, event.noremap);
749                     this.processor.keyEvents = this.keyEvents;
750                 }
751
752                 let { keyEvents, processor } = this;
753                 this._processor = processor;
754                 this.processor = null;
755                 this.keyEvents = [];
756
757                 if (!processor.process(event)) {
758                     this.keyEvents = keyEvents;
759                     this.processor = processor;
760                 }
761
762             }
763             catch (e) {
764                 dactyl.reportError(e);
765             }
766             finally {
767                 [duringFeed, this.duringFeed] = [this.duringFeed, duringFeed];
768                 if (this.feedingKeys)
769                     this.duringFeed = this.duringFeed.concat(duringFeed);
770                 else
771                     for (let event in values(duringFeed))
772                         try {
773                             DOM.Event.dispatch(event.originalTarget, event, event);
774                         }
775                         catch (e) {
776                             util.reportError(e);
777                         }
778             }
779         },
780
781         keyup: function onKeyUp(event) {
782             if (event.type == "keydown")
783                 this.keyEvents.push(event);
784             else if (!this.processor)
785                 this.keyEvents = [];
786
787             let pass = this.passing && !event.isMacro ||
788                     DOM.Event.feedingEvent && DOM.Event.feedingEvent.isReplay ||
789                     event.isReplay ||
790                     modes.main == modes.PASS_THROUGH ||
791                     modes.main == modes.QUOTE
792                         && modes.getStack(1).main !== modes.PASS_THROUGH
793                         && !this.shouldPass(event) ||
794                     !modes.passThrough && this.shouldPass(event) ||
795                     !this.processor && event.type === "keydown"
796                         && options.get("passunknown").getKey(modes.main.allBases)
797                         && let (key = DOM.Event.stringify(event))
798                             !(modes.main.count && /^\d$/.test(key) ||
799                               modes.main.allBases.some(
800                                 function (mode) mappings.hives.some(
801                                     function (hive) hive.get(mode, key) || hive.getCandidates(mode, key))));
802
803             events.dbg("ON " + event.type.toUpperCase() + " " + DOM.Event.stringify(event) +
804                        " passing: " + this.passing + " " +
805                        " pass: " + pass +
806                        " replay: " + event.isReplay +
807                        " macro: " + event.isMacro);
808
809             if (event.type === "keydown")
810                 this.passing = pass;
811
812             // Prevents certain sites from transferring focus to an input box
813             // before we get a chance to process our key bindings on the
814             // "keypress" event.
815             if (!pass)
816                 event.stopPropagation();
817         },
818         keydown: function onKeyDown(event) {
819             if (!event.isMacro)
820                 this.passing = false;
821             this.events.keyup.call(this, event);
822         },
823
824         mousedown: function onMouseDown(event) {
825             let elem = event.target;
826             let win = elem.ownerDocument && elem.ownerDocument.defaultView || elem;
827
828             for (; win; win = win != win.parent && win.parent) {
829                 for (; elem instanceof Element; elem = elem.parentNode)
830                     overlay.setData(elem, "focus-allowed", true);
831                 overlay.setData(win.document, "focus-allowed", true);
832             }
833         },
834
835         resize: function onResize(event) {
836             if (window.fullScreen != this._fullscreen) {
837                 statusline.statusBar.removeAttribute("moz-collapsed");
838                 this._fullscreen = window.fullScreen;
839                 dactyl.triggerObserver("fullscreen", this._fullscreen);
840                 autocommands.trigger("Fullscreen", { url: this._fullscreen ? "on" : "off", state: this._fullscreen });
841             }
842             statusline.updateZoomLevel();
843         }
844     },
845
846     // argument "event" is deliberately not used, as i don't seem to have
847     // access to the real focus target
848     // Huh? --djk
849     onFocusChange: util.wrapCallback(function onFocusChange(event) {
850         function hasHTMLDocument(win) win && win.document && win.document instanceof Ci.nsIDOMHTMLDocument
851         if (dactyl.ignoreFocus)
852             return;
853
854         let win  = window.document.commandDispatcher.focusedWindow;
855         let elem = window.document.commandDispatcher.focusedElement;
856
857         if (elem == null && Editor.getEditor(win))
858             elem = win;
859
860         if (win && win.top == content && dactyl.has("tabs"))
861             buffer.focusedFrame = win;
862
863         try {
864             if (elem && elem.readOnly)
865                 return;
866
867             if (isinstance(elem, [Ci.nsIDOMHTMLEmbedElement, Ci.nsIDOMHTMLEmbedElement])) {
868                 if (!modes.main.passthrough && modes.main != modes.EMBED)
869                     modes.push(modes.EMBED);
870                 return;
871             }
872
873             let haveInput = modes.stack.some(function (m) m.main.input);
874
875             if (DOM(elem || win).isEditable) {
876                 if (!haveInput)
877                     if (!isinstance(modes.main, [modes.INPUT, modes.TEXT_EDIT, modes.VISUAL]))
878                         if (options["insertmode"])
879                             modes.push(modes.INSERT);
880                         else {
881                             modes.push(modes.TEXT_EDIT);
882                             if (elem.selectionEnd - elem.selectionStart > 0)
883                                 modes.push(modes.VISUAL);
884                         }
885
886                 if (hasHTMLDocument(win))
887                     buffer.lastInputField = elem || win;
888                 return;
889             }
890
891             if (elem && Events.isInputElement(elem)) {
892                 if (!haveInput)
893                     modes.push(modes.INSERT);
894
895                 if (hasHTMLDocument(win))
896                     buffer.lastInputField = elem;
897                 return;
898             }
899
900             if (config.focusChange) {
901                 config.focusChange(win);
902                 return;
903             }
904
905             let urlbar = document.getElementById("urlbar");
906             if (elem == null && urlbar && urlbar.inputField == this._lastFocus.get())
907                 util.threadYield(true); // Why? --Kris
908
909             while (modes.main.ownsFocus
910                     && let ({ ownsFocus } = modes.topOfStack.params)
911                          (!ownsFocus ||
912                              ownsFocus.get() != elem &&
913                              ownsFocus.get() != win)
914                     && !modes.topOfStack.params.holdFocus)
915                  modes.pop(null, { fromFocus: true });
916         }
917         finally {
918             this._lastFocus = util.weakReference(elem);
919
920             if (modes.main.ownsFocus)
921                 modes.topOfStack.params.ownsFocus = util.weakReference(elem);
922         }
923     }),
924
925     onSelectionChange: function onSelectionChange(event) {
926         // Ignore selection events caused by editor commands.
927         if (editor.inEditMap || modes.main == modes.OPERATOR)
928             return;
929
930         let controller = document.commandDispatcher.getControllerForCommand("cmd_copy");
931         let couldCopy = controller && controller.isCommandEnabled("cmd_copy");
932
933         if (couldCopy) {
934             if (modes.main == modes.TEXT_EDIT)
935                 modes.push(modes.VISUAL);
936             else if (modes.main == modes.CARET)
937                 modes.push(modes.VISUAL);
938         }
939     },
940
941     shouldPass: function shouldPass(event)
942         !event.noremap && (!dactyl.focusedElement || events.isContentNode(dactyl.focusedElement)) &&
943         options.get("passkeys").has(DOM.Event.stringify(event))
944 }, {
945     ABORT: {},
946     KILL: true,
947     PASS: false,
948     PASS_THROUGH: {},
949     WAIT: null,
950
951     isEscape: function isEscape(event)
952         let (key = isString(event) ? event : DOM.Event.stringify(event))
953             key === "<Esc>" || key === "<C-[>",
954
955     isHidden: function isHidden(elem, aggressive) {
956         if (DOM(elem).style.visibility !== "visible")
957             return true;
958
959         if (aggressive)
960             for (let e = elem; e instanceof Element; e = e.parentNode) {
961                 if (!/set$/.test(e.localName) && e.boxObject && e.boxObject.height === 0)
962                     return true;
963                 else if (e.namespaceURI == XUL && e.localName === "panel")
964                     break;
965             }
966         return false;
967     },
968
969     isInputElement: function isInputElement(elem) {
970         return DOM(elem).isEditable ||
971                isinstance(elem, [Ci.nsIDOMHTMLEmbedElement,
972                                  Ci.nsIDOMHTMLObjectElement,
973                                  Ci.nsIDOMHTMLSelectElement]);
974     },
975
976     kill: function kill(event) {
977         event.stopPropagation();
978         event.preventDefault();
979     }
980 }, {
981     contexts: function initContexts(dactyl, modules, window) {
982         update(Events.prototype, {
983             hives: contexts.Hives("events", EventHive),
984             user: contexts.hives.events.user,
985             builtin: contexts.hives.events.builtin
986         });
987     },
988
989     commands: function initCommands() {
990         commands.add(["delmac[ros]"],
991             "Delete macros",
992             function (args) {
993                 dactyl.assert(!args.bang || !args[0], _("error.invalidArgument"));
994
995                 if (args.bang)
996                     events.deleteMacros();
997                 else if (args[0])
998                     events.deleteMacros(args[0]);
999                 else
1000                     dactyl.echoerr(_("error.argumentRequired"));
1001             }, {
1002                 argCount: "?",
1003                 bang: true,
1004                 completer: function (context) completion.macro(context),
1005                 literal: 0
1006             });
1007
1008         commands.add(["mac[ros]"],
1009             "List all macros",
1010             function (args) { completion.listCompleter("macro", args[0]); }, {
1011                 argCount: "?",
1012                 completer: function (context) completion.macro(context)
1013             });
1014     },
1015     completion: function initCompletion() {
1016         completion.macro = function macro(context) {
1017             context.title = ["Macro", "Keys"];
1018             context.completions = [item for (item in events.getMacros())];
1019         };
1020     },
1021     mappings: function initMappings() {
1022
1023         mappings.add([modes.MAIN],
1024             ["<A-b>", "<pass-next-key-builtin>"], "Process the next key as a builtin mapping",
1025             function () {
1026                 events.processor = ProcessorStack(modes.getStack(0), mappings.hives.array, true);
1027                 events.processor.keyEvents = events.keyEvents;
1028             });
1029
1030         mappings.add([modes.MAIN],
1031             ["<C-z>", "<pass-all-keys>"], "Temporarily ignore all " + config.appName + " key bindings",
1032             function () {
1033                 if (modes.main != modes.PASS_THROUGH)
1034                     modes.push(modes.PASS_THROUGH);
1035             });
1036
1037         mappings.add([modes.MAIN, modes.PASS_THROUGH, modes.QUOTE],
1038             ["<C-v>", "<pass-next-key>"], "Pass through next key",
1039             function () {
1040                 if (modes.main == modes.QUOTE)
1041                     return Events.PASS;
1042                 modes.push(modes.QUOTE);
1043             });
1044
1045         mappings.add([modes.BASE],
1046             ["<CapsLock>"], "Do Nothing",
1047             function () {});
1048
1049         mappings.add([modes.BASE],
1050             ["<Nop>"], "Do nothing",
1051             function () {});
1052
1053         mappings.add([modes.BASE],
1054             ["<Pass>"], "Pass the events consumed by the last executed mapping",
1055             function ({ keypressEvents: [event] }) {
1056                 dactyl.assert(event.dactylSavedEvents,
1057                               _("event.nothingToPass"));
1058                 return function () {
1059                     events.feedevents(null, event.dactylSavedEvents,
1060                                       { skipmap: true, isMacro: true, isReplay: true });
1061                 };
1062             });
1063
1064         // macros
1065         mappings.add([modes.COMMAND],
1066             ["q", "<record-macro>"], "Record a key sequence into a macro",
1067             function ({ arg }) {
1068                 util.assert(arg == null || /^[a-z]$/i.test(arg));
1069                 events._macroKeys.pop();
1070                 events.recording = arg;
1071             },
1072             { get arg() !modes.recording });
1073
1074         mappings.add([modes.COMMAND],
1075             ["@", "<play-macro>"], "Play a macro",
1076             function ({ arg, count }) {
1077                 count = Math.max(count, 1);
1078                 while (count--)
1079                     events.playMacro(arg);
1080             },
1081             { arg: true, count: true });
1082
1083         mappings.add([modes.COMMAND],
1084             ["<A-m>s", "<sleep>"], "Sleep for {count} milliseconds before continuing macro playback",
1085             function ({ command, count }) {
1086                 let now = Date.now();
1087                 dactyl.assert(count, _("error.countRequired", command));
1088                 if (events.feedingKeys)
1089                     util.sleep(count);
1090             },
1091             { count: true });
1092
1093         mappings.add([modes.COMMAND],
1094             ["<A-m>l", "<wait-for-page-load>"], "Wait for the current page to finish loading before continuing macro playback",
1095             function ({ count }) {
1096                 if (events.feedingKeys && !events.waitForPageLoad(count)) {
1097                     util.interrupted = true;
1098                     throw Error("Interrupted");
1099                 }
1100             },
1101             { count: true });
1102     },
1103     options: function initOptions() {
1104         const Hive = Class("Hive", {
1105             init: function init(values, map) {
1106                 this.name = "passkeys:" + map;
1107                 this.stack = MapHive.Stack(values.map(function (v) Map(v[map + "Keys"])));
1108                 function Map(keys) ({
1109                     execute: function () Events.PASS_THROUGH,
1110                     keys: keys
1111                 });
1112             },
1113
1114             get active() this.stack.length,
1115
1116             get: function get(mode, key) this.stack.mappings[key],
1117
1118             getCandidates: function getCandidates(mode, key) this.stack.candidates[key]
1119         });
1120         options.add(["passkeys", "pk"],
1121             "Pass certain keys through directly for the given URLs",
1122             "sitemap", "", {
1123                 flush: function flush() {
1124                     memoize(this, "filters", function () this.value.filter(function (f) f(buffer.documentURI)));
1125                     memoize(this, "pass", function () Set(array.flatten(this.filters.map(function (f) f.keys))));
1126                     memoize(this, "commandHive", function hive() Hive(this.filters, "command"));
1127                     memoize(this, "inputHive", function hive() Hive(this.filters, "input"));
1128                 },
1129
1130                 has: function (key) Set.has(this.pass, key) || Set.has(this.commandHive.stack.mappings, key),
1131
1132                 get pass() (this.flush(), this.pass),
1133
1134                 parse: function parse() {
1135                     let value = parse.superapply(this, arguments);
1136                     value.forEach(function (filter) {
1137                         let vals = Option.splitList(filter.result);
1138                         filter.keys = DOM.Event.parse(vals[0]).map(DOM.Event.closure.stringify);
1139
1140                         filter.commandKeys = vals.slice(1).map(DOM.Event.closure.canonicalKeys);
1141                         filter.inputKeys = filter.commandKeys.filter(bind("test", /^<[ACM]-/));
1142                     });
1143                     return value;
1144                 },
1145
1146                 keepQuotes: true,
1147
1148                 setter: function (value) {
1149                     this.flush();
1150                     return value;
1151                 }
1152             });
1153
1154         options.add(["strictfocus", "sf"],
1155             "Prevent scripts from focusing input elements without user intervention",
1156             "sitemap", "'chrome:*':laissez-faire,*:moderate",
1157             {
1158                 values: {
1159                     despotic: "Only allow focus changes when explicitly requested by the user",
1160                     moderate: "Allow focus changes after user-initiated focus change",
1161                     "laissez-faire": "Always allow focus changes"
1162                 }
1163             });
1164
1165         options.add(["timeout", "tmo"],
1166             "Whether to execute a shorter key command after a timeout when a longer command exists",
1167             "boolean", true);
1168
1169         options.add(["timeoutlen", "tmol"],
1170             "Maximum time (milliseconds) to wait for a longer key command when a shorter one exists",
1171             "number", 1000);
1172     }
1173 });
1174
1175 // vim: set fdm=marker sw=4 sts=4 ts=8 et: