]> git.gir.st - VimFx.git/blob - extension/lib/events-frame.coffee
Get XPCOM interfaces once at the top of files
[VimFx.git] / extension / lib / events-frame.coffee
1 ###
2 # Copyright Simon Lydell 2015, 2016.
3 #
4 # This file is part of VimFx.
5 #
6 # VimFx is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # VimFx is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
18 ###
19
20 # This file is the equivalent to events.coffee, but for frame scripts.
21
22 notation = require('vim-like-key-notation')
23 commands = require('./commands-frame')
24 messageManager = require('./message-manager')
25 utils = require('./utils')
26
27 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
28 .getService(Ci.nsIFocusManager)
29
30 class FrameEventManager
31 constructor: (@vim) ->
32 @numFocusToSuppress = 0
33 @keepInputs = false
34 @currentUrl = false
35
36 listen: utils.listen.bind(null, FRAME_SCRIPT_ENVIRONMENT)
37 listenOnce: utils.listenOnce.bind(null, FRAME_SCRIPT_ENVIRONMENT)
38
39 addListeners: ->
40 # If the page already was loaded when VimFx was initialized, send the
41 # 'frameCanReceiveEvents' message straight away.
42 if @vim.content.document.readyState == 'complete'
43 messageManager.send('frameCanReceiveEvents', true)
44
45 @listen('readystatechange', (event) =>
46 target = event.originalTarget
47 @currentUrl = @vim.content.location.href
48
49 if target == @vim.content.document
50 switch target.readyState
51 when 'interactive'
52 messageManager.send('locationChange', @currentUrl)
53 when 'complete'
54 messageManager.send('frameCanReceiveEvents', true)
55 )
56
57 @listen('pageshow', (event) =>
58 [oldUrl, @currentUrl] = [@currentUrl, @vim.content.location.href]
59
60 # When navigating the history, `event.persisted` is `true` (meaning that
61 # the page loaded from cache) and 'readystatechange' won’t be fired, so
62 # send a 'locationChange' message to make sure that the blacklist is
63 # applied etc. The reason we don’t simply _always_ do this on the
64 # 'pageshow' event, is because it usually fires too late. However, it also
65 # fires after having moved a tab to another window. In that case it is
66 # _not_ a location change; the blacklist should not be applied.
67 if event.persisted
68 url = @vim.content.location.href
69 messageManager.send('cachedPageshow', null, (movedToNewTab) =>
70 if not movedToNewTab and oldUrl != @currentUrl
71 messageManager.send('locationChange', @currentUrl)
72 )
73 )
74
75 @listen('pagehide', (event) =>
76 target = event.originalTarget
77 @currentUrl = null
78
79 if target == @vim.content.document
80 messageManager.send('frameCanReceiveEvents', false)
81
82 # If the target isn’t the topmost document, it means that a frame has
83 # changed: It could have been removed or its `src` attribute could have
84 # been changed. If the frame contains other frames, 'pagehide' events have
85 # already been fired for them.
86 @vim.resetState(target)
87 )
88
89 messageManager.listen('getMarkableElementsMovements', (data, {callback}) =>
90 diffs = @vim.state.markerElements.map(({element, originalRect}) ->
91 newRect = element.getBoundingClientRect()
92 return {
93 dx: newRect.left - originalRect.left
94 dy: newRect.top - originalRect.top
95 }
96 )
97 messageManager.send(callback, diffs)
98 )
99
100 @listen('overflow', (event) =>
101 target = event.originalTarget
102 @vim.state.scrollableElements.addChecked(target)
103 )
104
105 @listen('underflow', (event) =>
106 target = event.originalTarget
107 @vim.state.scrollableElements.deleteChecked(target)
108 )
109
110 @listen('keydown', (event) =>
111 @keepInputs = false
112
113 suppress = @vim.onInput(event)
114
115 # This also suppresses the 'keypress' and 'keyup' events. (Yes, in frame
116 # scripts, suppressing the 'keydown' events does seem to even suppress
117 # the 'keyup' event!)
118 utils.suppressEvent(event) if suppress
119
120 # From this line on, the rest of the code in `addListeners` is more or
121 # less devoted to autofocus prevention. When enabled, focus events that
122 # occur before the user has interacted with page are prevented.
123 #
124 # If this keydown event wasn’t suppressed (`not suppress`), it’s an
125 # obvious interaction with the page. If it _was_ suppressed, though, it’s
126 # an interaction depending on the command triggered; if it calls
127 # `vim.markPageInteraction()` or not.
128 @vim.markPageInteraction() unless suppress
129 )
130
131 @listen('keydown', ((event) =>
132 suppress = messageManager.get('lateKeydown', {
133 defaultPrevented: event.defaultPrevented
134 })
135
136 if @vim.state.inputs and @vim.mode == 'normal' and not suppress and
137 not event.defaultPrevented
138 # There is no need to take `ignore_keyboard_layout` and `translations`
139 # into account here, since we want to override the _native_ `<tab>`
140 # behavior. Then, `event.key` is the way to go. (Unless the prefs are
141 # customized. YAGNI until requested.)
142 keyStr = notation.stringify(event)
143 options = @vim.options(['focus_previous_key', 'focus_next_key'])
144 direction = switch keyStr
145 when '' then null
146 when options.focus_previous_key then -1
147 when options.focus_next_key then +1
148 else null
149 if direction?
150 suppress = commands.move_focus({@vim, direction})
151 @keepInputs = true
152
153 utils.suppressEvent(event) if suppress
154 ), false)
155
156 @listen('mousedown', (event) =>
157 # Allow clicking on another text input without exiting “gi mode”. Listen
158 # for 'mousedown' instead of 'click', because only the former runs before
159 # the 'blur' event. Also, `event.originalTarget` does _not_ work here.
160 @keepInputs = (@vim.state.inputs and event.target in @vim.state.inputs)
161
162 # Clicks are always counted as page interaction. Listen for 'mousedown'
163 # instead of 'click' to mark the interaction as soon as possible.
164 @vim.markPageInteraction()
165 )
166
167 messageManager.listen('browserRefocus', =>
168 # Suppress the next two focus events (for `document` and `window`; see
169 # `blurActiveBrowserElement`).
170 @numFocusToSuppress = 2
171 )
172
173 sendFocusType = =>
174 return unless activeElement = utils.getActiveElement(@vim.content)
175 focusType = utils.getFocusType(activeElement)
176 messageManager.send('focusType', focusType)
177
178 @listen('focus', (event) =>
179 target = event.originalTarget
180
181 if @numFocusToSuppress > 0
182 utils.suppressEvent(event)
183 @numFocusToSuppress--
184 return
185
186 @vim.state.explicitBodyFocus = (target == @vim.content.document.body)
187
188 sendFocusType()
189
190 # Reset `hasInteraction` when (re-)selecting a tab, or coming back from
191 # another window, in order to prevent the common “automatically re-focus
192 # when switching back to the tab” behaviour many sites have, unless a text
193 # input _should_ be re-focused when coming back to the tab (see the 'blur'
194 # event below).
195 if target == @vim.content.document
196 if @vim.state.shouldRefocus
197 @vim.state.hasInteraction = true
198 @vim.state.shouldRefocus = false
199 else
200 @vim.state.hasInteraction = false
201 return
202
203 # Save the last focused text input regardless of whether that input might
204 # be blurred because of autofocus prevention.
205 if utils.isTextInputElement(target)
206 @vim.state.lastFocusedTextInput = target
207 @vim.state.hasFocusedTextInput = true
208
209 # When moving a tab to another window, there is a short period of time
210 # when there’s no listener for this call.
211 return unless options = @vim.options(
212 ['prevent_autofocus', 'prevent_autofocus_modes']
213 )
214
215 # Blur the focus target, if autofocus prevention is enabled…
216 if options.prevent_autofocus and
217 @vim.mode in options.prevent_autofocus_modes and
218 # …and the user has interacted with the page…
219 not @vim.state.hasInteraction and
220 # …and the event is programmatic (not caused by clicks or keypresses)…
221 nsIFocusManager.getLastFocusMethod(null) == 0 and
222 # …and the target may steal most keystrokes.
223 utils.isTypingElement(target)
224 # Some sites (such as icloud.com) re-focuses inputs if they are blurred,
225 # causing an infinite loop of autofocus prevention and re-focusing.
226 # Therefore, blur events that happen just after an autofocus prevention
227 # are suppressed.
228 @listenOnce('blur', utils.suppressEvent)
229 target.blur()
230 @vim.state.hasFocusedTextInput = false
231 )
232
233 @listen('blur', (event) =>
234 target = event.originalTarget
235
236 sendFocusType()
237
238 # If a text input is blurred immediately before the document loses focus,
239 # it most likely means that the user switched tab, for example by pressing
240 # `<c-tab>`, or switched to another window, while the text input was
241 # focused. In this case, when switching back to that tab, the text input
242 # will, and should, be re-focused (because it was focused when you left
243 # the tab). This case is kept track of so that the autofocus prevention
244 # does not catch it.
245 if utils.isTypingElement(target)
246 utils.nextTick(@vim.content, =>
247 @vim.state.shouldRefocus = not @vim.content.document.hasFocus()
248
249 # “gi mode” ends when blurring a text input, unless `<tab>` was just
250 # pressed.
251 unless @vim.state.shouldRefocus or @keepInputs
252 commands.clear_inputs({@vim})
253 )
254 )
255
256 module.exports = FrameEventManager
Imprint / Impressum