forked from adobe/brackets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeyBindingManager.js
More file actions
1472 lines (1302 loc) · 55.6 KB
/
KeyBindingManager.js
File metadata and controls
1472 lines (1302 loc) · 55.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint regexp: true */
/*unittests: KeyBindingManager */
/**
* Manages the mapping of keyboard inputs to commands.
*/
define(function (require, exports, module) {
"use strict";
require("utils/Global");
var AppInit = require("utils/AppInit"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
DefaultDialogs = require("widgets/DefaultDialogs"),
EventDispatcher = require("utils/EventDispatcher"),
FileSystem = require("filesystem/FileSystem"),
FileSystemError = require("filesystem/FileSystemError"),
FileUtils = require("file/FileUtils"),
KeyEvent = require("utils/KeyEvent"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
UrlParams = require("utils/UrlParams").UrlParams,
_ = require("thirdparty/lodash");
var KeyboardPrefs = JSON.parse(require("text!base-config/keyboard.json"));
var KEYMAP_FILENAME = "keymap.json",
_userKeyMapFilePath = brackets.app.getApplicationSupportDirectory() + "/" + KEYMAP_FILENAME;
/**
* @private
* Maps normalized shortcut descriptor to key binding info.
* @type {!Object.<string, {commandID: string, key: string, displayKey: string}>}
*/
var _keyMap = {}, // For the actual key bindings including user specified ones
// For the default factory key bindings, cloned from _keyMap after all extensions are loaded.
_defaultKeyMap = {};
/**
* @typedef {{shortcut: !string,
* commandID: ?string}} UserKeyBinding
*/
/**
* @private
* Maps shortcut descriptor to a command id.
* @type {UserKeyBinding}
*/
var _customKeyMap = {},
_customKeyMapCache = {};
/**
* @private
* Maps commandID to the list of shortcuts that are bound to it.
* @type {!Object.<string, Array.<{key: string, displayKey: string}>>}
*/
var _commandMap = {};
/**
* @private
* An array of command ID for all the available commands including the commands
* of installed extensions.
* @type {Array.<string>}
*/
var _allCommands = [];
/**
* @private
* Maps key names to the corresponding unicode symols
* @type {{key: string, displayKey: string}}
*/
var _displayKeyMap = { "up": "\u2191",
"down": "\u2193",
"left": "\u2190",
"right": "\u2192",
"-": "\u2212" };
var _specialCommands = [Commands.EDIT_UNDO, Commands.EDIT_REDO, Commands.EDIT_SELECT_ALL,
Commands.EDIT_CUT, Commands.EDIT_COPY, Commands.EDIT_PASTE],
_reservedShortcuts = ["Ctrl-Z", "Ctrl-Y", "Ctrl-A", "Ctrl-X", "Ctrl-C", "Ctrl-V"],
_macReservedShortcuts = ["Cmd-,", "Cmd-H", "Cmd-Alt-H", "Cmd-M", "Cmd-Shift-Z", "Cmd-Q"],
_keyNames = ["Up", "Down", "Left", "Right", "Backspace", "Enter", "Space", "Tab",
"PageUp", "PageDown", "Home", "End", "Insert", "Delete"];
/**
* @private
* Flag to show key binding errors in the key map file. Default is true and
* it will be set to false when reloading without extensions. This flag is not
* used to suppress errors in loading or parsing the key map file. So if the key
* map file is corrupt, then the error dialog still shows up.
*
* @type {boolean}
*/
var _showErrors = true;
/**
* @private
* Allow clients to toggle key binding
* @type {boolean}
*/
var _enabled = true;
/**
* @private
* Stack of registered global keydown hooks.
* @type {Array.<function(Event): boolean>}
*/
var _globalKeydownHooks = [];
/**
* @private
* Forward declaration for JSLint.
* @type {Function}
*/
var _loadUserKeyMap;
/**
* @private
* States of Ctrl key down detection
* @enum {number}
*/
var CtrlDownStates = {
"NOT_YET_DETECTED" : 0,
"DETECTED" : 1,
"DETECTED_AND_IGNORED": 2 // For consecutive ctrl keydown events while a Ctrl key is being hold down
};
/**
* @private
* Flags used to determine whether right Alt key is pressed. When it is pressed,
* the following two keydown events are triggered in that specific order.
*
* 1. _ctrlDown - flag used to record { ctrlKey: true, keyIdentifier: "Control", ... } keydown event
* 2. _altGrDown - flag used to record { ctrlKey: true, altKey: true, keyIdentifier: "Alt", ... } keydown event
*
* @type {CtrlDownStates|boolean}
*/
var _ctrlDown = CtrlDownStates.NOT_YET_DETECTED,
_altGrDown = false;
/**
* @private
* Used to record the timeStamp property of the last keydown event.
* @type {number}
*/
var _lastTimeStamp;
/**
* @private
* Used to record the keyIdentifier property of the last keydown event.
* @type {string}
*/
var _lastKeyIdentifier;
/*
* @private
* Constant used for checking the interval between Control keydown event and Alt keydown event.
* If the right Alt key is down we get Control keydown followed by Alt keydown within 30 ms. if
* the user is pressing Control key and then Alt key, the interval will be larger than 30 ms.
* @type {number}
*/
var MAX_INTERVAL_FOR_CTRL_ALT_KEYS = 30;
/**
* @private
* Forward declaration for JSLint.
* @type {Function}
*/
var _onCtrlUp;
/**
* @private
* Resets all the flags and removes _onCtrlUp event listener.
*
*/
function _quitAltGrMode() {
_enabled = true;
_ctrlDown = CtrlDownStates.NOT_YET_DETECTED;
_altGrDown = false;
_lastTimeStamp = null;
_lastKeyIdentifier = null;
$(window).off("keyup", _onCtrlUp);
}
/**
* @private
* Detects the release of AltGr key by checking all keyup events
* until we receive one with ctrl key code. Once detected, reset
* all the flags and also remove this event listener.
*
* @param {!KeyboardEvent} e keyboard event object
*/
_onCtrlUp = function (e) {
var key = e.keyCode || e.which;
if (_altGrDown && key === KeyEvent.DOM_VK_CONTROL) {
_quitAltGrMode();
}
};
/**
* @private
* Detects whether AltGr key is pressed. When it is pressed, the first keydown event has
* ctrlKey === true with keyIdentifier === "Control". The next keydown event with
* altKey === true, ctrlKey === true and keyIdentifier === "Alt" is sent within 30 ms. Then
* the next keydown event with altKey === true, ctrlKey === true and keyIdentifier === "Control"
* is sent. If the user keep holding AltGr key down, then the second and third
* keydown events are repeatedly sent out alternately. If the user is also holding down Ctrl
* key, then either keyIdentifier === "Control" or keyIdentifier === "Alt" is repeatedly sent
* but not alternately.
*
* Once we detect the AltGr key down, then disable KeyBindingManager and set up a keyup
* event listener to detect the release of the altGr key so that we can re-enable KeyBindingManager.
* When we detect the addition of Ctrl key besides AltGr key, we also quit AltGr mode and re-enable
* KeyBindingManager.
*
* @param {!KeyboardEvent} e keyboard event object
*/
function _detectAltGrKeyDown(e) {
if (brackets.platform !== "win") {
return;
}
if (!_altGrDown) {
if (_ctrlDown !== CtrlDownStates.DETECTED_AND_IGNORED && e.ctrlKey && e.keyIdentifier === "Control") {
_ctrlDown = CtrlDownStates.DETECTED;
} else if (e.repeat && e.ctrlKey && e.keyIdentifier === "Control") {
// We get here if the user is holding down left/right Control key. Set it to false
// so that we don't misidentify the combination of Ctrl and Alt keys as AltGr key.
_ctrlDown = CtrlDownStates.DETECTED_AND_IGNORED;
} else if (_ctrlDown === CtrlDownStates.DETECTED && e.altKey && e.ctrlKey && e.keyIdentifier === "Alt" &&
(e.timeStamp - _lastTimeStamp) < MAX_INTERVAL_FOR_CTRL_ALT_KEYS) {
_altGrDown = true;
_lastKeyIdentifier = "Alt";
_enabled = false;
$(window).on("keyup", _onCtrlUp);
} else {
// Reset _ctrlDown so that we can start over in detecting the two key events
// required for AltGr key.
_ctrlDown = CtrlDownStates.NOT_YET_DETECTED;
}
_lastTimeStamp = e.timeStamp;
} else if (e.keyIdentifier === "Control" || e.keyIdentifier === "Alt") {
// If the user is NOT holding down AltGr key or is also pressing Ctrl key,
// then _lastKeyIdentifier will be the same as keyIdentifier in the current
// key event. So we need to quit AltGr mode to re-enable KBM.
if (e.altKey && e.ctrlKey && e.keyIdentifier === _lastKeyIdentifier) {
_quitAltGrMode();
} else {
_lastKeyIdentifier = e.keyIdentifier;
}
}
}
/**
* @private
*/
function _reset() {
_keyMap = {};
_defaultKeyMap = {};
_customKeyMap = {};
_customKeyMapCache = {};
_commandMap = {};
_globalKeydownHooks = [];
_userKeyMapFilePath = brackets.app.getApplicationSupportDirectory() + "/" + KEYMAP_FILENAME;
}
/**
* @private
* Initialize an empty keymap as the current keymap. It overwrites the current keymap if there is one.
* builds the keyDescriptor string from the given parts
* @param {boolean} hasCtrl Is Ctrl key enabled
* @param {boolean} hasAlt Is Alt key enabled
* @param {boolean} hasShift Is Shift key enabled
* @param {string} key The key that's pressed
* @return {string} The normalized key descriptor
*/
function _buildKeyDescriptor(hasMacCtrl, hasCtrl, hasAlt, hasShift, key) {
if (!key) {
console.log("KeyBindingManager _buildKeyDescriptor() - No key provided!");
return "";
}
var keyDescriptor = [];
if (hasMacCtrl) {
keyDescriptor.push("Ctrl");
}
if (hasAlt) {
keyDescriptor.push("Alt");
}
if (hasShift) {
keyDescriptor.push("Shift");
}
if (hasCtrl) {
// Windows display Ctrl first, Mac displays Command symbol last
if (brackets.platform === "mac") {
keyDescriptor.push("Cmd");
} else {
keyDescriptor.unshift("Ctrl");
}
}
keyDescriptor.push(key);
return keyDescriptor.join("-");
}
/**
* normalizes the incoming key descriptor so the modifier keys are always specified in the correct order
* @param {string} The string for a key descriptor, can be in any order, the result will be Ctrl-Alt-Shift-<Key>
* @return {string} The normalized key descriptor or null if the descriptor invalid
*/
function normalizeKeyDescriptorString(origDescriptor) {
var hasMacCtrl = false,
hasCtrl = false,
hasAlt = false,
hasShift = false,
key = "",
error = false;
function _compareModifierString(left, right) {
if (!left || !right) {
return false;
}
left = left.trim().toLowerCase();
right = right.trim().toLowerCase();
return (left.length > 0 && left === right);
}
origDescriptor.split("-").forEach(function parseDescriptor(ele, i, arr) {
if (_compareModifierString("ctrl", ele)) {
if (brackets.platform === "mac") {
hasMacCtrl = true;
} else {
hasCtrl = true;
}
} else if (_compareModifierString("cmd", ele)) {
if (brackets.platform === "mac") {
hasCtrl = true;
} else {
error = true;
}
} else if (_compareModifierString("alt", ele)) {
hasAlt = true;
} else if (_compareModifierString("opt", ele)) {
if (brackets.platform === "mac") {
hasAlt = true;
} else {
error = true;
}
} else if (_compareModifierString("shift", ele)) {
hasShift = true;
} else if (key.length > 0) {
console.log("KeyBindingManager normalizeKeyDescriptorString() - Multiple keys defined. Using key: " + key + " from: " + origDescriptor);
error = true;
} else {
key = ele;
}
});
if (error) {
return null;
}
// Check to see if the binding is for "-".
if (key === "" && origDescriptor.search(/^.+--$/) !== -1) {
key = "-";
}
// '+' char is valid if it's the only key. Keyboard shortcut strings should use
// unicode characters (unescaped). Keyboard shortcut display strings may use
// unicode escape sequences (e.g. \u20AC euro sign)
if ((key.indexOf("+")) >= 0 && (key.length > 1)) {
return null;
}
// Ensure that the first letter of the key name is in upper case and the rest are
// in lower case. i.e. 'a' => 'A' and 'up' => 'Up'
if (/^[a-z]/i.test(key)) {
key = _.capitalize(key.toLowerCase());
}
// Also make sure that the second word of PageUp/PageDown has the first letter in upper case.
if (/^Page/.test(key)) {
key = key.replace(/(up|down)$/, function (match, p1) {
return _.capitalize(p1);
});
}
// No restriction on single character key yet, but other key names are restricted to either
// Function keys or those listed in _keyNames array.
if (key.length > 1 && !/F\d+/.test(key) &&
_keyNames.indexOf(key) === -1) {
return null;
}
return _buildKeyDescriptor(hasMacCtrl, hasCtrl, hasAlt, hasShift, key);
}
/**
* @private
* Looks for keycodes that have os-inconsistent keys and fixes them.
* @param {number} The keycode from the keyboard event.
* @param {string} The current best guess at what the key is.
* @return {string} If the key is OS-inconsistent, the correct key; otherwise, the original key.
**/
function _mapKeycodeToKey(keycode, key) {
// If keycode represents one of the digit keys (0-9), then return the corresponding digit
// by subtracting KeyEvent.DOM_VK_0 from keycode. ie. [48-57] --> [0-9]
if (keycode >= KeyEvent.DOM_VK_0 && keycode <= KeyEvent.DOM_VK_9) {
return String(keycode - KeyEvent.DOM_VK_0);
// Do the same with the numpad numbers
// by subtracting KeyEvent.DOM_VK_NUMPAD0 from keycode. ie. [96-105] --> [0-9]
} else if (keycode >= KeyEvent.DOM_VK_NUMPAD0 && keycode <= KeyEvent.DOM_VK_NUMPAD9) {
return String(keycode - KeyEvent.DOM_VK_NUMPAD0);
}
switch (keycode) {
case KeyEvent.DOM_VK_SEMICOLON:
return ";";
case KeyEvent.DOM_VK_EQUALS:
return "=";
case KeyEvent.DOM_VK_COMMA:
return ",";
case KeyEvent.DOM_VK_SUBTRACT:
case KeyEvent.DOM_VK_DASH:
return "-";
case KeyEvent.DOM_VK_ADD:
return "+";
case KeyEvent.DOM_VK_DECIMAL:
case KeyEvent.DOM_VK_PERIOD:
return ".";
case KeyEvent.DOM_VK_DIVIDE:
case KeyEvent.DOM_VK_SLASH:
return "/";
case KeyEvent.DOM_VK_BACK_QUOTE:
return "`";
case KeyEvent.DOM_VK_OPEN_BRACKET:
return "[";
case KeyEvent.DOM_VK_BACK_SLASH:
return "\\";
case KeyEvent.DOM_VK_CLOSE_BRACKET:
return "]";
case KeyEvent.DOM_VK_QUOTE:
return "'";
default:
return key;
}
}
/**
* Takes a keyboard event and translates it into a key in a key map
*/
function _translateKeyboardEvent(event) {
var hasMacCtrl = (brackets.platform === "mac") ? (event.ctrlKey) : false,
hasCtrl = (brackets.platform !== "mac") ? (event.ctrlKey) : (event.metaKey),
hasAlt = (event.altKey),
hasShift = (event.shiftKey),
key = String.fromCharCode(event.keyCode);
//From the W3C, if we can get the KeyboardEvent.keyIdentifier then look here
//As that will let us use keys like then function keys "F5" for commands. The
//full set of values we can use is here
//http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/keyset.html#KeySet-Set
var ident = event.keyIdentifier;
if (ident) {
if (ident.charAt(0) === "U" && ident.charAt(1) === "+") {
//This is a unicode code point like "U+002A", get the 002A and use that
key = String.fromCharCode(parseInt(ident.substring(2), 16));
} else {
//This is some non-character key, just use the raw identifier
key = ident;
}
}
// Translate some keys to their common names
if (key === "\t") {
key = "Tab";
} else if (key === " ") {
key = "Space";
} else if (key === "\b") {
key = "Backspace";
} else if (key === "Help") {
key = "Insert";
} else if (event.keyCode === KeyEvent.DOM_VK_DELETE) {
key = "Delete";
} else {
key = _mapKeycodeToKey(event.keyCode, key);
}
return _buildKeyDescriptor(hasMacCtrl, hasCtrl, hasAlt, hasShift, key);
}
/**
* Convert normalized key representation to display appropriate for platform.
* @param {!string} descriptor Normalized key descriptor.
* @return {!string} Display/Operating system appropriate string
*/
function formatKeyDescriptor(descriptor) {
var displayStr;
if (brackets.platform === "mac") {
displayStr = descriptor.replace(/-(?!$)/g, ""); // remove dashes
displayStr = displayStr.replace("Ctrl", "\u2303"); // Ctrl > control symbol
displayStr = displayStr.replace("Cmd", "\u2318"); // Cmd > command symbol
displayStr = displayStr.replace("Shift", "\u21E7"); // Shift > shift symbol
displayStr = displayStr.replace("Alt", "\u2325"); // Alt > option symbol
} else {
displayStr = descriptor.replace("Ctrl", Strings.KEYBOARD_CTRL);
displayStr = displayStr.replace("Shift", Strings.KEYBOARD_SHIFT);
displayStr = displayStr.replace(/-(?!$)/g, "+");
}
displayStr = displayStr.replace("Space", Strings.KEYBOARD_SPACE);
displayStr = displayStr.replace("PageUp", Strings.KEYBOARD_PAGE_UP);
displayStr = displayStr.replace("PageDown", Strings.KEYBOARD_PAGE_DOWN);
displayStr = displayStr.replace("Home", Strings.KEYBOARD_HOME);
displayStr = displayStr.replace("End", Strings.KEYBOARD_END);
displayStr = displayStr.replace("Ins", Strings.KEYBOARD_INSERT);
displayStr = displayStr.replace("Del", Strings.KEYBOARD_DELETE);
return displayStr;
}
/**
* @private
* @param {string} A normalized key-description string.
* @return {boolean} true if the key is already assigned, false otherwise.
*/
function _isKeyAssigned(key) {
return (_keyMap[key] !== undefined);
}
/**
* Remove a key binding from _keymap
*
* @param {!string} key - a key-description string that may or may not be normalized.
* @param {?string} platform - OS from which to remove the binding (all platforms if unspecified)
*/
function removeBinding(key, platform) {
if (!key || ((platform !== null) && (platform !== undefined) && (platform !== brackets.platform))) {
return;
}
var normalizedKey = normalizeKeyDescriptorString(key);
if (!normalizedKey) {
console.log("Failed to normalize " + key);
} else if (_isKeyAssigned(normalizedKey)) {
var binding = _keyMap[normalizedKey],
command = CommandManager.get(binding.commandID),
bindings = _commandMap[binding.commandID];
// delete key binding record
delete _keyMap[normalizedKey];
if (bindings) {
// delete mapping from command to key binding
_commandMap[binding.commandID] = bindings.filter(function (b) {
return (b.key !== normalizedKey);
});
if (command) {
command.trigger("keyBindingRemoved", {key: normalizedKey, displayKey: binding.displayKey});
}
}
}
}
/**
* @private
*
* Updates _allCommands array and _defaultKeyMap with the new key binding
* if it is not yet in the _allCommands array. _allCommands array is initialized
* only in extensionsLoaded event. So any new commands or key bindings added after
* that will be updated here.
*
* @param {{commandID: string, key: string, displayKey:string, explicitPlatform: string}} newBinding
*/
function _updateCommandAndKeyMaps(newBinding) {
if (_allCommands.length === 0) {
return;
}
if (newBinding && newBinding.commandID && _allCommands.indexOf(newBinding.commandID) === -1) {
_defaultKeyMap[newBinding.commandID] = _.cloneDeep(newBinding);
// Process user key map again to catch any reassignment to all new key bindings added from extensions.
_loadUserKeyMap();
}
}
/**
* @private
*
* @param {string} commandID
* @param {string|{{key: string, displayKey: string}}} keyBinding - a single shortcut.
* @param {?string} platform
* - "all" indicates all platforms, not overridable
* - undefined indicates all platforms, overridden by platform-specific binding
* @param {boolean=} userBindings true if adding a user key binding or undefined otherwise.
* @return {?{key: string, displayKey:String}} Returns a record for valid key bindings.
* Returns null when key binding platform does not match, binding does not normalize,
* or is already assigned.
*/
function _addBinding(commandID, keyBinding, platform, userBindings) {
var key,
result = null,
normalized,
normalizedDisplay,
explicitPlatform = keyBinding.platform || platform,
targetPlatform,
command,
bindingsToDelete = [],
existing;
// For platform: "all", use explicit current platform
if (explicitPlatform && explicitPlatform !== "all") {
targetPlatform = explicitPlatform;
} else {
targetPlatform = brackets.platform;
}
// Skip if the key binding is not for this platform.
if (explicitPlatform === "mac" && brackets.platform !== "mac") {
return null;
}
// if the request does not specify an explicit platform, and we're
// currently on a mac, then replace Ctrl with Cmd.
key = (keyBinding.key) || keyBinding;
if (brackets.platform === "mac" && (explicitPlatform === undefined || explicitPlatform === "all")) {
key = key.replace("Ctrl", "Cmd");
if (keyBinding.displayKey !== undefined) {
keyBinding.displayKey = keyBinding.displayKey.replace("Ctrl", "Cmd");
}
}
normalized = normalizeKeyDescriptorString(key);
// skip if the key binding is invalid
if (!normalized) {
console.error("Unable to parse key binding " + key + ". Permitted modifiers: Ctrl, Cmd, Alt, Opt, Shift; separated by '-' (not '+').");
return null;
}
// check for duplicate key bindings
existing = _keyMap[normalized];
// for cross-platform compatibility
if (exports.useWindowsCompatibleBindings) {
// windows-only key bindings are used as the default binding
// only if a default binding wasn't already defined
if (explicitPlatform === "win") {
// search for a generic or platform-specific binding if it
// already exists
if (existing && (!existing.explicitPlatform ||
existing.explicitPlatform === brackets.platform ||
existing.explicitPlatform === "all")) {
// do not clobber existing binding with windows-only binding
return null;
}
// target this windows binding for the current platform
targetPlatform = brackets.platform;
}
}
// skip if this binding doesn't match the current platform
if (targetPlatform !== brackets.platform) {
return null;
}
// skip if the key is already assigned
if (existing) {
if (!existing.explicitPlatform && explicitPlatform) {
// remove the the generic binding to replace with this new platform-specific binding
removeBinding(normalized);
existing = false;
}
}
// delete existing bindings when
// (1) replacing a windows-compatible binding with a generic or
// platform-specific binding
// (2) replacing a generic binding with a platform-specific binding
var existingBindings = _commandMap[commandID] || [],
isWindowsCompatible,
isReplaceGeneric,
ignoreGeneric;
existingBindings.forEach(function (binding) {
// remove windows-only bindings in _commandMap
isWindowsCompatible = exports.useWindowsCompatibleBindings &&
binding.explicitPlatform === "win";
// remove existing generic binding
isReplaceGeneric = !binding.explicitPlatform &&
explicitPlatform;
if (isWindowsCompatible || isReplaceGeneric) {
bindingsToDelete.push(binding);
} else {
// existing binding is platform-specific and the requested binding is generic
ignoreGeneric = binding.explicitPlatform && !explicitPlatform;
}
});
if (ignoreGeneric) {
// explicit command binding overrides this one
return null;
}
if (existing) {
// do not re-assign a key binding
console.error("Cannot assign " + normalized + " to " + commandID + ". It is already assigned to " + _keyMap[normalized].commandID);
return null;
}
// remove generic or windows-compatible bindings
bindingsToDelete.forEach(function (binding) {
removeBinding(binding.key);
});
// optional display-friendly string (e.g. CMD-+ instead of CMD-=)
normalizedDisplay = (keyBinding.displayKey) ? normalizeKeyDescriptorString(keyBinding.displayKey) : normalized;
// 1-to-many commandID mapping to key binding
if (!_commandMap[commandID]) {
_commandMap[commandID] = [];
}
result = {
key : normalized,
displayKey : normalizedDisplay,
explicitPlatform : explicitPlatform
};
_commandMap[commandID].push(result);
// 1-to-1 key binding to commandID
_keyMap[normalized] = {
commandID : commandID,
key : normalized,
displayKey : normalizedDisplay,
explicitPlatform : explicitPlatform
};
if (!userBindings) {
_updateCommandAndKeyMaps(_keyMap[normalized]);
}
// notify listeners
command = CommandManager.get(commandID);
if (command) {
command.trigger("keyBindingAdded", result);
}
return result;
}
/**
* Returns a copy of the current key map. If the optional 'defaults' parameter is true,
* then a copy of the default key map is returned.
* @param {boolean=} defaults true if the caller wants a copy of the default key map.
* Otherwise, the current active key map is returned.
* @return {!Object.<string, {commandID: string, key: string, displayKey: string}>}
*/
function getKeymap(defaults) {
return $.extend({}, defaults ? _defaultKeyMap : _keyMap);
}
/**
* Process the keybinding for the current key.
*
* @param {string} A key-description string.
* @return {boolean} true if the key was processed, false otherwise
*/
function _handleKey(key) {
if (_enabled && _keyMap[key]) {
// The execute() function returns a promise because some commands are async.
// Generally, commands decide whether they can run or not synchronously,
// and reject immediately, so we can test for that synchronously.
var promise = CommandManager.execute(_keyMap[key].commandID);
return (promise.state() !== "rejected");
}
return false;
}
/**
* @private
*
* Sort objects by platform property. Objects with a platform property come
* before objects without a platform property.
*/
function _sortByPlatform(a, b) {
var a1 = (a.platform) ? 1 : 0,
b1 = (b.platform) ? 1 : 0;
return b1 - a1;
}
/**
* Add one or more key bindings to a particular Command.
*
* @param {!string | Command} command - A command ID or command object
* @param {?({key: string, displayKey: string}|Array.<{key: string, displayKey: string, platform: string}>)} keyBindings
* A single key binding or an array of keybindings. Example:
* "Shift-Cmd-F". Mac and Win key equivalents are automatically
* mapped to each other. Use displayKey property to display a different
* string (e.g. "CMD+" instead of "CMD=").
* @param {?string} platform The target OS of the keyBindings either
* "mac", "win" or "linux". If undefined, all platforms not explicitly
* defined will use the key binding.
* NOTE: If platform is not specified, Ctrl will be replaced by Cmd for "mac" platform
* @return {{key: string, displayKey:String}|Array.<{key: string, displayKey:String}>}
* Returns record(s) for valid key binding(s)
*/
function addBinding(command, keyBindings, platform) {
var commandID = "",
results;
if (!command) {
console.error("addBinding(): missing required parameter: command");
return;
}
if (!keyBindings) { return; }
if (typeof (command) === "string") {
commandID = command;
} else {
commandID = command.getID();
}
if (Array.isArray(keyBindings)) {
var keyBinding;
results = [];
// process platform-specific bindings first
keyBindings.sort(_sortByPlatform);
keyBindings.forEach(function addSingleBinding(keyBindingRequest) {
// attempt to add keybinding
keyBinding = _addBinding(commandID, keyBindingRequest, keyBindingRequest.platform);
if (keyBinding) {
results.push(keyBinding);
}
});
} else {
results = _addBinding(commandID, keyBindings, platform);
}
return results;
}
/**
* Retrieve key bindings currently associated with a command
*
* @param {!string | Command} command - A command ID or command object
* @return {!Array.<{{key: string, displayKey: string}}>} An array of associated key bindings.
*/
function getKeyBindings(command) {
var bindings = [],
commandID = "";
if (!command) {
console.error("getKeyBindings(): missing required parameter: command");
return [];
}
if (typeof (command) === "string") {
commandID = command;
} else {
commandID = command.getID();
}
bindings = _commandMap[commandID];
return bindings || [];
}
/**
* Adds default key bindings when commands are registered to CommandManager
* @param {$.Event} event jQuery event
* @param {Command} command Newly registered command
*/
function _handleCommandRegistered(event, command) {
var commandId = command.getID(),
defaults = KeyboardPrefs[commandId];
if (defaults) {
addBinding(commandId, defaults);
}
}
/**
* Adds a global keydown hook that gets first crack at keydown events
* before standard keybindings do. This is intended for use by modal or
* semi-modal UI elements like dialogs or the code hint list that should
* execute before normal command bindings are run.
*
* The hook is passed one parameter, the original keyboard event. If the
* hook handles the event (or wants to block other global hooks from
* handling the event), it should return true. Note that this will *only*
* stop other global hooks and KeyBindingManager from handling the
* event; to prevent further event propagation, you will need to call
* stopPropagation(), stopImmediatePropagation(), and/or preventDefault()
* as usual.
*
* Multiple keydown hooks can be registered, and are executed in order,
* most-recently-added first.
*
* (We have to have a special API for this because (1) handlers are normally
* called in least-recently-added order, and we want most-recently-added;
* (2) native DOM events don't have a way for us to find out if
* stopImmediatePropagation()/stopPropagation() has been called on the
* event, so we have to have some other way for one of the hooks to
* indicate that it wants to block the other hooks from running.)
*
* @param {function(Event): boolean} hook The global hook to add.
*/
function addGlobalKeydownHook(hook) {
_globalKeydownHooks.push(hook);
}
/**
* Removes a global keydown hook added by `addGlobalKeydownHook`.
* Does not need to be the most recently added hook.
*
* @param {function(Event): boolean} hook The global hook to remove.
*/
function removeGlobalKeydownHook(hook) {
var index = _globalKeydownHooks.indexOf(hook);
if (index !== -1) {
_globalKeydownHooks.splice(index, 1);
}
}
/**
* Handles a given keydown event, checking global hooks first before
* deciding to handle it ourselves.
* @param {Event} The keydown event to handle.
*/
function _handleKeyEvent(event) {
var i, handled = false;
for (i = _globalKeydownHooks.length - 1; i >= 0; i--) {
if (_globalKeydownHooks[i](event)) {
handled = true;
break;
}
}
_detectAltGrKeyDown(event);
if (!handled && _handleKey(_translateKeyboardEvent(event))) {
event.stopPropagation();
event.preventDefault();
}
}
AppInit.htmlReady(function () {
// Install keydown event listener.
window.document.body.addEventListener(
"keydown",
_handleKeyEvent,
true
);
exports.useWindowsCompatibleBindings = (brackets.platform !== "mac") &&
(brackets.platform !== "win");