]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Fix failing API tests
[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 button = require('./button')
22 utils = require('./utils')
23
24 { interfaces: Ci } = Components
25
26 HTMLDocument = Ci.nsIDOMHTMLDocument
27 HTMLInputElement = Ci.nsIDOMHTMLInputElement
28
29 # Will be set by `addEventListeners`. It’s a bit hacky, but will do for now.
30 vimfx = null
31 vimBucket = null
32
33 # When a menu or panel is shown VimFx should temporarily stop processing
34 # keyboard input, allowing accesskeys to be used.
35 popupPassthrough = false
36 checkPassthrough = (event) ->
37 if event.target.nodeName in ['menupopup', 'panel']
38 popupPassthrough = switch event.type
39 when 'popupshown' then true
40 when 'popuphidden' then false
41
42 suppress = false
43 suppressEvent = (event) ->
44 event.preventDefault()
45 event.stopPropagation()
46
47 # Returns the appropriate vim instance for `event`.
48 getVimFromEvent = (event) ->
49 return unless window = utils.getEventCurrentTabWindow(event)
50 return unless vim = vimBucket.get(window)
51 return vim
52
53 # Save the time of the last user interaction. This is used to determine whether
54 # a focus event was automatic or voluntarily dispatched.
55 markLastInteraction = (event, vim = null) ->
56 return unless vim ?= getVimFromEvent(event)
57 return unless event.originalTarget.ownerDocument instanceof HTMLDocument
58 vim.state.lastInteraction = Date.now()
59
60 removeVimFromTab = (tab, gBrowser) ->
61 return unless browser = gBrowser.getBrowserForTab(tab)
62 vimBucket.forget(browser.contentWindow)
63
64 # The following listeners are installed on every top level Chrome window.
65 windowsListeners =
66 keydown: (event) ->
67 try
68 # No matter what, always reset the `suppress` flag, so we don't suppress
69 # more than intended.
70 suppress = false
71
72 if popupPassthrough
73 # The `popupPassthrough` flag is set a bit unreliably. Sometimes it can
74 # be stuck as `true` even though no popup is shown, effectively
75 # disabling the extension. Therefore we check if there actually _are_
76 # any open popups before stopping processing keyboard input. This is
77 # only done when popups (might) be open (not on every keystroke) of
78 # performance reasons.
79 #
80 # The autocomplete popup in text inputs (for example) is technically a
81 # panel, but it does not respond to key presses. Therefore
82 # `[ignorekeys="true"]` is excluded.
83 #
84 # coffeelint: disable=max_line_length
85 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
86 # coffeelint: enable=max_line_length
87 return unless rootWindow = utils.getEventRootWindow(event)
88 popups = rootWindow.document.querySelectorAll(
89 ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
90 )
91 for popup in popups
92 return if popup.state == 'open'
93 popupPassthrough = false # No popup was actually open: Reset the flag.
94
95 return unless vim = getVimFromEvent(event)
96
97 markLastInteraction(event, vim)
98
99 suppress = vim.onInput(event)
100
101 suppressEvent(event) if suppress
102
103 catch error
104 console.error(utils.formatError(error))
105
106 keypress: (event) -> suppressEvent(event) if suppress
107 keyup: (event) -> suppressEvent(event) if suppress
108
109 popupshown: checkPassthrough
110 popuphidden: checkPassthrough
111
112 focus: (event) ->
113 target = event.originalTarget
114 return unless vim = getVimFromEvent(event)
115
116 findBar = vim.rootWindow.gBrowser.getFindBar()
117 if target == findBar._findField.mInputField
118 vim.enterMode('find')
119 return
120
121 if target.ownerDocument instanceof HTMLDocument and
122 utils.isTextInputElement(target)
123 vim.state.lastFocusedTextInput = target
124
125 # If the user has interacted with the page and the `window` of the page gets
126 # focus, it means that the user just switched back to the page from another
127 # window or tab. If a text input was focused when the user focused _away_
128 # from the page Firefox blurs it and then re-focuses it when the user
129 # switches back. Therefore we count this case as an interaction, so the
130 # re-focus event isn’t caught as autofocus.
131 if vim.state.lastInteraction != null and target == vim.window
132 vim.state.lastInteraction = Date.now()
133
134 # Autofocus prevention. Strictly speaking, autofocus may only happen during
135 # page load, which means that we should only prevent focus events during
136 # page load. However, it is very difficult to reliably determine when the
137 # page load ends. Moreover, a page may load very slowly. Then it is likely
138 # that the user tries to focus something before the page has loaded fully.
139 # Therefore focus events that aren’t reasonably close to a user interaction
140 # (click or key press) are blurred (regardless of whether the page is loaded
141 # or not -- but that isn’t so bad: if the user doesn’t like autofocus, he
142 # doesn’t like any automatic focusing, right? This is actually useful on
143 # devdocs.io). There is a slight risk that the user presses a key just
144 # before an autofocus, causing it not to be blurred, but that’s not likely.
145 # Autofocus prevention is also restricted to `<input>` elements, since only
146 # such elements are commonly autofocused. Many sites have buttons which
147 # inserts a `<textarea>` when clicked (which might take up to a second) and
148 # then focuses the `<textarea>`. Such focus events should _not_ be blurred.
149 # There are also many buttons that do the same thing but insert an `<input>`
150 # element. There is sadly always a risk that those events are blurred.
151 focusManager = Cc['@mozilla.org/focus-manager;1']
152 .getService(Ci.nsIFocusManager)
153 if vimfx.options.prevent_autofocus and
154 vim.mode in vimfx.options.prevent_autofocus_modes and
155 target.ownerDocument instanceof HTMLDocument and
156 target instanceof HTMLInputElement and
157 # Only blur programmatic events (not caused by clicks or keypresses).
158 focusManager.getLastFocusMethod(null) == 0 and
159 (vim.state.lastInteraction == null or
160 Date.now() - vim.state.lastInteraction > vimfx.options.autofocus_limit)
161 vim.state.lastAutofocusPrevention = Date.now()
162 target.blur()
163
164 blur: (event) ->
165 target = event.originalTarget
166 return unless vim = getVimFromEvent(event)
167
168 findBar = vim.rootWindow.gBrowser.getFindBar()
169 if target == findBar._findField.mInputField
170 vim.enterMode('normal')
171 return
172
173 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
174 # causing an infinite loop autofocus prevention and re-focusing. Therefore
175 # we suppress blur events that happen just after an autofocus prevention.
176 if vim.state.lastAutofocusPrevention != null and
177 Date.now() - vim.state.lastAutofocusPrevention < 1
178 vim.state.lastAutofocusPrevention = null
179 suppressEvent(event)
180 return
181
182 click: (event) ->
183 target = event.originalTarget
184 return unless vim = getVimFromEvent(event)
185
186 # If the user clicks the reload button or a link when in hints mode, we’re
187 # going to end up in hints mode without any markers. Or if the user clicks a
188 # text input, then that input will be focused, but you can’t type in it
189 # (instead markers will be matched). So if the user clicks anything in hints
190 # mode it’s better to leave it.
191 if vim.mode == 'hints' and not utils.isEventSimulated(event) and
192 # Exclude the VimFx button, though, since clicking it returns to normal
193 # mode. Otherwise we’d first returned to normal mode and then the button
194 # would have opened the help dialog.
195 target != vim.rootWindow.getElementById(button.BUTTON_ID)
196 vim.enterMode('normal')
197 return
198
199 mousedown: markLastInteraction
200 mouseup: markLastInteraction
201
202 overflow: (event) ->
203 return unless vim = getVimFromEvent(event)
204 return unless computedStyle = vim.window.getComputedStyle(event.target)
205 return if computedStyle.getPropertyValue('overflow') == 'hidden'
206 vim.state.scrollableElements.set(event.target)
207
208 underflow: (event) ->
209 return unless vim = getVimFromEvent(event)
210 vim.state.scrollableElements.delete(event.target)
211
212 # When the top level window closes we should release all Vims that were
213 # associated with tabs in this window.
214 DOMWindowClose: (event) ->
215 { gBrowser } = event.originalTarget
216 return unless gBrowser
217 for tab in gBrowser.tabs
218 removeVimFromTab(tab, gBrowser)
219
220 TabClose: (event) ->
221 { gBrowser } = utils.getEventRootWindow(event) ? {}
222 return unless gBrowser
223 tab = event.originalTarget
224 removeVimFromTab(tab, gBrowser)
225
226 TabSelect: (event) ->
227 return unless window = event.originalTarget?.linkedBrowser?.contentDocument
228 ?.defaultView
229 # Get the current vim in order to trigger an update event for the toolbar
230 # button.
231 vimBucket.get(window)
232
233
234 # This listener works on individual tabs within Chrome Window.
235 tabsListener =
236 onLocationChange: (browser, webProgress, request, location) ->
237 return unless vim = vimBucket.get(browser.contentWindow)
238 vim.resetState()
239
240 addEventListeners = (_vimfx, window) ->
241 vimfx = _vimfx
242 { vimBucket } = _vimfx
243 for name, listener of windowsListeners
244 window.addEventListener(name, listener, true)
245
246 window.gBrowser.addTabsProgressListener(tabsListener)
247
248 module.onShutdown(->
249 for name, listener of windowsListeners
250 window.removeEventListener(name, listener, true)
251
252 window.gBrowser.removeTabsProgressListener(tabsListener)
253 )
254
255 module.exports = {
256 addEventListeners
257 }
Imprint / Impressum