]> git.donarmstrong.com Git - dactyl.git/blob - common/content/events.js
8006c4cdb422a0aa203159400d69d58ed011c922
[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-2013 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(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 = this) {
216         method.wrapper = wrappedListener;
217         wrappedListener.wrapped = method;
218         function wrappedListener(event) {
219             try {
220                 method.apply(self, arguments);
221             }
222             catch (e) {
223                 dactyl.reportError(e);
224                 if (e.message == "Interrupted")
225                     dactyl.echoerr(_("error.interrupted"), commandline.FORCE_SINGLELINE);
226                 else
227                     dactyl.echoerr(_("event.error", event.type, e.echoerr || e),
228                                    commandline.FORCE_SINGLELINE);
229             }
230         };
231         return wrappedListener;
232     },
233
234     /**
235      * @property {boolean} Whether synthetic key events are currently being
236      *     processed.
237      */
238     feedingKeys: false,
239
240     /**
241      * Initiates the recording of a key event macro.
242      *
243      * @param {string} macro The name for the macro.
244      */
245     _recording: null,
246     get recording() this._recording,
247
248     set recording(macro) {
249         dactyl.assert(macro == null || /[a-zA-Z0-9]/.test(macro),
250                       _("macro.invalid", macro));
251
252         modes.recording = macro;
253
254         if (/[A-Z]/.test(macro)) { // Append.
255             macro = macro.toLowerCase();
256             this._macroKeys = DOM.Event.iterKeys(editor.getRegister(macro))
257                                  .toArray();
258         }
259         else if (macro) { // Record afresh.
260             this._macroKeys = [];
261         }
262         else if (this.recording) { // Save.
263             editor.setRegister(this.recording, this._macroKeys.join(""));
264
265             dactyl.log(_("macro.recorded", this.recording, this._macroKeys.join("")), 9);
266             dactyl.echomsg(_("macro.recorded", this.recording));
267         }
268         this._recording = macro || null;
269     },
270
271     /**
272      * Replays a macro.
273      *
274      * @param {string} The name of the macro to replay.
275      * @returns {boolean}
276      */
277     playMacro: function (macro) {
278         dactyl.assert(/^[a-zA-Z0-9@]$/.test(macro),
279                       _("macro.invalid", macro));
280
281         if (macro == "@")
282             dactyl.assert(this._lastMacro, _("macro.noPrevious"));
283         else
284             this._lastMacro = macro.toLowerCase(); // XXX: sets last played macro, even if it does not yet exist
285
286         let keys = editor.getRegister(this._lastMacro);
287         if (keys)
288             return modes.withSavedValues(["replaying"], function () {
289                 this.replaying = true;
290                 return events.feedkeys(keys, { noremap: true });
291             });
292
293         // TODO: ignore this like Vim?
294         dactyl.echoerr(_("macro.noSuch", this._lastMacro));
295         return false;
296     },
297
298     /**
299      * Returns all macros matching *filter*.
300      *
301      * @param {string} filter A regular expression filter string. A null
302      *     filter selects all macros.
303      */
304     getMacros: function (filter) {
305         let re = RegExp(filter || "");
306         return ([k, m.text] for ([k, m] in editor.registers) if (re.test(k)));
307     },
308
309     /**
310      * Deletes all macros matching *filter*.
311      *
312      * @param {string} filter A regular expression filter string. A null
313      *     filter deletes all macros.
314      */
315     deleteMacros: function (filter) {
316         let re = RegExp(filter || "");
317         for (let [item, ] in editor.registers) {
318             if (!filter || re.test(item))
319                 editor.registers.remove(item);
320         }
321     },
322
323     /**
324      * Feeds a list of events to *target* or the originalTarget member
325      * of each event if *target* is null.
326      *
327      * @param {EventTarget} target The destination node for the events.
328      *      @optional
329      * @param {[Event]} list The events to dispatch.
330      * @param {object} extra Extra properties for processing by dactyl.
331      *      @optional
332      */
333     feedevents: function feedevents(target, list, extra) {
334         list.forEach(function _feedevent(event, i) {
335             let elem = target || event.originalTarget;
336             if (elem) {
337                 let doc = elem.ownerDocument || elem.document || elem;
338                 let evt = DOM.Event(doc, event.type, event);
339                 DOM.Event.dispatch(elem, evt, extra);
340             }
341             else if (i > 0 && event.type === "keypress")
342                 events.events.keypress.call(events, event);
343         });
344     },
345
346     /**
347      * Pushes keys onto the event queue from dactyl. It is similar to
348      * Vim's feedkeys() method, but cannot cope with 2 partially-fed
349      * strings, you have to feed one parseable string.
350      *
351      * @param {string} keys A string like "2<C-f>" to push onto the event
352      *     queue. If you want "<" to be taken literally, prepend it with a
353      *     "\\".
354      * @param {boolean} noremap Whether recursive mappings should be
355      *     disallowed.
356      * @param {boolean} silent Whether the command should be echoed to the
357      *     command line.
358      * @returns {boolean}
359      */
360     feedkeys: function (keys, noremap, quiet, mode) {
361         try {
362             var savedEvents = this._processor && this._processor.keyEvents;
363
364             var wasFeeding = this.feedingKeys;
365             this.feedingKeys = true;
366
367             var wasQuiet = commandline.quiet;
368             if (quiet)
369                 commandline.quiet = quiet;
370
371             for (let [, evt_obj] in Iterator(DOM.Event.parse(keys))) {
372                 let now = Date.now();
373                 let key = DOM.Event.stringify(evt_obj);
374                 for (let type in values(["keydown", "keypress", "keyup"])) {
375                     let evt = update({}, evt_obj, { type: type });
376                     if (type !== "keypress" && !evt.keyCode)
377                         evt.keyCode = evt._keyCode || 0;
378
379                     if (isObject(noremap))
380                         update(evt, noremap);
381                     else
382                         evt.noremap = !!noremap;
383                     evt.isMacro = true;
384                     evt.dactylMode = mode;
385                     evt.dactylSavedEvents = savedEvents;
386                     DOM.Event.feedingEvent = evt;
387
388                     let doc = document.commandDispatcher.focusedWindow.document;
389
390                     let target = dactyl.focusedElement
391                               || ["complete", "interactive"].indexOf(doc.readyState) >= 0 && doc.documentElement
392                               || doc.defaultView;
393
394                     if (target instanceof Element && !Events.isInputElement(target) &&
395                         ["<Return>", "<Space>"].indexOf(key) == -1)
396                         target = target.ownerDocument.documentElement;
397
398                     let event = DOM.Event(doc, type, evt);
399                     if (!evt_obj.dactylString && !mode)
400                         DOM.Event.dispatch(target, event, evt);
401                     else if (type === "keypress")
402                         events.events.keypress.call(events, event);
403                 }
404
405                 if (!this.feedingKeys)
406                     return false;
407             }
408         }
409         catch (e) {
410             util.reportError(e);
411         }
412         finally {
413             DOM.Event.feedingEvent = null;
414             this.feedingKeys = wasFeeding;
415             if (quiet)
416                 commandline.quiet = wasQuiet;
417             dactyl.triggerObserver("events.doneFeeding");
418         }
419         return true;
420     },
421
422     canonicalKeys: deprecated("DOM.Event.canonicalKeys", { get: function canonicalKeys() DOM.Event.closure.canonicalKeys }),
423     create:        deprecated("DOM.Event", function create() DOM.Event.apply(null, arguments)),
424     dispatch:      deprecated("DOM.Event.dispatch", function dispatch() DOM.Event.dispatch.apply(DOM.Event, arguments)),
425     fromString:    deprecated("DOM.Event.parse", { get: function fromString() DOM.Event.closure.parse }),
426     iterKeys:      deprecated("DOM.Event.iterKeys", { get: function iterKeys() DOM.Event.closure.iterKeys }),
427
428     toString: function toString() {
429         if (!arguments.length)
430             return toString.supercall(this);
431
432         deprecated.warn(toString, "toString", "DOM.Event.stringify");
433         return DOM.Event.stringify.apply(DOM.Event, arguments);
434     },
435
436     get defaultTarget() dactyl.focusedElement || content.document.body || document.documentElement,
437
438     /**
439      * Returns true if there's a known native key handler for the given
440      * event in the given mode.
441      *
442      * @param {Event} event A keypress event.
443      * @param {Modes.Mode} mode The main mode.
444      * @param {boolean} passUnknown Whether unknown keys should be passed.
445      */
446     hasNativeKey: function hasNativeKey(event, mode, passUnknown) {
447         if (mode.input && event.charCode && !(event.ctrlKey || event.metaKey))
448             return true;
449
450         if (!passUnknown)
451             return false;
452
453         var elements = document.getElementsByTagNameNS(XUL, "key");
454         var filters = [];
455
456         if (event.keyCode)
457             filters.push(["keycode", this._code_nativeKey[event.keyCode]]);
458         if (event.charCode) {
459             let key = String.fromCharCode(event.charCode);
460             filters.push(["key", key.toUpperCase()],
461                          ["key", key.toLowerCase()]);
462         }
463
464         let accel = config.OS.isMacOSX ? "metaKey" : "ctrlKey";
465
466         let access = iter({ 1: "shiftKey", 2: "ctrlKey", 4: "altKey", 8: "metaKey" })
467                         .filter(function ([k, v]) this & k,
468                                 prefs.get("ui.key.chromeAccess"))
469                         .map(([k, v]) => [v, true])
470                         .toObject();
471
472     outer:
473         for (let [, key] in iter(elements))
474             if (filters.some(([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, ([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(([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(() => buffer.loaded, this,
546                      maxWaitTime * 1000, true);
547
548         dactyl.echo("", commandline.FORCE_SINGLELINE);
549         if (!buffer.loaded)
550             dactyl.echoerr(_("macro.loadFailed", maxWaitTime));
551
552         return buffer.loaded;
553     },
554
555     /**
556      * Ensures that the currently focused element is visible and blurs
557      * it if it's not.
558      */
559     checkFocus: function () {
560         if (dactyl.focusedElement) {
561             let rect = dactyl.focusedElement.getBoundingClientRect();
562             if (!rect.width || !rect.height) {
563                 services.focus.clearFocus(window);
564                 document.commandDispatcher.focusedWindow = content;
565                 // onFocusChange needs to die.
566                 this.onFocusChange();
567             }
568         }
569     },
570
571     events: {
572         blur: function onBlur(event) {
573             let elem = event.originalTarget;
574             if (DOM(elem).isEditable)
575                 util.trapErrors("removeEditActionListener",
576                                 DOM(elem).editor, editor);
577
578             if (elem instanceof Window && services.focus.activeWindow == null
579                 && document.commandDispatcher.focusedWindow !== window) {
580                 // Deals with circumstances where, after the main window
581                 // blurs while a collapsed frame has focus, re-activating
582                 // the main window does not restore focus and we lose key
583                 // input.
584                 services.focus.clearFocus(window);
585                 document.commandDispatcher.focusedWindow = Editor.getEditor(content) ? window : content;
586             }
587
588             let hold = modes.topOfStack.params.holdFocus;
589             if (elem == hold) {
590                 dactyl.focus(hold);
591                 this.timeout(function () { dactyl.focus(hold); });
592             }
593         },
594
595         // TODO: Merge with onFocusChange
596         focus: function onFocus(event) {
597             let elem = event.originalTarget;
598             if (DOM(elem).isEditable)
599                 util.trapErrors("addEditActionListener",
600                                 DOM(elem).editor, editor);
601
602             if (elem == window)
603                 overlay.activeWindow = window;
604
605             overlay.setData(elem, "had-focus", true);
606             if (event.target instanceof Ci.nsIDOMXULTextBoxElement)
607                 if (Events.isHidden(elem, true))
608                     elem.blur();
609
610             let win = (elem.ownerDocument || elem).defaultView || elem;
611
612             if (!(services.focus.getLastFocusMethod(win) & 0x3000)
613                 && events.isContentNode(elem)
614                 && !buffer.focusAllowed(elem)
615                 && isinstance(elem, [Ci.nsIDOMHTMLInputElement,
616                                      Ci.nsIDOMHTMLSelectElement,
617                                      Ci.nsIDOMHTMLTextAreaElement,
618                                      Ci.nsIDOMWindow])) {
619
620                 if (elem.frameElement)
621                     dactyl.focusContent(true);
622                 else if (!(elem instanceof Window) || Editor.getEditor(elem))
623                     dactyl.focus(window);
624             }
625
626             if (elem instanceof Element)
627                 delete overlay.getData(elem)["focus-allowed"];
628         },
629
630         /*
631         onFocus: function onFocus(event) {
632             let elem = event.originalTarget;
633             if (!(elem instanceof Element))
634                 return;
635             let win = elem.ownerDocument.defaultView;
636
637             try {
638                 util.dump(elem, services.focus.getLastFocusMethod(win) & (0x7000));
639                 if (buffer.focusAllowed(win))
640                     win.dactylLastFocus = elem;
641                 else if (isinstance(elem, [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement])) {
642                     if (win.dactylLastFocus)
643                         dactyl.focus(win.dactylLastFocus);
644                     else
645                         elem.blur();
646                 }
647             }
648             catch (e) {
649                 util.dump(win, String(elem.ownerDocument), String(elem.ownerDocument && elem.ownerDocument.defaultView));
650                 util.reportError(e);
651             }
652         },
653         */
654
655         input: function onInput(event) {
656             event.originalTarget.dactylKeyPress = undefined;
657         },
658
659         // this keypress handler gets always called first, even if e.g.
660         // the command-line has focus
661         // TODO: ...help me...please...
662         keypress: function onKeyPress(event) {
663             event.dactylDefaultPrevented = event.defaultPrevented;
664
665             let duringFeed = this.duringFeed || [];
666             this.duringFeed = [];
667             try {
668                 let ourEvent = DOM.Event.feedingEvent;
669                 DOM.Event.feedingEvent = null;
670                 if (ourEvent)
671                     for (let [k, v] in Iterator(ourEvent))
672                         if (!(k in event))
673                             event[k] = v;
674
675                 let key = DOM.Event.stringify(ourEvent || event);
676                 event.dactylString = key;
677
678                 // Hack to deal with <BS> and so forth not dispatching input
679                 // events
680                 if (key && event.originalTarget instanceof Ci.nsIDOMHTMLInputElement && !modes.main.passthrough) {
681                     let elem = event.originalTarget;
682                     elem.dactylKeyPress = elem.value;
683                     util.timeout(function () {
684                         if (elem.dactylKeyPress !== undefined && elem.value !== elem.dactylKeyPress)
685                             DOM(elem).dactylInput();
686                         elem.dactylKeyPress = undefined;
687                     });
688                 }
689
690                 if (!key)
691                      return null;
692
693                 if (modes.recording && !event.isReplay)
694                     events._macroKeys.push(key);
695
696                 // feedingKeys needs to be separate from interrupted so
697                 // we can differentiate between a recorded <C-c>
698                 // interrupting whatever it's started and a real <C-c>
699                 // interrupting our playback.
700                 if (events.feedingKeys && !event.isMacro) {
701                     if (key == "<C-c>") {
702                         events.feedingKeys = false;
703                         if (modes.replaying) {
704                             modes.replaying = false;
705                             this.timeout(function () { dactyl.echomsg(_("macro.canceled", this._lastMacro)); }, 100);
706                         }
707                     }
708                     else
709                         duringFeed.push(event);
710
711                     return Events.kill(event);
712                 }
713
714                 if (!this.processor) {
715                     let mode = modes.getStack(0);
716                     if (event.dactylMode)
717                         mode = Modes.StackElement(event.dactylMode);
718
719                     let ignore = false;
720
721                     if (mode.main == modes.PASS_THROUGH)
722                         ignore = !Events.isEscape(key) && key != "<C-v>";
723                     else if (mode.main == modes.QUOTE) {
724                         if (modes.getStack(1).main == modes.PASS_THROUGH) {
725                             mode = Modes.StackElement(modes.getStack(2).main);
726                             ignore = Events.isEscape(key);
727                         }
728                         else if (events.shouldPass(event))
729                             mode = Modes.StackElement(modes.getStack(1).main);
730                         else
731                             ignore = true;
732
733                         modes.pop();
734                     }
735                     else if (!event.isMacro && !event.noremap && events.shouldPass(event))
736                         ignore = true;
737
738                     events.dbg("\n\n");
739                     events.dbg("ON KEYPRESS " + key + " ignore: " + ignore,
740                                event.originalTarget instanceof Element ? event.originalTarget : String(event.originalTarget));
741
742                     if (ignore)
743                         return null;
744
745                     // FIXME: Why is this hard coded? --Kris
746                     if (key == "<C-c>")
747                         util.interrupted = true;
748
749                     this.processor = ProcessorStack(mode, mappings.hives.array, event.noremap);
750                     this.processor.keyEvents = this.keyEvents;
751                 }
752
753                 let { keyEvents, processor } = this;
754                 this._processor = processor;
755                 this.processor = null;
756                 this.keyEvents = [];
757
758                 if (!processor.process(event)) {
759                     this.keyEvents = keyEvents;
760                     this.processor = processor;
761                 }
762
763             }
764             catch (e) {
765                 dactyl.reportError(e);
766             }
767             finally {
768                 [duringFeed, this.duringFeed] = [this.duringFeed, duringFeed];
769                 if (this.feedingKeys)
770                     this.duringFeed = this.duringFeed.concat(duringFeed);
771                 else
772                     for (let event in values(duringFeed))
773                         try {
774                             DOM.Event.dispatch(event.originalTarget, event, event);
775                         }
776                         catch (e) {
777                             util.reportError(e);
778                         }
779             }
780         },
781
782         keyup: function onKeyUp(event) {
783             if (event.type == "keydown")
784                 this.keyEvents.push(event);
785             else if (!this.processor)
786                 this.keyEvents = [];
787
788             let pass = this.passing && !event.isMacro ||
789                     DOM.Event.feedingEvent && DOM.Event.feedingEvent.isReplay ||
790                     event.isReplay ||
791                     modes.main == modes.PASS_THROUGH ||
792                     modes.main == modes.QUOTE
793                         && modes.getStack(1).main !== modes.PASS_THROUGH
794                         && !this.shouldPass(event) ||
795                     !modes.passThrough && this.shouldPass(event) ||
796                     !this.processor && event.type === "keydown"
797                         && options.get("passunknown").getKey(modes.main.allBases)
798                         && let (key = DOM.Event.stringify(event))
799                             !(modes.main.count && /^\d$/.test(key) ||
800                               modes.main.allBases.some(
801                                 mode => mappings.hives
802                                                 .some(hive => hive.get(mode, key)
803                                                            || hive.getCandidates(mode, key))));
804
805             events.dbg("ON " + event.type.toUpperCase() + " " + DOM.Event.stringify(event) +
806                        " passing: " + this.passing + " " +
807                        " pass: " + pass +
808                        " replay: " + event.isReplay +
809                        " macro: " + event.isMacro);
810
811             if (event.type === "keydown")
812                 this.passing = pass;
813
814             // Prevents certain sites from transferring focus to an input box
815             // before we get a chance to process our key bindings on the
816             // "keypress" event.
817             if (!pass)
818                 event.stopPropagation();
819         },
820         keydown: function onKeyDown(event) {
821             if (!event.isMacro)
822                 this.passing = false;
823             this.events.keyup.call(this, event);
824         },
825
826         mousedown: function onMouseDown(event) {
827             let elem = event.target;
828             let win = elem.ownerDocument && elem.ownerDocument.defaultView || elem;
829
830             for (; win; win = win != win.parent && win.parent) {
831                 for (; elem instanceof Element; elem = elem.parentNode)
832                     overlay.setData(elem, "focus-allowed", true);
833                 overlay.setData(win.document, "focus-allowed", true);
834             }
835         },
836
837         resize: function onResize(event) {
838             if (window.fullScreen != this._fullscreen) {
839                 statusline.statusBar.removeAttribute("moz-collapsed");
840                 this._fullscreen = window.fullScreen;
841                 dactyl.triggerObserver("fullscreen", this._fullscreen);
842                 autocommands.trigger("Fullscreen", { url: this._fullscreen ? "on" : "off", state: this._fullscreen });
843             }
844             statusline.updateZoomLevel();
845         }
846     },
847
848     // argument "event" is deliberately not used, as i don't seem to have
849     // access to the real focus target
850     // Huh? --djk
851     onFocusChange: util.wrapCallback(function onFocusChange(event) {
852         function hasHTMLDocument(win) win && win.document && win.document instanceof Ci.nsIDOMHTMLDocument
853         if (dactyl.ignoreFocus)
854             return;
855
856         let win  = window.document.commandDispatcher.focusedWindow;
857         let elem = window.document.commandDispatcher.focusedElement;
858
859         if (elem == null && Editor.getEditor(win))
860             elem = win;
861
862         if (win && win.top == content && dactyl.has("tabs"))
863             buffer.focusedFrame = win;
864
865         try {
866             if (elem && elem.readOnly)
867                 return;
868
869             if (isinstance(elem, [Ci.nsIDOMHTMLEmbedElement, Ci.nsIDOMHTMLEmbedElement])) {
870                 if (!modes.main.passthrough && modes.main != modes.EMBED)
871                     modes.push(modes.EMBED);
872                 return;
873             }
874
875             let haveInput = modes.stack.some(m => m.main.input);
876
877             if (DOM(elem || win).isEditable) {
878                 if (!haveInput)
879                     if (!isinstance(modes.main, [modes.INPUT, modes.TEXT_EDIT, modes.VISUAL]))
880                         if (options["insertmode"])
881                             modes.push(modes.INSERT);
882                         else {
883                             modes.push(modes.TEXT_EDIT);
884                             if (elem.selectionEnd - elem.selectionStart > 0)
885                                 modes.push(modes.VISUAL);
886                         }
887
888                 if (hasHTMLDocument(win))
889                     buffer.lastInputField = elem || win;
890                 return;
891             }
892
893             if (elem && Events.isInputElement(elem)) {
894                 if (!haveInput)
895                     modes.push(modes.INSERT);
896
897                 if (hasHTMLDocument(win))
898                     buffer.lastInputField = elem;
899                 return;
900             }
901
902             if (config.focusChange) {
903                 config.focusChange(win);
904                 return;
905             }
906
907             let urlbar = document.getElementById("urlbar");
908             if (elem == null && urlbar && urlbar.inputField == this._lastFocus.get())
909                 util.threadYield(true); // Why? --Kris
910
911             while (modes.main.ownsFocus
912                     && let ({ ownsFocus } = modes.topOfStack.params)
913                          (!ownsFocus ||
914                              ownsFocus.get() != elem &&
915                              ownsFocus.get() != win)
916                     && !modes.topOfStack.params.holdFocus)
917                  modes.pop(null, { fromFocus: true });
918         }
919         finally {
920             this._lastFocus = util.weakReference(elem);
921
922             if (modes.main.ownsFocus)
923                 modes.topOfStack.params.ownsFocus = util.weakReference(elem);
924         }
925     }),
926
927     onSelectionChange: function onSelectionChange(event) {
928         // Ignore selection events caused by editor commands.
929         if (editor.inEditMap || modes.main == modes.OPERATOR)
930             return;
931
932         let controller = document.commandDispatcher.getControllerForCommand("cmd_copy");
933         let couldCopy = controller && controller.isCommandEnabled("cmd_copy");
934
935         if (couldCopy) {
936             if (modes.main == modes.TEXT_EDIT)
937                 modes.push(modes.VISUAL);
938             else if (modes.main == modes.CARET)
939                 modes.push(modes.VISUAL);
940         }
941     },
942
943     shouldPass: function shouldPass(event)
944         !event.noremap && (!dactyl.focusedElement || events.isContentNode(dactyl.focusedElement)) &&
945         options.get("passkeys").has(DOM.Event.stringify(event))
946 }, {
947     ABORT: {},
948     KILL: true,
949     PASS: false,
950     PASS_THROUGH: {},
951     WAIT: null,
952
953     isEscape: function isEscape(event)
954         let (key = isString(event) ? event : DOM.Event.stringify(event))
955             key === "<Esc>" || key === "<C-[>",
956
957     isHidden: function isHidden(elem, aggressive) {
958         if (DOM(elem).style.visibility !== "visible")
959             return true;
960
961         if (aggressive)
962             for (let e = elem; e instanceof Element; e = e.parentNode) {
963                 if (!/set$/.test(e.localName) && e.boxObject && e.boxObject.height === 0)
964                     return true;
965                 else if (e.namespaceURI == XUL && e.localName === "panel")
966                     break;
967             }
968         return false;
969     },
970
971     isInputElement: function isInputElement(elem) {
972         return DOM(elem).isEditable ||
973                isinstance(elem, [Ci.nsIDOMHTMLEmbedElement,
974                                  Ci.nsIDOMHTMLObjectElement,
975                                  Ci.nsIDOMHTMLSelectElement]);
976     },
977
978     kill: function kill(event) {
979         event.stopPropagation();
980         event.preventDefault();
981     }
982 }, {
983     contexts: function initContexts(dactyl, modules, window) {
984         update(Events.prototype, {
985             hives: contexts.Hives("events", EventHive),
986             user: contexts.hives.events.user,
987             builtin: contexts.hives.events.builtin
988         });
989     },
990
991     commands: function initCommands() {
992         commands.add(["delmac[ros]"],
993             "Delete macros",
994             function (args) {
995                 dactyl.assert(!args.bang || !args[0], _("error.invalidArgument"));
996
997                 if (args.bang)
998                     events.deleteMacros();
999                 else if (args[0])
1000                     events.deleteMacros(args[0]);
1001                 else
1002                     dactyl.echoerr(_("error.argumentRequired"));
1003             }, {
1004                 argCount: "?",
1005                 bang: true,
1006                 completer: function (context) completion.macro(context),
1007                 literal: 0
1008             });
1009
1010         commands.add(["mac[ros]"],
1011             "List all macros",
1012             function (args) { completion.listCompleter("macro", args[0]); }, {
1013                 argCount: "?",
1014                 completer: function (context) completion.macro(context)
1015             });
1016     },
1017     completion: function initCompletion() {
1018         completion.macro = function macro(context) {
1019             context.title = ["Macro", "Keys"];
1020             context.completions = [item for (item in events.getMacros())];
1021         };
1022     },
1023     mappings: function initMappings() {
1024
1025         mappings.add([modes.MAIN],
1026             ["<A-b>", "<pass-next-key-builtin>"], "Process the next key as a builtin mapping",
1027             function () {
1028                 events.processor = ProcessorStack(modes.getStack(0), mappings.hives.array, true);
1029                 events.processor.keyEvents = events.keyEvents;
1030             });
1031
1032         mappings.add([modes.MAIN],
1033             ["<C-z>", "<pass-all-keys>"], "Temporarily ignore all " + config.appName + " key bindings",
1034             function () {
1035                 if (modes.main != modes.PASS_THROUGH)
1036                     modes.push(modes.PASS_THROUGH);
1037             });
1038
1039         mappings.add([modes.MAIN, modes.PASS_THROUGH, modes.QUOTE],
1040             ["<C-v>", "<pass-next-key>"], "Pass through next key",
1041             function () {
1042                 if (modes.main == modes.QUOTE)
1043                     return Events.PASS;
1044                 modes.push(modes.QUOTE);
1045             });
1046
1047         mappings.add([modes.BASE],
1048             ["<CapsLock>"], "Do Nothing",
1049             function () {});
1050
1051         mappings.add([modes.BASE],
1052             ["<Nop>"], "Do nothing",
1053             function () {});
1054
1055         mappings.add([modes.BASE],
1056             ["<Pass>"], "Pass the events consumed by the last executed mapping",
1057             function ({ keypressEvents: [event] }) {
1058                 dactyl.assert(event.dactylSavedEvents,
1059                               _("event.nothingToPass"));
1060                 return function () {
1061                     events.feedevents(null, event.dactylSavedEvents,
1062                                       { skipmap: true, isMacro: true, isReplay: true });
1063                 };
1064             });
1065
1066         // macros
1067         mappings.add([modes.COMMAND],
1068             ["q", "<record-macro>"], "Record a key sequence into a macro",
1069             function ({ arg }) {
1070                 util.assert(arg == null || /^[a-z]$/i.test(arg));
1071                 events._macroKeys.pop();
1072                 events.recording = arg;
1073             },
1074             { get arg() !modes.recording });
1075
1076         mappings.add([modes.COMMAND],
1077             ["@", "<play-macro>"], "Play a macro",
1078             function ({ arg, count }) {
1079                 count = Math.max(count, 1);
1080                 while (count--)
1081                     events.playMacro(arg);
1082             },
1083             { arg: true, count: true });
1084
1085         mappings.add([modes.COMMAND],
1086             ["<A-m>s", "<sleep>"], "Sleep for {count} milliseconds before continuing macro playback",
1087             function ({ command, count }) {
1088                 let now = Date.now();
1089                 dactyl.assert(count, _("error.countRequired", command));
1090                 if (events.feedingKeys)
1091                     util.sleep(count);
1092             },
1093             { count: true });
1094
1095         mappings.add([modes.COMMAND],
1096             ["<A-m>l", "<wait-for-page-load>"], "Wait for the current page to finish loading before continuing macro playback",
1097             function ({ count }) {
1098                 if (events.feedingKeys && !events.waitForPageLoad(count)) {
1099                     util.interrupted = true;
1100                     throw Error("Interrupted");
1101                 }
1102             },
1103             { count: true });
1104     },
1105     options: function initOptions() {
1106         const Hive = Class("Hive", {
1107             init: function init(values, map) {
1108                 this.name = "passkeys:" + map;
1109                 this.stack = MapHive.Stack(values.map(v => Map(v[map + "Keys"])));
1110                 function Map(keys) ({
1111                     execute: function () Events.PASS_THROUGH,
1112                     keys: keys
1113                 });
1114             },
1115
1116             get active() this.stack.length,
1117
1118             get: function get(mode, key) this.stack.mappings[key],
1119
1120             getCandidates: function getCandidates(mode, key) this.stack.candidates[key]
1121         });
1122         options.add(["passkeys", "pk"],
1123             "Pass certain keys through directly for the given URLs",
1124             "sitemap", "", {
1125                 flush: function flush() {
1126                     memoize(this, "filters", function () this.value.filter(function (f) f(buffer.documentURI)));
1127                     memoize(this, "pass", function () Set(array.flatten(this.filters.map(function (f) f.keys))));
1128                     memoize(this, "commandHive", function hive() Hive(this.filters, "command"));
1129                     memoize(this, "inputHive", function hive() Hive(this.filters, "input"));
1130                 },
1131
1132                 has: function (key) Set.has(this.pass, key) || Set.has(this.commandHive.stack.mappings, key),
1133
1134                 get pass() (this.flush(), this.pass),
1135
1136                 parse: function parse() {
1137                     let value = parse.superapply(this, arguments);
1138                     value.forEach(function (filter) {
1139                         let vals = Option.splitList(filter.result);
1140                         filter.keys = DOM.Event.parse(vals[0]).map(DOM.Event.closure.stringify);
1141
1142                         filter.commandKeys = vals.slice(1).map(DOM.Event.closure.canonicalKeys);
1143                         filter.inputKeys = filter.commandKeys.filter(bind("test", /^<[ACM]-/));
1144                     });
1145                     return value;
1146                 },
1147
1148                 keepQuotes: true,
1149
1150                 setter: function (value) {
1151                     this.flush();
1152                     return value;
1153                 }
1154             });
1155
1156         options.add(["strictfocus", "sf"],
1157             "Prevent scripts from focusing input elements without user intervention",
1158             "sitemap", "'chrome:*':laissez-faire,*:moderate",
1159             {
1160                 values: {
1161                     despotic: "Only allow focus changes when explicitly requested by the user",
1162                     moderate: "Allow focus changes after user-initiated focus change",
1163                     "laissez-faire": "Always allow focus changes"
1164                 }
1165             });
1166
1167         options.add(["timeout", "tmo"],
1168             "Whether to execute a shorter key command after a timeout when a longer command exists",
1169             "boolean", true);
1170
1171         options.add(["timeoutlen", "tmol"],
1172             "Maximum time (milliseconds) to wait for a longer key command when a shorter one exists",
1173             "number", 1000);
1174     }
1175 });
1176
1177 // vim: set fdm=marker sw=4 sts=4 ts=8 et: