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 keypresses 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 @ignoreKeyEventsUntilTime = 0
39 @skipCreateKeyTrees = false
42 @on('modeChange', ({vim}) => @reset(vim.mode))
46 '<late>': {single: true}
58 vim = new Vim(browser, this)
59 @vims.set(browser, vim)
60 # Calling `vim._start` will emit VimFx events. It might seem as if the logic
61 # of `vim._start` could be moved into the constructor, but splitting it like
62 # this allows to save the `vim` instance in `vimfx.vims` first, which in
63 # turn allows `vimfx.on(...)` listeners to use `vimfx.getCurrentVim()`.
66 # NOTE: This method is often called in event handlers. Many events may fire
67 # before a `vim` object has been created for the current tab yet (such as when
68 # the browser is starting up). Therefore always check if anything was
71 # return unless vim = @vimfx.getCurrentVim(@window)
72 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
74 reset: (mode = null) ->
75 # Modes without commands are returned by neither `.getGroupedCommands()` nor
76 # `createKeyTrees`. Fall back to an empty tree.
77 @currentKeyTree = @keyTrees[mode] ? {}
82 return if @skipCreateKeyTrees
83 {@keyTrees, @errors} =
84 createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS, @MODIFIER_KEYS)
86 stringifyKeyEvent: (event) ->
87 return '' if event.key.endsWith('Lock')
88 return notation.stringify(event, {
89 ignoreCtrlAlt: @options.ignore_ctrl_alt
90 ignoreKeyboardLayout: @options.ignore_keyboard_layout
91 translations: @options.translations
94 consumeKeyEvent: (event, vim) ->
96 return unless keyStr = @stringifyKeyEvent(event)
100 return true if now <= @ignoreKeyEventsUntilTime
102 @reset(mode) if now - @lastInputTime >= @options.timeout
105 toplevel = (@currentKeyTree == @keyTrees[mode])
107 if toplevel and @options.keyValidator
108 unless @options.keyValidator(keyStr, mode)
117 when keyStr of @currentKeyTree and
118 not (toplevel and keyStr == '0' and @count != '')
119 next = @currentKeyTree[keyStr]
120 if next instanceof Leaf
122 {command, specialKeys} = next
124 @currentKeyTree = next
127 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
128 not (keyStr == '0' and @count == '')
135 count = if @count == '' then undefined else Number(@count)
136 unmodifiedKey = notation.parse(keyStr).key
138 focusTypeKeys = @options["#{vim.focusType}_element_keys"]
142 keyStr in focusTypeKeys
144 vim.focusType != 'none'
148 @reset(mode) if type == 'full'
150 type, command, count, toplevel
151 specialKeys, keyStr, unmodifiedKey, likelyConflict
152 rawKey: event.key, rawCode: event.code
153 discard: @reset.bind(this, mode)
156 getGroupedCommands: (options = {}) ->
158 for modeName, mode of @modes
159 if options.enabledOnly
160 usedSequences = getUsedSequences(@keyTrees[modeName])
161 for commandName, command of mode.commands
162 enabledSequences = null
163 if options.enabledOnly
164 enabledSequences = utils.removeDuplicates(
165 command._sequences.filter((sequence) ->
166 return (usedSequences[sequence] == command.pref)
169 continue if enabledSequences.length == 0
170 categories = modes[modeName] ?= {}
171 category = categories[command.category] ?= []
173 {command, enabledSequences, order: command.order, name: commandName}
177 for modeName, categories of modes
178 categoriesSorted = []
179 for categoryName, commands of categories
180 category = @options.categories[categoryName]
181 categoriesSorted.push({
184 order: category.order
185 commands: commands.sort(byOrder)
187 mode = @modes[modeName]
192 categories: categoriesSorted.sort(byOrder)
194 return modesSorted.sort(byOrder)
196 byOrder = (a, b) -> a.order - b.order
199 constructor: (@command, @originalSequence, @specialKeys) ->
201 createKeyTrees = (groupedCommands, specialKeysSpec, modifierKeys) ->
205 pushError = (error, command) ->
206 (errors[command.pref] ?= []).push(error)
208 pushOverrideErrors = (command, originalSequence, tree) ->
209 {command: overridingCommand} = getFirstLeaf(tree)
212 subject: overridingCommand.description
213 context: originalSequence
215 pushError(error, command)
217 pushKeyError = (command, id, originalSequence, key) ->
218 pushError({id, subject: key, context: originalSequence}, command)
220 for mode in groupedCommands
221 keyTrees[mode._name] = {}
222 for category in mode.categories then for {command} in category.commands
223 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
224 pushError(error, command) for error in parseErrors
225 command._sequences = []
227 for shortcut in shortcuts
228 [prefixKeys..., lastKey] = shortcut.normalized
229 tree = keyTrees[mode._name]
230 command._sequences.push(shortcut.original)
231 seenNonSpecialKey = false
235 for prefixKey, index in prefixKeys
236 if prefixKey of modifierKeys
238 command, 'mistake_modifier', shortcut.original, prefixKey
242 if prefixKey of specialKeysSpec
245 command, 'special_key.prefix_only', shortcut.original, prefixKey
250 specialKeys[prefixKey] = true
252 unless seenNonSpecialKey
253 for specialKey of specialKeys
254 options = specialKeysSpec[specialKey]
257 command, 'special_key.single_only', shortcut.original,
263 seenNonSpecialKey = true
266 next = tree[prefixKey]
267 if next instanceof Leaf
268 pushOverrideErrors(command, shortcut.original, next)
274 tree = tree[prefixKey] = {}
278 if lastKey of modifierKeys
279 pushKeyError(command, 'lone_modifier', shortcut.original, lastKey)
282 if lastKey of specialKeysSpec
283 subject = if seenNonSpecialKey then lastKey else shortcut.original
285 command, 'special_key.prefix_only', shortcut.original, subject
289 pushOverrideErrors(command, shortcut.original, tree[lastKey])
291 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
293 return {keyTrees, errors}
295 parseShortcutPref = (pref) ->
299 prefValue = prefs.root.get(pref).trim()
301 unless prefValue == ''
302 for sequence in prefValue.split(/\s+/)
305 for key in notation.parseSequence(sequence)
307 shortcut.push(notation.normalize(key))
309 throw error unless error.id?
313 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
315 return {shortcuts, errors}
317 getFirstLeaf = (node) ->
318 if node instanceof Leaf
320 for key, value of node
321 return getFirstLeaf(value)
323 getLeaves = (node) ->
324 if node instanceof Leaf
327 for key, value of node
328 leaves.push(getLeaves(value)...)
331 getUsedSequences = (tree) ->
333 for leaf in getLeaves(tree)
334 usedSequences[leaf.originalSequence] = leaf.command.pref
337 module.exports = VimFx