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>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
12 * A hive used mainly for tracking event listeners and cleaning them up when a
15 var EventHive = Class("EventHive", Contexts.Hive, {
16 init: function init(group) {
17 init.supercall(this, group);
18 this.sessionListeners = [];
21 cleanup: function cleanup() {
25 _events: function _events(event, callback) {
27 var [self, events] = [null, array.toObject([[event, callback]])];
29 [self, events] = [event, event[callback || "events"]];
31 if (Set.has(events, "input") && !Set.has(events, "dactyl-input"))
32 events["dactyl-input"] = events.input;
34 return [self, events];
38 * Adds an event listener for this session and removes it on
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
49 listen: function (target, event, callback, capture, allowUntrusted) {
50 var [self, events] = this._events(event, callback);
52 for (let [event, callback] in Iterator(events)) {
53 let args = [util.weakReference(target),
54 util.weakReference(self),
56 this.wrapListener(callback, self),
60 target.addEventListener.apply(target, args.slice(2));
61 this.sessionListeners.push(args);
66 * Remove an event listener.
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.
74 unlisten: function (target, event, callback, capture) {
76 var [self, events] = this._events(event, callback);
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) {
86 elem.removeEventListener.apply(elem, args.slice(2));
93 get wrapListener() events.closure.wrapListener
99 var Events = Module("events", {
105 overlay.overlayWindow(window, {
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 }]]]
115 this._fullscreen = window.fullScreen;
116 this._lastFocus = { get: function () null };
117 this._macroKeys = [];
118 this._lastMacro = "";
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");
132 update: function update(elem) {
134 if (elem instanceof Ci.nsIAutoCompletePopup
135 || elem.localName == "tooltip"
136 || !elem.popupBoxObject)
139 if (!~this.active.indexOf(elem))
140 this.active.push(elem);
143 this.active = this.active.filter(function (e) e.popupBoxObject && e.popupBoxObject.popupState != "closed");
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);
152 DOMMenuBarActive: function onDOMMenuBarActive(event) {
153 this.activeMenubar = event.target;
154 if (modes.main != modes.MENU)
155 modes.push(modes.MENU);
158 DOMMenuBarInactive: function onDOMMenuBarInactive(event) {
159 this.activeMenubar = null;
160 modes.remove(modes.MENU, true);
163 popupshowing: function onPopupShowing(event) {
164 this.update(event.originalTarget);
167 popupshown: function onPopupShown(event) {
168 let elem = event.originalTarget;
171 if (elem instanceof Ci.nsIAutoCompletePopup) {
172 if (modes.main != modes.AUTOCOMPLETE)
173 modes.push(modes.AUTOCOMPLETE);
175 else if (elem.hidePopup && elem.localName !== "tooltip"
176 && Events.isHidden(elem)
177 && Events.isHidden(elem.parentNode)) {
182 popuphidden: function onPopupHidden(event) {
184 modes.remove(modes.AUTOCOMPLETE);
189 this.listen(window, this, "events", true);
190 this.listen(window, this.popups, "events", true);
193 cleanup: function cleanup() {
194 let elem = dactyl.focusedElement;
195 if (DOM(elem).isEditable)
196 util.trapErrors("removeEditActionListener",
197 DOM(elem).editor, editor);
201 "browser.locationChange": function (webProgress, request, uri) {
202 options.get("passkeys").flush();
204 "modes.change": function (oldMode, newMode) {
205 delete this.processor;
209 get listen() this.builtin.closure.listen,
210 addSessionListener: deprecated("events.listen", { get: function addSessionListener() this.listen }),
213 * Wraps an event listener to ensure that errors are reported.
215 wrapListener: function wrapListener(method, self) {
217 method.wrapper = wrappedListener;
218 wrappedListener.wrapped = method;
219 function wrappedListener(event) {
221 method.apply(self, arguments);
224 dactyl.reportError(e);
225 if (e.message == "Interrupted")
226 dactyl.echoerr(_("error.interrupted"), commandline.FORCE_SINGLELINE);
228 dactyl.echoerr(_("event.error", event.type, e.echoerr || e),
229 commandline.FORCE_SINGLELINE);
232 return wrappedListener;
236 * @property {boolean} Whether synthetic key events are currently being
242 * Initiates the recording of a key event macro.
244 * @param {string} macro The name for the macro.
247 get recording() this._recording,
249 set recording(macro) {
250 dactyl.assert(macro == null || /[a-zA-Z0-9]/.test(macro),
251 _("macro.invalid", macro));
253 modes.recording = macro;
255 if (/[A-Z]/.test(macro)) { // Append.
256 macro = macro.toLowerCase();
257 this._macroKeys = DOM.Event.iterKeys(editor.getRegister(macro))
260 else if (macro) { // Record afresh.
261 this._macroKeys = [];
263 else if (this.recording) { // Save.
264 editor.setRegister(this.recording, this._macroKeys.join(""));
266 dactyl.log(_("macro.recorded", this.recording, this._macroKeys.join("")), 9);
267 dactyl.echomsg(_("macro.recorded", this.recording));
269 this._recording = macro || null;
275 * @param {string} The name of the macro to replay.
278 playMacro: function (macro) {
279 dactyl.assert(/^[a-zA-Z0-9@]$/.test(macro),
280 _("macro.invalid", macro));
283 dactyl.assert(this._lastMacro, _("macro.noPrevious"));
285 this._lastMacro = macro.toLowerCase(); // XXX: sets last played macro, even if it does not yet exist
287 let keys = editor.getRegister(this._lastMacro);
289 return modes.withSavedValues(["replaying"], function () {
290 this.replaying = true;
291 return events.feedkeys(keys, { noremap: true });
294 // TODO: ignore this like Vim?
295 dactyl.echoerr(_("macro.noSuch", this._lastMacro));
300 * Returns all macros matching *filter*.
302 * @param {string} filter A regular expression filter string. A null
303 * filter selects all macros.
305 getMacros: function (filter) {
306 let re = RegExp(filter || "");
307 return ([k, m.text] for ([k, m] in editor.registers) if (re.test(k)));
311 * Deletes all macros matching *filter*.
313 * @param {string} filter A regular expression filter string. A null
314 * filter deletes all macros.
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);
325 * Feeds a list of events to *target* or the originalTarget member
326 * of each event if *target* is null.
328 * @param {EventTarget} target The destination node for the events.
330 * @param {[Event]} list The events to dispatch.
331 * @param {object} extra Extra properties for processing by dactyl.
334 feedevents: function feedevents(target, list, extra) {
335 list.forEach(function _feedevent(event, i) {
336 let elem = target || event.originalTarget;
338 let doc = elem.ownerDocument || elem.document || elem;
339 let evt = DOM.Event(doc, event.type, event);
340 DOM.Event.dispatch(elem, evt, extra);
342 else if (i > 0 && event.type === "keypress")
343 events.events.keypress.call(events, event);
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.
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
355 * @param {boolean} noremap Whether recursive mappings should be
357 * @param {boolean} silent Whether the command should be echoed to the
361 feedkeys: function (keys, noremap, quiet, mode) {
363 var savedEvents = this._processor && this._processor.keyEvents;
365 var wasFeeding = this.feedingKeys;
366 this.feedingKeys = true;
368 var wasQuiet = commandline.quiet;
370 commandline.quiet = quiet;
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;
380 if (isObject(noremap))
381 update(evt, noremap);
383 evt.noremap = !!noremap;
385 evt.dactylMode = mode;
386 evt.dactylSavedEvents = savedEvents;
387 DOM.Event.feedingEvent = evt;
389 let doc = document.commandDispatcher.focusedWindow.document;
391 let target = dactyl.focusedElement
392 || ["complete", "interactive"].indexOf(doc.readyState) >= 0 && doc.documentElement
395 if (target instanceof Element && !Events.isInputElement(target) &&
396 ["<Return>", "<Space>"].indexOf(key) == -1)
397 target = target.ownerDocument.documentElement;
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);
406 if (!this.feedingKeys)
414 DOM.Event.feedingEvent = null;
415 this.feedingKeys = wasFeeding;
417 commandline.quiet = wasQuiet;
418 dactyl.triggerObserver("events.doneFeeding");
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 }),
429 toString: function toString() {
430 if (!arguments.length)
431 return toString.supercall(this);
433 deprecated.warn(toString, "toString", "DOM.Event.stringify");
434 return DOM.Event.stringify.apply(DOM.Event, arguments);
437 get defaultTarget() dactyl.focusedElement || content.document.body || document.documentElement,
440 * Returns true if there's a known native key handler for the given
441 * event in the given mode.
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.
447 hasNativeKey: function hasNativeKey(event, mode, passUnknown) {
448 if (mode.input && event.charCode && !(event.ctrlKey || event.metaKey))
454 var elements = document.getElementsByTagNameNS(XUL, "key");
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()]);
465 let accel = config.OS.isMacOSX ? "metaKey" : "ctrlKey";
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])
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 };
478 let modifiers = (key.getAttribute("modifiers") || "").trim().split(/[\s,]+/);
479 for (let modifier in values(modifiers))
481 case "access": update(keys, access); break;
482 case "accel": keys[accel] = true; break;
483 default: keys[modifier + "Key"] = true; break;
485 if (!iter.some(keys, function ([k, v]) v && needed[k]))
487 for (let [k, v] in iter(keys)) {
495 if (iter(needed).every(function ([k, v]) v == keys[k]))
503 * Returns true if *key* is a key code defined to accept/execute input on
506 * @param {string} key The key code to test.
509 isAcceptKey: function (key) key == "<Return>" || key == "<C-j>" || key == "<C-m>",
512 * Returns true if *key* is a key code defined to reject/cancel input on
515 * @param {string} key The key code to test.
518 isCancelKey: function (key) key == "<Esc>" || key == "<C-[>" || key == "<C-c>",
521 * Returns true if *node* belongs to the current content document or any
524 * @param {Node|Document|Window} node The node to test.
527 isContentNode: function isContentNode(node) {
528 let win = (node.ownerDocument || node).defaultView || node;
529 return XPCNativeWrapper(win).top == content;
533 * Waits for the current buffer to successfully finish loading. Returns
534 * true for a successful page load otherwise false.
538 waitForPageLoad: function (time) {
542 dactyl.echo(_("macro.loadWaiting"), commandline.FORCE_SINGLELINE);
544 const maxWaitTime = (time || 25);
545 util.waitFor(function () buffer.loaded, this, maxWaitTime * 1000, true);
547 dactyl.echo("", commandline.FORCE_SINGLELINE);
549 dactyl.echoerr(_("macro.loadFailed", maxWaitTime));
551 return buffer.loaded;
555 * Ensures that the currently focused element is visible and blurs
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();
571 blur: function onBlur(event) {
572 let elem = event.originalTarget;
573 if (DOM(elem).isEditable)
574 util.trapErrors("removeEditActionListener",
575 DOM(elem).editor, editor);
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
583 services.focus.clearFocus(window);
584 document.commandDispatcher.focusedWindow = Editor.getEditor(content) ? window : content;
587 let hold = modes.topOfStack.params.holdFocus;
590 this.timeout(function () { dactyl.focus(hold); });
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);
602 overlay.activeWindow = window;
604 overlay.setData(elem, "had-focus", true);
605 if (event.target instanceof Ci.nsIDOMXULTextBoxElement)
606 if (Events.isHidden(elem, true))
609 let win = (elem.ownerDocument || elem).defaultView || elem;
611 if (!(services.focus.getLastFocusMethod(win) & 0x3000)
612 && events.isContentNode(elem)
613 && !buffer.focusAllowed(elem)
614 && isinstance(elem, [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement, Window])) {
616 if (elem.frameElement)
617 dactyl.focusContent(true);
618 else if (!(elem instanceof Window) || Editor.getEditor(elem))
619 dactyl.focus(window);
622 if (elem instanceof Element)
623 delete overlay.getData(elem)["focus-allowed"];
627 onFocus: function onFocus(event) {
628 let elem = event.originalTarget;
629 if (!(elem instanceof Element))
631 let win = elem.ownerDocument.defaultView;
634 util.dump(elem, services.focus.getLastFocusMethod(win) & (0x7000));
635 if (buffer.focusAllowed(win))
636 win.dactylLastFocus = elem;
637 else if (isinstance(elem, [HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement])) {
638 if (win.dactylLastFocus)
639 dactyl.focus(win.dactylLastFocus);
645 util.dump(win, String(elem.ownerDocument), String(elem.ownerDocument && elem.ownerDocument.defaultView));
651 input: function onInput(event) {
652 event.originalTarget.dactylKeyPress = undefined;
655 // this keypress handler gets always called first, even if e.g.
656 // the command-line has focus
657 // TODO: ...help me...please...
658 keypress: function onKeyPress(event) {
659 event.dactylDefaultPrevented = event.getPreventDefault();
661 let duringFeed = this.duringFeed || [];
662 this.duringFeed = [];
664 let ourEvent = DOM.Event.feedingEvent;
665 DOM.Event.feedingEvent = null;
667 for (let [k, v] in Iterator(ourEvent))
671 let key = DOM.Event.stringify(ourEvent || event);
672 event.dactylString = key;
674 // Hack to deal with <BS> and so forth not dispatching input
676 if (key && event.originalTarget instanceof HTMLInputElement && !modes.main.passthrough) {
677 let elem = event.originalTarget;
678 elem.dactylKeyPress = elem.value;
679 util.timeout(function () {
680 if (elem.dactylKeyPress !== undefined && elem.value !== elem.dactylKeyPress)
681 DOM(elem).dactylInput();
682 elem.dactylKeyPress = undefined;
689 if (modes.recording && !event.isReplay)
690 events._macroKeys.push(key);
692 // feedingKeys needs to be separate from interrupted so
693 // we can differentiate between a recorded <C-c>
694 // interrupting whatever it's started and a real <C-c>
695 // interrupting our playback.
696 if (events.feedingKeys && !event.isMacro) {
697 if (key == "<C-c>") {
698 events.feedingKeys = false;
699 if (modes.replaying) {
700 modes.replaying = false;
701 this.timeout(function () { dactyl.echomsg(_("macro.canceled", this._lastMacro)); }, 100);
705 duringFeed.push(event);
707 return Events.kill(event);
710 if (!this.processor) {
711 let mode = modes.getStack(0);
712 if (event.dactylMode)
713 mode = Modes.StackElement(event.dactylMode);
717 if (mode.main == modes.PASS_THROUGH)
718 ignore = !Events.isEscape(key) && key != "<C-v>";
719 else if (mode.main == modes.QUOTE) {
720 if (modes.getStack(1).main == modes.PASS_THROUGH) {
721 mode = Modes.StackElement(modes.getStack(2).main);
722 ignore = Events.isEscape(key);
724 else if (events.shouldPass(event))
725 mode = Modes.StackElement(modes.getStack(1).main);
731 else if (!event.isMacro && !event.noremap && events.shouldPass(event))
735 events.dbg("ON KEYPRESS " + key + " ignore: " + ignore,
736 event.originalTarget instanceof Element ? event.originalTarget : String(event.originalTarget));
741 // FIXME: Why is this hard coded? --Kris
743 util.interrupted = true;
745 this.processor = ProcessorStack(mode, mappings.hives.array, event.noremap);
746 this.processor.keyEvents = this.keyEvents;
749 let { keyEvents, processor } = this;
750 this._processor = processor;
751 this.processor = null;
754 if (!processor.process(event)) {
755 this.keyEvents = keyEvents;
756 this.processor = processor;
761 dactyl.reportError(e);
764 [duringFeed, this.duringFeed] = [this.duringFeed, duringFeed];
765 if (this.feedingKeys)
766 this.duringFeed = this.duringFeed.concat(duringFeed);
768 for (let event in values(duringFeed))
770 DOM.Event.dispatch(event.originalTarget, event, event);
778 keyup: function onKeyUp(event) {
779 if (event.type == "keydown")
780 this.keyEvents.push(event);
781 else if (!this.processor)
784 let pass = this.passing && !event.isMacro ||
785 DOM.Event.feedingEvent && DOM.Event.feedingEvent.isReplay ||
787 modes.main == modes.PASS_THROUGH ||
788 modes.main == modes.QUOTE
789 && modes.getStack(1).main !== modes.PASS_THROUGH
790 && !this.shouldPass(event) ||
791 !modes.passThrough && this.shouldPass(event) ||
792 !this.processor && event.type === "keydown"
793 && options.get("passunknown").getKey(modes.main.allBases)
794 && let (key = DOM.Event.stringify(event))
795 !(modes.main.count && /^\d$/.test(key) ||
796 modes.main.allBases.some(
797 function (mode) mappings.hives.some(
798 function (hive) hive.get(mode, key) || hive.getCandidates(mode, key))));
800 events.dbg("ON " + event.type.toUpperCase() + " " + DOM.Event.stringify(event) +
801 " passing: " + this.passing + " " +
803 " replay: " + event.isReplay +
804 " macro: " + event.isMacro);
806 if (event.type === "keydown")
809 // Prevents certain sites from transferring focus to an input box
810 // before we get a chance to process our key bindings on the
813 event.stopPropagation();
815 keydown: function onKeyDown(event) {
817 this.passing = false;
818 this.events.keyup.call(this, event);
821 mousedown: function onMouseDown(event) {
822 let elem = event.target;
823 let win = elem.ownerDocument && elem.ownerDocument.defaultView || elem;
825 for (; win; win = win != win.parent && win.parent) {
826 for (; elem instanceof Element; elem = elem.parentNode)
827 overlay.setData(elem, "focus-allowed", true);
828 overlay.setData(win.document, "focus-allowed", true);
832 resize: function onResize(event) {
833 if (window.fullScreen != this._fullscreen) {
834 statusline.statusBar.removeAttribute("moz-collapsed");
835 this._fullscreen = window.fullScreen;
836 dactyl.triggerObserver("fullscreen", this._fullscreen);
837 autocommands.trigger("Fullscreen", { url: this._fullscreen ? "on" : "off", state: this._fullscreen });
839 statusline.updateZoomLevel();
843 // argument "event" is deliberately not used, as i don't seem to have
844 // access to the real focus target
846 onFocusChange: util.wrapCallback(function onFocusChange(event) {
847 function hasHTMLDocument(win) win && win.document && win.document instanceof HTMLDocument
848 if (dactyl.ignoreFocus)
851 let win = window.document.commandDispatcher.focusedWindow;
852 let elem = window.document.commandDispatcher.focusedElement;
854 if (elem == null && Editor.getEditor(win))
857 if (win && win.top == content && dactyl.has("tabs"))
858 buffer.focusedFrame = win;
861 if (elem && elem.readOnly)
864 if (isinstance(elem, [HTMLEmbedElement, HTMLEmbedElement])) {
865 if (!modes.main.passthrough && modes.main != modes.EMBED)
866 modes.push(modes.EMBED);
870 let haveInput = modes.stack.some(function (m) m.main.input);
872 if (DOM(elem || win).isEditable) {
874 if (!isinstance(modes.main, [modes.INPUT, modes.TEXT_EDIT, modes.VISUAL]))
875 if (options["insertmode"])
876 modes.push(modes.INSERT);
878 modes.push(modes.TEXT_EDIT);
879 if (elem.selectionEnd - elem.selectionStart > 0)
880 modes.push(modes.VISUAL);
883 if (hasHTMLDocument(win))
884 buffer.lastInputField = elem || win;
888 if (elem && Events.isInputElement(elem)) {
890 modes.push(modes.INSERT);
892 if (hasHTMLDocument(win))
893 buffer.lastInputField = elem;
897 if (config.focusChange) {
898 config.focusChange(win);
902 let urlbar = document.getElementById("urlbar");
903 if (elem == null && urlbar && urlbar.inputField == this._lastFocus.get())
904 util.threadYield(true); // Why? --Kris
906 while (modes.main.ownsFocus
907 && let ({ ownsFocus } = modes.topOfStack.params)
909 ownsFocus.get() != elem &&
910 ownsFocus.get() != win)
911 && !modes.topOfStack.params.holdFocus)
912 modes.pop(null, { fromFocus: true });
915 this._lastFocus = util.weakReference(elem);
917 if (modes.main.ownsFocus)
918 modes.topOfStack.params.ownsFocus = util.weakReference(elem);
922 onSelectionChange: function onSelectionChange(event) {
923 // Ignore selection events caused by editor commands.
924 if (editor.inEditMap || modes.main == modes.OPERATOR)
927 let controller = document.commandDispatcher.getControllerForCommand("cmd_copy");
928 let couldCopy = controller && controller.isCommandEnabled("cmd_copy");
931 if (modes.main == modes.TEXT_EDIT)
932 modes.push(modes.VISUAL);
933 else if (modes.main == modes.CARET)
934 modes.push(modes.VISUAL);
938 shouldPass: function shouldPass(event)
939 !event.noremap && (!dactyl.focusedElement || events.isContentNode(dactyl.focusedElement)) &&
940 options.get("passkeys").has(DOM.Event.stringify(event))
948 isEscape: function isEscape(event)
949 let (key = isString(event) ? event : DOM.Event.stringify(event))
950 key === "<Esc>" || key === "<C-[>",
952 isHidden: function isHidden(elem, aggressive) {
953 if (DOM(elem).style.visibility !== "visible")
957 for (let e = elem; e instanceof Element; e = e.parentNode) {
958 if (!/set$/.test(e.localName) && e.boxObject && e.boxObject.height === 0)
960 else if (e.namespaceURI == XUL && e.localName === "panel")
966 isInputElement: function isInputElement(elem) {
967 return DOM(elem).isEditable ||
968 isinstance(elem, [HTMLEmbedElement, HTMLObjectElement,
972 kill: function kill(event) {
973 event.stopPropagation();
974 event.preventDefault();
977 contexts: function initContexts(dactyl, modules, window) {
978 update(Events.prototype, {
979 hives: contexts.Hives("events", EventHive),
980 user: contexts.hives.events.user,
981 builtin: contexts.hives.events.builtin
985 commands: function initCommands() {
986 commands.add(["delmac[ros]"],
989 dactyl.assert(!args.bang || !args[0], _("error.invalidArgument"));
992 events.deleteMacros();
994 events.deleteMacros(args[0]);
996 dactyl.echoerr(_("error.argumentRequired"));
1000 completer: function (context) completion.macro(context),
1004 commands.add(["mac[ros]"],
1006 function (args) { completion.listCompleter("macro", args[0]); }, {
1008 completer: function (context) completion.macro(context)
1011 completion: function initCompletion() {
1012 completion.macro = function macro(context) {
1013 context.title = ["Macro", "Keys"];
1014 context.completions = [item for (item in events.getMacros())];
1017 mappings: function initMappings() {
1019 mappings.add([modes.MAIN],
1020 ["<A-b>", "<pass-next-key-builtin>"], "Process the next key as a builtin mapping",
1022 events.processor = ProcessorStack(modes.getStack(0), mappings.hives.array, true);
1023 events.processor.keyEvents = events.keyEvents;
1026 mappings.add([modes.MAIN],
1027 ["<C-z>", "<pass-all-keys>"], "Temporarily ignore all " + config.appName + " key bindings",
1029 if (modes.main != modes.PASS_THROUGH)
1030 modes.push(modes.PASS_THROUGH);
1033 mappings.add([modes.MAIN, modes.PASS_THROUGH, modes.QUOTE],
1034 ["<C-v>", "<pass-next-key>"], "Pass through next key",
1036 if (modes.main == modes.QUOTE)
1038 modes.push(modes.QUOTE);
1041 mappings.add([modes.BASE],
1042 ["<CapsLock>"], "Do Nothing",
1045 mappings.add([modes.BASE],
1046 ["<Nop>"], "Do nothing",
1049 mappings.add([modes.BASE],
1050 ["<Pass>"], "Pass the events consumed by the last executed mapping",
1051 function ({ keypressEvents: [event] }) {
1052 dactyl.assert(event.dactylSavedEvents,
1053 _("event.nothingToPass"));
1054 return function () {
1055 events.feedevents(null, event.dactylSavedEvents,
1056 { skipmap: true, isMacro: true, isReplay: true });
1061 mappings.add([modes.COMMAND],
1062 ["q", "<record-macro>"], "Record a key sequence into a macro",
1063 function ({ arg }) {
1064 util.assert(arg == null || /^[a-z]$/i.test(arg));
1065 events._macroKeys.pop();
1066 events.recording = arg;
1068 { get arg() !modes.recording });
1070 mappings.add([modes.COMMAND],
1071 ["@", "<play-macro>"], "Play a macro",
1072 function ({ arg, count }) {
1073 count = Math.max(count, 1);
1075 events.playMacro(arg);
1077 { arg: true, count: true });
1079 mappings.add([modes.COMMAND],
1080 ["<A-m>s", "<sleep>"], "Sleep for {count} milliseconds before continuing macro playback",
1081 function ({ command, count }) {
1082 let now = Date.now();
1083 dactyl.assert(count, _("error.countRequired", command));
1084 if (events.feedingKeys)
1089 mappings.add([modes.COMMAND],
1090 ["<A-m>l", "<wait-for-page-load>"], "Wait for the current page to finish loading before continuing macro playback",
1091 function ({ count }) {
1092 if (events.feedingKeys && !events.waitForPageLoad(count)) {
1093 util.interrupted = true;
1094 throw Error("Interrupted");
1099 options: function initOptions() {
1100 const Hive = Class("Hive", {
1101 init: function init(values, map) {
1102 this.name = "passkeys:" + map;
1103 this.stack = MapHive.Stack(values.map(function (v) Map(v[map + "Keys"])));
1104 function Map(keys) ({
1105 execute: function () Events.PASS_THROUGH,
1110 get active() this.stack.length,
1112 get: function get(mode, key) this.stack.mappings[key],
1114 getCandidates: function getCandidates(mode, key) this.stack.candidates[key]
1116 options.add(["passkeys", "pk"],
1117 "Pass certain keys through directly for the given URLs",
1119 flush: function flush() {
1120 memoize(this, "filters", function () this.value.filter(function (f) f(buffer.documentURI)));
1121 memoize(this, "pass", function () Set(array.flatten(this.filters.map(function (f) f.keys))));
1122 memoize(this, "commandHive", function hive() Hive(this.filters, "command"));
1123 memoize(this, "inputHive", function hive() Hive(this.filters, "input"));
1126 has: function (key) Set.has(this.pass, key) || Set.has(this.commandHive.stack.mappings, key),
1128 get pass() (this.flush(), this.pass),
1130 parse: function parse() {
1131 let value = parse.superapply(this, arguments);
1132 value.forEach(function (filter) {
1133 let vals = Option.splitList(filter.result);
1134 filter.keys = DOM.Event.parse(vals[0]).map(DOM.Event.closure.stringify);
1136 filter.commandKeys = vals.slice(1).map(DOM.Event.closure.canonicalKeys);
1137 filter.inputKeys = filter.commandKeys.filter(bind("test", /^<[ACM]-/));
1144 setter: function (value) {
1150 options.add(["strictfocus", "sf"],
1151 "Prevent scripts from focusing input elements without user intervention",
1152 "sitemap", "'chrome:*':laissez-faire,*:moderate",
1155 despotic: "Only allow focus changes when explicitly requested by the user",
1156 moderate: "Allow focus changes after user-initiated focus change",
1157 "laissez-faire": "Always allow focus changes"
1161 options.add(["timeout", "tmo"],
1162 "Whether to execute a shorter key command after a timeout when a longer command exists",
1165 options.add(["timeoutlen", "tmol"],
1166 "Maximum time (milliseconds) to wait for a longer key command when a shorter one exists",
1171 // vim: set fdm=marker sw=4 ts=4 et: