]> git.gir.st - VimFx.git/blob - extension/lib/vimfx.coffee
Merge branch 'master' into develop
[VimFx.git] / extension / lib / vimfx.coffee
1 ###
2 # Copyright Simon Lydell 2015.
3 #
4 # This file is part of VimFx.
5 #
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.
10 #
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.
15 #
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/>.
18 ###
19
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.
24
25 notation = require('vim-like-key-notation')
26 prefs = require('./prefs')
27 utils = require('./utils')
28 Vim = require('./vim')
29
30 DIGIT = /^\d$/
31
32 class VimFx extends utils.EventEmitter
33 constructor: (@modes, @options) ->
34 super()
35 @vims = new WeakMap()
36 @lastClosedVim = null
37 @createKeyTrees()
38 @reset()
39 @on('modeChange', ({mode}) => @reset(mode))
40
41 SPECIAL_KEYS: ['<force>', '<late>']
42
43 addVim: (browser) ->
44 @vims.set(browser, new Vim(browser, this))
45
46 # NOTE: This method is often called in event handlers. Many events may fire
47 # before a `vim` object has been created for the current tab yet (such as when
48 # the browser is starting up). Therefore always check if anything was
49 # returned, such as:
50 #
51 # return unless vim = @vimfx.getCurrentVim(@window)
52 getCurrentVim: (window) -> @vims.get(window.gBrowser.selectedBrowser)
53
54 reset: (mode = null) ->
55 # Modes without commands are returned by neither `.getGroupedCommands()` nor
56 # `createKeyTrees`. Fall back to an empty tree.
57 @currentKeyTree = @keyTrees[mode] ? {}
58 @lastInputTime = 0
59 @count = ''
60
61 createKeyTrees: ->
62 {@keyTrees, @errors} = createKeyTrees(@getGroupedCommands(), @SPECIAL_KEYS)
63
64 stringifyKeyEvent: (event) ->
65 return notation.stringify(event, {
66 ignoreKeyboardLayout: @options.ignore_keyboard_layout
67 translations: @options.translations
68 })
69
70 consumeKeyEvent: (event, vim, focusType) ->
71 {mode} = vim
72 return unless keyStr = @stringifyKeyEvent(event)
73
74 now = Date.now()
75 @reset(mode) if now - @lastInputTime >= @options.timeout
76 @lastInputTime = now
77
78 toplevel = (@currentKeyTree == @keyTrees[mode])
79
80 if toplevel and @options.keyValidator
81 unless @options.keyValidator(keyStr, mode)
82 @reset(mode)
83 return
84
85 type = 'none'
86 command = null
87 specialKeys = {}
88
89 switch
90 when keyStr of @currentKeyTree and
91 not (toplevel and keyStr == '0' and @count != '')
92 next = @currentKeyTree[keyStr]
93 if next instanceof Leaf
94 type = 'full'
95 {command, specialKeys} = next
96 else
97 @currentKeyTree = next
98 type = 'partial'
99
100 when toplevel and DIGIT.test(keyStr) and
101 not (keyStr == '0' and @count == '')
102 @count += keyStr
103 type = 'count'
104
105 else
106 @reset(mode)
107
108 count = if @count == '' then undefined else Number(@count)
109 focus = @adjustFocusType(event, vim, focusType, keyStr)
110 unmodifiedKey = notation.parse(keyStr).key
111 @reset(mode) if type == 'full'
112 return {
113 type, focus, command, count, specialKeys, keyStr, unmodifiedKey, toplevel
114 }
115
116 adjustFocusType: (event, vim, focusType, keyStr) ->
117 # Frame scripts and the tests don’t pass in `originalTarget`.
118 document = event.originalTarget?.ownerDocument
119 if focusType == null and document and
120 # TODO: Remove when Tab Groups have been removed.
121 (vim.window.TabView?.isVisible() or
122 document.fullscreenElement or document.mozFullScreenElement)
123 return 'other'
124
125 keys = @options["#{focusType}_element_keys"]
126 return null if keys and keyStr not in keys
127
128 return focusType
129
130 getGroupedCommands: (options = {}) ->
131 modes = {}
132 for modeName, mode of @modes
133 if options.enabledOnly
134 usedSequences = getUsedSequences(@keyTrees[modeName])
135 for commandName, command of mode.commands
136 enabledSequences = null
137 if options.enabledOnly
138 enabledSequences = utils.removeDuplicates(
139 command._sequences.filter((sequence) ->
140 return (usedSequences[sequence] == command.pref)
141 )
142 )
143 continue if enabledSequences.length == 0
144 categories = modes[modeName] ?= {}
145 category = categories[command.category] ?= []
146 category.push(
147 {command, enabledSequences, order: command.order, name: commandName}
148 )
149
150 modesSorted = []
151 for modeName, categories of modes
152 categoriesSorted = []
153 for categoryName, commands of categories
154 category = @options.categories[categoryName]
155 categoriesSorted.push({
156 name: category.name()
157 _name: categoryName
158 order: category.order
159 commands: commands.sort(byOrder)
160 })
161 mode = @modes[modeName]
162 modesSorted.push({
163 name: mode.name()
164 _name: modeName
165 order: mode.order
166 categories: categoriesSorted.sort(byOrder)
167 })
168 return modesSorted.sort(byOrder)
169
170 byOrder = (a, b) -> a.order - b.order
171
172 class Leaf
173 constructor: (@command, @originalSequence, @specialKeys) ->
174
175 createKeyTrees = (groupedCommands, specialKeyStrings) ->
176 keyTrees = {}
177 errors = {}
178
179 pushError = (error, command) ->
180 (errors[command.pref] ?= []).push(error)
181
182 pushOverrideErrors = (command, tree) ->
183 {command: overridingCommand, originalSequence} = getFirstLeaf(tree)
184 error =
185 id: 'overridden_by'
186 subject: overridingCommand.description()
187 context: originalSequence
188 pushError(error, command)
189
190 pushSpecialKeyError = (command, originalSequence, key) ->
191 error =
192 id: 'illegal_special_key'
193 subject: key
194 context: originalSequence
195 pushError(error, command)
196
197 for mode in groupedCommands
198 keyTrees[mode._name] = {}
199 for category in mode.categories then for {command} in category.commands
200 {shortcuts, errors: parseErrors} = parseShortcutPref(command.pref)
201 pushError(error, command) for error in parseErrors
202 command._sequences = []
203
204 for shortcut in shortcuts
205 [prefixKeys..., lastKey] = shortcut.normalized
206 tree = keyTrees[mode._name]
207 command._sequences.push(shortcut.original)
208 seenNonSpecialKey = false
209 specialKeys = {}
210
211 errored = false
212 for prefixKey, index in prefixKeys
213 if prefixKey in specialKeyStrings
214 if seenNonSpecialKey
215 pushSpecialKeyError(command, shortcut.original, prefixKey)
216 errored = true
217 break
218 else
219 specialKeys[prefixKey] = true
220 continue
221 else
222 seenNonSpecialKey = true
223
224 if prefixKey of tree
225 next = tree[prefixKey]
226 if next instanceof Leaf
227 pushOverrideErrors(command, next)
228 errored = true
229 break
230 else
231 tree = next
232 else
233 tree = tree[prefixKey] = {}
234 continue if errored
235
236 if lastKey in specialKeyStrings
237 subject = if seenNonSpecialKey then lastKey else shortcut.original
238 pushSpecialKeyError(command, shortcut.original, subject)
239 continue
240 if lastKey of tree
241 pushOverrideErrors(command, tree[lastKey])
242 continue
243 tree[lastKey] = new Leaf(command, shortcut.original, specialKeys)
244
245 return {keyTrees, errors}
246
247 parseShortcutPref = (pref) ->
248 shortcuts = []
249 errors = []
250
251 # The shorcut prefs are read from root in order to support other extensions to
252 # extend VimFx with custom commands.
253 prefValue = prefs.root.get(pref).trim()
254
255 unless prefValue == ''
256 for sequence in prefValue.split(/\s+/)
257 shortcut = []
258 errored = false
259 for key in notation.parseSequence(sequence)
260 try
261 shortcut.push(notation.normalize(key))
262 catch error
263 throw error unless error.id?
264 errors.push(error)
265 errored = true
266 break
267 shortcuts.push({normalized: shortcut, original: sequence}) unless errored
268
269 return {shortcuts, errors}
270
271 getFirstLeaf = (node) ->
272 if node instanceof Leaf
273 return node
274 for key, value of node
275 return getFirstLeaf(value)
276
277 getLeaves = (node) ->
278 if node instanceof Leaf
279 return [node]
280 leaves = []
281 for key, value of node
282 leaves.push(getLeaves(value)...)
283 return leaves
284
285 getUsedSequences = (tree) ->
286 usedSequences = {}
287 for leaf in getLeaves(tree)
288 usedSequences[leaf.originalSequence] = leaf.command.pref
289 return usedSequences
290
291 module.exports = VimFx
Imprint / Impressum