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