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