macLinuxKeyboardMapper.ts 44.9 KB
Newer Older
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import { OperatingSystem } from 'vs/base/common/platform';
9
import { KeyCode, ResolvedKeybinding, KeyCodeUtils, SimpleKeybinding, Keybinding, KeybindingType, USER_SETTINGS } from 'vs/base/common/keyCodes';
10
import { ScanCode, ScanCodeUtils, IMMUTABLE_CODE_TO_KEY_CODE, IMMUTABLE_KEY_CODE_TO_CODE, ScanCodeBinding } from 'vs/workbench/services/keybinding/common/scanCode';
11
import { CharCode } from 'vs/base/common/charCode';
12
import { UILabelProvider, AriaLabelProvider, UserSettingsLabelProvider, ElectronAcceleratorLabelProvider, NO_MODIFIERS } from 'vs/platform/keybinding/common/keybindingLabels';
13
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
14
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
15

16
export interface IMacLinuxKeyMapping {
17 18 19 20
	value: string;
	withShift: string;
	withAltGr: string;
	withShiftAltGr: string;
A
Alex Dima 已提交
21
}
22

A
Alex Dima 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35
function macLinuxKeyMappingEquals(a: IMacLinuxKeyMapping, b: IMacLinuxKeyMapping): boolean {
	if (!a && !b) {
		return true;
	}
	if (!a || !b) {
		return false;
	}
	return (
		a.value === b.value
		&& a.withShift === b.withShift
		&& a.withAltGr === b.withAltGr
		&& a.withShiftAltGr === b.withShiftAltGr
	);
36 37
}

38
export interface IMacLinuxKeyboardMapping {
A
Renames  
Alex Dima 已提交
39
	[scanCode: string]: IMacLinuxKeyMapping;
40 41
}

A
Alex Dima 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
export function macLinuxKeyboardMappingEquals(a: IMacLinuxKeyboardMapping, b: IMacLinuxKeyboardMapping): boolean {
	if (!a && !b) {
		return true;
	}
	if (!a || !b) {
		return false;
	}
	for (let scanCode = 0; scanCode < ScanCode.MAX_VALUE; scanCode++) {
		const strScanCode = ScanCodeUtils.toString(scanCode);
		const aEntry = a[strScanCode];
		const bEntry = b[strScanCode];
		if (!macLinuxKeyMappingEquals(aEntry, bEntry)) {
			return false;
		}
	}
	return true;
}

60 61 62 63 64 65 66
const LOG = false;
function log(str: string): void {
	if (LOG) {
		console.info(str);
	}
}

A
Renames  
Alex Dima 已提交
67 68 69 70 71 72
/**
 * A map from character to key codes.
 * e.g. Contains entries such as:
 *  - '/' => { keyCode: KeyCode.US_SLASH, shiftKey: false }
 *  - '?' => { keyCode: KeyCode.US_SLASH, shiftKey: true }
 */
73 74 75 76 77 78
const CHAR_CODE_TO_KEY_CODE: { keyCode: KeyCode; shiftKey: boolean }[] = [];

export class NativeResolvedKeybinding extends ResolvedKeybinding {

	private readonly _mapper: MacLinuxKeyboardMapper;
	private readonly _OS: OperatingSystem;
A
Alex Dima 已提交
79 80
	private readonly _firstPart: ScanCodeBinding;
	private readonly _chordPart: ScanCodeBinding;
81

A
Alex Dima 已提交
82
	constructor(mapper: MacLinuxKeyboardMapper, OS: OperatingSystem, firstPart: ScanCodeBinding, chordPart: ScanCodeBinding) {
83 84 85 86 87 88 89
		super();
		this._mapper = mapper;
		this._OS = OS;
		this._firstPart = firstPart;
		this._chordPart = chordPart;
	}

90 91 92 93 94 95 96 97 98 99
	private _getUILabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._mapper.getUILabelForScanCode(binding.scanCode);
	}

100
	public getLabel(): string {
101 102
		let firstPart = this._getUILabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getUILabelForScanCodeBinding(this._chordPart);
103 104 105
		return UILabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
	}

106 107 108 109 110 111
	public getLabelWithoutModifiers(): string {
		let firstPart = this._getUILabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getUILabelForScanCodeBinding(this._chordPart);
		return UILabelProvider.toLabel(NO_MODIFIERS, firstPart, NO_MODIFIERS, chordPart, this._OS);
	}

112 113 114 115 116 117 118 119 120 121
	private _getAriaLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._mapper.getAriaLabelForScanCode(binding.scanCode);
	}

122
	public getAriaLabel(): string {
123 124
		let firstPart = this._getAriaLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getAriaLabelForScanCodeBinding(this._chordPart);
125 126 127
		return AriaLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
	}

128 129 130 131
	public getAriaLabelWithoutModifiers(): string {
		let firstPart = this._getAriaLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getAriaLabelForScanCodeBinding(this._chordPart);
		return AriaLabelProvider.toLabel(NO_MODIFIERS, firstPart, NO_MODIFIERS, chordPart, this._OS);
132 133
	}

134 135 136 137 138 139 140 141 142 143
	private _getElectronAcceleratorLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return null;
		}
		return this._mapper.getElectronLabelForScanCode(binding.scanCode);
	}

144
	public getElectronAccelerator(): string {
145 146 147 148 149
		if (this._chordPart !== null) {
			// Electron cannot handle chords
			return null;
		}

150
		let firstPart = this._getElectronAcceleratorLabelForScanCodeBinding(this._firstPart);
151
		return ElectronAcceleratorLabelProvider.toLabel(this._firstPart, firstPart, null, null, this._OS);
152 153
	}

154 155 156 157 158 159 160 161 162 163
	private _getUserSettingsLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._mapper.getUserSettingsLabel(binding.scanCode);
	}

164
	public getUserSettingsLabel(): string {
165 166
		let firstPart = this._getUserSettingsLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getUserSettingsLabelForScanCodeBinding(this._chordPart);
167
		return UserSettingsLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
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
	private _isWYSIWYG(scanCode: ScanCode): boolean {
		if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
			return true;
		}
		let a = this._mapper.getAriaLabelForScanCode(scanCode);
		let b = this._mapper.getUserSettingsLabel(scanCode);

		if (!a && !b) {
			return true;
		}
		if (!a || !b) {
			return false;
		}
		return (a.toLowerCase() === b.toLowerCase());
	}

	public isWYSIWYG(): boolean {
		let result = true;
		result = result && (this._firstPart ? this._isWYSIWYG(this._firstPart.scanCode) : true);
		result = result && (this._chordPart ? this._isWYSIWYG(this._chordPart.scanCode) : true);
		return result;
	}

193
	public isChord(): boolean {
A
Alex Dima 已提交
194
		return (this._chordPart ? true : false);
195 196 197
	}

	public hasCtrlModifier(): boolean {
A
Alex Dima 已提交
198 199 200 201
		if (this._chordPart) {
			return false;
		}
		return this._firstPart.ctrlKey;
202 203 204
	}

	public hasShiftModifier(): boolean {
A
Alex Dima 已提交
205 206 207 208
		if (this._chordPart) {
			return false;
		}
		return this._firstPart.shiftKey;
209 210 211
	}

	public hasAltModifier(): boolean {
A
Alex Dima 已提交
212 213 214 215
		if (this._chordPart) {
			return false;
		}
		return this._firstPart.altKey;
216 217 218
	}

	public hasMetaModifier(): boolean {
A
Alex Dima 已提交
219 220 221 222
		if (this._chordPart) {
			return false;
		}
		return this._firstPart.metaKey;
223 224
	}

225 226 227 228
	public getParts(): [ResolvedKeybinding, ResolvedKeybinding] {
		return [new NativeResolvedKeybinding(this._mapper, this._OS, this._firstPart, null), this._chordPart ? new NativeResolvedKeybinding(this._mapper, this._OS, this._chordPart, null) : null];
	}

229
	public getDispatchParts(): [string, string] {
A
Alex Dima 已提交
230 231
		let firstPart = this._firstPart ? this._mapper.getDispatchStrForScanCodeBinding(this._firstPart) : null;
		let chordPart = this._chordPart ? this._mapper.getDispatchStrForScanCodeBinding(this._chordPart) : null;
232
		return [firstPart, chordPart];
233 234 235
	}
}

A
Renames  
Alex Dima 已提交
236 237
interface IScanCodeMapping {
	scanCode: ScanCode;
238 239 240 241 242 243
	value: number;
	withShift: number;
	withAltGr: number;
	withShiftAltGr: number;
}

244 245 246 247 248 249 250 251 252 253 254 255
class ScanCodeCombo {
	public readonly ctrlKey: boolean;
	public readonly shiftKey: boolean;
	public readonly altKey: boolean;
	public readonly scanCode: ScanCode;

	constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, scanCode: ScanCode) {
		this.ctrlKey = ctrlKey;
		this.shiftKey = shiftKey;
		this.altKey = altKey;
		this.scanCode = scanCode;
	}
A
Alex Dima 已提交
256 257 258 259 260

	public toString(): string {
		return `${this.ctrlKey ? 'Ctrl+' : ''}${this.shiftKey ? 'Shift+' : ''}${this.altKey ? 'Alt+' : ''}${ScanCodeUtils.toString(this.scanCode)}`;
	}

A
Alex Dima 已提交
261 262 263 264 265 266 267 268 269
	public equals(other: ScanCodeCombo): boolean {
		return (
			this.ctrlKey === other.ctrlKey
			&& this.shiftKey === other.shiftKey
			&& this.altKey === other.altKey
			&& this.scanCode === other.scanCode
		);
	}

A
Alex Dima 已提交
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
	private getProducedCharCode(mapping: IScanCodeMapping): number {
		if (!mapping) {
			return 0;
		}
		if (this.ctrlKey && this.shiftKey && this.altKey) {
			return mapping.withShiftAltGr;
		}
		if (this.ctrlKey && this.altKey) {
			return mapping.withAltGr;
		}
		if (this.shiftKey) {
			return mapping.withShift;
		}
		return mapping.value;
	}

	public getProducedChar(mapping: IScanCodeMapping): string {
		const charCode = this.getProducedCharCode(mapping);
		if (charCode === 0) {
			return ' --- ';
		}
		if (charCode >= CharCode.U_Combining_Grave_Accent && charCode <= CharCode.U_Combining_Latin_Small_Letter_X) {
			// combining
			return 'U+' + charCode.toString(16);
		}
		return '  ' + String.fromCharCode(charCode) + '  ';
	}
297 298 299 300 301 302 303 304 305 306 307 308 309 310
}

class KeyCodeCombo {
	public readonly ctrlKey: boolean;
	public readonly shiftKey: boolean;
	public readonly altKey: boolean;
	public readonly keyCode: KeyCode;

	constructor(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, keyCode: KeyCode) {
		this.ctrlKey = ctrlKey;
		this.shiftKey = shiftKey;
		this.altKey = altKey;
		this.keyCode = keyCode;
	}
A
Alex Dima 已提交
311 312 313 314

	public toString(): string {
		return `${this.ctrlKey ? 'Ctrl+' : ''}${this.shiftKey ? 'Shift+' : ''}${this.altKey ? 'Alt+' : ''}${KeyCodeUtils.toString(this.keyCode)}`;
	}
315 316 317 318 319 320 321 322
}

class ScanCodeKeyCodeMapper {

	/**
	 * ScanCode combination => KeyCode combination.
	 * Only covers relevant modifiers ctrl, shift, alt (since meta does not influence the mappings).
	 */
323
	private readonly _scanCodeToKeyCode: number[][] = [];
324 325 326 327 328 329 330 331 332 333 334 335
	/**
	 * inverse of `_scanCodeToKeyCode`.
	 * KeyCode combination => ScanCode combination.
	 * Only covers relevant modifiers ctrl, shift, alt (since meta does not influence the mappings).
	 */
	private readonly _keyCodeToScanCode: number[][] = [];

	constructor() {
		this._scanCodeToKeyCode = [];
		this._keyCodeToScanCode = [];
	}

A
Alex Dima 已提交
336
	public registrationComplete(): void {
337 338 339 340 341 342 343 344 345 346
		for (let i = 0; i < ScanCode.MAX_VALUE; i++) {
			let base = (i << 3);
			for (let j = 0; j < 8; j++) {
				let actual = base + j;
				let entry = this._scanCodeToKeyCode[actual];
				if (typeof entry === 'undefined') {
					log(`${ScanCodeUtils.toString(i)} - ${j.toString(2)} --- is missing`);
				}
			}
		}
A
Alex Dima 已提交
347 348

		// IntlHash and IntlBackslash are rare keys, so ensure they don't end up being the preferred...
349 350
		this._moveToEnd(ScanCode.IntlHash);
		this._moveToEnd(ScanCode.IntlBackslash);
A
Alex Dima 已提交
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
	private _moveToEnd(scanCode: ScanCode): void {
		for (let mod = 0; mod < 8; mod++) {
			const encodedKeyCodeCombos = this._scanCodeToKeyCode[(scanCode << 3) + mod];
			if (!encodedKeyCodeCombos) {
				continue;
			}
			for (let i = 0, len = encodedKeyCodeCombos.length; i < len; i++) {
				const encodedScanCodeCombos = this._keyCodeToScanCode[encodedKeyCodeCombos[i]];
				if (encodedScanCodeCombos.length === 1) {
					continue;
				}
				for (let j = 0, len = encodedScanCodeCombos.length; j < len; j++) {
					const entry = encodedScanCodeCombos[j];
					const entryScanCode = (entry >>> 3);
					if (entryScanCode === scanCode) {
						// Move this entry to the end
						for (let k = j + 1; k < len; k++) {
							encodedScanCodeCombos[k - 1] = encodedScanCodeCombos[k];
						}
						encodedScanCodeCombos[len - 1] = entry;
					}
				}
			}
		}
	}
378 379

	public registerIfUnknown(scanCodeCombo: ScanCodeCombo, keyCodeCombo: KeyCodeCombo): void {
380 381 382
		if (keyCodeCombo.keyCode === KeyCode.Unknown) {
			return;
		}
383 384 385
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
		const keyCodeComboEncoded = this._encodeKeyCodeCombo(keyCodeCombo);

A
Alex Dima 已提交
386 387 388
		const keyCodeIsDigit = (keyCodeCombo.keyCode >= KeyCode.KEY_0 && keyCodeCombo.keyCode <= KeyCode.KEY_9);
		const keyCodeIsLetter = (keyCodeCombo.keyCode >= KeyCode.KEY_A && keyCodeCombo.keyCode <= KeyCode.KEY_Z);

A
Alex Dima 已提交
389
		const existingKeyCodeCombos = this._scanCodeToKeyCode[scanCodeComboEncoded];
A
Alex Dima 已提交
390 391 392 393

		// Allow a scan code to map to multiple key codes if it is a digit or a letter key code
		if (keyCodeIsDigit || keyCodeIsLetter) {
			// Only check that we don't insert the same entry twice
A
Alex Dima 已提交
394 395 396
			if (existingKeyCodeCombos) {
				for (let i = 0, len = existingKeyCodeCombos.length; i < len; i++) {
					if (existingKeyCodeCombos[i] === keyCodeComboEncoded) {
A
Alex Dima 已提交
397 398 399 400 401 402 403
						// avoid duplicates
						return;
					}
				}
			}
		} else {
			// Don't allow multiples
A
Alex Dima 已提交
404
			if (existingKeyCodeCombos && existingKeyCodeCombos.length !== 0) {
A
Alex Dima 已提交
405 406
				return;
			}
407 408
		}

409 410
		this._scanCodeToKeyCode[scanCodeComboEncoded] = this._scanCodeToKeyCode[scanCodeComboEncoded] || [];
		this._scanCodeToKeyCode[scanCodeComboEncoded].unshift(keyCodeComboEncoded);
411

412 413
		this._keyCodeToScanCode[keyCodeComboEncoded] = this._keyCodeToScanCode[keyCodeComboEncoded] || [];
		this._keyCodeToScanCode[keyCodeComboEncoded].unshift(scanCodeComboEncoded);
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
	}

	public lookupKeyCodeCombo(keyCodeCombo: KeyCodeCombo): ScanCodeCombo[] {
		const keyCodeComboEncoded = this._encodeKeyCodeCombo(keyCodeCombo);
		const scanCodeCombosEncoded = this._keyCodeToScanCode[keyCodeComboEncoded];
		if (!scanCodeCombosEncoded || scanCodeCombosEncoded.length === 0) {
			return [];
		}

		let result: ScanCodeCombo[] = [];
		for (let i = 0, len = scanCodeCombosEncoded.length; i < len; i++) {
			const scanCodeComboEncoded = scanCodeCombosEncoded[i];

			const ctrlKey = (scanCodeComboEncoded & 0b001) ? true : false;
			const shiftKey = (scanCodeComboEncoded & 0b010) ? true : false;
			const altKey = (scanCodeComboEncoded & 0b100) ? true : false;
			const scanCode: ScanCode = (scanCodeComboEncoded >>> 3);

			result[i] = new ScanCodeCombo(ctrlKey, shiftKey, altKey, scanCode);
		}
		return result;
	}

437
	public lookupScanCodeCombo(scanCodeCombo: ScanCodeCombo): KeyCodeCombo[] {
438
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
439 440 441 442 443 444 445 446
		const keyCodeCombosEncoded = this._scanCodeToKeyCode[scanCodeComboEncoded];
		if (!keyCodeCombosEncoded || keyCodeCombosEncoded.length === 0) {
			return [];
		}

		let result: KeyCodeCombo[] = [];
		for (let i = 0, len = keyCodeCombosEncoded.length; i < len; i++) {
			const keyCodeComboEncoded = keyCodeCombosEncoded[i];
447

448 449 450 451
			const ctrlKey = (keyCodeComboEncoded & 0b001) ? true : false;
			const shiftKey = (keyCodeComboEncoded & 0b010) ? true : false;
			const altKey = (keyCodeComboEncoded & 0b100) ? true : false;
			const keyCode: KeyCode = (keyCodeComboEncoded >>> 3);
452

453 454 455
			result[i] = new KeyCodeCombo(ctrlKey, shiftKey, altKey, keyCode);
		}
		return result;
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
	public guessStableKeyCode(scanCode: ScanCode): KeyCode {
		if (scanCode >= ScanCode.Digit1 && scanCode <= ScanCode.Digit0) {
			// digits are ok
			switch (scanCode) {
				case ScanCode.Digit1: return KeyCode.KEY_1;
				case ScanCode.Digit2: return KeyCode.KEY_2;
				case ScanCode.Digit3: return KeyCode.KEY_3;
				case ScanCode.Digit4: return KeyCode.KEY_4;
				case ScanCode.Digit5: return KeyCode.KEY_5;
				case ScanCode.Digit6: return KeyCode.KEY_6;
				case ScanCode.Digit7: return KeyCode.KEY_7;
				case ScanCode.Digit8: return KeyCode.KEY_8;
				case ScanCode.Digit9: return KeyCode.KEY_9;
				case ScanCode.Digit0: return KeyCode.KEY_0;
			}
		}

		// Lookup the scanCode with and without shift and see if the keyCode is stable
		const keyCodeCombos1 = this.lookupScanCodeCombo(new ScanCodeCombo(false, false, false, scanCode));
		const keyCodeCombos2 = this.lookupScanCodeCombo(new ScanCodeCombo(false, true, false, scanCode));
		if (keyCodeCombos1.length === 1 && keyCodeCombos2.length === 1) {
			const shiftKey1 = keyCodeCombos1[0].shiftKey;
			const keyCode1 = keyCodeCombos1[0].keyCode;
			const shiftKey2 = keyCodeCombos2[0].shiftKey;
			const keyCode2 = keyCodeCombos2[0].keyCode;
			if (keyCode1 === keyCode2 && shiftKey1 !== shiftKey2) {
				// This looks like a stable mapping
				return keyCode1;
			}
		}

		return -1;
	}

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
	private _encodeScanCodeCombo(scanCodeCombo: ScanCodeCombo): number {
		return this._encode(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, scanCodeCombo.scanCode);
	}

	private _encodeKeyCodeCombo(keyCodeCombo: KeyCodeCombo): number {
		return this._encode(keyCodeCombo.ctrlKey, keyCodeCombo.shiftKey, keyCodeCombo.altKey, keyCodeCombo.keyCode);
	}

	private _encode(ctrlKey: boolean, shiftKey: boolean, altKey: boolean, principal: number): number {
		return (
			((ctrlKey ? 1 : 0) << 0)
			| ((shiftKey ? 1 : 0) << 1)
			| ((altKey ? 1 : 0) << 2)
			| principal << 3
		) >>> 0;
	}
}

510 511
export class MacLinuxKeyboardMapper implements IKeyboardMapper {

512
	/**
513 514 515 516 517
	 * Is the keyboard type ISO (on Mac)
	 */
	private readonly _isISOKeyboard: boolean;
	/**
	 * Is this the standard US keyboard layout?
518 519
	 */
	private readonly _isUSStandard: boolean;
A
Renames  
Alex Dima 已提交
520 521 522
	/**
	 * OS (can be Linux or Macintosh)
	 */
523
	private readonly _OS: OperatingSystem;
524 525 526
	/**
	 * used only for debug purposes.
	 */
A
Renames  
Alex Dima 已提交
527 528
	private readonly _codeInfo: IScanCodeMapping[];
	/**
529
	 * Maps ScanCode combos <-> KeyCode combos.
A
Renames  
Alex Dima 已提交
530
	 */
531
	private readonly _scanCodeKeyCodeMapper: ScanCodeKeyCodeMapper;
A
Renames  
Alex Dima 已提交
532 533 534 535
	/**
	 * UI label for a ScanCode.
	 */
	private readonly _scanCodeToLabel: string[] = [];
536
	/**
A
Renames  
Alex Dima 已提交
537
	 * Dispatching string for a ScanCode.
538
	 */
A
Renames  
Alex Dima 已提交
539
	private readonly _scanCodeToDispatch: string[] = [];
540

541 542
	constructor(isISOKeyboard: boolean, isUSStandard: boolean, rawMappings: IMacLinuxKeyboardMapping, OS: OperatingSystem) {
		this._isISOKeyboard = isISOKeyboard;
543
		this._isUSStandard = isUSStandard;
544
		this._OS = OS;
545 546
		this._codeInfo = [];
		this._scanCodeKeyCodeMapper = new ScanCodeKeyCodeMapper();
A
Renames  
Alex Dima 已提交
547 548
		this._scanCodeToLabel = [];
		this._scanCodeToDispatch = [];
549

A
Alex Dima 已提交
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
		const _registerIfUnknown = (
			hwCtrlKey: 0 | 1, hwShiftKey: 0 | 1, hwAltKey: 0 | 1, scanCode: ScanCode,
			kbCtrlKey: 0 | 1, kbShiftKey: 0 | 1, kbAltKey: 0 | 1, keyCode: KeyCode,
		): void => {
			this._scanCodeKeyCodeMapper.registerIfUnknown(
				new ScanCodeCombo(hwCtrlKey ? true : false, hwShiftKey ? true : false, hwAltKey ? true : false, scanCode),
				new KeyCodeCombo(kbCtrlKey ? true : false, kbShiftKey ? true : false, kbAltKey ? true : false, keyCode)
			);
		};

		const _registerAllCombos = (_ctrlKey: 0 | 1, _shiftKey: 0 | 1, _altKey: 0 | 1, scanCode: ScanCode, keyCode: KeyCode): void => {
			for (let ctrlKey = _ctrlKey; ctrlKey <= 1; ctrlKey++) {
				for (let shiftKey = _shiftKey; shiftKey <= 1; shiftKey++) {
					for (let altKey = _altKey; altKey <= 1; altKey++) {
						_registerIfUnknown(
							ctrlKey, shiftKey, altKey, scanCode,
							ctrlKey, shiftKey, altKey, keyCode
						);
					}
				}
			}
		};

		let producesLetter: boolean[] = [];
		const _registerLetterIfMissing = (charCode: CharCode, scanCode: ScanCode, keyCode: KeyCode): void => {
			if (!producesLetter[charCode]) {
				_registerAllCombos(0, 0, 0, scanCode, keyCode);
			}
		};


581 582 583 584 585 586 587 588 589 590 591
		// Initialize `_scanCodeToLabel`
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			this._scanCodeToLabel[scanCode] = null;
		}

		// Initialize `_scanCodeToDispatch`
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			this._scanCodeToDispatch[scanCode] = null;
		}

		// Handle immutable mappings
A
Renames  
Alex Dima 已提交
592 593 594
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			const keyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
			if (keyCode !== -1) {
A
Alex Dima 已提交
595
				_registerAllCombos(0, 0, 0, scanCode, keyCode);
A
Renames  
Alex Dima 已提交
596
				this._scanCodeToLabel[scanCode] = KeyCodeUtils.toString(keyCode);
A
Alex Dima 已提交
597

A
Renames  
Alex Dima 已提交
598 599
				if (keyCode === KeyCode.Unknown || keyCode === KeyCode.Ctrl || keyCode === KeyCode.Meta || keyCode === KeyCode.Alt || keyCode === KeyCode.Shift) {
					this._scanCodeToDispatch[scanCode] = null; // cannot dispatch on this ScanCode
A
Alex Dima 已提交
600
				} else {
A
Renames  
Alex Dima 已提交
601
					this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
602
				}
603 604 605
			}
		}

A
Renames  
Alex Dima 已提交
606 607 608 609 610 611
		let mappings: IScanCodeMapping[] = [], mappingsLen = 0;
		for (let strScanCode in rawMappings) {
			if (rawMappings.hasOwnProperty(strScanCode)) {
				const scanCode = ScanCodeUtils.toEnum(strScanCode);
				if (scanCode === ScanCode.None) {
					log(`Unknown ScanCode ${strScanCode} in mapping.`);
612 613
					continue;
				}
A
Renames  
Alex Dima 已提交
614
				if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
615 616 617
					continue;
				}

A
Renames  
Alex Dima 已提交
618
				const rawMapping = rawMappings[strScanCode];
619 620 621 622 623
				const value = MacLinuxKeyboardMapper._getCharCode(rawMapping.value);
				const withShift = MacLinuxKeyboardMapper._getCharCode(rawMapping.withShift);
				const withAltGr = MacLinuxKeyboardMapper._getCharCode(rawMapping.withAltGr);
				const withShiftAltGr = MacLinuxKeyboardMapper._getCharCode(rawMapping.withShiftAltGr);

A
Renames  
Alex Dima 已提交
624 625
				const mapping: IScanCodeMapping = {
					scanCode: scanCode,
626 627 628 629 630 631
					value: value,
					withShift: withShift,
					withAltGr: withAltGr,
					withShiftAltGr: withShiftAltGr,
				};
				mappings[mappingsLen++] = mapping;
A
Renames  
Alex Dima 已提交
632
				this._codeInfo[scanCode] = mapping;
633

A
Renames  
Alex Dima 已提交
634
				this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
635

636
				if (value >= CharCode.a && value <= CharCode.z) {
637 638 639 640 641 642
					const upperCaseValue = CharCode.A + (value - CharCode.a);
					producesLetter[upperCaseValue] = true;
					this._scanCodeToLabel[scanCode] = String.fromCharCode(upperCaseValue);
				} else if (value >= CharCode.A && value <= CharCode.Z) {
					producesLetter[value] = true;
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
643
				} else if (value) {
A
Renames  
Alex Dima 已提交
644
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
645
				} else {
A
Renames  
Alex Dima 已提交
646
					this._scanCodeToLabel[scanCode] = null;
647 648 649 650 651 652 653
				}
			}
		}

		// Handle all `withShiftAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
654
			const scanCode = mapping.scanCode;
655 656 657 658 659
			const withShiftAltGr = mapping.withShiftAltGr;
			if (withShiftAltGr === mapping.withAltGr || withShiftAltGr === mapping.withShift || withShiftAltGr === mapping.value) {
				// handled below
				continue;
			}
660 661 662 663 664 665 666
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShiftAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

667 668
			if (kbShiftKey) {
				// Ctrl+Shift+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
669
				_registerIfUnknown(1, 1, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
670 671
			} else {
				// Ctrl+Shift+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
672
				_registerIfUnknown(1, 1, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
673
			}
674 675 676 677
		}
		// Handle all `withAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
678
			const scanCode = mapping.scanCode;
679 680 681 682 683
			const withAltGr = mapping.withAltGr;
			if (withAltGr === mapping.withShift || withAltGr === mapping.value) {
				// handled below
				continue;
			}
684 685 686 687 688 689 690
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

691 692
			if (kbShiftKey) {
				// Ctrl+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
693
				_registerIfUnknown(1, 0, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
694 695
			} else {
				// Ctrl+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
696
				_registerIfUnknown(1, 0, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
697
			}
698 699 700 701
		}
		// Handle all `withShift` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
702
			const scanCode = mapping.scanCode;
703 704 705 706 707
			const withShift = mapping.withShift;
			if (withShift === mapping.value) {
				// handled below
				continue;
			}
708 709 710 711 712 713 714
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShift);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

715 716
			if (kbShiftKey) {
				// Shift+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
717 718 719 720
				_registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode); //          Shift+ScanCode =>          Shift+KeyCode
				_registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode); //      Shift+Alt+ScanCode =>      Shift+Alt+KeyCode
				_registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode); //     Ctrl+Shift+ScanCode =>     Ctrl+Shift+KeyCode
				_registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode); // Ctrl+Shift+Alt+ScanCode => Ctrl+Shift+Alt+KeyCode
721 722
			} else {
				// Shift+ScanCode => KeyCode
A
Alex Dima 已提交
723 724 725 726 727 728 729 730
				_registerIfUnknown(0, 1, 0, scanCode, 0, 0, 0, keyCode); //          Shift+ScanCode =>                KeyCode
				_registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode); //          Shift+ScanCode =>          Shift+KeyCode
				_registerIfUnknown(0, 1, 1, scanCode, 0, 0, 1, keyCode); //      Shift+Alt+ScanCode =>            Alt+KeyCode
				_registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode); //      Shift+Alt+ScanCode =>      Shift+Alt+KeyCode
				_registerIfUnknown(1, 1, 0, scanCode, 1, 0, 0, keyCode); //     Ctrl+Shift+ScanCode =>           Ctrl+KeyCode
				_registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode); //     Ctrl+Shift+ScanCode =>     Ctrl+Shift+KeyCode
				_registerIfUnknown(1, 1, 1, scanCode, 1, 0, 1, keyCode); // Ctrl+Shift+Alt+ScanCode =>       Ctrl+Alt+KeyCode
				_registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode); // Ctrl+Shift+Alt+ScanCode => Ctrl+Shift+Alt+KeyCode
731
			}
732 733 734 735
		}
		// Handle all `value` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
736 737 738 739 740 741 742 743
			const scanCode = mapping.scanCode;
			const kb = MacLinuxKeyboardMapper._charCodeToKb(mapping.value);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

744 745
			if (kbShiftKey) {
				// ScanCode => Shift+KeyCode
A
Alex Dima 已提交
746 747 748 749
				_registerIfUnknown(0, 0, 0, scanCode, 0, 1, 0, keyCode); //                ScanCode =>          Shift+KeyCode
				_registerIfUnknown(0, 0, 1, scanCode, 0, 1, 1, keyCode); //            Alt+ScanCode =>      Shift+Alt+KeyCode
				_registerIfUnknown(1, 0, 0, scanCode, 1, 1, 0, keyCode); //           Ctrl+ScanCode =>     Ctrl+Shift+KeyCode
				_registerIfUnknown(1, 0, 1, scanCode, 1, 1, 1, keyCode); //       Ctrl+Alt+ScanCode => Ctrl+Shift+Alt+KeyCode
750 751
			} else {
				// ScanCode => KeyCode
A
Alex Dima 已提交
752 753 754 755 756 757 758 759
				_registerIfUnknown(0, 0, 0, scanCode, 0, 0, 0, keyCode); //                ScanCode =>                KeyCode
				_registerIfUnknown(0, 0, 1, scanCode, 0, 0, 1, keyCode); //            Alt+ScanCode =>            Alt+KeyCode
				_registerIfUnknown(0, 1, 0, scanCode, 0, 1, 0, keyCode); //          Shift+ScanCode =>          Shift+KeyCode
				_registerIfUnknown(0, 1, 1, scanCode, 0, 1, 1, keyCode); //      Shift+Alt+ScanCode =>      Shift+Alt+KeyCode
				_registerIfUnknown(1, 0, 0, scanCode, 1, 0, 0, keyCode); //           Ctrl+ScanCode =>           Ctrl+KeyCode
				_registerIfUnknown(1, 0, 1, scanCode, 1, 0, 1, keyCode); //       Ctrl+Alt+ScanCode =>       Ctrl+Alt+KeyCode
				_registerIfUnknown(1, 1, 0, scanCode, 1, 1, 0, keyCode); //     Ctrl+Shift+ScanCode =>     Ctrl+Shift+KeyCode
				_registerIfUnknown(1, 1, 1, scanCode, 1, 1, 1, keyCode); // Ctrl+Shift+Alt+ScanCode => Ctrl+Shift+Alt+KeyCode
760
			}
761
		}
762
		// Handle all left-over available digits
A
Alex Dima 已提交
763 764 765 766 767 768 769 770 771 772
		_registerAllCombos(0, 0, 0, ScanCode.Digit1, KeyCode.KEY_1);
		_registerAllCombos(0, 0, 0, ScanCode.Digit2, KeyCode.KEY_2);
		_registerAllCombos(0, 0, 0, ScanCode.Digit3, KeyCode.KEY_3);
		_registerAllCombos(0, 0, 0, ScanCode.Digit4, KeyCode.KEY_4);
		_registerAllCombos(0, 0, 0, ScanCode.Digit5, KeyCode.KEY_5);
		_registerAllCombos(0, 0, 0, ScanCode.Digit6, KeyCode.KEY_6);
		_registerAllCombos(0, 0, 0, ScanCode.Digit7, KeyCode.KEY_7);
		_registerAllCombos(0, 0, 0, ScanCode.Digit8, KeyCode.KEY_8);
		_registerAllCombos(0, 0, 0, ScanCode.Digit9, KeyCode.KEY_9);
		_registerAllCombos(0, 0, 0, ScanCode.Digit0, KeyCode.KEY_0);
A
Renames  
Alex Dima 已提交
773

774
		// Ensure letters are mapped
A
Alex Dima 已提交
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
		_registerLetterIfMissing(CharCode.A, ScanCode.KeyA, KeyCode.KEY_A);
		_registerLetterIfMissing(CharCode.B, ScanCode.KeyB, KeyCode.KEY_B);
		_registerLetterIfMissing(CharCode.C, ScanCode.KeyC, KeyCode.KEY_C);
		_registerLetterIfMissing(CharCode.D, ScanCode.KeyD, KeyCode.KEY_D);
		_registerLetterIfMissing(CharCode.E, ScanCode.KeyE, KeyCode.KEY_E);
		_registerLetterIfMissing(CharCode.F, ScanCode.KeyF, KeyCode.KEY_F);
		_registerLetterIfMissing(CharCode.G, ScanCode.KeyG, KeyCode.KEY_G);
		_registerLetterIfMissing(CharCode.H, ScanCode.KeyH, KeyCode.KEY_H);
		_registerLetterIfMissing(CharCode.I, ScanCode.KeyI, KeyCode.KEY_I);
		_registerLetterIfMissing(CharCode.J, ScanCode.KeyJ, KeyCode.KEY_J);
		_registerLetterIfMissing(CharCode.K, ScanCode.KeyK, KeyCode.KEY_K);
		_registerLetterIfMissing(CharCode.L, ScanCode.KeyL, KeyCode.KEY_L);
		_registerLetterIfMissing(CharCode.M, ScanCode.KeyM, KeyCode.KEY_M);
		_registerLetterIfMissing(CharCode.N, ScanCode.KeyN, KeyCode.KEY_N);
		_registerLetterIfMissing(CharCode.O, ScanCode.KeyO, KeyCode.KEY_O);
		_registerLetterIfMissing(CharCode.P, ScanCode.KeyP, KeyCode.KEY_P);
		_registerLetterIfMissing(CharCode.Q, ScanCode.KeyQ, KeyCode.KEY_Q);
		_registerLetterIfMissing(CharCode.R, ScanCode.KeyR, KeyCode.KEY_R);
		_registerLetterIfMissing(CharCode.S, ScanCode.KeyS, KeyCode.KEY_S);
		_registerLetterIfMissing(CharCode.T, ScanCode.KeyT, KeyCode.KEY_T);
		_registerLetterIfMissing(CharCode.U, ScanCode.KeyU, KeyCode.KEY_U);
		_registerLetterIfMissing(CharCode.V, ScanCode.KeyV, KeyCode.KEY_V);
		_registerLetterIfMissing(CharCode.W, ScanCode.KeyW, KeyCode.KEY_W);
		_registerLetterIfMissing(CharCode.X, ScanCode.KeyX, KeyCode.KEY_X);
		_registerLetterIfMissing(CharCode.Y, ScanCode.KeyY, KeyCode.KEY_Y);
		_registerLetterIfMissing(CharCode.Z, ScanCode.KeyZ, KeyCode.KEY_Z);
801

A
Alex Dima 已提交
802
		this._scanCodeKeyCodeMapper.registrationComplete();
803 804 805 806 807
	}

	public dumpDebugInfo(): string {
		let result: string[] = [];

808 809 810 811 812
		let immutableSamples = [
			ScanCode.ArrowUp,
			ScanCode.Numpad0
		];

813
		let cnt = 0;
814
		result.push(`isUSStandard: ${this._isUSStandard}`);
815
		result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
A
Renames  
Alex Dima 已提交
816 817
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
818 819 820
				if (immutableSamples.indexOf(scanCode) === -1) {
					continue;
				}
821 822 823
			}

			if (cnt % 4 === 0) {
824 825
				result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
				result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
826 827 828
			}
			cnt++;

A
Renames  
Alex Dima 已提交
829
			const mapping = this._codeInfo[scanCode];
830 831

			for (let mod = 0; mod < 8; mod++) {
832 833 834
				const hwCtrlKey = (mod & 0b001) ? true : false;
				const hwShiftKey = (mod & 0b010) ? true : false;
				const hwAltKey = (mod & 0b100) ? true : false;
A
Alex Dima 已提交
835
				const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
836
				const resolvedKb = this.resolveKeyboardEvent({
A
Alex Dima 已提交
837 838 839
					ctrlKey: scanCodeCombo.ctrlKey,
					shiftKey: scanCodeCombo.shiftKey,
					altKey: scanCodeCombo.altKey,
840 841 842 843
					metaKey: false,
					keyCode: -1,
					code: ScanCodeUtils.toString(scanCode)
				});
844

A
Alex Dima 已提交
845 846 847 848 849 850 851 852
				const outScanCodeCombo = scanCodeCombo.toString();
				const outKey = scanCodeCombo.getProducedChar(mapping);
				const ariaLabel = resolvedKb.getAriaLabel();
				const outUILabel = (ariaLabel ? ariaLabel.replace(/Control\+/, 'Ctrl+') : null);
				const outUserSettings = resolvedKb.getUserSettingsLabel();
				const outElectronAccelerator = resolvedKb.getElectronAccelerator();
				const outDispatchStr = resolvedKb.getDispatchParts()[0];

853 854 855
				const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false);
				const outWYSIWYG = (isWYSIWYG ? '       ' : '   NO  ');

A
Alex Dima 已提交
856
				const kbCombos = this._scanCodeKeyCodeMapper.lookupScanCodeCombo(scanCodeCombo);
857
				if (kbCombos.length === 0) {
858
					result.push(`| ${this._leftPad(outScanCodeCombo, 30)} | ${outKey} | ${this._leftPad('', 25)} | ${this._leftPad('', 3)} | ${this._leftPad(outUILabel, 25)} | ${this._leftPad(outUserSettings, 30)} | ${this._leftPad(outElectronAccelerator, 25)} | ${this._leftPad(outDispatchStr, 30)} | ${outWYSIWYG} |`);
859 860 861
				} else {
					for (let i = 0, len = kbCombos.length; i < len; i++) {
						const kbCombo = kbCombos[i];
A
Alex Dima 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
						// find out the priority of this scan code for this key code
						let colPriority = '-';

						const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(kbCombo);
						if (scanCodeCombos.length === 1) {
							// no need for priority, this key code combo maps to precisely this scan code combo
							colPriority = '';
						} else {
							let priority = -1;
							for (let j = 0; j < scanCodeCombos.length; j++) {
								if (scanCodeCombos[j].equals(scanCodeCombo)) {
									priority = j + 1;
									break;
								}
							}
							colPriority = String(priority);
						}

A
Alex Dima 已提交
880
						const outKeybinding = kbCombo.toString();
A
Alex Dima 已提交
881
						if (i === 0) {
882
							result.push(`| ${this._leftPad(outScanCodeCombo, 30)} | ${outKey} | ${this._leftPad(outKeybinding, 25)} | ${this._leftPad(colPriority, 3)} | ${this._leftPad(outUILabel, 25)} | ${this._leftPad(outUserSettings, 30)} | ${this._leftPad(outElectronAccelerator, 25)} | ${this._leftPad(outDispatchStr, 30)} | ${outWYSIWYG} |`);
A
Alex Dima 已提交
883 884
						} else {
							// secondary keybindings
885
							result.push(`| ${this._leftPad('', 30)} |       | ${this._leftPad(outKeybinding, 25)} | ${this._leftPad(colPriority, 3)} | ${this._leftPad('', 25)} | ${this._leftPad('', 30)} | ${this._leftPad('', 25)} | ${this._leftPad('', 30)} |         |`);
A
Alex Dima 已提交
886
						}
887 888
					}
				}
889 890

			}
891
			result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
892 893 894 895 896 897
		}

		return result.join('\n');
	}

	private _leftPad(str: string, cnt: number): string {
A
Alex Dima 已提交
898 899 900
		if (str === null) {
			str = 'null';
		}
901 902 903 904 905 906
		while (str.length < cnt) {
			str = ' ' + str;
		}
		return str;
	}

A
Alex Dima 已提交
907
	public simpleKeybindingToScanCodeBinding(keybinding: SimpleKeybinding): ScanCodeBinding[] {
908 909 910 911 912
		// Avoid double Enter bindings (both ScanCode.NumpadEnter and ScanCode.Enter point to KeyCode.Enter)
		if (keybinding.keyCode === KeyCode.Enter) {
			return [new ScanCodeBinding(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, ScanCode.Enter)];
		}

913 914 915
		const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(
			new KeyCodeCombo(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.keyCode)
		);
916

A
Alex Dima 已提交
917
		let result: ScanCodeBinding[] = [];
918 919
		for (let i = 0, len = scanCodeCombos.length; i < len; i++) {
			const scanCodeCombo = scanCodeCombos[i];
A
Alex Dima 已提交
920
			result[i] = new ScanCodeBinding(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, keybinding.metaKey, scanCodeCombo.scanCode);
921 922 923 924
		}
		return result;
	}

A
Renames  
Alex Dima 已提交
925
	public getUILabelForScanCode(scanCode: ScanCode): string {
926
		if (this._OS === OperatingSystem.Macintosh) {
A
Renames  
Alex Dima 已提交
927 928
			switch (scanCode) {
				case ScanCode.ArrowLeft:
929
					return '';
A
Renames  
Alex Dima 已提交
930
				case ScanCode.ArrowUp:
931
					return '';
A
Renames  
Alex Dima 已提交
932
				case ScanCode.ArrowRight:
933
					return '';
A
Renames  
Alex Dima 已提交
934
				case ScanCode.ArrowDown:
935 936 937
					return '';
			}
		}
A
Renames  
Alex Dima 已提交
938
		return this._scanCodeToLabel[scanCode];
939 940
	}

A
Renames  
Alex Dima 已提交
941 942
	public getAriaLabelForScanCode(scanCode: ScanCode): string {
		return this._scanCodeToLabel[scanCode];
943 944
	}

A
Alex Dima 已提交
945
	public getDispatchStrForScanCodeBinding(keypress: ScanCodeBinding): string {
A
Renames  
Alex Dima 已提交
946
		const codeDispatch = this._scanCodeToDispatch[keypress.scanCode];
A
Alex Dima 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
		if (!codeDispatch) {
			return null;
		}
		let result = '';

		if (keypress.ctrlKey) {
			result += 'ctrl+';
		}
		if (keypress.shiftKey) {
			result += 'shift+';
		}
		if (keypress.altKey) {
			result += 'alt+';
		}
		if (keypress.metaKey) {
			result += 'meta+';
		}
		result += codeDispatch;

		return result;
	}

A
Renames  
Alex Dima 已提交
969 970
	public getUserSettingsLabel(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
971 972 973 974
		if (immutableKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(immutableKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
975
		// Check if this scanCode always maps to the same keyCode and back
976
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
977 978 979 980
		if (constantKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(constantKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
981
		return this._scanCodeToDispatch[scanCode];
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
	}

	private _getElectronLabelForKeyCode(keyCode: KeyCode): string {
		if (keyCode >= KeyCode.NUMPAD_0 && keyCode <= KeyCode.NUMPAD_DIVIDE) {
			// Electron cannot handle numpad keys
			return null;
		}

		switch (keyCode) {
			case KeyCode.UpArrow:
				return 'Up';
			case KeyCode.DownArrow:
				return 'Down';
			case KeyCode.LeftArrow:
				return 'Left';
			case KeyCode.RightArrow:
				return 'Right';
		}

		// electron menus always do the correct rendering on Windows
		return KeyCodeUtils.toString(keyCode);
	}

A
Renames  
Alex Dima 已提交
1005 1006
	public getElectronLabelForScanCode(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
1007 1008 1009 1010
		if (immutableKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(immutableKeyCode);
		}

A
Renames  
Alex Dima 已提交
1011
		// Check if this scanCode always maps to the same keyCode and back
1012
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

		if (!this._isUSStandard) {
			// Electron cannot handle these key codes on anything else than standard US
			const isOEMKey = (
				constantKeyCode === KeyCode.US_SEMICOLON
				|| constantKeyCode === KeyCode.US_EQUAL
				|| constantKeyCode === KeyCode.US_COMMA
				|| constantKeyCode === KeyCode.US_MINUS
				|| constantKeyCode === KeyCode.US_DOT
				|| constantKeyCode === KeyCode.US_SLASH
				|| constantKeyCode === KeyCode.US_BACKTICK
				|| constantKeyCode === KeyCode.US_OPEN_SQUARE_BRACKET
				|| constantKeyCode === KeyCode.US_BACKSLASH
				|| constantKeyCode === KeyCode.US_CLOSE_SQUARE_BRACKET
			);

			if (isOEMKey) {
				return null;
			}
		}

1034 1035 1036 1037 1038 1039 1040
		if (constantKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(constantKeyCode);
		}

		return null;
	}

1041 1042 1043 1044
	public resolveKeybinding(keybinding: Keybinding): NativeResolvedKeybinding[] {
		let result: NativeResolvedKeybinding[] = [], resultLen = 0;

		if (keybinding.type === KeybindingType.Chord) {
A
Alex Dima 已提交
1045 1046
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding.firstPart);
			const chordParts = this.simpleKeybindingToScanCodeBinding(keybinding.chordPart);
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

			for (let i = 0, len = firstParts.length; i < len; i++) {
				const firstPart = firstParts[i];
				for (let j = 0, lenJ = chordParts.length; j < lenJ; j++) {
					const chordPart = chordParts[j];

					result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, chordPart);
				}
			}
		} else {
A
Alex Dima 已提交
1057
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding);
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

			for (let i = 0, len = firstParts.length; i < len; i++) {
				const firstPart = firstParts[i];

				result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, null);
			}
		}

		return result;
	}

1069
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): NativeResolvedKeybinding {
1070
		let code = ScanCodeUtils.toEnum(keyboardEvent.code);
1071

1072 1073 1074 1075
		// Treat NumpadEnter as Enter
		if (code === ScanCode.NumpadEnter) {
			code = ScanCode.Enter;
		}
1076

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
		if (this._OS === OperatingSystem.Macintosh && this._isISOKeyboard) {
			// See https://github.com/Microsoft/vscode/issues/24153
			// On OSX, on ISO keyboards, Chromium swaps the scan codes
			// of IntlBackslash and Backquote.

			switch (code) {
				case ScanCode.IntlBackslash:
					code = ScanCode.Backquote;
					break;
				case ScanCode.Backquote:
					code = ScanCode.IntlBackslash;
					break;
			}
		}

1092 1093
		const keyCode = keyboardEvent.keyCode;

1094
		if (
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
			(keyCode === KeyCode.LeftArrow)
			|| (keyCode === KeyCode.UpArrow)
			|| (keyCode === KeyCode.RightArrow)
			|| (keyCode === KeyCode.DownArrow)
			|| (keyCode === KeyCode.Delete)
			|| (keyCode === KeyCode.Insert)
			|| (keyCode === KeyCode.Home)
			|| (keyCode === KeyCode.End)
			|| (keyCode === KeyCode.PageDown)
			|| (keyCode === KeyCode.PageUp)
1105
		) {
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
			// "Dispatch" on keyCode for these key codes to workaround issues with remote desktoping software
			// where the scan codes appear to be incorrect (see https://github.com/Microsoft/vscode/issues/24107)
			const immutableScanCode = IMMUTABLE_KEY_CODE_TO_CODE[keyCode];
			if (immutableScanCode !== -1) {
				code = immutableScanCode;
			}

		} else {

			if (
				(code === ScanCode.Numpad1)
				|| (code === ScanCode.Numpad2)
				|| (code === ScanCode.Numpad3)
				|| (code === ScanCode.Numpad4)
				|| (code === ScanCode.Numpad5)
				|| (code === ScanCode.Numpad6)
				|| (code === ScanCode.Numpad7)
				|| (code === ScanCode.Numpad8)
				|| (code === ScanCode.Numpad9)
				|| (code === ScanCode.Numpad0)
				|| (code === ScanCode.NumpadDecimal)
			) {
				// "Dispatch" on keyCode for all numpad keys in order for NumLock to work correctly
				if (keyCode >= 0) {
					const immutableScanCode = IMMUTABLE_KEY_CODE_TO_CODE[keyCode];
					if (immutableScanCode !== -1) {
						code = immutableScanCode;
					}
1134 1135 1136 1137
				}
			}
		}

1138
		const keypress = new ScanCodeBinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, code);
1139 1140 1141
		return new NativeResolvedKeybinding(this, this._OS, keypress, null);
	}

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	private _resolveSimpleUserBinding(binding: SimpleKeybinding | ScanCodeBinding): ScanCodeBinding[] {
		if (!binding) {
			return [];
		}
		if (binding instanceof ScanCodeBinding) {
			return [binding];
		}
		return this.simpleKeybindingToScanCodeBinding(binding);
	}

A
Alex Dima 已提交
1152 1153 1154
	public resolveUserBinding(_firstPart: SimpleKeybinding | ScanCodeBinding, _chordPart: SimpleKeybinding | ScanCodeBinding): ResolvedKeybinding[] {
		const firstParts = this._resolveSimpleUserBinding(_firstPart);
		const chordParts = this._resolveSimpleUserBinding(_chordPart);
1155 1156 1157 1158

		let result: NativeResolvedKeybinding[] = [], resultLen = 0;
		for (let i = 0, len = firstParts.length; i < len; i++) {
			const firstPart = firstParts[i];
A
Alex Dima 已提交
1159 1160 1161
			if (_chordPart) {
				for (let j = 0, lenJ = chordParts.length; j < lenJ; j++) {
					const chordPart = chordParts[j];
1162

A
Alex Dima 已提交
1163 1164 1165 1166
					result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, chordPart);
				}
			} else {
				result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, null);
1167 1168 1169 1170 1171
			}
		}
		return result;
	}

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
	private static _charCodeToKb(charCode: number): { keyCode: KeyCode; shiftKey: boolean } {
		if (charCode < CHAR_CODE_TO_KEY_CODE.length) {
			return CHAR_CODE_TO_KEY_CODE[charCode];
		}
		return null;
	}

	/**
	 * Attempt to map a combining character to a regular one that renders the same way.
	 *
	 * To the brave person following me: Good Luck!
	 * https://www.compart.com/en/unicode/bidiclass/NSM
	 */
	private static _getCharCode(char: string): number {
		if (char.length === 0) {
			return 0;
		}
		const charCode = char.charCodeAt(0);
		switch (charCode) {
			case CharCode.U_Combining_Grave_Accent: return CharCode.U_GRAVE_ACCENT;
			case CharCode.U_Combining_Acute_Accent: return CharCode.U_ACUTE_ACCENT;
			case CharCode.U_Combining_Circumflex_Accent: return CharCode.U_CIRCUMFLEX;
			case CharCode.U_Combining_Tilde: return CharCode.U_SMALL_TILDE;
			case CharCode.U_Combining_Macron: return CharCode.U_MACRON;
			case CharCode.U_Combining_Overline: return CharCode.U_OVERLINE;
			case CharCode.U_Combining_Breve: return CharCode.U_BREVE;
			case CharCode.U_Combining_Dot_Above: return CharCode.U_DOT_ABOVE;
			case CharCode.U_Combining_Diaeresis: return CharCode.U_DIAERESIS;
			case CharCode.U_Combining_Ring_Above: return CharCode.U_RING_ABOVE;
			case CharCode.U_Combining_Double_Acute_Accent: return CharCode.U_DOUBLE_ACUTE_ACCENT;
		}
		return charCode;
	}
}

(function () {
	function define(charCode: number, keyCode: KeyCode, shiftKey: boolean): void {
		for (let i = CHAR_CODE_TO_KEY_CODE.length; i < charCode; i++) {
			CHAR_CODE_TO_KEY_CODE[i] = null;
		}
		CHAR_CODE_TO_KEY_CODE[charCode] = { keyCode: keyCode, shiftKey: shiftKey };
	}

	for (let chCode = CharCode.A; chCode <= CharCode.Z; chCode++) {
		define(chCode, KeyCode.KEY_A + (chCode - CharCode.A), true);
	}

	for (let chCode = CharCode.a; chCode <= CharCode.z; chCode++) {
		define(chCode, KeyCode.KEY_A + (chCode - CharCode.a), false);
	}

	define(CharCode.Semicolon, KeyCode.US_SEMICOLON, false);
	define(CharCode.Colon, KeyCode.US_SEMICOLON, true);

	define(CharCode.Equals, KeyCode.US_EQUAL, false);
	define(CharCode.Plus, KeyCode.US_EQUAL, true);

	define(CharCode.Comma, KeyCode.US_COMMA, false);
	define(CharCode.LessThan, KeyCode.US_COMMA, true);

	define(CharCode.Dash, KeyCode.US_MINUS, false);
	define(CharCode.Underline, KeyCode.US_MINUS, true);

	define(CharCode.Period, KeyCode.US_DOT, false);
	define(CharCode.GreaterThan, KeyCode.US_DOT, true);

	define(CharCode.Slash, KeyCode.US_SLASH, false);
	define(CharCode.QuestionMark, KeyCode.US_SLASH, true);

	define(CharCode.BackTick, KeyCode.US_BACKTICK, false);
	define(CharCode.Tilde, KeyCode.US_BACKTICK, true);

	define(CharCode.OpenSquareBracket, KeyCode.US_OPEN_SQUARE_BRACKET, false);
	define(CharCode.OpenCurlyBrace, KeyCode.US_OPEN_SQUARE_BRACKET, true);

	define(CharCode.Backslash, KeyCode.US_BACKSLASH, false);
	define(CharCode.Pipe, KeyCode.US_BACKSLASH, true);

	define(CharCode.CloseSquareBracket, KeyCode.US_CLOSE_SQUARE_BRACKET, false);
	define(CharCode.CloseCurlyBrace, KeyCode.US_CLOSE_SQUARE_BRACKET, true);

	define(CharCode.SingleQuote, KeyCode.US_QUOTE, false);
	define(CharCode.DoubleQuote, KeyCode.US_QUOTE, true);
})();