]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Don't prevent autofocus in insert mode
[VimFx.git] / extension / lib / events.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
4 #
5 # This file is part of VimFx.
6 #
7 # VimFx is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # VimFx is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
19 ###
20
21 notation = require('vim-like-key-notation')
22 utils = require('./utils')
23 Vim = require('./vim')
24 { getPref } = require('./prefs')
25 { updateToolbarButton } = require('./button')
26
27 { interfaces: Ci } = Components
28
29 HTMLDocument = Ci.nsIDOMHTMLDocument
30 HTMLInputElement = Ci.nsIDOMHTMLInputElement
31
32 vimBucket = new utils.Bucket((window) -> new Vim(window))
33
34 keyStrFromEvent = (event) ->
35 return notation.stringify(event, {
36 # Check that `event.code` really is available before using the
37 # 'ignore_keyboard_layout' option. If not `event.key` will be used anyway,
38 # and the user needs to enable `event.code` support (which can be done from
39 # VimFx’s settings page).
40 ignoreKeyboardLayout: getPref('ignore_keyboard_layout') and event.code?
41 # Advanced setting for advanced users. Currently requires you to modifiy it
42 # from about:config and check the error console for errors.
43 translations: JSON.parse(getPref('translations'))
44 })
45
46 # When a menu or panel is shown VimFx should temporarily stop processing
47 # keyboard input, allowing accesskeys to be used.
48 popupPassthrough = false
49 checkPassthrough = (event) ->
50 if event.target.nodeName in ['menupopup', 'panel']
51 popupPassthrough = switch event.type
52 when 'popupshown' then true
53 when 'popuphidden' then false
54
55 suppress = false
56 suppressEvent = (event) ->
57 event.preventDefault()
58 event.stopPropagation()
59
60 # Returns the appropriate vim instance for `event`, but only if it’s okay to do
61 # so. VimFx must not be disabled or blacklisted.
62 getVimFromEvent = (event) ->
63 return if getPref('disabled')
64 return unless window = utils.getEventCurrentTabWindow(event)
65 return unless vim = vimBucket.get(window)
66 return if vim.blacklisted
67
68 return vim
69
70 # Save the time of the last user interaction. This is used to determine whether
71 # a focus event was automatic or voluntarily dispatched.
72 markLastInteraction = (event, vim = null) ->
73 return unless vim ?= getVimFromEvent(event)
74 return unless event.originalTarget.ownerDocument instanceof HTMLDocument
75 vim.lastInteraction = Date.now()
76
77 removeVimFromTab = (tab, gBrowser) ->
78 return unless browser = gBrowser.getBrowserForTab(tab)
79 vimBucket.forget(browser.contentWindow)
80
81 updateButton = (vim) ->
82 updateToolbarButton(vim.rootWindow, {
83 blacklisted: vim.blacklisted
84 insertMode: vim.mode == 'insert'
85 })
86
87 # The following listeners are installed on every top level Chrome window.
88 windowsListeners =
89 keydown: (event) ->
90 try
91 # No matter what, always reset the `suppress` flag, so we don't suppress
92 # more than intended.
93 suppress = false
94
95 if popupPassthrough
96 # The `popupPassthrough` flag is set a bit unreliably. Sometimes it can
97 # be stuck as `true` even though no popup is shown, effectively
98 # disabling the extension. Therefore we check if there actually _are_
99 # any open popups before stopping processing keyboard input. This is
100 # only done when popups (might) be open (not on every keystroke) of
101 # performance reasons.
102 #
103 # The autocomplete popup in text inputs (for example) is technically a
104 # panel, but it does not respond to key presses. Therefore
105 # `[ignorekeys="true"]` is excluded.
106 #
107 # coffeelint: disable=max_line_length
108 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
109 # coffeelint: enable=max_line_length
110 return unless rootWindow = utils.getEventRootWindow(event)
111 popups = rootWindow.document.querySelectorAll(
112 ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
113 )
114 for popup in popups
115 return if popup.state == 'open'
116 popupPassthrough = false # No popup was actually open: Reset the flag.
117
118 return unless vim = getVimFromEvent(event)
119
120 markLastInteraction(event, vim)
121
122 return unless keyStr = keyStrFromEvent(event)
123 suppress = vim.onInput(keyStr, event)
124
125 suppressEvent(event) if suppress
126
127 catch error
128 console.error("#{ error }\n#{ error.stack?.replace(/@.+-> /g, '@') }")
129
130 # Note that the below event listeners can suppress the event even in
131 # blacklisted sites. That's intentional. For example, if you press 'x' to
132 # close the current tab, it will close before keyup fires. So keyup (and
133 # perhaps keypress) will fire in another tab. Even if that particular tab is
134 # blacklisted, we must suppress the event, so that 'x' isn't sent to the page.
135 # The rule is simple: If the `suppress` flag is `true`, the event should be
136 # suppressed, no matter what. It has the highest priority.
137 keypress: (event) -> suppressEvent(event) if suppress
138 keyup: (event) -> suppressEvent(event) if suppress
139
140 popupshown: checkPassthrough
141 popuphidden: checkPassthrough
142
143 focus: (event) ->
144 target = event.originalTarget
145 return unless vim = getVimFromEvent(event)
146
147 findBar = vim.rootWindow.gBrowser.getFindBar()
148 if target == findBar._findField.mInputField
149 vim.enterMode('find')
150 return
151
152 # If the user has interacted with the page and the `window` of the page gets
153 # focus, it means that the user just switched back to the page from another
154 # window or tab. If a text input was focused when the user focused _away_
155 # from the page Firefox blurs it and then re-focuses it when the user
156 # switches back. Therefore we count this case as an interaction, so the
157 # re-focus event isn’t caught as autofocus.
158 if vim.lastInteraction != null and target == vim.window
159 vim.lastInteraction = Date.now()
160
161 # Autofocus prevention. Strictly speaking, autofocus may only happen during
162 # page load, which means that we should only prevent focus events during
163 # page load. However, it is very difficult to reliably determine when the
164 # page load ends. Moreover, a page may load very slowly. Then it is likely
165 # that the user tries to focus something before the page has loaded fully.
166 # Therefore focus events that aren’t reasonably close to a user interaction
167 # (click or key press) are blurred (regardless of whether the page is loaded
168 # or not -- but that isn’t so bad: if the user doesn’t like autofocus, he
169 # doesn’t like any automatic focusing, right? This is actually useful on
170 # devdocs.io). There is a slight risk that the user presses a key just
171 # before an autofocus, causing it not to be blurred, but that’s not likely.
172 # Lastly, the autofocus prevention is restricted to `<input>` elements,
173 # since only such elements are commonly autofocused. Many sites have
174 # buttons which inserts a `<textarea>` when clicked (which might take up to
175 # a second) and then focuses the `<textarea>`. Such focus events should
176 # _not_ be blurred.
177 if getPref('prevent_autofocus') and
178 vim.mode != 'insert' and
179 target.ownerDocument instanceof HTMLDocument and
180 target instanceof HTMLInputElement and
181 (vim.lastInteraction == null or
182 Date.now() - vim.lastInteraction > getPref('autofocus_limit'))
183 vim.lastAutofocusPrevention = Date.now()
184 target.blur()
185
186 blur: (event) ->
187 target = event.originalTarget
188 return unless vim = getVimFromEvent(event)
189
190 findBar = vim.rootWindow.gBrowser.getFindBar()
191 if target == findBar._findField.mInputField
192 vim.enterMode('normal')
193 return
194
195 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
196 # causing an infinite loop autofocus prevention and re-focusing. Therefore
197 # we suppress blur events that happen just after an autofocus prevention.
198 if vim.lastAutofocusPrevention != null and
199 Date.now() - vim.lastAutofocusPrevention < 1
200 vim.lastAutofocusPrevention = null
201 suppressEvent(event)
202 return
203
204 click: (event) ->
205 target = event.originalTarget
206 return unless vim = getVimFromEvent(event)
207
208 # If the user clicks the reload button or a link when in hints mode, we’re
209 # going to end up in hints mode without any markers. Or if the user clicks a
210 # text input, then that input will be focused, but you can’t type in it
211 # (instead markers will be matched). So if the user clicks anything in hints
212 # mode it’s better to leave it.
213 if vim.mode == 'hints' and not utils.isEventSimulated(event)
214 vim.enterMode('normal')
215 return
216
217 mousedown: markLastInteraction
218 mouseup: markLastInteraction
219
220 # When the top level window closes we should release all Vims that were
221 # associated with tabs in this window.
222 DOMWindowClose: (event) ->
223 { gBrowser } = event.originalTarget
224 return unless gBrowser
225 for tab in gBrowser.tabs
226 removeVimFromTab(tab, gBrowser)
227
228 TabClose: (event) ->
229 { gBrowser } = utils.getEventRootWindow(event) ? {}
230 return unless gBrowser
231 tab = event.originalTarget
232 removeVimFromTab(tab, gBrowser)
233
234 # Update the toolbar button icon to reflect the blacklisted state.
235 TabSelect: (event) ->
236 return unless window = event.originalTarget?.linkedBrowser?.contentDocument
237 ?.defaultView
238 return unless vim = vimBucket.get(window)
239 updateButton(vim)
240
241
242 # This listener works on individual tabs within Chrome Window.
243 tabsListener =
244 onLocationChange: (browser, webProgress, request, location) ->
245 return unless vim = vimBucket.get(browser.contentWindow)
246
247 # There hasn’t been any interaction on the page yet, so reset it.
248 vim.lastInteraction = null
249
250 # Update the blacklist state.
251 vim.blacklisted = utils.isBlacklisted(location.spec)
252 vim.blacklistedKeys = utils.getBlacklistedKeys(location.spec)
253 # If only specific keys are blacklisted, remove blacklist state.
254 if vim.blacklistedKeys.length > 0
255 vim.blacklisted = false
256 updateButton(vim)
257
258 addEventListeners = (window) ->
259 for name, listener of windowsListeners
260 window.addEventListener(name, listener, true)
261
262 window.gBrowser.addTabsProgressListener(tabsListener)
263
264 module.onShutdown(->
265 for name, listener of windowsListeners
266 window.removeEventListener(name, listener, true)
267
268 window.gBrowser.removeTabsProgressListener(tabsListener)
269 )
270
271 exports.addEventListeners = addEventListeners
272 exports.vimBucket = vimBucket
Imprint / Impressum