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
192 pushError(error, command)
194 pushSpecialKeyError = (command, originalSequence, key) ->
196 id: 'illegal_special_key'
198 context: originalSequence
200 pushError(error, command)
202 for mode in groupedCommands
203 keyTrees[mode._name] = {}
204 for category in mode.categories then for {command} in category.commands
205 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
206 pushError(error, command) for error in parseErrors
207 command._sequences = []
209 for shortcut in shortcuts
210 [prefixKeys..., lastKey] = shortcut.normalized
211 tree = keyTrees[mode._name]
212 command._sequences.push(shortcut.original)
213 seenNonSpecialKey = false
217 for prefixKey, index in prefixKeys
218 if prefixKey in specialKeyStrings
220 pushSpecialKeyError(command, shortcut.original, prefixKey)
224 specialKeys[prefixKey] = true
227 seenNonSpecialKey = true
230 next = tree[prefixKey]
231 if next instanceof Leaf
232 pushOverrideErrors(command, shortcut.original, next)
238 tree = tree[prefixKey] = {}
241 if lastKey in specialKeyStrings
242 subject = if seenNonSpecialKey then lastKey else shortcut.original
243 pushSpecialKeyError(command, shortcut.original, subject)
246 pushOverrideErrors(command, shortcut.original, tree[lastKey])
248 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
250 return {keyTrees, errors}
252 parseShortcutPref = (pref) ->
256 # The shorcut prefs are read from root in order to support other extensions to
257 # extend VimFx with custom commands.
258 prefValue = prefs.root.get(pref).trim()
260 unless prefValue == ''
261 for sequence in prefValue.split(/\s+/)
264 for key in notation.parseSequence(sequence)
266 shortcut.push(notation.normalize(key))
268 throw error unless error.id?
272 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
274 return {shortcuts, errors}
276 getFirstLeaf = (node) ->
277 if node instanceof Leaf
279 for key, value of node
280 return getFirstLeaf(value)
282 getLeaves = (node) ->
283 if node instanceof Leaf
286 for key, value of node
287 leaves.push(getLeaves(value)...)
290 getUsedSequences = (tree) ->
292 for leaf in getLeaves(tree)
293 usedSequences[leaf.originalSequence] = leaf.command.pref
296 module.exports = VimFx