-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathKeyBindingManager.js
More file actions
2175 lines (1970 loc) · 84.1 KB
/
KeyBindingManager.js
File metadata and controls
2175 lines (1970 loc) · 84.1 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2012 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// @INCLUDE_IN_API_DOCS
/*globals path, logger*/
/*jslint regexp: true */
/*unittests: KeyBindingManager */
/**
* Manages the mapping of keyboard inputs to commands.
*/
define(function (require, exports, module) {
require("utils/Global");
let 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"),
Keys = require("command/Keys"),
KeyboardOverlayMode = require("command/KeyboardOverlayMode"),
StringUtils = require("utils/StringUtils"),
Metrics = require("utils/Metrics"),
Dialogs = require("widgets/Dialogs"),
Mustache = require("thirdparty/mustache/mustache"),
UrlParams = require("utils/UrlParams").UrlParams,
_ = require("thirdparty/lodash");
let KeyboardPrefs = JSON.parse(require("text!base-config/keyboard.json"));
let KeyboardDialogTemplate = require("text!./ChangeShortcutTemplate.html");
let KEYMAP_FILENAME = "keymap.json",
_userKeyMapFilePath = path.normalize(brackets.app.getApplicationSupportDirectory() + "/" + KEYMAP_FILENAME);
/**
* key binding add event
*
* @const
* @type {string}
*/
const EVENT_KEY_BINDING_ADDED = "keyBindingAdded";
/**
* key binding remove event
*
* @const
* @type {string}
*/
const EVENT_KEY_BINDING_REMOVED = "keyBindingRemoved";
/**
* new preset event
*
* @const
* @type {string}
*/
const EVENT_NEW_PRESET = "newPreset";
/**
* preset change event
*
* @const
* @type {string}
*/
const EVENT_PRESET_CHANGED = "presetChanged";
/**
* @const
* @type {Object}
*/
const KEY = Keys.KEY;
const knownBindableCommands = new Set();
/**
* Forward declaration for JSLint.
*
* @private
* @type {Function}
*/
let _loadUserKeyMap = _.debounce(_loadUserKeyMapImmediate, 200);
let PreferencesManager;
let _customKeymapIDInUse;
const _registeredCustomKeyMaps = {};
const STATE_CUSTOM_KEY_MAP_ID = "customKeyMapID";
const PREF_TRIPLE_CTRL_KEY_PRESS_ENABLED = "tripleCtrlPalette";
/**
* Maps normalized shortcut descriptor to key binding info.
*
* @private
* @type {!Object.<string, {commandID: string, key: string, displayKey: string}>}
*/
let _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
*/
/**
* Maps shortcut descriptor to a command id.
*
* @private
* @type {UserKeyBinding}
*/
let _originalUserKeyMap = {},
_customKeyMap = {},
_customKeyMapCache = {};
/**
* Maps commandID to the list of shortcuts that are bound to it.
*
* @private
* @type {!Object.<string, Array.<{key: string, displayKey: string}>>}
*/
let _commandMap = {};
/**
* An array of command ID for all the available commands including the commands
* of installed extensions.
*
* @private
* @type {Array.<string>}
*/
let _allCommands = [];
/**
* Maps key names to the corresponding unicode symbols
*
* @private
* @type {{key: string, displayKey: string}}
*/
let _displayKeyMap = { "up": "\u2191",
"down": "\u2193",
"left": "\u2190",
"right": "\u2192",
"-": "\u2212" };
let _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", "Ctrl-=", "Ctrl--"],
_macReservedShortcuts = ["Cmd-,", "Cmd-H", "Cmd-Alt-H", "Cmd-M", "Cmd-Shift-Z", "Cmd-Q", "Cmd-=", "Cmd--"],
_keyNames = ["Up", "Down", "Left", "Right", "Backspace", "Enter", "Space", "Tab",
"PageUp", "PageDown", "Home", "End", "Insert", "Delete"];
/**
* 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.
*
* @private
* @type {boolean}
*/
let _showErrors = true;
/**
* Allow clients to toggle key binding
*
* @private
* @type {boolean}
*/
let _enabled = true;
/**
* Stack of registered global keydown hooks.
*
* @private
* @type {Array.<function(Event): boolean>}
*/
let _globalKeydownHooks = [];
/**
* States of Ctrl key down detection
*
* @private
* @enum {number}
*/
let CtrlDownStates = {
"NOT_YET_DETECTED": 0,
"DETECTED": 1,
"DETECTED_AND_IGNORED": 2 // For consecutive ctrl keydown events while a Ctrl key is being hold down
};
/**
* 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
*
* @private
* @type {CtrlDownStates|boolean}
*/
let _ctrlDown = CtrlDownStates.NOT_YET_DETECTED,
_altGrDown = false;
/**
* Used to record the timeStamp property of the last keydown event.
*
* @private
* @type {number}
*/
let _lastTimeStamp;
/**
* Used to record the keyIdentifier property of the last keydown event.
*
* @private
* @type {string}
*/
let _lastKeyIdentifier;
/**
* 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.
*
* @private
* @type {number}
*/
let MAX_INTERVAL_FOR_CTRL_ALT_KEYS = 30;
/**
* Forward declaration for JSLint.
*
* @private
* @type {Function}
*/
let _onCtrlUp;
/**
* Resets all the flags and removes _onCtrlUp event listener.
*
* @private
*/
function _quitAltGrMode() {
_enabled = true;
_ctrlDown = CtrlDownStates.NOT_YET_DETECTED;
_altGrDown = false;
_lastTimeStamp = null;
_lastKeyIdentifier = null;
$(window).off("keyup", _onCtrlUp);
}
/**
* 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.
*
* @private
* @param {!KeyboardEvent} e keyboard event object
*/
_onCtrlUp = function (e) {
let key = e.keyCode || e.which;
if (_altGrDown && key === KeyEvent.DOM_VK_CONTROL) {
_quitAltGrMode();
}
};
/**
* 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.
*
* @private
* @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.key === "Control") {
_ctrlDown = CtrlDownStates.DETECTED;
} else if (e.repeat && e.ctrlKey && e.key === "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.key === "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.key === "Control" || e.key === "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.key === _lastKeyIdentifier) {
_quitAltGrMode();
} else {
_lastKeyIdentifier = e.key;
}
}
}
/**
* @private
*/
function _reset() {
_keyMap = {};
_defaultKeyMap = {};
_customKeyMap = {};
_customKeyMapCache = {};
_commandMap = {};
_globalKeydownHooks = [];
_userKeyMapFilePath = path.normalize(brackets.app.getApplicationSupportDirectory() + "/" + KEYMAP_FILENAME);
}
/**
* 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
*
* @private
* @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 "";
}
let 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
*
* @private
* @param {string} origDescriptor 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) {
let 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 = "-";
}
// Check if it is a shift key only press
if (key === "" && origDescriptor.toLowerCase() === 'shift-shift') {
key = "Shift";
}
// '+' 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);
}
function _mapKeycodeToKeyLegacy(keycode) {
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
// keycode is deprecated. We only use this in one edge case in mac listed in the caller.
// 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) ||
(keycode >= KeyEvent.DOM_VK_A && keycode <= KeyEvent.DOM_VK_Z)){
return String.fromCharCode(keycode);
// 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.fromCharCode(keycode - KeyEvent.DOM_VK_NUMPAD0 + KeyEvent.DOM_VK_0);
}
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 null;
}
}
/**
* Looks for keycodes that have os-inconsistent keys and fixes them.
*
* @private
* @return {string} If the key is OS-inconsistent, the correct key; otherwise, the original key.
**/
function _mapKeycodeToKey(event) {
// key code mapping https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values
if((event.ctrlKey || event.metaKey) && event.altKey && brackets.platform === "mac"){
// in mac, Cmd-alt-<shift?>-key are valid. But alt-key will trigger international keyboard typing and
// hence instead of Cmd-Alt-O, mac will get event Cmd-alt-Φ which is not what we want. So we will
// fallback to the deprecated keyCode event in the case
const key = _mapKeycodeToKeyLegacy(event.keyCode);
if(key){
return key;
}
}
const key = event.key;
let codes = {
"ArrowUp": "Up",
"ArrowDown": "Down",
"ArrowLeft": "Left",
"ArrowRight": "Right",
" ": "Space"
};
if(codes[key]){
return codes[key];
}
return key;
}
/**
* Takes a keyboard event and translates it into a key in a key map
*
* @private
*/
function _translateKeyboardEvent(event) {
let hasMacCtrl = (brackets.platform === "mac") ? (event.ctrlKey) : false,
hasCtrl = (brackets.platform !== "mac") ? (event.ctrlKey) : (event.metaKey),
hasAlt = (event.altKey),
hasShift = (event.shiftKey),
key = _mapKeycodeToKey(event);
return normalizeKeyDescriptorString(_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) {
let 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;
}
let normalizedKey = normalizeKeyDescriptorString(key);
if (!normalizedKey) {
console.log("Failed to normalize " + key);
} else if (_isKeyAssigned(normalizedKey)) {
let 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(EVENT_KEY_BINDING_REMOVED, {key: normalizedKey, displayKey: binding.displayKey});
exports.trigger(EVENT_KEY_BINDING_REMOVED, {
commandID: command.getID(),
key: normalizedKey,
displayKey: binding.displayKey
});
}
}
}
}
/**
* 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.
*
* @private
* @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.
* @param {boolean?} isMenuShortcut
* @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, isMenuShortcut}) {
knownBindableCommands.add(commandID);
let key,
result = null,
normalized,
normalizedDisplay,
explicitPlatform = keyBinding.platform || platform,
explicitBrowserOnly = keyBinding.browserOnly,
explicitNativeOnly = keyBinding.nativeOnly,
targetPlatform,
command,
bindingsToDelete = [],
existing;
if(Phoenix.isNativeApp && explicitBrowserOnly) {
return null;
}
if(!Phoenix.isNativeApp && explicitNativeOnly) {
return null;
}
// 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}' for command '${commandID}'. Permitted modifiers: Ctrl, Cmd, Alt, Opt, Shift; separated by '-' (not '+').`);
return null;
}
function isSingleCharAZ(str) {
return /^[A-Z]$/i.test(str);
}
const keySplit = normalized.split("-");
if(!isMenuShortcut && ((keySplit.length ===2 && keySplit[0] === 'Alt' && isSingleCharAZ(keySplit[1])) ||
(keySplit.length ===3 && keySplit[0] === 'Alt' && keySplit[1] === 'Shift' && isSingleCharAZ(keySplit[2])))){
console.error(`Key binding '${normalized}' for command '${commandID}' may cause issues. The key combinations starting with 'Alt-<letter>' and 'Alt-Shift-<letter>' are reserved. On macOS, they are used for AltGr internationalization, and on Windows/Linux, they are used for menu navigation shortcuts. If this is a menu shortcut, use 'isMenuShortcut' option.`);
}
// ctrl-alt-<key> events are allowed in all platforms. In windows ctrl-alt-<key> events are treated as altGr
// and used for international keyboards. But we have special handling for detecting alt gr key press that
// accounts for this and disables keybinding manager inwindows on detecting altGr key press.
// See _detectAltGrKeyDown function in this file.
// 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
let 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
if(commandID !== _keyMap[normalized].commandID) {
console.error("Cannot assign " + normalized + " to " + commandID + ". It is already assigned to " + _keyMap[normalized].commandID);
}// else the same shortcut is already there, do nothing
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(EVENT_KEY_BINDING_ADDED, result, commandID);
exports.trigger(EVENT_KEY_BINDING_ADDED, result, commandID);
}
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.
* In the default keymap each key is associated with an object containing `commandID`, `key`, and `displayKey`.
*
* @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}
*/
function getKeymap(defaults) {
return $.extend({}, defaults ? _defaultKeyMap : _keyMap);
}
function _makeMapFromArray(map, arr){
for(let item of arr) {
map[item] = true;
}
return map;
}
/**
* If there is a registered and enabled key event, we always mark the event as processed
* except the ones in UN_SWALLOWED_EVENTS.
*
* @private
* @type {Array.<string>}
*/
const UN_SWALLOWED_EVENTS = _makeMapFromArray({}, [
Commands.EDIT_SELECT_ALL,
Commands.EDIT_UNDO,
Commands.EDIT_REDO,
Commands.EDIT_CUT,
Commands.EDIT_COPY,
Commands.EDIT_PASTE
]);
// single keys except function keys and key combinations are never swallowed. Áka we want default behavior
// for the below keys if the command handler for the registered key didnt do anything.
let UN_SWALLOWED_KEYS = _makeMapFromArray({},
_keyNames.concat(_reservedShortcuts)
.concat(_macReservedShortcuts));
function _isUnSwallowedKeys(key) {
return UN_SWALLOWED_KEYS[key] || key.length === 1; // keys like a-z, 0-9 etc
}
/**
* Process the keybinding for the current key.
*
* @private
* @param {string} key A key-description string.
* @return {boolean} true if the key was processed, false otherwise
*/
function _handleKey(key) {
if (_enabled && _keyMap[key]) {
Metrics.countEvent(Metrics.EVENT_TYPE.KEYBOARD, "shortcut", key);
Metrics.countEvent(Metrics.EVENT_TYPE.KEYBOARD, "command", _keyMap[key].commandID);
logger.leaveTrail("Keyboard shortcut: " + key + " command: " + _keyMap[key].commandID);
// If there is a registered and enabled key event except the swallowed key events,
// we always mark the event as processed and return true.
// We don't want multiple behavior tied to the same key event. For Instance, in browser, if `ctrl-k`
// is not handled by quick edit, it will open browser url bar if we return false here(which is bad ux).
let command = CommandManager.get(_keyMap[key].commandID);
let eventDetails = undefined;
if(command._options.eventSource){
eventDetails = {
eventSource: CommandManager.SOURCE_KEYBOARD_SHORTCUT,
sourceType: key
};
}
let promise = CommandManager.execute(_keyMap[key].commandID, eventDetails);
if(UN_SWALLOWED_EVENTS[_keyMap[key].commandID] || _isUnSwallowedKeys(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.
return (promise.state() !== "rejected");
}
return true;
}
return false;
}
/**
* Sort objects by platform property. Objects with a platform property come
* before objects without a platform property.
*
* @private
*/
function _sortByPlatform(a, b) {
let a1 = (a.platform) ? 1 : 0,
b1 = (b.platform) ? 1 : 0;
return b1 - a1;
}
/**
* Add one or more key bindings to a particular Command.
* Returns record(s) for valid key binding(s).
*
* @param {!string | Command} command - A command ID or command object
* @param {{key: string, displayKey:string, platform: string, browserOnly: boolean, nativeOnly:boolean}} keyBindings
* A single key binding or an array of keybindings.
* In an array of keybinding `platform` property is also available. 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="). if browserOnly is true, then the shortcut will only apply in browser
* if nativeOnly is set, the shortcut will only apply in native apps