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')
30 {EventEmitter} = utils
34 class VimFx extends EventEmitter
35 constructor: (@modes, @options) ->
40 @skipCreateKeyTrees = false
43 @on('modeChange', ({mode}) => @reset(mode))
45 SPECIAL_KEYS: ['<force>', '<late>']
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()`.
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
61 # return unless vim = @vimfx.getCurrentVim(@window)
62 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
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] ? {}
72 return if @skipCreateKeyTrees
73 {@keyTrees, @errors} = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
75 stringifyKeyEvent: (event) ->
76 return notation.stringify(event, {
77 ignoreCtrlAlt: @options.ignore_ctrl_alt
78 ignoreKeyboardLayout: @options.ignore_keyboard_layout
79 translations: @options.translations
82 consumeKeyEvent: (event, vim, focusType) ->
84 return unless keyStr = @stringifyKeyEvent(event)
87 @reset(mode) if now - @lastInputTime >= @options.timeout
90 toplevel = (@currentKeyTree == @keyTrees[mode])
92 if toplevel and @options.keyValidator
93 unless @options.keyValidator(keyStr, mode)
102 when keyStr of @currentKeyTree and
103 not (toplevel and keyStr == '0' and @count != '')
104 next = @currentKeyTree[keyStr]
105 if next instanceof Leaf
107 {command, specialKeys} = next
109 @currentKeyTree = next
112 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
113 not (keyStr == '0' and @count == '')
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'
125 type, focus, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
126 discard: @reset.bind(this, mode)
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()
137 keys = @options["#{focusType}_element_keys"]
138 return null if keys and keyStr not in keys
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, specialKeyStrings) ->
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, originalSequence, key) ->
205 id: 'illegal_special_key'
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 in specialKeyStrings
229 pushSpecialKeyError(command, shortcut.original, prefixKey)
233 specialKeys[prefixKey] = true
236 seenNonSpecialKey = true
239 next = tree[prefixKey]
240 if next instanceof Leaf
241 pushOverrideErrors(command, shortcut.original, next)
247 tree = tree[prefixKey] = {}
250 if lastKey in specialKeyStrings
251 subject = if seenNonSpecialKey then lastKey else shortcut.original
252 pushSpecialKeyError(command, shortcut.original, subject)
255 pushOverrideErrors(command, shortcut.original, tree[lastKey])
257 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
259 return {keyTrees, errors}
261 parseShortcutPref = (pref) ->
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()
269 unless prefValue == ''
270 for sequence in prefValue.split(/\s+/)
273 for key in notation.parseSequence(sequence)
275 shortcut.push(notation.normalize(key))
277 throw error unless error.id?
281 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
283 return {shortcuts, errors}
285 getFirstLeaf = (node) ->
286 if node instanceof Leaf
288 for key, value of node
289 return getFirstLeaf(value)
291 getLeaves = (node) ->
292 if node instanceof Leaf
295 for key, value of node
296 leaves.push(getLeaves(value)...)
299 getUsedSequences = (tree) ->
301 for leaf in getLeaves(tree)
302 usedSequences[leaf.originalSequence] = leaf.command.pref
305 module.exports = VimFx