2 # Copyright Simon Lydell 2015.
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) ->
38 @on('modechange', ({mode}) => @reset(mode))
40 SPECIAL_KEYS: ['<force>', '<late>']
43 @vims.set(browser, new Vim(browser, this))
45 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
47 reset: (mode = null) ->
48 @currentKeyTree = if mode then @keyTrees[mode] else {}
55 @commandsWithSpecialKeys
57 } = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
59 stringifyKeyEvent: (event) ->
60 return notation.stringify(event, {
61 ignoreKeyboardLayout: @options.ignore_keyboard_layout
62 translations: @options.translations
65 consumeKeyEvent: (event, vim, focusType) ->
67 return unless keyStr = @stringifyKeyEvent(event)
70 @reset(mode) if now - @lastInputTime >= @options.timeout
73 toplevel = (@currentKeyTree == @keyTrees[mode])
75 if toplevel and @options.keyValidator
76 unless @options.keyValidator(keyStr, mode)
84 when toplevel and DIGIT.test(keyStr) and
85 not (keyStr == '0' and @count == '')
89 when keyStr of @currentKeyTree
90 next = @currentKeyTree[keyStr]
91 if next instanceof Leaf
93 command = next.command
95 @currentKeyTree = next
101 count = if @count == '' then undefined else Number(@count)
102 specialKeys = @commandsWithSpecialKeys[command?.pref] ? {}
103 focus = @adjustFocusType(event, vim, focusType, keyStr)
104 unmodifiedKey = notation.parse(keyStr).key
105 @reset(mode) if type == 'full'
107 type, focus, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
110 adjustFocusType: (event, vim, focusType, keyStr) ->
111 # Frame scripts and the tests don’t pass in `originalTarget`.
112 document = event.originalTarget?.ownerDocument
113 if focusType == null and document and
114 (vim.window.TabView.isVisible() or
115 document.fullscreenElement or document.mozFullScreenElement)
118 keys = @options["#{ focusType }_element_keys"]
119 return null if keys and keyStr not in keys
123 getGroupedCommands: (options = {}) ->
125 for modeName, mode of @modes
126 if options.enabledOnly
127 usedSequences = getUsedSequences(@keyTrees[modeName])
128 for commandName, command of mode.commands
129 enabledSequences = null
130 if options.enabledOnly
131 enabledSequences = utils.removeDuplicates(
132 command._sequences.filter((sequence) ->
133 return (usedSequences[sequence] == command.pref)
136 continue if enabledSequences.length == 0
137 categories = modes[modeName] ?= {}
138 category = categories[command.category] ?= []
139 category.push({command, enabledSequences, order: command.order})
142 for modeName, categories of modes
143 categoriesSorted = []
144 for categoryName, commands of categories
145 category = @options.categories[categoryName]
146 categoriesSorted.push({
147 name: category.name()
149 order: category.order
150 commands: commands.sort(byOrder)
152 mode = @modes[modeName]
157 categories: categoriesSorted.sort(byOrder)
159 return modesSorted.sort(byOrder)
161 byOrder = (a, b) -> a.order - b.order
164 constructor: (@command, @originalSequence) ->
166 createKeyTrees = (groupedCommands, specialKeys) ->
169 commandsWithSpecialKeys = {}
171 pushError = (error, command) ->
172 (errors[command.pref] ?= []).push(error)
174 pushOverrideErrors = (command, tree) ->
175 { command: overridingCommand, originalSequence } = getFirstLeaf(tree)
178 subject: overridingCommand.description()
179 context: originalSequence
180 pushError(error, command)
182 pushSpecialKeyError = (command, originalSequence, key) ->
184 id: 'illegal_special_key'
186 context: originalSequence
187 pushError(error, command)
189 for mode in groupedCommands
190 keyTrees[mode._name] = {}
191 for category in mode.categories then for { command } in category.commands
192 { shortcuts, errors: parseErrors } = parseShortcutPref(command.pref)
193 pushError(error, command) for error in parseErrors
194 command._sequences = []
196 for shortcut in shortcuts
197 [ prefixKeys..., lastKey ] = shortcut.normalized
198 tree = keyTrees[mode._name]
199 command._sequences.push(shortcut.original)
200 seenNonSpecialKey = false
203 for prefixKey, index in prefixKeys
204 if prefixKey in specialKeys
206 pushSpecialKeyError(command, shortcut.original, prefixKey)
210 (commandsWithSpecialKeys[command.pref] ?= {})[prefixKey] = true
213 seenNonSpecialKey = true
216 next = tree[prefixKey]
217 if next instanceof Leaf
218 pushOverrideErrors(command, next)
224 tree = tree[prefixKey] = {}
227 if lastKey in specialKeys
228 subject = if seenNonSpecialKey then lastKey else shortcut.original
229 pushSpecialKeyError(command, shortcut.original, subject)
232 pushOverrideErrors(command, tree[lastKey])
234 tree[lastKey] = new Leaf(command, shortcut.original)
236 return {keyTrees, commandsWithSpecialKeys, errors}
238 parseShortcutPref = (pref) ->
242 # The shorcut prefs are read from root in order to support other extensions to
243 # extend VimFx with custom commands.
244 prefValue = prefs.root.get(pref).trim()
246 unless prefValue == ''
247 for sequence in prefValue.split(/\s+/)
250 for key in notation.parseSequence(sequence)
252 shortcut.push(notation.normalize(key))
254 throw error unless error.id?
258 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
260 return {shortcuts, errors}
262 getFirstLeaf = (node) ->
263 if node instanceof Leaf
265 for key, value of node
266 return getFirstLeaf(value)
268 getLeaves = (node) ->
269 if node instanceof Leaf
272 for key, value of node
273 leaves.push(getLeaves(value)...)
276 getUsedSequences = (tree) ->
278 for leaf in getLeaves(tree)
279 usedSequences[leaf.originalSequence] = leaf.command.pref
282 module.exports = VimFx