]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Tiny code cleanup
[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 utils = require('./utils')
27
28 HELD_MODIFIERS_ATTRIBUTE = 'vimfx-held-modifiers'
29
30 class UIEventManager
31 constructor: (@vimfx, @window) ->
32 @listen = utils.listen.bind(null, @window)
33 @listenOnce = utils.listenOnce.bind(null, @window)
34
35 # This flag controls whether to suppress the various key events or not.
36 @suppress = false
37
38 # If a matched shortcut has the `<late>` special key, this flag is set to
39 # `true`.
40 @late = false
41
42 # When a menu or panel is shown VimFx should temporarily stop processing
43 # keyboard input, allowing accesskeys to be used.
44 @popupPassthrough = false
45
46 @locationState =
47 lastUrl: null
48 numToSkip: 0
49
50 addListeners: ->
51 checkPassthrough = (value, event) =>
52 target = event.originalTarget
53 if target.nodeName in ['menupopup', 'panel']
54 @popupPassthrough = value
55
56 @listen('popupshown', checkPassthrough.bind(null, true))
57 @listen('popuphidden', checkPassthrough.bind(null, false))
58
59 @listen('keydown', (event) =>
60 try
61 # No matter what, always reset the `@suppress` flag, so we don't
62 # suppress more than intended.
63 @suppress = false
64
65 # Reset the `@late` flag, telling any late listeners for the previous
66 # event not to run.
67 @late = false
68
69 if @popupPassthrough
70 # The `@popupPassthrough` flag is set a bit unreliably. Sometimes it
71 # can be stuck as `true` even though no popup is shown, effectively
72 # disabling the extension. Therefore we check if there actually _are_
73 # any open popups before stopping processing keyboard input. This is
74 # only done when popups (might) be open (not on every keystroke) of
75 # performance reasons.
76 #
77 # The autocomplete popup in text inputs (for example) is technically a
78 # panel, but it does not respond to key presses. Therefore
79 # `[ignorekeys="true"]` is excluded.
80 #
81 # coffeelint: disable=max_line_length
82 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
83 # coffeelint: enable=max_line_length
84 popups = @window.document.querySelectorAll(
85 ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
86 )
87 for popup in popups
88 return if popup.state == 'open'
89 @popupPassthrough = false # No popup was actually open.
90
91 return unless vim = @vimfx.getCurrentVim(@window)
92
93 if vim.isUIEvent(event)
94 @consumeKeyEvent(vim, event, utils.getFocusType(event), 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 checkFindbar = (mode, event) =>
113 target = event.originalTarget
114 findBar = @window.gBrowser.getFindBar()
115 if target == findBar._findField.mInputField
116 return unless vim = @vimfx.getCurrentVim(@window)
117 vim.enterMode(mode)
118
119 @listen('focus', checkFindbar.bind(null, 'find'))
120 @listen('blur', checkFindbar.bind(null, 'normal'))
121
122 @listen('click', (event) =>
123 target = event.originalTarget
124 return unless vim = @vimfx.getCurrentVim(@window)
125
126 # If the user clicks the reload button or a link when in hints mode, we’re
127 # going to end up in hints mode without any markers. Or if the user clicks
128 # a text input, then that input will be focused, but you can’t type in it
129 # (instead markers will be matched). So if the user clicks anything in
130 # hints mode it’s better to leave it.
131 if vim.mode == 'hints' and vim.isUIEvent(event) and
132 # Exclude the VimFx button, though, since clicking it returns to normal
133 # mode. Otherwise we’d first return to normal mode and then the button
134 # would open the help dialog.
135 target != button.getButton(@window)
136 vim.enterMode('normal')
137 )
138
139 @listen('TabSelect', @vimfx.emit.bind(@vimfx, 'TabSelect'))
140
141 @listen('TabOpen', (event) =>
142 browser = @window.gBrowser.getBrowserForTab(event.originalTarget)
143 focusedWindow = utils.getCurrentWindow()
144
145 # If a tab is opened in another window than the focused window, it might
146 # mean that a tab has been dragged to it from the focused window. Unless
147 # that’s the case, do nothing.
148 return if @window == focusedWindow
149
150 if MULTI_PROCESS_ENABLED
151 # In multi-process, tabs dragged to new windows re-use the frame script.
152 # This means that no new `vim` instance is created (which is good since
153 # state is kept). A new `<browser>` is created, though. So if we’re
154 # already tracking this `<browser>` there’s nothing to do.
155 return if @vimfx.vims.has(browser)
156
157 # Grab the current `vim` (which corresponds to the dragged tab) from the
158 # focused window and update its `.browser`.
159 vim = @vimfx.getCurrentVim(focusedWindow)
160 vim._setBrowser(browser)
161 @vimfx.vims.set(browser, vim)
162
163 # For some reason, three 'onLocationChange' events will fire for this
164 # tab now, all of which are unwanted because the location didn’t really
165 # change. Otherwise another mode might be entered based on the “changed”
166 # URL. The mode should not change when dragging a tab to another window.
167 @locationState.numToSkip = 3
168
169 else
170 # In non-multi-process, a new frame script _is_ created, which means
171 # that a new `vim` instance is created as well, and also that all state
172 # for the page is lost. The best we can do is to copy over the mode.
173 vim = @vimfx.vims.get(browser)
174 oldVim = @vimfx.getCurrentVim(focusedWindow)
175 vim._state.lastUrl = oldVim._state.lastUrl
176 vim.enterMode(oldVim.mode)
177
178 # In non-multi-process, the magic number seems to be four.
179 @locationState.numToSkip = 4
180 )
181
182 progressListener =
183 onLocationChange: (progress, request, location, flags) =>
184 if @locationState.numToSkip > 0
185 @locationState.numToSkip--
186 return
187
188 url = location.spec
189 refresh = (url == @locationState.lastUrl)
190 @locationState.lastUrl = url
191
192 unless flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT
193 return unless vim = @vimfx.getCurrentVim(@window)
194 vim._onLocationChange(url, {refresh})
195
196 @window.gBrowser.addProgressListener(progressListener)
197 module.onShutdown(=>
198 @window.gBrowser.removeProgressListener(progressListener)
199 )
200
201 consumeKeyEvent: (vim, event, focusType, uiEvent = false) ->
202 match = vim._consumeKeyEvent(event, focusType)
203 switch
204 when not match
205 @suppress = null
206 when match.specialKeys['<late>']
207 @suppress = false
208 @consumeLateKeydown(vim, event, match, uiEvent)
209 else
210 @suppress = vim._onInput(match, uiEvent)
211 @setHeldModifiers(event)
212
213 consumeLateKeydown: (vim, event, match, uiEvent) ->
214 @late = true
215
216 # The passed in `event` is the regular non-late browser UI keydown event.
217 # It is only used to set held keys. This is easier than sending an event
218 # subset from frame scripts.
219 listener = ({ defaultPrevented }) =>
220 # `@late` is reset on every keydown. If it is no longer `true`, it means
221 # that the page called `event.stopPropagation()`, which prevented this
222 # listener from running for that event.
223 return unless @late
224 @suppress =
225 if defaultPrevented
226 false
227 else
228 vim._onInput(match, uiEvent)
229 @setHeldModifiers(event)
230 return @suppress
231
232 if uiEvent
233 @listenOnce('keydown', ((lateEvent) =>
234 listener(lateEvent)
235 if @suppress
236 utils.suppressEvent(lateEvent)
237 @listenOnce('keyup', utils.suppressEvent, false)
238 ), false)
239 else
240 vim._listenOnce('lateKeydown', listener)
241
242 setHeldModifiers: (event, { filterCurrentOnly = false } = {}) ->
243 mainWindow = @window.document.documentElement
244 modifiers =
245 if filterCurrentOnly
246 mainWindow.getAttribute(HELD_MODIFIERS_ATTRIBUTE)
247 else
248 if @suppress == null then 'alt ctrl meta shift' else ''
249 isHeld = (modifier) -> event["#{ modifier }Key"]
250 mainWindow.setAttribute(HELD_MODIFIERS_ATTRIBUTE,
251 modifiers.split(' ').filter(isHeld).join(' '))
252
253 module.exports = UIEventManager
Imprint / Impressum