]> git.gir.st - VimFx.git/blob - extension/lib/vimfx.coffee
Allow to temporarily enter Ignore mode based on focusType
[VimFx.git] / extension / lib / vimfx.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 defines a top-level object to hold global state for VimFx. It keeps
21 # track of all `Vim` instances (vim.coffee), all options and all keyboard
22 # shortcuts. It can consume key presses according to its commands, and return
23 # the commands for UI presentation. There is only one `VimFx` instance.
24
25 notation = require('vim-like-key-notation')
26 prefs = require('./prefs')
27 utils = require('./utils')
28 Vim = require('./vim')
29
30 {EventEmitter} = utils
31
32 DIGIT = /^\d$/
33
34 class VimFx extends EventEmitter
35 constructor: (@modes, @options) ->
36 super()
37 @vims = new WeakMap()
38 @lastClosedVim = null
39 @goToCommand = null
40 @skipCreateKeyTrees = false
41 @createKeyTrees()
42 @reset()
43 @on('modeChange', ({mode}) => @reset(mode))
44
45 SPECIAL_KEYS: ['<force>', '<late>']
46
47 addVim: (browser) ->
48 vim = new Vim(browser, this)
49 @vims.set(browser, vim)
50 # Calling `vim._start` will emit VimFx events. It might seem as if the logic
51 # of `vim._start` could be moved into the constructor, but splitting it like
52 # this allows to save the `vim` instance in `vimfx.vims` first, which in
53 # turn allows `vimfx.on(...)` listeners to use `vimfx.getCurrentVim()`.
54 vim._start()
55
56 # NOTE: This method is often called in event handlers. Many events may fire
57 # before a `vim` object has been created for the current tab yet (such as when
58 # the browser is starting up). Therefore always check if anything was
59 # returned, such as:
60 #
61 # return unless vim = @vimfx.getCurrentVim(@window)
62 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
63
64 reset: (mode = null) ->
65 # Modes without commands are returned by neither `.getGroupedCommands()` nor
66 # `createKeyTrees`. Fall back to an empty tree.
67 @currentKeyTree = @keyTrees[mode] ? {}
68 @lastInputTime = 0
69 @count = ''
70
71 createKeyTrees: ->
72 return if @skipCreateKeyTrees
73 {@keyTrees, @errors} = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
74
75 stringifyKeyEvent: (event) ->
76 return notation.stringify(event, {
77 ignoreCtrlAlt: @options.ignore_ctrl_alt
78 ignoreKeyboardLayout: @options.ignore_keyboard_layout
79 translations: @options.translations
80 })
81
82 consumeKeyEvent: (event, vim, focusType) ->
83 {mode} = vim
84 return unless keyStr = @stringifyKeyEvent(event)
85
86 now = Date.now()
87 @reset(mode) if now - @lastInputTime >= @options.timeout
88 @lastInputTime = now
89
90 toplevel = (@currentKeyTree == @keyTrees[mode])
91
92 if toplevel and @options.keyValidator
93 unless @options.keyValidator(keyStr, mode)
94 @reset(mode)
95 return
96
97 type = 'none'
98 command = null
99 specialKeys = {}
100
101 switch
102 when keyStr of @currentKeyTree and
103 not (toplevel and keyStr == '0' and @count != '')
104 next = @currentKeyTree[keyStr]
105 if next instanceof Leaf
106 type = 'full'
107 {command, specialKeys} = next
108 else
109 @currentKeyTree = next
110 type = 'partial'
111
112 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
113 not (keyStr == '0' and @count == '')
114 @count += keyStr
115 type = 'count'
116
117 else
118 @reset(mode)
119
120 count = if @count == '' then undefined else Number(@count)
121 focus = @adjustFocusType(event, vim, focusType, keyStr)
122 unmodifiedKey = notation.parse(keyStr).key
123 @reset(mode) if type == 'full'
124 return {
125 type, focus, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
126 discard: @reset.bind(this, mode)
127 }
128
129 adjustFocusType: (event, vim, focusType, keyStr) ->
130 # Frame scripts and the tests don’t pass in `originalTarget`.
131 document = event.originalTarget?.ownerDocument
132 if focusType == null and document and
133 # TODO: Remove when Tab Groups have been removed.
134 vim.window.TabView?.isVisible()
135 return 'other'
136
137 keys = @options["#{focusType}_element_keys"]
138 return null if keys and keyStr not in keys
139
140 return focusType
141
142 getGroupedCommands: (options = {}) ->
143 modes = {}
144 for modeName, mode of @modes
145 if options.enabledOnly
146 usedSequences = getUsedSequences(@keyTrees[modeName])
147 for commandName, command of mode.commands
148 enabledSequences = null
149 if options.enabledOnly
150 enabledSequences = utils.removeDuplicates(
151 command._sequences.filter((sequence) ->
152 return (usedSequences[sequence] == command.pref)
153 )
154 )
155 continue if enabledSequences.length == 0
156 categories = modes[modeName] ?= {}
157 category = categories[command.category] ?= []
158 category.push(
159 {command, enabledSequences, order: command.order, name: commandName}
160 )
161
162 modesSorted = []
163 for modeName, categories of modes
164 categoriesSorted = []
165 for categoryName, commands of categories
166 category = @options.categories[categoryName]
167 categoriesSorted.push({
168 name: category.name
169 _name: categoryName
170 order: category.order
171 commands: commands.sort(byOrder)
172 })
173 mode = @modes[modeName]
174 modesSorted.push({
175 name: mode.name
176 _name: modeName
177 order: mode.order
178 categories: categoriesSorted.sort(byOrder)
179 })
180 return modesSorted.sort(byOrder)
181
182 byOrder = (a, b) -> a.order - b.order
183
184 class Leaf
185 constructor: (@command, @originalSequence, @specialKeys) ->
186
187 createKeyTrees = (groupedCommands, specialKeyStrings) ->
188 keyTrees = {}
189 errors = {}
190
191 pushError = (error, command) ->
192 (errors[command.pref] ?= []).push(error)
193
194 pushOverrideErrors = (command, originalSequence, tree) ->
195 {command: overridingCommand} = getFirstLeaf(tree)
196 error = {
197 id: 'overridden_by'
198 subject: overridingCommand.description
199 context: originalSequence
200 }
201 pushError(error, command)
202
203 pushSpecialKeyError = (command, originalSequence, key) ->
204 error = {
205 id: 'illegal_special_key'
206 subject: key
207 context: originalSequence
208 }
209 pushError(error, command)
210
211 for mode in groupedCommands
212 keyTrees[mode._name] = {}
213 for category in mode.categories then for {command} in category.commands
214 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
215 pushError(error, command) for error in parseErrors
216 command._sequences = []
217
218 for shortcut in shortcuts
219 [prefixKeys..., lastKey] = shortcut.normalized
220 tree = keyTrees[mode._name]
221 command._sequences.push(shortcut.original)
222 seenNonSpecialKey = false
223 specialKeys = {}
224
225 errored = false
226 for prefixKey, index in prefixKeys
227 if prefixKey in specialKeyStrings
228 if seenNonSpecialKey
229 pushSpecialKeyError(command, shortcut.original, prefixKey)
230 errored = true
231 break
232 else
233 specialKeys[prefixKey] = true
234 continue
235 else
236 seenNonSpecialKey = true
237
238 if prefixKey of tree
239 next = tree[prefixKey]
240 if next instanceof Leaf
241 pushOverrideErrors(command, shortcut.original, next)
242 errored = true
243 break
244 else
245 tree = next
246 else
247 tree = tree[prefixKey] = {}
248 continue if errored
249
250 if lastKey in specialKeyStrings
251 subject = if seenNonSpecialKey then lastKey else shortcut.original
252 pushSpecialKeyError(command, shortcut.original, subject)
253 continue
254 if lastKey of tree
255 pushOverrideErrors(command, shortcut.original, tree[lastKey])
256 continue
257 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
258
259 return {keyTrees, errors}
260
261 parseShortcutPref = (pref) ->
262 shortcuts = []
263 errors = []
264
265 # The shorcut prefs are read from root in order to support other extensions to
266 # extend VimFx with custom commands.
267 prefValue = prefs.root.get(pref).trim()
268
269 unless prefValue == ''
270 for sequence in prefValue.split(/\s+/)
271 shortcut = []
272 errored = false
273 for key in notation.parseSequence(sequence)
274 try
275 shortcut.push(notation.normalize(key))
276 catch error
277 throw error unless error.id?
278 errors.push(error)
279 errored = true
280 break
281 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
282
283 return {shortcuts, errors}
284
285 getFirstLeaf = (node) ->
286 if node instanceof Leaf
287 return node
288 for key, value of node
289 return getFirstLeaf(value)
290
291 getLeaves = (node) ->
292 if node instanceof Leaf
293 return [node]
294 leaves = []
295 for key, value of node
296 leaves.push(getLeaves(value)...)
297 return leaves
298
299 getUsedSequences = (tree) ->
300 usedSequences = {}
301 for leaf in getLeaves(tree)
302 usedSequences[leaf.originalSequence] = leaf.command.pref
303 return usedSequences
304
305 module.exports = VimFx
Imprint / Impressum