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