]> git.gir.st - VimFx.git/blob - extension/lib/vim.coffee
Simplify handling of `uiEvent` in events.coffee
[VimFx.git] / extension / lib / vim.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
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 defines the `vim` API, available to all modes and commands. There is
22 # one `Vim` instance for each tab. Most importantly, it provides access to the
23 # owning Firefox window and the current mode, and allows you to change mode.
24 # `vim` objects are exposed by the config file API. Underscored names are
25 # private and should not be used by API consumers.
26
27 messageManager = require('./message-manager')
28 ScrollableElements = require('./scrollable-elements')
29 statusPanel = require('./status-panel')
30 utils = require('./utils')
31
32 ChromeWindow = Ci.nsIDOMChromeWindow
33
34 class Vim
35 constructor: (browser, @_parent) ->
36 @focusType = 'none'
37 @_setBrowser(browser, {addListeners: false})
38 @_storage = {}
39
40 @_resetState()
41
42 Object.defineProperty(this, 'options', {
43 get: => @_parent.options
44 enumerable: true
45 })
46
47 _start: ->
48 @_onLocationChange(@browser.currentURI.spec)
49 @_addListeners()
50
51 _addListeners: ->
52 # Require the subset of the options needed to be listed explicitly (as
53 # opposed to sending _all_ options) for performance. Each option access
54 # might trigger an optionOverride.
55 @_listen('options', ({prefs}) =>
56 options = {}
57 for pref in prefs
58 options[pref] = @options[pref]
59 return options
60 )
61
62 @_listen('vimMethod', ({method, args = []}, callback = null) =>
63 result = @[method](args...)
64 callback?(result)
65 )
66
67 @_listen('vimMethodSync', ({method, args = []}) =>
68 return @[method](args...)
69 )
70
71 @_listen('locationChange', @_onLocationChange.bind(this))
72
73 @_listen('frameCanReceiveEvents', (value) =>
74 @_state.frameCanReceiveEvents = value
75 )
76
77 @_listen('focusType', (focusType) =>
78 # If the focus moves from a web page element to a browser UI element, the
79 # focus and blur events happen in the expected order, but the message from
80 # the frame script arrives too late. Therefore, check that the currently
81 # active element isn’t a browser UI element first.
82 unless @_isUIElement(utils.getActiveElement(@window))
83 @_setFocusType(focusType)
84 )
85
86 _setBrowser: (@browser, {addListeners = true} = {}) ->
87 @window = @browser.ownerGlobal
88 @_messageManager = @browser.messageManager
89
90 @_statusPanel?.remove()
91 @_statusPanel = statusPanel.injectStatusPanel(@browser)
92 @_statusPanel.onclick = @hideNotification.bind(this)
93
94 @_addListeners() if addListeners
95
96 _resetState: ->
97 @_state = {
98 frameCanReceiveEvents: false
99 scrollableElements: new ScrollableElements(@window)
100 }
101
102 _isBlacklisted: (url) -> @options.black_list.some((regex) -> regex.test(url))
103
104 isUIEvent: (event) ->
105 return not @_state.frameCanReceiveEvents or
106 @_isUIElement(event.originalTarget)
107
108 _isUIElement: (element) ->
109 # TODO: The `element.ownerGlobal` check will be redundant when
110 # non-multi-process is removed from Firefox.
111 return element.ownerGlobal instanceof ChromeWindow and
112 element != @window.gBrowser.selectedBrowser
113
114 # `args...` is passed to the mode's `onEnter` method.
115 enterMode: (mode, args...) ->
116 return if @mode == mode
117
118 unless utils.has(@_parent.modes, mode)
119 modes = Object.keys(@_parent.modes).join(', ')
120 throw new Error("VimFx: Unknown mode. Available modes are: #{modes}.
121 Got: #{mode}")
122
123 @_call('onLeave') if @mode?
124 @mode = mode
125 result = @_call('onEnter', null, args...)
126 @_parent.emit('modeChange', this)
127 @_send('modeChange', {mode})
128 return result
129
130 _consumeKeyEvent: (event) ->
131 return @_parent.consumeKeyEvent(event, this)
132
133 _onInput: (match, event) ->
134 uiEvent = if @isUIEvent(event) then event else false
135 suppress = @_call('onInput', {uiEvent, count: match.count}, match)
136 return suppress
137
138 _onLocationChange: (url) ->
139 unless @mode == 'ignore' and @_storage.ignore.type == 'explicit'
140 if @_isBlacklisted(url)
141 @enterMode('ignore', {type: 'blacklist'})
142 else
143 @enterMode('normal')
144 @_parent.emit('locationChange', {vim: this, location: new @window.URL(url)})
145
146 _call: (method, data = {}, extraArgs...) ->
147 args = Object.assign({vim: this, storage: @_storage[@mode] ?= {}}, data)
148 currentMode = @_parent.modes[@mode]
149 return currentMode[method].call(currentMode, args, extraArgs...)
150
151 _run: (name, data = {}, callback = null) ->
152 @_send('runCommand', {name, data}, callback)
153
154 _messageManagerOptions: (options) ->
155 return Object.assign({
156 messageManager: @_messageManager
157 }, options)
158
159 _listen: (name, listener, options = {}) ->
160 messageManager.listen(name, listener, @_messageManagerOptions(options))
161
162 _listenOnce: (name, listener, options = {}) ->
163 messageManager.listenOnce(name, listener, @_messageManagerOptions(options))
164
165 _send: (name, data, callback = null, options = {}) ->
166 messageManager.send(name, data, callback, @_messageManagerOptions(options))
167
168 notify: (message) ->
169 @_parent.emit('notification', {vim: this, message})
170 if @_parent.options.notifications_enabled
171 @_statusPanel.setAttribute('label', message)
172 @_statusPanel.removeAttribute('inactive')
173
174 hideNotification: ->
175 @_parent.emit('hideNotification', {vim: this})
176 @_statusPanel.setAttribute('inactive', 'true')
177
178 markPageInteraction: (value = null) -> @_send('markPageInteraction', value)
179
180 _focusMarkerElement: (elementIndex, options = {}) ->
181 # If you, for example, focus the location bar, unfocus it by pressing
182 # `<esc>` and then try to focus a link or text input in a web page the focus
183 # won’t work unless `@browser` is focused first.
184 @browser.focus()
185 @_run('focus_marker_element', {elementIndex, options})
186
187 _setFocusType: (@focusType) ->
188 switch
189 when @focusType == 'ignore'
190 @enterMode('ignore', {type: 'focusType'})
191 when @mode == 'ignore' and @_storage.ignore.type == 'focusType'
192 @enterMode('normal')
193 @_parent.emit('focusTypeChange', this)
194
195 module.exports = Vim
Imprint / Impressum