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) ->
40 @on('modeChange', ({mode}) => @reset(mode))
42 SPECIAL_KEYS: ['<force>', '<late>']
45 @vims.set(browser, new Vim(browser, this))
47 # NOTE: This method is often called in event handlers. Many events may fire
48 # before a `vim` object has been created for the current tab yet (such as when
49 # the browser is starting up). Therefore always check if anything was
52 # return unless vim = @vimfx.getCurrentVim(@window)
53 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
55 reset: (mode = null) ->
56 # Modes without commands are returned by neither `.getGroupedCommands()` nor
57 # `createKeyTrees`. Fall back to an empty tree.
58 @currentKeyTree = @keyTrees[mode] ? {}
63 {@keyTrees, @errors} = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
65 stringifyKeyEvent: (event) ->
66 return notation.stringify(event, {
67 ignoreCtrlAlt: @options.ignore_ctrl_alt
68 ignoreKeyboardLayout: @options.ignore_keyboard_layout
69 translations: @options.translations
72 consumeKeyEvent: (event, vim, focusType) ->
74 return unless keyStr = @stringifyKeyEvent(event)
77 @reset(mode) if now - @lastInputTime >= @options.timeout
80 toplevel = (@currentKeyTree == @keyTrees[mode])
82 if toplevel and @options.keyValidator
83 unless @options.keyValidator(keyStr, mode)
92 when keyStr of @currentKeyTree and
93 not (toplevel and keyStr == '0' and @count != '')
94 next = @currentKeyTree[keyStr]
95 if next instanceof Leaf
97 {command, specialKeys} = next
99 @currentKeyTree = next
102 when @options.counts_enabled and toplevel and DIGIT.test(keyStr) and
103 not (keyStr == '0' and @count == '')
110 count = if @count == '' then undefined else Number(@count)
111 focus = @adjustFocusType(event, vim, focusType, keyStr)
112 unmodifiedKey = notation.parse(keyStr).key
113 @reset(mode) if type == 'full'
115 type, focus, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
116 discard: @reset.bind(this, mode)
119 adjustFocusType: (event, vim, focusType, keyStr) ->
120 # Frame scripts and the tests don’t pass in `originalTarget`.
121 document = event.originalTarget?.ownerDocument
122 if focusType == null and document and
123 # TODO: Remove when Tab Groups have been removed.
124 (vim.window.TabView?.isVisible() or
125 document.fullscreenElement or document.mozFullScreenElement)
128 keys = @options["#{focusType}_element_keys"]
129 return null if keys and keyStr not in keys
133 getGroupedCommands: (options = {}) ->
135 for modeName, mode of @modes
136 if options.enabledOnly
137 usedSequences = getUsedSequences(@keyTrees[modeName])
138 for commandName, command of mode.commands
139 enabledSequences = null
140 if options.enabledOnly
141 enabledSequences = utils.removeDuplicates(
142 command._sequences.filter((sequence) ->
143 return (usedSequences[sequence] == command.pref)
146 continue if enabledSequences.length == 0
147 categories = modes[modeName] ?= {}
148 category = categories[command.category] ?= []
150 {command, enabledSequences, order: command.order, name: commandName}
154 for modeName, categories of modes
155 categoriesSorted = []
156 for categoryName, commands of categories
157 category = @options.categories[categoryName]
158 categoriesSorted.push({
161 order: category.order
162 commands: commands.sort(byOrder)
164 mode = @modes[modeName]
169 categories: categoriesSorted.sort(byOrder)
171 return modesSorted.sort(byOrder)
173 byOrder = (a, b) -> a.order - b.order
176 constructor: (@command, @originalSequence, @specialKeys) ->
178 createKeyTrees = (groupedCommands, specialKeyStrings) ->
182 pushError = (error, command) ->
183 (errors[command.pref] ?= []).push(error)
185 pushOverrideErrors = (command, originalSequence, tree) ->
186 {command: overridingCommand} = getFirstLeaf(tree)
189 subject: overridingCommand.description
190 context: originalSequence
191 pushError(error, command)
193 pushSpecialKeyError = (command, originalSequence, key) ->
195 id: 'illegal_special_key'
197 context: originalSequence
198 pushError(error, command)
200 for mode in groupedCommands
201 keyTrees[mode._name] = {}
202 for category in mode.categories then for {command} in category.commands
203 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
204 pushError(error, command) for error in parseErrors
205 command._sequences = []
207 for shortcut in shortcuts
208 [prefixKeys..., lastKey] = shortcut.normalized
209 tree = keyTrees[mode._name]
210 command._sequences.push(shortcut.original)
211 seenNonSpecialKey = false
215 for prefixKey, index in prefixKeys
216 if prefixKey in specialKeyStrings
218 pushSpecialKeyError(command, shortcut.original, prefixKey)
222 specialKeys[prefixKey] = true
225 seenNonSpecialKey = true
228 next = tree[prefixKey]
229 if next instanceof Leaf
230 pushOverrideErrors(command, shortcut.original, next)
236 tree = tree[prefixKey] = {}
239 if lastKey in specialKeyStrings
240 subject = if seenNonSpecialKey then lastKey else shortcut.original
241 pushSpecialKeyError(command, shortcut.original, subject)
244 pushOverrideErrors(command, shortcut.original, tree[lastKey])
246 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
248 return {keyTrees, errors}
250 parseShortcutPref = (pref) ->
254 # The shorcut prefs are read from root in order to support other extensions to
255 # extend VimFx with custom commands.
256 prefValue = prefs.root.get(pref).trim()
258 unless prefValue == ''
259 for sequence in prefValue.split(/\s+/)
262 for key in notation.parseSequence(sequence)
264 shortcut.push(notation.normalize(key))
266 throw error unless error.id?
270 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
272 return {shortcuts, errors}
274 getFirstLeaf = (node) ->
275 if node instanceof Leaf
277 for key, value of node
278 return getFirstLeaf(value)
280 getLeaves = (node) ->
281 if node instanceof Leaf
284 for key, value of node
285 leaves.push(getLeaves(value)...)
288 getUsedSequences = (tree) ->
290 for leaf in getLeaves(tree)
291 usedSequences[leaf.originalSequence] = leaf.command.pref
294 module.exports = VimFx