]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Implement filtering hints by text and related changes
[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 @listen('focus', => @setFocusType())
102 @listen('blur', =>
103 @window.setTimeout((=>
104 @setFocusType()
105 ), @vimfx.options.blur_timeout)
106 )
107
108 @listen('click', (event) =>
109 target = event.originalTarget
110 return unless vim = @vimfx.getCurrentVim(@window)
111
112 vim.hideNotification()
113
114 # In multi-process, clicks simulated by VimFx cannot be caught here. In
115 # non-multi-process, they unfortunately can. This hack should be
116 # sufficient for that case until non-multi-process is removed from
117 # Firefox.
118 isVimFxGeneratedEvent = (
119 event.layerX == 0 and event.layerY == 0 and
120 event.movementX == 0 and event.movementY == 0
121 )
122
123 # If the user clicks the reload button or a link when in hints mode, we’re
124 # going to end up in hints mode without any markers. Or if the user clicks
125 # a text input, then that input will be focused, but you can’t type in it
126 # (instead markers will be matched). So if the user clicks anything in
127 # hints mode it’s better to leave it.
128 if vim.mode == 'hints' and not isVimFxGeneratedEvent and
129 # Exclude the VimFx button, though, since clicking it returns to normal
130 # mode. Otherwise we’d first return to normal mode and then the button
131 # would open the help dialog.
132 target != button.getButton(@window)
133 vim._enterMode('normal')
134
135 vim._send('clearHover') unless isVimFxGeneratedEvent
136 )
137
138 @listen('overflow', (event) =>
139 target = event.originalTarget
140 return unless vim = @vimfx.getCurrentVim(@window)
141 if vim._isUIElement(target)
142 vim._state.scrollableElements.addChecked(target)
143 )
144
145 @listen('underflow', (event) =>
146 target = event.originalTarget
147 return unless vim = @vimfx.getCurrentVim(@window)
148 if vim._isUIElement(target)
149 vim._state.scrollableElements.deleteChecked(target)
150 )
151
152 @listen('TabSelect', (event) =>
153 target = event.originalTarget
154 target.setAttribute('VimFx-visited', 'true')
155 @vimfx.emit('TabSelect', {event})
156
157 return unless vim = @vimfx.getCurrentVim(@window)
158 vim.hideNotification()
159 @vimfx.emit('focusTypeChange', {vim})
160 )
161
162 @listen('TabClose', (event) =>
163 browser = @window.gBrowser.getBrowserForTab(event.originalTarget)
164 return unless vim = @vimfx.vims.get(browser)
165 # Note: `lastClosedVim` must be stored so that any window can access it.
166 @vimfx.lastClosedVim = vim
167 )
168
169 messageManager.listen('cachedPageshow', ((data, callback, browser) =>
170 [oldVim, @vimfx.lastClosedVim] = [@vimfx.lastClosedVim, null]
171 unless oldVim
172 callback(false)
173 return
174
175 if @vimfx.vims.has(browser)
176 vim = @vimfx.vims.get(browser)
177 if vim._messageManager == vim.browser.messageManager
178 callback(false)
179 return
180
181 # If we get here, it means that we’ve detected a tab dragged from one
182 # window to another. If so, the `vim` object from the last closed tab (the
183 # moved tab) should be re-used. See the commit message for commit bb70257d
184 # for more details.
185 oldVim._setBrowser(browser)
186 @vimfx.vims.set(browser, oldVim)
187 @vimfx.emit('modeChange', {vim: oldVim})
188 callback(true)
189 ), {messageManager: @window.messageManager})
190
191 setFocusType: ->
192 return unless vim = @vimfx.getCurrentVim(@window)
193
194 activeElement = utils.getActiveElement(@window)
195
196 if activeElement == @window.gBrowser.selectedBrowser
197 vim._send('checkFocusType')
198 return
199
200 focusType = utils.getFocusType(activeElement)
201 vim._setFocusType(focusType)
202
203 if focusType == 'editable' and vim.mode == 'caret'
204 vim._enterMode('normal')
205
206 consumeKeyEvent: (vim, event) ->
207 match = vim._consumeKeyEvent(event)
208
209 if typeof match == 'boolean'
210 @suppress = match
211 return
212
213 if match
214 if @vimfx.options.notify_entered_keys and vim.mode != 'ignore'
215 if match.type in ['none', 'full'] or match.likelyConflict
216 @enteredKeys.clear(vim)
217 else
218 @enteredKeys.push(vim, match.keyStr, @vimfx.options.timeout)
219 else
220 vim.hideNotification()
221
222 if match.specialKeys['<late>']
223 @suppress = false
224 @consumeLateKeydown(vim, event, match)
225 else
226 @suppress = vim._onInput(match, event)
227 else
228 @suppress = null
229 @setHeldModifiers(event)
230
231 consumeLateKeydown: (vim, event, match) ->
232 @late = true
233
234 # The passed in `event` is the regular non-late browser UI keydown event.
235 # It is only used to set held keys. This is easier than sending an event
236 # subset from frame scripts.
237 listener = ({defaultPrevented}) =>
238 # `@late` is reset on every keydown. If it is no longer `true`, it means
239 # that the page called `event.stopPropagation()`, which prevented this
240 # listener from running for that event.
241 return unless @late
242 @suppress =
243 if defaultPrevented
244 false
245 else
246 vim._onInput(match, event)
247 @setHeldModifiers(event)
248 return @suppress
249
250 if vim.isUIEvent(event)
251 @listenOnce('keydown', ((lateEvent) =>
252 listener(lateEvent)
253 if @suppress
254 utils.suppressEvent(lateEvent)
255 @listenOnce('keyup', utils.suppressEvent, false)
256 ), false)
257 else
258 # Hack to avoid synchronous messages on every keydown (see
259 # events-frame.coffee).
260 prefs.set('late', true)
261 vim._listenOnce('lateKeydown', listener)
262
263 setHeldModifiers: (event, {filterCurrentOnly = false} = {}) ->
264 mainWindow = @window.document.documentElement
265 modifiers =
266 if filterCurrentOnly
267 mainWindow.getAttribute(HELD_MODIFIERS_ATTRIBUTE)
268 else
269 if @suppress == null then 'alt ctrl meta shift' else ''
270 isHeld = (modifier) -> event["#{modifier}Key"]
271 mainWindow.setAttribute(
272 HELD_MODIFIERS_ATTRIBUTE, modifiers.split(' ').filter(isHeld).join(' ')
273 )
274
275 anyPopupsOpen: ->
276 # The autocomplete popup in text inputs (for example) is technically a
277 # panel, but it does not respond to key presses. Therefore
278 # `[ignorekeys="true"]` is excluded.
279 #
280 # coffeelint: disable=max_line_length
281 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
282 # coffeelint: enable=max_line_length
283 popups = utils.querySelectorAllDeep(
284 @window, ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
285 )
286 for popup in popups
287 return true if popup.state == 'open'
288 return false
289
290 class EnteredKeysManager
291 constructor: (@window) ->
292 @keys = []
293 @timeout = null
294
295 clear: (notifier) ->
296 @clearTimeout()
297 if @keys.length > 0
298 @keys = []
299 notifier.hideNotification()
300
301 push: (notifier, keyStr, duration) ->
302 @keys.push(keyStr)
303 @clearTimeout()
304 notifier.notify(@keys.join(''))
305 clear = @clear.bind(this)
306 @timeout = @window.setTimeout((-> clear(notifier)), duration)
307
308 clearTimeout: ->
309 @window.clearTimeout(@timeout) if @timeout?
310 @timeout = null
311
312 module.exports = UIEventManager
Imprint / Impressum