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