]> git.gir.st - VimFx.git/blob - extension/lib/events.coffee
Don't lose state when loading tabs in the background
[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 addListeners: ->
47 checkPassthrough = (value, event) =>
48 target = event.originalTarget
49 if target.nodeName in ['menupopup', 'panel']
50 @popupPassthrough = value
51
52 @listen('popupshown', checkPassthrough.bind(null, true))
53 @listen('popuphidden', checkPassthrough.bind(null, false))
54
55 @listen('keydown', (event) =>
56 try
57 # No matter what, always reset the `@suppress` flag, so we don't
58 # suppress more than intended.
59 @suppress = false
60
61 # Reset the `@late` flag, telling any late listeners for the previous
62 # event not to run.
63 @late = false
64
65 if @popupPassthrough
66 # The `@popupPassthrough` flag is set a bit unreliably. Sometimes it
67 # can be stuck as `true` even though no popup is shown, effectively
68 # disabling the extension. Therefore we check if there actually _are_
69 # any open popups before stopping processing keyboard input. This is
70 # only done when popups (might) be open (not on every keystroke) of
71 # performance reasons.
72 #
73 # The autocomplete popup in text inputs (for example) is technically a
74 # panel, but it does not respond to key presses. Therefore
75 # `[ignorekeys="true"]` is excluded.
76 #
77 # coffeelint: disable=max_line_length
78 # <https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/PopupGuide/PopupKeys#Ignoring_Keys>
79 # coffeelint: enable=max_line_length
80 popups = @window.document.querySelectorAll(
81 ':-moz-any(menupopup, panel):not([ignorekeys="true"])'
82 )
83 for popup in popups
84 return if popup.state == 'open'
85 @popupPassthrough = false # No popup was actually open.
86
87 return unless vim = @vimfx.getCurrentVim(@window)
88
89 if vim.isUIEvent(event)
90 @consumeKeyEvent(vim, event, utils.getFocusType(event), event)
91 # This also suppresses the 'keypress' event.
92 utils.suppressEvent(event) if @suppress
93 else
94 vim._listenOnce('consumeKeyEvent', ({ focusType }) =>
95 @consumeKeyEvent(vim, event, focusType)
96 return @suppress
97 )
98
99 catch error
100 console.error(utils.formatError(error))
101 )
102
103 @listen('keyup', (event) =>
104 utils.suppressEvent(event) if @suppress
105 @setHeldModifiers(event, {filterCurrentOnly: true})
106 )
107
108 checkFindbar = (mode, event) =>
109 target = event.originalTarget
110 findBar = @window.gBrowser.getFindBar()
111 if target == findBar._findField.mInputField
112 return unless vim = @vimfx.getCurrentVim(@window)
113 vim.enterMode(mode)
114
115 @listen('focus', checkFindbar.bind(null, 'find'))
116 @listen('blur', checkFindbar.bind(null, 'normal'))
117
118 @listen('click', (event) =>
119 target = event.originalTarget
120 return unless vim = @vimfx.getCurrentVim(@window)
121
122 # If the user clicks the reload button or a link when in hints mode, we’re
123 # going to end up in hints mode without any markers. Or if the user clicks
124 # a text input, then that input will be focused, but you can’t type in it
125 # (instead markers will be matched). So if the user clicks anything in
126 # hints mode it’s better to leave it.
127 if vim.mode == 'hints' and vim.isUIEvent(event) and
128 # Exclude the VimFx button, though, since clicking it returns to normal
129 # mode. Otherwise we’d first return to normal mode and then the button
130 # would open the help dialog.
131 target != button.getButton(@window)
132 vim.enterMode('normal')
133 )
134
135 @listen('TabSelect', @vimfx.emit.bind(@vimfx, 'TabSelect'))
136
137 @listen('TabOpen', (event) =>
138 browser = @window.gBrowser.getBrowserForTab(event.originalTarget)
139 focusedWindow = utils.getCurrentWindow()
140
141 # If a tab is opened in another window than the focused window, it might
142 # mean that a tab has been dragged to it from the focused window. Unless
143 # that’s the case, do nothing.
144 return if @window == focusedWindow
145
146 if MULTI_PROCESS_ENABLED
147 # In multi-process, tabs dragged to new windows re-use the frame script.
148 # This means that no new `vim` instance is created (which is good since
149 # state is kept). A new `<browser>` is created, though. So if we’re
150 # already tracking this `<browser>` there’s nothing to do.
151 return if @vimfx.vims.has(browser)
152
153 # Grab the current `vim` (which corresponds to the dragged tab) from the
154 # focused window and update its `.browser`.
155 vim = @vimfx.getCurrentVim(focusedWindow)
156 vim._setBrowser(browser)
157 @vimfx.vims.set(browser, vim)
158
159 else
160 # In non-multi-process, a new frame script _is_ created, which means
161 # that a new `vim` instance is created as well, and also that all state
162 # for the page is lost. The best we can do is to copy over the mode.
163 vim = @vimfx.vims.get(browser)
164 oldVim = @vimfx.getCurrentVim(focusedWindow)
165 vim.enterMode(oldVim.mode)
166
167 # When a new `vim` object is created, `._onLocationChange` is run in the
168 # next tick. In this case, we _don’t_ want that to happen. This is a
169 # hack, but it doesn’t matter since it will be removed when
170 # multi-process is enabled by default.
171 { _onLocationChange } = vim
172 vim._onLocationChange = -> vim._onLocationChange = _onLocationChange
173 )
174
175 consumeKeyEvent: (vim, event, focusType, uiEvent = false) ->
176 match = vim._consumeKeyEvent(event, focusType)
177 switch
178 when not match
179 @suppress = null
180 when match.specialKeys['<late>']
181 @suppress = false
182 @consumeLateKeydown(vim, event, match, uiEvent)
183 else
184 @suppress = vim._onInput(match, uiEvent)
185 @setHeldModifiers(event)
186
187 consumeLateKeydown: (vim, event, match, uiEvent) ->
188 @late = true
189
190 # The passed in `event` is the regular non-late browser UI keydown event.
191 # It is only used to set held keys. This is easier than sending an event
192 # subset from frame scripts.
193 listener = ({ defaultPrevented }) =>
194 # `@late` is reset on every keydown. If it is no longer `true`, it means
195 # that the page called `event.stopPropagation()`, which prevented this
196 # listener from running for that event.
197 return unless @late
198 @suppress =
199 if defaultPrevented
200 false
201 else
202 vim._onInput(match, uiEvent)
203 @setHeldModifiers(event)
204 return @suppress
205
206 if uiEvent
207 @listenOnce('keydown', ((lateEvent) =>
208 listener(lateEvent)
209 if @suppress
210 utils.suppressEvent(lateEvent)
211 @listenOnce('keyup', utils.suppressEvent, false)
212 ), false)
213 else
214 vim._listenOnce('lateKeydown', listener)
215
216 setHeldModifiers: (event, { filterCurrentOnly = false } = {}) ->
217 mainWindow = @window.document.documentElement
218 modifiers =
219 if filterCurrentOnly
220 mainWindow.getAttribute(HELD_MODIFIERS_ATTRIBUTE)
221 else
222 if @suppress == null then 'alt ctrl meta shift' else ''
223 isHeld = (modifier) -> event["#{ modifier }Key"]
224 mainWindow.setAttribute(HELD_MODIFIERS_ATTRIBUTE,
225 modifiers.split(' ').filter(isHeld).join(' '))
226
227 module.exports = UIEventManager
Imprint / Impressum