]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Fix `scroll.reset_timeout` pref typo
[VimFx.git] / extension / lib / events.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
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 # This file sets up all event listeners needed to power VimFx: To know when to
22 # launch commands and to provide state to them. Events in web page content are
23 # listened for in events-frame.coffee.
24
25 button = require('./button')
26 messageManager = require('./message-manager')
27 prefs = require('./prefs')
28 utils = require('./utils')
29
30 HELD_MODIFIERS_ATTRIBUTE = 'vimfx-held-modifiers'
31
32 class UIEventManager
33 constructor: (@vimfx, @window) ->
34 @listen = utils.listen.bind(null, @window)
35 @listenOnce = utils.listenOnce.bind(null, @window)
36
37 # This flag controls whether to suppress the various key events or not.
38 @suppress = false
39
40 # If a matched shortcut has the `<late>` special key, this flag is set to
41 # `true`.
42 @late = false
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
48 @enteredKeys = new EnteredKeysManager(@window)
49
50 addListeners: ->
51 checkPassthrough = (value, event) =>
52 target = event.originalTarget
53 if target.localName in ['menupopup', 'panel'] and
54 # Don’t set `@popupPassthrough` to `false` if there actually are popups
55 # open. This is the case when a sub-menu closes.
56 (value or not @anyPopupsOpen())
57 @popupPassthrough = value
58
59 @listen('popupshown', checkPassthrough.bind(null, true))
60 @listen('popuphidden', checkPassthrough.bind(null, false))
61
62 @listen('keydown', (event) =>
63 # No matter what, always reset the `@suppress` flag, so we don't
64 # suppress more than intended.
65 @suppress = false
66
67 # Reset the `@late` flag, telling any late listeners for the previous
68 # event not to run. Also reset the `late` pref, telling frame scripts not
69 # to do synchronous message passing on every keydown.
70 @late = false
71 prefs.set('late', false)
72
73 if @popupPassthrough
74 # The `@popupPassthrough` flag is set a bit unreliably. Sometimes it
75 # can be stuck as `true` even though no popup is shown, effectively
76 # disabling the extension. Therefore we check if there actually _are_
77 # any open popups before stopping processing keyboard input. This is
78 # only done when popups (might) be open (not on every keystroke) for
79 # performance reasons.
80 return if @anyPopupsOpen()
81 @popupPassthrough = false # No popup was actually open.
82
83 return unless vim = @vimfx.getCurrentVim(@window)
84
85 @consumeKeyEvent(vim, event)
86 if @suppress
87 utils.suppressEvent(event) # This also suppresses the 'keypress' event.
88 else
89 # If this keydown event wasn’t suppressed, it’s an obvious interaction
90 # with the page. If it _was_ suppressed, though, it’s an interaction
91 # depending on the command triggered; if _it_ calls
92 # `vim.markPageInteraction()` or not.
93 vim.markPageInteraction() if vim.isUIEvent(event)
94 )
95
96 @listen('keyup', (event) =>
97 utils.suppressEvent(event) if @suppress
98 @setHeldModifiers(event, {filterCurrentOnly: true})
99 )
100
101 handleFocusRelatedEvent = (event) =>
102 target = event.originalTarget
103 return unless vim = @vimfx.getCurrentVim(@window)
104
105 if vim.isUIEvent(event)
106 focusType = utils.getFocusType(utils.getActiveElement(@window))
107 vim._setFocusType(focusType)
108
109 if focusType == 'editable' and vim.mode == 'caret'
110 vim.enterMode('normal')
111
112 @listen('focus', handleFocusRelatedEvent)
113 @listen('blur', handleFocusRelatedEvent)
114
115 @listen('click', (event) =>
116 target = event.originalTarget
117 return unless vim = @vimfx.getCurrentVim(@window)
118
119 # In multi-process, clicks simulated by VimFx cannot be caught here. In
120 # non-multi-process, they unfortunately can. This hack should be
121 # sufficient for that case until non-multi-process is removed from
122 # Firefox.
123 isVimFxGeneratedEvent = (
124 event.layerX == 0 and event.layerY == 0 and
125 event.movementX == 0 and event.movementY == 0
126 )
127
128 # If the user clicks the reload button or a link when in hints mode, we’re
129 # going to end up in hints mode without any markers. Or if the user clicks
130 # a text input, then that input will be focused, but you can’t type in it
131 # (instead markers will be matched). So if the user clicks anything in
132 # hints mode it’s better to leave it.
133 if vim.mode == 'hints' and not isVimFxGeneratedEvent and
134 # Exclude the VimFx button, though, since clicking it returns to normal
135 # mode. Otherwise we’d first return to normal mode and then the button
136 # would open the help dialog.
137 target != button.getButton(@window)
138 vim.enterMode('normal')
139
140 vim._send('clearHover') unless isVimFxGeneratedEvent
141 )
142
143 @listen('overflow', (event) =>
144 target = event.originalTarget
145 return unless vim = @vimfx.getCurrentVim(@window)
146 if vim._isUIElement(target)
147 vim._state.scrollableElements.addChecked(target)
148 )
149
150 @listen('underflow', (event) =>
151 target = event.originalTarget
152 return unless vim = @vimfx.getCurrentVim(@window)
153 if vim._isUIElement(target)
154 vim._state.scrollableElements.deleteChecked(target)
155 )
156
157 @listen('TabSelect', (event) =>
158 target = event.originalTarget
159 target.setAttribute('VimFx-visited', 'true')
160 @vimfx.emit('TabSelect', {event})
161
162 return unless vim = @vimfx.getCurrentVim(@window)
163 vim.hideNotification()
164 )
165
166 @listen('TabClose', (event) =>
167 browser = @window.gBrowser.getBrowserForTab(event.originalTarget)
168 return unless vim = @vimfx.vims.get(browser)
169 # Note: `lastClosedVim` must be stored so that any window can access it.
170 @vimfx.lastClosedVim = vim
171 )
172
173 messageManager.listen('cachedPageshow', ((data, callback, browser) =>
174 [oldVim, @vimfx.lastClosedVim] = [@vimfx.lastClosedVim, null]
175 unless oldVim
176 callback(false)
177 return
178
179 if @vimfx.vims.has(browser)
180 vim = @vimfx.vims.get(browser)
181 if vim._messageManager == vim.browser.messageManager
182 callback(false)
183 return
184
185 # If we get here, it means that we’ve detected a tab dragged from one
186 # window to another. If so, the `vim` object from the last closed tab (the
187 # moved tab) should be re-used. See the commit message for commit bb70257d
188 # for more details.
189 oldVim._setBrowser(browser)
190 @vimfx.vims.set(browser, oldVim)
191 @vimfx.emit('modeChange', {vim: oldVim})
192 callback(true)
193 ), {messageManager: @window.messageManager})
194
195 consumeKeyEvent: (vim, event) ->
196 match = vim._consumeKeyEvent(event)
197
198 if match
199 if @vimfx.options.notify_entered_keys
200 if match.type in ['none', 'full'] or match.likelyConflict
201 @enteredKeys.clear(vim)
202 else
203 @enteredKeys.push(vim, match.keyStr, @vimfx.options.timeout)
204 else
205 vim.hideNotification()
206
207 if match.specialKeys['<late>']
208 @suppress = false
209 @consumeLateKeydown(vim, event, match)
210 else
211 @suppress = vim._onInput(match, event)
212 else
213 @suppress = null
214 @setHeldModifiers(event)
215
216 consumeLateKeydown: (vim, event, match) ->
217 @late = true
218
219 # The passed in `event` is the regular non-late browser UI keydown event.
220 # It is only used to set held keys. This is easier than sending an event
221 # subset from frame scripts.
222 listener = ({defaultPrevented}) =>
223 # `@late` is reset on every keydown. If it is no longer `true`, it means
224 # that the page called `event.stopPropagation()`, which prevented this
225 # listener from running for that event.
226 return unless @late
227 @suppress =
228 if defaultPrevented
229 false
230 else
231 vim._onInput(match, event)
232 @setHeldModifiers(event)
233 return @suppress
234
235 if vim.isUIEvent(event)
236 @listenOnce('keydown', ((lateEvent) =>
237 listener(lateEvent)
238 if @suppress
239 utils.suppressEvent(lateEvent)
240 @listenOnce('keyup', utils.suppressEvent, false)
241 ), false)
242 else
243 # Hack to avoid synchronous messages on every keydown (see
244 # events-frame.coffee).
245 prefs.set('late', true)
246 vim._listenOnce('lateKeydown', listener)
247
248 setHeldModifiers: (event, {filterCurrentOnly = false} = {}) ->
249 mainWindow = @window.document.documentElement
250 modifiers =
251 if filterCurrentOnly
252 mainWindow.getAttribute(HELD_MODIFIERS_ATTRIBUTE)
253 else
254 if @suppress == null then 'alt ctrl meta shift' else ''
255 isHeld = (modifier) -> event["#{modifier}Key"]
256 mainWindow.setAttribute(
257 HELD_MODIFIERS_ATTRIBUTE, modifiers.split(' ').filter(isHeld).join(' ')
258 )
259
260 anyPopupsOpen: ->
261 # The autocomplete popup in text inputs (for example) is technically a
262 # panel, but it does not respond to key presses. Therefore
263 # `[ignorekeys="true"]` is excluded.
264 #
265 # coffeelint: disable=max_line_length
266 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
267 # coffeelint: enable=max_line_length
268 popups = utils.querySelectorAllDeep(
269 @window, ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
270 )
271 for popup in popups
272 return true if popup.state == 'open'
273 return false
274
275 class EnteredKeysManager
276 constructor: (@window) ->
277 @keys = []
278 @timeout = null
279
280 clear: (notifier) ->
281 @keys = []
282 @clearTimeout()
283 notifier.hideNotification()
284
285 push: (notifier, keyStr, duration) ->
286 @keys.push(keyStr)
287 @clearTimeout()
288 notifier.notify(@keys.join(''))
289 clear = @clear.bind(this)
290 @timeout = @window.setTimeout((-> clear(notifier)), duration)
291
292 clearTimeout: ->
293 @window.clearTimeout(@timeout) if @timeout?
294 @timeout = null
295
296 module.exports = UIEventManager
Imprint / Impressum