]> git.gir.st - VimFx.git/blob - extension/lib/events-frame.coffee
Don't crash on pages with out-of-process iframes when fission is enabled
[VimFx.git] / extension / lib / events-frame.coffee
1 # This file is the equivalent to events.coffee, but for frame scripts.
2
3 notation = require('vim-like-key-notation')
4 commands = require('./commands-frame')
5 messageManager = require('./message-manager')
6 prefs = require('./prefs')
7 utils = require('./utils')
8
9 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
10 .getService(Ci.nsIFocusManager)
11
12 class FrameEventManager
13 constructor: (@vim) ->
14 @numFocusToSuppress = 0
15 @keepInputs = false
16 @currentUrl = false
17 @disconnectActiveElementObserver = null
18
19 listen: utils.listen.bind(null, FRAME_SCRIPT_ENVIRONMENT)
20 listenOnce: utils.listenOnce.bind(null, FRAME_SCRIPT_ENVIRONMENT)
21
22 addListeners: ->
23 # If the page already was loaded when VimFx was initialized, send the
24 # 'frameCanReceiveEvents' message straight away.
25 if @vim.content.document.readyState == 'complete'
26 messageManager.send('frameCanReceiveEvents', true)
27
28 @listen('readystatechange', (event) =>
29 target = event.originalTarget
30 topDocument = @vim.content.document
31 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
32
33 switch target.readyState
34 when 'interactive'
35 if target == topDocument or
36 # When loading the editor on codepen.io, a frame gets
37 # 'readystatechange' → 'interactive' quite a bit before the
38 # toplevel document does. Checking for this case lets us send
39 # 'locationChange' earlier, allowing to enter Ignore mode earlier,
40 # for example. Be careful not to trigger a 'locationChange' for
41 # frames loading _after_ the toplevel document, though. Finally,
42 # checking for 'uninitialized' is needed to be able to blacklist
43 # some XUL pages.
44 (topDocument.readyState in ['loading', 'uninitialized'] and
45 oldUrl == null)
46 messageManager.send('locationChange', @currentUrl)
47
48 when 'complete'
49 if target == topDocument
50 messageManager.send('frameCanReceiveEvents', true)
51 )
52
53 @listen('pageshow', (event) =>
54 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
55
56 # When navigating the history, `event.persisted` is `true` (meaning that
57 # the page loaded from cache) and 'readystatechange' won’t be fired, so
58 # send a 'locationChange' message to make sure that the blacklist is
59 # applied etc. The reason we don’t simply _always_ do this on the
60 # 'pageshow' event, is because it usually fires too late. However, it also
61 # fires after having moved a tab to another window. In that case it is
62 # _not_ a location change; the blacklist should not be applied.
63 if event.persisted
64 url = @vim.content.location.href
65 messageManager.send('cachedPageshow', null, (movedToNewTab) =>
66 if not movedToNewTab and oldUrl != @currentUrl
67 messageManager.send('locationChange', @currentUrl)
68 )
69 )
70
71 @listen('pagehide', (event) =>
72 target = event.originalTarget
73 @currentUrl = null
74
75 if target == @vim.content.document
76 messageManager.send('frameCanReceiveEvents', false)
77 @vim._enterMode('normal') if @vim.mode == 'hints'
78
79 # If the target isn’t the topmost document, it means that a frame has
80 # changed: It could have been removed or its `src` attribute could have
81 # been changed. If the frame contains other frames, 'pagehide' events have
82 # already been fired for them.
83 @vim.resetState(target)
84 )
85
86 messageManager.listen('getMarkableElementsMovements', (data, callback) =>
87 diffs = @vim.state.markerElements.map(({element, originalRect}) ->
88 newRect = element.getBoundingClientRect()
89 return {
90 dx: newRect.left - originalRect.left
91 dy: newRect.top - originalRect.top
92 }
93 )
94 callback(diffs)
95 )
96
97 messageManager.listen('highlightMarkableElements', (data) =>
98 {elements, strings} = data
99 utils.clearSelectionDeep(@vim.content)
100 for {elementIndex, selectAll} in elements
101 {element} = @vim.state.markerElements[elementIndex]
102 if selectAll
103 utils.selectElement(element)
104 else
105 for string in strings
106 utils.selectAllSubstringMatches(
107 element, string, {caseSensitive: false}
108 )
109 return
110 )
111
112 @listen('overflow', (event) =>
113 # XXX(fission): this eventually calls utils::containsDeep(), which if the
114 # element that caused the event sits in an out-of-process iframe, might
115 # cause a SecurityError. However, as of Nightly 78, events originating
116 # from such frames are not raised.
117 target = event.originalTarget
118 @vim.state.scrollableElements.addChecked(target)
119 )
120
121 @listen('underflow', (event) =>
122 target = event.originalTarget
123 @vim.state.scrollableElements.deleteChecked(target)
124 )
125
126 @listen('submit', ((event) ->
127 return if event.defaultPrevented
128 target = event.originalTarget
129 activeElement = utils.getActiveElement(target.ownerDocument.defaultView)
130 if activeElement?.form == target and utils.isTypingElement(activeElement)
131 activeElement.blur()
132 ), false)
133
134 @listen('keydown', (event) =>
135 @keepInputs = false
136 )
137
138 @listen('keydown', ((event) =>
139 suppress = false
140
141 # This message _has_ to be synchronous so we can suppress the event if
142 # needed. To avoid sending a synchronous message on _every_ keydown, this
143 # hack of toggling a pref when a `<late>` shortcut is encountered is used.
144 if prefs.get('late')
145 suppress = messageManager.get('lateKeydown', {
146 defaultPrevented: event.defaultPrevented
147 })
148
149 if @vim.state.inputs and @vim.mode == 'normal' and not suppress and
150 not event.defaultPrevented
151 # There is no need to take `ignore_keyboard_layout` and `translations`
152 # into account here, since we want to override the _native_ `<tab>`
153 # behavior. Then, `event.key` is the way to go. (Unless the prefs are
154 # customized. YAGNI until requested.) Also, since 'keydown' is fired so
155 # often the options are read directly from the prefs system for
156 # performance. That means you can’t override them with
157 # `vimfx.addOptionOverrides`. YAGNI until requested.
158 keyStr = notation.stringify(event)
159 direction = switch keyStr
160 when ''
161 null
162 when prefs.get('focus_previous_key')
163 -1
164 when prefs.get('focus_next_key')
165 +1
166 else
167 null
168 if direction?
169 suppress = commands.move_focus({@vim, direction})
170 @keepInputs = true
171
172 if suppress
173 utils.suppressEvent(event)
174 @listenOnce('keyup', utils.suppressEvent, false)
175 ), false)
176
177 @listen('mousedown', (event) =>
178 # Allow clicking on another text input without exiting “gi mode”. Listen
179 # for 'mousedown' instead of 'click', because only the former runs before
180 # the 'blur' event. Also, `event.originalTarget` does _not_ work here.
181 @keepInputs = (@vim.state.inputs and event.target in @vim.state.inputs)
182
183 # Clicks are always counted as page interaction. Listen for 'mousedown'
184 # instead of 'click' to mark the interaction as soon as possible.
185 @vim.markPageInteraction()
186
187 @vim.hideNotification()
188 )
189
190 messageManager.listen('browserRefocus', =>
191 # Suppress the next two focus events (for `document` and `window`; see
192 # `blurActiveBrowserElement`).
193 @numFocusToSuppress = 2
194 )
195
196 @listen('focus', (event) =>
197 target = event.originalTarget
198
199 if @numFocusToSuppress > 0
200 utils.suppressEvent(event)
201 @numFocusToSuppress -= 1
202 return
203
204 @vim.state.explicitBodyFocus = (target == @vim.content.document.body)
205
206 @sendFocusType()
207
208 # Reset `hasInteraction` when (re-)selecting a tab, or coming back from
209 # another window, in order to prevent the common “automatically re-focus
210 # when switching back to the tab” behaviour many sites have, unless a text
211 # input _should_ be re-focused when coming back to the tab (see the 'blur'
212 # event below).
213 if target == @vim.content.document
214 if @vim.state.shouldRefocus
215 @vim.markPageInteraction(true)
216 # When Firefox is re-focused after using a keyboard shortcut to switch
217 # keyboard layout in GNOME, _two_ focus events for the document are
218 # triggered, about 50ms apart. Therefore, reset the `shouldRefocus`
219 # after a timeout.
220 @vim.content.setTimeout((=>
221 @vim.state.shouldRefocus = false
222 ), prefs.get('refocus_timeout'))
223 else
224 @vim.markPageInteraction(false)
225 return
226
227 if utils.isTextInputElement(target)
228 # Save the last focused text input regardless of whether that input
229 # might be blurred because of autofocus prevention.
230 @vim.state.lastFocusedTextInput = target
231 @vim.state.hasFocusedTextInput = true
232
233 if @vim.mode == 'caret' and not utils.isContentEditable(target)
234 @vim._enterMode('normal')
235
236 # When moving a tab to another window, there is a short period of time
237 # when there’s no listener for this call.
238 return unless options = @vim.options(
239 ['prevent_autofocus', 'prevent_autofocus_modes']
240 )
241
242 # Blur the focus target, if autofocus prevention is enabled…
243 if options.prevent_autofocus and
244 @vim.mode in options.prevent_autofocus_modes and
245 # …and the user has interacted with the page…
246 not @vim.state.hasInteraction and
247 # …and the event is programmatic (not caused by clicks or keypresses)…
248 nsIFocusManager.getLastFocusMethod(null) == 0 and
249 # …and the target may steal most keystrokes
250 utils.isTypingElement(target)
251 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
252 # causing an infinite loop of autofocus prevention and re-focusing.
253 # Therefore, blur events that happen just after an autofocus prevention
254 # are suppressed.
255 @listenOnce('blur', utils.suppressEvent)
256 target.blur()
257 @vim.state.hasFocusedTextInput = false
258 )
259
260 @listen('blur', (event) =>
261 target = event.originalTarget
262
263 if target == @vim.state.lastHover.element and
264 # Facebook “like” button exception. The “emoji picker” immediately
265 # closes otherwise.
266 not target.classList?.contains('UFILikeLink')
267 @vim.clearHover()
268
269 @vim.content.setTimeout((=>
270 @sendFocusType()
271 ), prefs.get('blur_timeout'))
272
273 # If a text input is blurred immediately before the document loses focus,
274 # it most likely means that the user switched tab, for example by pressing
275 # `<c-tab>`, or switched to another window, while the text input was
276 # focused. In this case, when switching back to that tab, the text input
277 # will, and should, be re-focused (because it was focused when you left
278 # the tab). This case is kept track of so that the autofocus prevention
279 # does not catch it.
280 if utils.isTypingElement(target)
281 utils.nextTick(@vim.content, =>
282 @vim.state.shouldRefocus = not @vim.content.document.hasFocus()
283
284 # “gi mode” ends when blurring a text input, unless `<tab>` was just
285 # pressed.
286 unless @vim.state.shouldRefocus or @keepInputs
287 commands.clear_inputs({@vim})
288 )
289 )
290
291 @listen('popstate', =>
292 @vim.markPageInteraction(false)
293 )
294
295 messageManager.listen('checkFocusType', @sendFocusType.bind(this))
296
297 sendFocusType: ({ignore = []} = {}) ->
298 return unless utils and activeElement = utils.getActiveElement(@vim.content)
299 focusType = utils.getFocusType(activeElement)
300 messageManager.send('focusType', focusType) unless focusType in ignore
301
302 # If a text input is removed from the DOM while it is focused, no 'focus'
303 # or 'blur' events will be fired, making VimFx think that the text input is
304 # still focused. Therefore we add a temporary observer for the currently
305 # focused element and re-send the focusType if it gets removed.
306 @disconnectActiveElementObserver?()
307 @disconnectActiveElementObserver =
308 if focusType == 'none'
309 null
310 else
311 utils.onRemoved(activeElement, @sendFocusType.bind(this))
312
313 module.exports = FrameEventManager
Imprint / Impressum