]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Merge branch 'develop' of github.com:akhodakivskiy/VimFx into develop
[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 utils = require('./utils')
22 keyUtils = require('./key-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 { ctrlKey: ctrl, metaKey: meta, altKey: alt, shiftKey: shift } = event
36
37 if not meta and not alt
38 return unless keyChar = keyUtils.keyCharFromCode(event.keyCode, shift)
39 keyStr = keyUtils.applyModifiers(keyChar, ctrl, alt, meta)
40 return keyStr
41
42 return null
43
44 # When a menu or panel is shown VimFx should temporarily stop processing
45 # keyboard input, allowing accesskeys to be used.
46 popupPassthrough = false
47 checkPassthrough = (event) ->
48 if event.target.nodeName in ['menupopup', 'panel']
49 popupPassthrough = switch event.type
50 when 'popupshown' then true
51 when 'popuphidden' then false
52
53 suppress = false
54 suppressEvent = (event) ->
55 event.preventDefault()
56 event.stopPropagation()
57
58 # Returns the appropriate vim instance for `event`, but only if it’s okay to do
59 # so. VimFx must not be disabled or blacklisted.
60 getVimFromEvent = (event) ->
61 return if getPref('disabled')
62 return unless window = utils.getEventCurrentTabWindow(event)
63 return unless vim = vimBucket.get(window)
64 return if vim.blacklisted
65
66 return vim
67
68 # Save the time of the last user interaction. This is used to determine whether
69 # a focus event was automatic or voluntarily dispatched.
70 markLastInteraction = (event, vim = null) ->
71 return unless vim ?= getVimFromEvent(event)
72 return unless event.originalTarget.ownerDocument instanceof HTMLDocument
73 vim.lastInteraction = Date.now()
74
75 removeVimFromTab = (tab, gBrowser) ->
76 return unless browser = gBrowser.getBrowserForTab(tab)
77 vimBucket.forget(browser.contentWindow)
78
79 updateButton = (vim) ->
80 updateToolbarButton(vim.rootWindow, {
81 blacklisted: vim.blacklisted
82 insertMode: vim.mode == 'insert'
83 })
84
85 # The following listeners are installed on every top level Chrome window.
86 windowsListeners =
87 keydown: (event) ->
88 try
89 # No matter what, always reset the `suppress` flag, so we don't suppress
90 # more than intended.
91 suppress = false
92
93 if popupPassthrough
94 # The `popupPassthrough` flag is set a bit unreliably. Sometimes it can
95 # be stuck as `true` even though no popup is shown, effectively
96 # disabling the extension. Therefore we check if there actually _are_
97 # any open popups before stopping processing keyboard input. This is
98 # only done when popups (might) be open (not on every keystroke) of
99 # performance reasons.
100 #
101 # The autocomplete popup in text inputs (for example) is technically a
102 # panel, but it does not respond to key presses. Therefore
103 # `[ignorekeys="true"]` is excluded.
104 #
105 # coffeelint: disable=max_line_length
106 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
107 # coffeelint: enable=max_line_length
108 return unless rootWindow = utils.getEventRootWindow(event)
109 popups = rootWindow.document.querySelectorAll(
110 ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
111 )
112 for popup in popups
113 return if popup.state == 'open'
114 popupPassthrough = false # No popup was actually open: Reset the flag.
115
116 return unless vim = getVimFromEvent(event)
117
118 markLastInteraction(event, vim)
119
120 return unless keyStr = keyStrFromEvent(event)
121 suppress = vim.onInput(keyStr, event)
122
123 suppressEvent(event) if suppress
124
125 catch error
126 console.error("#{ error }\n#{ error.stack?.replace(/@.+-> /g, '@') }")
127
128 # Note that the below event listeners can suppress the event even in
129 # blacklisted sites. That's intentional. For example, if you press 'x' to
130 # close the current tab, it will close before keyup fires. So keyup (and
131 # perhaps keypress) will fire in another tab. Even if that particular tab is
132 # blacklisted, we must suppress the event, so that 'x' isn't sent to the page.
133 # The rule is simple: If the `suppress` flag is `true`, the event should be
134 # suppressed, no matter what. It has the highest priority.
135 keypress: (event) -> suppressEvent(event) if suppress
136 keyup: (event) -> suppressEvent(event) if suppress
137
138 popupshown: checkPassthrough
139 popuphidden: checkPassthrough
140
141 focus: (event) ->
142 target = event.originalTarget
143 return unless vim = getVimFromEvent(event)
144
145 findBar = vim.rootWindow.gBrowser.getFindBar()
146 if target == findBar._findField.mInputField
147 vim.enterMode('find')
148 return
149
150 # If the user has interacted with the page and the `window` of the page gets
151 # focus, it means that the user just switched back to the page from another
152 # window or tab. If a text input was focused when the user focused _away_
153 # from the page Firefox blurs it and then re-focuses it when the user
154 # switches back. Therefore we count this case as an interaction, so the
155 # re-focus event isn’t caught as autofocus.
156 if vim.lastInteraction != null and target == vim.window
157 vim.lastInteraction = Date.now()
158
159 # Autofocus prevention. Strictly speaking, autofocus may only happen during
160 # page load, which means that we should only prevent focus events during
161 # page load. However, it is very difficult to reliably determine when the
162 # page load ends. Moreover, a page may load very slowly. Then it is likely
163 # that the user tries to focus something before the page has loaded fully.
164 # Therefore focus events that aren’t reasonably close to a user interaction
165 # (click or key press) are blurred (regardless of whether the page is loaded
166 # or not -- but that isn’t so bad: if the user doesn’t like autofocus, he
167 # doesn’t like any automatic focusing, right? This is actually useful on
168 # devdocs.io). There is a slight risk that the user presses a key just
169 # before an autofocus, causing it not to be blurred, but that’s not likely.
170 # Lastly, the autofocus prevention is restricted to `<input>` elements,
171 # since only such elements are commonly autofocused. Many sites have
172 # buttons which inserts a `<textarea>` when clicked (which might take up to
173 # a second) and then focuses the `<textarea>`. Such focus events should
174 # _not_ be blurred.
175 if getPref('prevent_autofocus') and
176 target.ownerDocument instanceof HTMLDocument and
177 target instanceof HTMLInputElement and
178 (vim.lastInteraction == null or Date.now() - vim.lastInteraction > 100)
179 target.blur()
180
181 blur: (event) ->
182 target = event.originalTarget
183 return unless vim = getVimFromEvent(event)
184
185 findBar = vim.rootWindow.gBrowser.getFindBar()
186 if target == findBar._findField.mInputField
187 vim.enterMode('normal')
188 return
189
190 click: (event) ->
191 target = event.originalTarget
192 return unless vim = getVimFromEvent(event)
193
194 # If the user clicks the reload button or a link when in hints mode, we’re
195 # going to end up in hints mode without any markers. Or if the user clicks a
196 # text input, then that input will be focused, but you can’t type in it
197 # (instead markers will be matched). So if the user clicks anything in hints
198 # mode it’s better to leave it.
199 if vim.mode == 'hints' and not utils.isEventSimulated(event)
200 vim.enterMode('normal')
201 return
202
203 mousedown: markLastInteraction
204 mouseup: markLastInteraction
205
206 # When the top level window closes we should release all Vims that were
207 # associated with tabs in this window.
208 DOMWindowClose: (event) ->
209 { gBrowser } = event.originalTarget
210 return unless gBrowser
211 for tab in gBrowser.tabs
212 removeVimFromTab(tab, gBrowser)
213
214 TabClose: (event) ->
215 { gBrowser } = utils.getEventRootWindow(event) ? {}
216 return unless gBrowser
217 tab = event.originalTarget
218 removeVimFromTab(tab, gBrowser)
219
220 # Update the toolbar button icon to reflect the blacklisted state.
221 TabSelect: (event) ->
222 return unless window = event.originalTarget?.linkedBrowser?.contentDocument
223 ?.defaultView
224 return unless vim = vimBucket.get(window)
225 updateButton(vim)
226
227
228 # This listener works on individual tabs within Chrome Window.
229 tabsListener =
230 onLocationChange: (browser, webProgress, request, location) ->
231 return unless vim = vimBucket.get(browser.contentWindow)
232
233 # There hasn’t been any interaction on the page yet, so reset it.
234 vim.lastInteraction = null
235
236 # Update the blacklist state.
237 vim.blacklisted = utils.isBlacklisted(location.spec)
238 updateButton(vim)
239
240 addEventListeners = (window) ->
241 for name, listener of windowsListeners
242 window.addEventListener(name, listener, true)
243
244 window.gBrowser.addTabsProgressListener(tabsListener)
245
246 module.onShutdown(->
247 for name, listener of windowsListeners
248 window.removeEventListener(name, listener, true)
249
250 window.gBrowser.removeTabsProgressListener(tabsListener)
251 )
252
253 exports.addEventListeners = addEventListeners
254 exports.vimBucket = vimBucket
Imprint / Impressum