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