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