]> git.gir.st - VimFx.git/blob - extension/lib/vim.coffee
Streamline `vimfx.on` events
[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 @_listen('vimMethod', ({method, args = []}, callback = null) =>
53 result = @[method](args...)
54 callback?(result)
55 )
56
57 @_listen('vimMethodSync', ({method, args = []}) =>
58 return @[method](args...)
59 )
60
61 @_listen('locationChange', @_onLocationChange.bind(this))
62
63 @_listen('frameCanReceiveEvents', (value) =>
64 @_state.frameCanReceiveEvents = value
65 )
66
67 @_listen('focusType', (focusType) =>
68 # If the focus moves from a web page element to a browser UI element, the
69 # focus and blur events happen in the expected order, but the message from
70 # the frame script arrives too late. Therefore, check that the currently
71 # active element isn’t a browser UI element first.
72 unless @_isUIElement(utils.getActiveElement(@window))
73 @_setFocusType(focusType)
74 )
75
76 _setBrowser: (@browser, {addListeners = true} = {}) ->
77 @window = @browser.ownerGlobal
78 @_messageManager = @browser.messageManager
79
80 @_statusPanel?.remove()
81 @_statusPanel = statusPanel.injectStatusPanel(@browser)
82 @_statusPanel.onclick = @hideNotification.bind(this)
83
84 @_addListeners() if addListeners
85
86 _resetState: ->
87 @_state = {
88 frameCanReceiveEvents: false
89 scrollableElements: new ScrollableElements(@window)
90 }
91
92 _isBlacklisted: (url) -> @options.black_list.some((regex) -> regex.test(url))
93
94 isUIEvent: (event) ->
95 return not @_state.frameCanReceiveEvents or
96 @_isUIElement(event.originalTarget)
97
98 _isUIElement: (element) ->
99 # TODO: The `element.ownerGlobal` check will be redundant when
100 # non-multi-process is removed from Firefox.
101 return element.ownerGlobal instanceof ChromeWindow and
102 element != @window.gBrowser.selectedBrowser
103
104 # `args...` is passed to the mode's `onEnter` method.
105 enterMode: (mode, args...) ->
106 return if @mode == mode
107
108 unless utils.has(@_parent.modes, mode)
109 modes = Object.keys(@_parent.modes).join(', ')
110 throw new Error("VimFx: Unknown mode. Available modes are: #{modes}.
111 Got: #{mode}")
112
113 @_call('onLeave') if @mode?
114 @mode = mode
115 result = @_call('onEnter', null, args...)
116 @_parent.emit('modeChange', {vim: this})
117 @_send('modeChange', {mode})
118 return result
119
120 _consumeKeyEvent: (event) ->
121 return @_parent.consumeKeyEvent(event, this)
122
123 _onInput: (match, event) ->
124 uiEvent = if @isUIEvent(event) then event else false
125 suppress = @_call('onInput', {uiEvent, count: match.count}, match)
126 return suppress
127
128 _onLocationChange: (url) ->
129 unless @mode == 'ignore' and @_storage.ignore.type == 'explicit'
130 if @_isBlacklisted(url)
131 @enterMode('ignore', {type: 'blacklist'})
132 else
133 @enterMode('normal')
134 @_parent.emit('locationChange', {vim: this, location: new @window.URL(url)})
135
136 _call: (method, data = {}, extraArgs...) ->
137 args = Object.assign({vim: this, storage: @_storage[@mode] ?= {}}, data)
138 currentMode = @_parent.modes[@mode]
139 return currentMode[method].call(currentMode, args, extraArgs...)
140
141 _run: (name, data = {}, callback = null) ->
142 @_send('runCommand', {name, data}, callback)
143
144 _messageManagerOptions: (options) ->
145 return Object.assign({
146 messageManager: @_messageManager
147 }, options)
148
149 _listen: (name, listener, options = {}) ->
150 messageManager.listen(name, listener, @_messageManagerOptions(options))
151
152 _listenOnce: (name, listener, options = {}) ->
153 messageManager.listenOnce(name, listener, @_messageManagerOptions(options))
154
155 _send: (name, data, callback = null, options = {}) ->
156 messageManager.send(name, data, callback, @_messageManagerOptions(options))
157
158 notify: (message) ->
159 @_parent.emit('notification', {vim: this, message})
160 if @options.notifications_enabled
161 @_statusPanel.setAttribute('label', message)
162 @_statusPanel.removeAttribute('inactive')
163
164 hideNotification: ->
165 @_parent.emit('hideNotification', {vim: this})
166 @_statusPanel.setAttribute('inactive', 'true')
167
168 markPageInteraction: (value = null) -> @_send('markPageInteraction', value)
169
170 _focusMarkerElement: (elementIndex, options = {}) ->
171 # If you, for example, focus the location bar, unfocus it by pressing
172 # `<esc>` and then try to focus a link or text input in a web page the focus
173 # won’t work unless `@browser` is focused first.
174 @browser.focus()
175 @_run('focus_marker_element', {elementIndex, options})
176
177 _setFocusType: (@focusType) ->
178 switch
179 when @focusType == 'ignore'
180 @enterMode('ignore', {type: 'focusType'})
181 when @mode == 'ignore' and @_storage.ignore.type == 'focusType'
182 @enterMode('normal')
183 @_parent.emit('focusTypeChange', {vim: this})
184
185 module.exports = Vim
Imprint / Impressum