2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
5 # This file is part of VimFx.
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.
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.
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/>.
21 button = require('./button')
22 utils = require('./utils')
24 { interfaces: Ci } = Components
26 HTMLDocument = Ci.nsIDOMHTMLDocument
27 HTMLInputElement = Ci.nsIDOMHTMLInputElement
29 # Will be set by `addEventListeners`. It’s a bit hacky, but will do for now.
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
43 suppressEvent = (event) ->
44 event.preventDefault()
45 event.stopPropagation()
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)
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()
60 removeVimFromTab = (tab, gBrowser) ->
61 return unless browser = gBrowser.getBrowserForTab(tab)
62 vimBucket.forget(browser.contentWindow)
64 # The following listeners are installed on every top level Chrome window.
68 # No matter what, always reset the `suppress` flag, so we don't suppress
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.
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.
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"])'
92 return if popup.state == 'open'
93 popupPassthrough = false # No popup was actually open: Reset the flag.
95 return unless vim = getVimFromEvent(event)
97 markLastInteraction(event, vim)
99 suppress = vim.onInput(event)
101 suppressEvent(event) if suppress
104 console.error(utils.formatError(error))
106 keypress: (event) -> suppressEvent(event) if suppress
107 keyup: (event) -> suppressEvent(event) if suppress
109 popupshown: checkPassthrough
110 popuphidden: checkPassthrough
113 target = event.originalTarget
114 return unless vim = getVimFromEvent(event)
116 findBar = vim.rootWindow.gBrowser.getFindBar()
117 if target == findBar._findField.mInputField
118 vim.enterMode('find')
121 if target.ownerDocument instanceof HTMLDocument and
122 utils.isTextInputElement(target)
123 vim.state.lastFocusedTextInput = target
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()
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 # Lastly, the autofocus prevention is restricted to `<input>` elements,
146 # since only such elements are commonly autofocused. Many sites have
147 # buttons which inserts a `<textarea>` when clicked (which might take up to
148 # a second) and then focuses the `<textarea>`. Such focus events should
150 if vimfx.options.prevent_autofocus and
151 vim.mode != 'insert' and
152 target.ownerDocument instanceof HTMLDocument and
153 target instanceof HTMLInputElement and
154 (vim.state.lastInteraction == null or
155 Date.now() - vim.state.lastInteraction > vimfx.options.autofocus_limit)
156 vim.state.lastAutofocusPrevention = Date.now()
160 target = event.originalTarget
161 return unless vim = getVimFromEvent(event)
163 findBar = vim.rootWindow.gBrowser.getFindBar()
164 if target == findBar._findField.mInputField
165 vim.enterMode('normal')
168 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
169 # causing an infinite loop autofocus prevention and re-focusing. Therefore
170 # we suppress blur events that happen just after an autofocus prevention.
171 if vim.state.lastAutofocusPrevention != null and
172 Date.now() - vim.state.lastAutofocusPrevention < 1
173 vim.state.lastAutofocusPrevention = null
178 target = event.originalTarget
179 return unless vim = getVimFromEvent(event)
181 # If the user clicks the reload button or a link when in hints mode, we’re
182 # going to end up in hints mode without any markers. Or if the user clicks a
183 # text input, then that input will be focused, but you can’t type in it
184 # (instead markers will be matched). So if the user clicks anything in hints
185 # mode it’s better to leave it.
186 if vim.mode == 'hints' and not utils.isEventSimulated(event) and
187 # Exclude the VimFx button, though, since clicking it returns to normal
188 # mode. Otherwise we’d first returned to normal mode and then the button
189 # would have opened the help dialog.
190 target != vim.rootWindow.getElementById(button.BUTTON_ID)
191 vim.enterMode('normal')
194 mousedown: markLastInteraction
195 mouseup: markLastInteraction
198 return unless vim = getVimFromEvent(event)
199 return unless computedStyle = vim.window.getComputedStyle(event.target)
200 return if computedStyle.getPropertyValue('overflow') == 'hidden'
201 vim.state.scrollableElements.set(event.target)
203 underflow: (event) ->
204 return unless vim = getVimFromEvent(event)
205 vim.state.scrollableElements.delete(event.target)
207 # When the top level window closes we should release all Vims that were
208 # associated with tabs in this window.
209 DOMWindowClose: (event) ->
210 { gBrowser } = event.originalTarget
211 return unless gBrowser
212 for tab in gBrowser.tabs
213 removeVimFromTab(tab, gBrowser)
216 { gBrowser } = utils.getEventRootWindow(event) ? {}
217 return unless gBrowser
218 tab = event.originalTarget
219 removeVimFromTab(tab, gBrowser)
221 TabSelect: (event) ->
222 return unless window = event.originalTarget?.linkedBrowser?.contentDocument
224 # Get the current vim in order to trigger an update event for the toolbar
226 vimBucket.get(window)
229 # This listener works on individual tabs within Chrome Window.
231 onLocationChange: (browser, webProgress, request, location) ->
232 return unless vim = vimBucket.get(browser.contentWindow)
235 addEventListeners = (_vimfx, window) ->
237 { vimBucket } = _vimfx
238 for name, listener of windowsListeners
239 window.addEventListener(name, listener, true)
241 window.gBrowser.addTabsProgressListener(tabsListener)
244 for name, listener of windowsListeners
245 window.removeEventListener(name, listener, true)
247 window.gBrowser.removeTabsProgressListener(tabsListener)