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