1 # This file defines a top-level object to hold global state for VimFx. It keeps
2 # track of all `Vim` instances (vim.coffee), all options and all keyboard
3 # shortcuts. It can consume keypresses according to its commands, and return
4 # the commands for UI presentation. There is only one `VimFx` instance.
6 notation = require('vim-like-key-notation')
7 prefs = require('./prefs')
8 utils = require('./utils')
11 CARET_BROWSING_PREF = 'accessibility.browsewithcaret'
14 class VimFx extends utils.EventEmitter
15 constructor: (@modes, @options) ->
20 @skipObserveCaretBrowsing = false
21 @ignoreKeyEventsUntilTime = 0
22 @skipCreateKeyTrees = false
25 @observeCaretBrowsing()
26 @on('modeChange', ({vim}) => @reset(vim.mode))
30 '<late>': {single: true}
42 vim = new Vim(browser, this)
43 @vims.set(browser, vim)
44 # Calling `vim._start` will emit VimFx events. It might seem as if the logic
45 # of `vim._start` could be moved into the constructor, but splitting it like
46 # this allows to save the `vim` instance in `vimfx.vims` first, which in
47 # turn allows `vimfx.on(...)` listeners to use `vimfx.getCurrentVim()`.
50 # NOTE: This method is often called in event handlers. Many events may fire
51 # before a `vim` object has been created for the current tab yet (such as when
52 # the browser is starting up). Therefore always check if anything was
55 # return unless vim = @vimfx.getCurrentVim(@window)
56 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
58 reset: (mode = null) ->
59 # Modes without commands are returned by neither `.getGroupedCommands()` nor
60 # `createKeyTrees`. Fall back to an empty tree.
61 @currentKeyTree = @keyTrees[mode] ? {}
65 resetCaretBrowsing: (value = @options.browsewithcaret) ->
66 @skipObserveCaretBrowsing = true
67 prefs.root.set(CARET_BROWSING_PREF, value)
68 @skipObserveCaretBrowsing = false
70 observeCaretBrowsing: ->
71 prefs.root.observe(CARET_BROWSING_PREF, =>
72 return if @skipObserveCaretBrowsing
73 prefs.set('browsewithcaret', prefs.root.get(CARET_BROWSING_PREF))
77 return if @skipCreateKeyTrees
78 {@keyTrees, @errors} =
79 createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS, @MODIFIER_KEYS)
81 stringifyKeyEvent: (event) ->
82 return '' if event.key.endsWith('Lock')
83 return notation.stringify(event, {
84 ignoreCtrlAlt: @options.ignore_ctrl_alt
85 ignoreKeyboardLayout: @options.ignore_keyboard_layout
86 translations: @options.translations
89 consumeKeyEvent: (event, vim) ->
91 return unless keyStr = @stringifyKeyEvent(event)
95 return true if now <= @ignoreKeyEventsUntilTime
97 @reset(mode) if now - @lastInputTime >= @options.timeout
100 toplevel = (@currentKeyTree == @keyTrees[mode])
102 if toplevel and @options.keyValidator
103 unless @options.keyValidator(keyStr, mode)
112 when keyStr of @currentKeyTree and
113 not (toplevel and keyStr == '0' and @count != '')
114 next = @currentKeyTree[keyStr]
115 if next instanceof Leaf
117 {command, specialKeys} = next
119 @currentKeyTree = next
122 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
123 not (keyStr == '0' and @count == '')
130 count = if @count == '' then undefined else Number(@count)
131 unmodifiedKey = notation.parse(keyStr).key
133 focusTypeKeys = @options["#{vim.focusType}_element_keys"]
137 keyStr in focusTypeKeys
139 vim.focusType != 'none'
143 @reset(mode) if type == 'full'
145 type, command, count, toplevel
146 specialKeys, keyStr, unmodifiedKey, likelyConflict
147 rawKey: event.key, rawCode: event.code
148 discard: @reset.bind(this, mode)
151 getGroupedCommands: (options = {}) ->
153 for modeName, mode of @modes
154 if options.enabledOnly
155 usedSequences = getUsedSequences(@keyTrees[modeName])
156 for commandName, command of mode.commands
157 enabledSequences = null
158 if options.enabledOnly
159 enabledSequences = utils.removeDuplicates(
160 command._sequences.filter((sequence) ->
161 return (usedSequences[sequence] == command.pref)
164 continue if enabledSequences.length == 0
165 categories = modes[modeName] ?= {}
166 category = categories[command.category] ?= []
168 {command, enabledSequences, order: command.order, name: commandName}
172 for modeName, categories of modes
173 categoriesSorted = []
174 for categoryName, commands of categories
175 category = @options.categories[categoryName]
176 categoriesSorted.push({
179 order: category.order
180 commands: commands.sort(byOrder)
182 mode = @modes[modeName]
187 categories: categoriesSorted.sort(byOrder)
189 return modesSorted.sort(byOrder)
191 byOrder = (a, b) -> a.order - b.order
194 constructor: (@command, @originalSequence, @specialKeys) ->
196 createKeyTrees = (groupedCommands, specialKeysSpec, modifierKeys) ->
200 pushError = (error, command) ->
201 (errors[command.pref] ?= []).push(error)
203 pushOverrideErrors = (command, originalSequence, tree) ->
204 {command: overridingCommand} = getFirstLeaf(tree)
207 subject: overridingCommand.description
208 context: originalSequence
210 pushError(error, command)
212 pushKeyError = (command, id, originalSequence, key) ->
213 pushError({id, subject: key, context: originalSequence}, command)
215 for mode in groupedCommands
216 keyTrees[mode._name] = {}
217 for category in mode.categories then for {command} in category.commands
218 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
219 pushError(error, command) for error in parseErrors
220 command._sequences = []
222 for shortcut in shortcuts
223 [prefixKeys..., lastKey] = shortcut.normalized
224 tree = keyTrees[mode._name]
225 command._sequences.push(shortcut.original)
226 seenNonSpecialKey = false
230 for prefixKey, index in prefixKeys
231 if prefixKey of modifierKeys
233 command, 'mistake_modifier', shortcut.original, prefixKey
237 if prefixKey of specialKeysSpec
240 command, 'special_key.prefix_only', shortcut.original, prefixKey
245 specialKeys[prefixKey] = true
247 unless seenNonSpecialKey
248 for specialKey of specialKeys
249 options = specialKeysSpec[specialKey]
252 command, 'special_key.single_only', shortcut.original,
258 seenNonSpecialKey = true
261 next = tree[prefixKey]
262 if next instanceof Leaf
263 pushOverrideErrors(command, shortcut.original, next)
269 tree = tree[prefixKey] = {}
273 if lastKey of modifierKeys
274 pushKeyError(command, 'lone_modifier', shortcut.original, lastKey)
277 if lastKey of specialKeysSpec
278 subject = if seenNonSpecialKey then lastKey else shortcut.original
280 command, 'special_key.prefix_only', shortcut.original, subject
284 pushOverrideErrors(command, shortcut.original, tree[lastKey])
286 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
288 return {keyTrees, errors}
290 parseShortcutPref = (pref) ->
294 prefValue = prefs.root.get(pref).trim()
296 unless prefValue == ''
297 for sequence in prefValue.split(/\s+/)
300 for key in notation.parseSequence(sequence)
302 shortcut.push(notation.normalize(key))
304 throw error unless error.id?
308 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
310 return {shortcuts, errors}
312 getFirstLeaf = (node) ->
313 if node instanceof Leaf
315 for key, value of node
316 return getFirstLeaf(value)
318 getLeaves = (node) ->
319 if node instanceof Leaf
322 for key, value of node
323 leaves.push(getLeaves(value)...)
326 getUsedSequences = (tree) ->
328 for leaf in getLeaves(tree)
329 usedSequences[leaf.originalSequence] = leaf.command.pref
332 module.exports = VimFx