2 # Copyright Simon Lydell 2015, 2016.
4 # This file is part of VimFx.
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.
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.
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/>.
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.
25 notation = require('vim-like-key-notation')
26 prefs = require('./prefs')
27 utils = require('./utils')
28 Vim = require('./vim')
32 class VimFx extends utils.EventEmitter
33 constructor: (@modes, @options) ->
38 @skipCreateKeyTrees = false
41 @on('modeChange', ({vim}) => @reset(vim.mode))
45 '<late>': {single: true}
49 vim = new Vim(browser, this)
50 @vims.set(browser, vim)
51 # Calling `vim._start` will emit VimFx events. It might seem as if the logic
52 # of `vim._start` could be moved into the constructor, but splitting it like
53 # this allows to save the `vim` instance in `vimfx.vims` first, which in
54 # turn allows `vimfx.on(...)` listeners to use `vimfx.getCurrentVim()`.
57 # NOTE: This method is often called in event handlers. Many events may fire
58 # before a `vim` object has been created for the current tab yet (such as when
59 # the browser is starting up). Therefore always check if anything was
62 # return unless vim = @vimfx.getCurrentVim(@window)
63 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
65 reset: (mode = null) ->
66 # Modes without commands are returned by neither `.getGroupedCommands()` nor
67 # `createKeyTrees`. Fall back to an empty tree.
68 @currentKeyTree = @keyTrees[mode] ? {}
73 return if @skipCreateKeyTrees
74 {@keyTrees, @errors} = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
76 stringifyKeyEvent: (event) ->
77 return '' if event.key.endsWith('Lock')
78 return notation.stringify(event, {
79 ignoreCtrlAlt: @options.ignore_ctrl_alt
80 ignoreKeyboardLayout: @options.ignore_keyboard_layout
81 translations: @options.translations
84 consumeKeyEvent: (event, vim) ->
86 return unless keyStr = @stringifyKeyEvent(event)
89 @reset(mode) if now - @lastInputTime >= @options.timeout
92 toplevel = (@currentKeyTree == @keyTrees[mode])
94 if toplevel and @options.keyValidator
95 unless @options.keyValidator(keyStr, mode)
104 when keyStr of @currentKeyTree and
105 not (toplevel and keyStr == '0' and @count != '')
106 next = @currentKeyTree[keyStr]
107 if next instanceof Leaf
109 {command, specialKeys} = next
111 @currentKeyTree = next
114 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
115 not (keyStr == '0' and @count == '')
122 count = if @count == '' then undefined else Number(@count)
123 unmodifiedKey = notation.parse(keyStr).key
125 focusTypeKeys = @options["#{vim.focusType}_element_keys"]
129 keyStr in focusTypeKeys
131 vim.focusType != 'none'
135 @reset(mode) if type == 'full'
137 type, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
139 discard: @reset.bind(this, mode)
142 getGroupedCommands: (options = {}) ->
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)
155 continue if enabledSequences.length == 0
156 categories = modes[modeName] ?= {}
157 category = categories[command.category] ?= []
159 {command, enabledSequences, order: command.order, name: commandName}
163 for modeName, categories of modes
164 categoriesSorted = []
165 for categoryName, commands of categories
166 category = @options.categories[categoryName]
167 categoriesSorted.push({
170 order: category.order
171 commands: commands.sort(byOrder)
173 mode = @modes[modeName]
178 categories: categoriesSorted.sort(byOrder)
180 return modesSorted.sort(byOrder)
182 byOrder = (a, b) -> a.order - b.order
185 constructor: (@command, @originalSequence, @specialKeys) ->
187 createKeyTrees = (groupedCommands, specialKeysSpec) ->
191 pushError = (error, command) ->
192 (errors[command.pref] ?= []).push(error)
194 pushOverrideErrors = (command, originalSequence, tree) ->
195 {command: overridingCommand} = getFirstLeaf(tree)
198 subject: overridingCommand.description
199 context: originalSequence
201 pushError(error, command)
203 pushSpecialKeyError = (command, id, originalSequence, key) ->
205 id: "special_key.#{id}"
207 context: originalSequence
209 pushError(error, command)
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 = []
218 for shortcut in shortcuts
219 [prefixKeys..., lastKey] = shortcut.normalized
220 tree = keyTrees[mode._name]
221 command._sequences.push(shortcut.original)
222 seenNonSpecialKey = false
226 for prefixKey, index in prefixKeys
227 if prefixKey of specialKeysSpec
230 command, 'prefix_only', shortcut.original, prefixKey
235 specialKeys[prefixKey] = true
237 else if not seenNonSpecialKey
238 for specialKey of specialKeys
239 options = specialKeysSpec[specialKey]
242 command, 'single_only', shortcut.original, specialKey
247 seenNonSpecialKey = true
250 next = tree[prefixKey]
251 if next instanceof Leaf
252 pushOverrideErrors(command, shortcut.original, next)
258 tree = tree[prefixKey] = {}
261 if lastKey of specialKeysSpec
262 subject = if seenNonSpecialKey then lastKey else shortcut.original
264 command, 'prefix_only', shortcut.original, subject
268 pushOverrideErrors(command, shortcut.original, tree[lastKey])
270 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
272 return {keyTrees, errors}
274 parseShortcutPref = (pref) ->
278 # The shorcut prefs are read from root in order to support other extensions to
279 # extend VimFx with custom commands.
280 prefValue = prefs.root.get(pref).trim()
282 unless prefValue == ''
283 for sequence in prefValue.split(/\s+/)
286 for key in notation.parseSequence(sequence)
288 shortcut.push(notation.normalize(key))
290 throw error unless error.id?
294 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
296 return {shortcuts, errors}
298 getFirstLeaf = (node) ->
299 if node instanceof Leaf
301 for key, value of node
302 return getFirstLeaf(value)
304 getLeaves = (node) ->
305 if node instanceof Leaf
308 for key, value of node
309 leaves.push(getLeaves(value)...)
312 getUsedSequences = (tree) ->
314 for leaf in getLeaves(tree)
315 usedSequences[leaf.originalSequence] = leaf.command.pref
318 module.exports = VimFx