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

import { CharCode } from 'vs/base/common/charCode';
7
import { KeyCode, KeyCodeUtils, Keybinding, ResolvedKeybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
A
Alex Dima 已提交
8 9
import { OperatingSystem } from 'vs/base/common/platform';
import { IMMUTABLE_CODE_TO_KEY_CODE, IMMUTABLE_KEY_CODE_TO_CODE, ScanCode, ScanCodeBinding, ScanCodeUtils } from 'vs/base/common/scanCode';
10
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
A
Alex Dima 已提交
11
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
12
import { BaseResolvedKeybinding } from 'vs/platform/keybinding/common/baseResolvedKeybinding';
13

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

A
Alex Dima 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33
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
	);
34 35
}

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

A
Alex Dima 已提交
40
export function macLinuxKeyboardMappingEquals(a: IMacLinuxKeyboardMapping | null, b: IMacLinuxKeyboardMapping | null): boolean {
A
Alex Dima 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
	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;
}

A
Renames  
Alex Dima 已提交
58 59 60 61 62 63
/**
 * 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 }
 */
A
Alex Dima 已提交
64
const CHAR_CODE_TO_KEY_CODE: ({ keyCode: KeyCode; shiftKey: boolean } | null)[] = [];
65

A
Alex Dima 已提交
66
export class NativeResolvedKeybinding extends BaseResolvedKeybinding<ScanCodeBinding> {
67 68 69

	private readonly _mapper: MacLinuxKeyboardMapper;

A
Alex Dima 已提交
70 71
	constructor(mapper: MacLinuxKeyboardMapper, os: OperatingSystem, parts: ScanCodeBinding[]) {
		super(os, parts);
72 73 74
		this._mapper = mapper;
	}

A
Alex Dima 已提交
75 76
	protected _getLabel(keybinding: ScanCodeBinding): string | null {
		return this._mapper.getUILabelForScanCodeBinding(keybinding);
77 78
	}

A
Alex Dima 已提交
79 80
	protected _getAriaLabel(keybinding: ScanCodeBinding): string | null {
		return this._mapper.getAriaLabelForScanCodeBinding(keybinding);
81 82
	}

A
Alex Dima 已提交
83 84
	protected _getElectronAccelerator(keybinding: ScanCodeBinding): string | null {
		return this._mapper.getElectronAcceleratorLabelForScanCodeBinding(keybinding);
85 86
	}

A
Alex Dima 已提交
87 88
	protected _getUserSettingsLabel(keybinding: ScanCodeBinding): string | null {
		return this._mapper.getUserSettingsLabelForScanCodeBinding(keybinding);
89 90
	}

A
Alex Dima 已提交
91
	protected _isWYSIWYG(binding: ScanCodeBinding | null): boolean {
92
		if (!binding) {
93 94
			return true;
		}
95 96 97 98 99
		if (IMMUTABLE_CODE_TO_KEY_CODE[binding.scanCode] !== -1) {
			return true;
		}
		let a = this._mapper.getAriaLabelForScanCodeBinding(binding);
		let b = this._mapper.getUserSettingsLabelForScanCodeBinding(binding);
100 101 102 103 104 105 106 107 108 109

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

A
Alex Dima 已提交
110 111
	protected _getDispatchPart(keybinding: ScanCodeBinding): string | null {
		return this._mapper.getDispatchStrForScanCodeBinding(keybinding);
112 113 114
	}
}

A
Renames  
Alex Dima 已提交
115 116
interface IScanCodeMapping {
	scanCode: ScanCode;
117 118 119 120 121 122
	value: number;
	withShift: number;
	withAltGr: number;
	withShiftAltGr: number;
}

123 124 125 126 127 128 129 130 131 132 133 134
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 已提交
135 136 137 138 139

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

A
Alex Dima 已提交
140 141 142 143 144 145 146 147 148
	public equals(other: ScanCodeCombo): boolean {
		return (
			this.ctrlKey === other.ctrlKey
			&& this.shiftKey === other.shiftKey
			&& this.altKey === other.altKey
			&& this.scanCode === other.scanCode
		);
	}

149
	private getProducedCharCode(mapping: IMacLinuxKeyMapping): string {
A
Alex Dima 已提交
150
		if (!mapping) {
151
			return '';
A
Alex Dima 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164
		}
		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;
	}

165 166
	public getProducedChar(mapping: IMacLinuxKeyMapping): string {
		const charCode = MacLinuxKeyboardMapper.getCharCode(this.getProducedCharCode(mapping));
A
Alex Dima 已提交
167 168 169 170 171 172 173 174 175
		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) + '  ';
	}
176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

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 已提交
190 191 192 193

	public toString(): string {
		return `${this.ctrlKey ? 'Ctrl+' : ''}${this.shiftKey ? 'Shift+' : ''}${this.altKey ? 'Alt+' : ''}${KeyCodeUtils.toString(this.keyCode)}`;
	}
194 195 196 197 198 199 200 201
}

class ScanCodeKeyCodeMapper {

	/**
	 * ScanCode combination => KeyCode combination.
	 * Only covers relevant modifiers ctrl, shift, alt (since meta does not influence the mappings).
	 */
202
	private readonly _scanCodeToKeyCode: number[][] = [];
203 204 205 206 207 208 209 210 211 212 213 214
	/**
	 * 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 已提交
215 216
	public registrationComplete(): void {
		// IntlHash and IntlBackslash are rare keys, so ensure they don't end up being the preferred...
217 218
		this._moveToEnd(ScanCode.IntlHash);
		this._moveToEnd(ScanCode.IntlBackslash);
A
Alex Dima 已提交
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
	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;
					}
				}
			}
		}
	}
246 247

	public registerIfUnknown(scanCodeCombo: ScanCodeCombo, keyCodeCombo: KeyCodeCombo): void {
248 249 250
		if (keyCodeCombo.keyCode === KeyCode.Unknown) {
			return;
		}
251 252 253
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
		const keyCodeComboEncoded = this._encodeKeyCodeCombo(keyCodeCombo);

A
Alex Dima 已提交
254 255 256
		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 已提交
257
		const existingKeyCodeCombos = this._scanCodeToKeyCode[scanCodeComboEncoded];
A
Alex Dima 已提交
258 259 260 261

		// 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 已提交
262 263 264
			if (existingKeyCodeCombos) {
				for (let i = 0, len = existingKeyCodeCombos.length; i < len; i++) {
					if (existingKeyCodeCombos[i] === keyCodeComboEncoded) {
A
Alex Dima 已提交
265 266 267 268 269 270 271
						// avoid duplicates
						return;
					}
				}
			}
		} else {
			// Don't allow multiples
A
Alex Dima 已提交
272
			if (existingKeyCodeCombos && existingKeyCodeCombos.length !== 0) {
A
Alex Dima 已提交
273 274
				return;
			}
275 276
		}

277 278
		this._scanCodeToKeyCode[scanCodeComboEncoded] = this._scanCodeToKeyCode[scanCodeComboEncoded] || [];
		this._scanCodeToKeyCode[scanCodeComboEncoded].unshift(keyCodeComboEncoded);
279

280 281
		this._keyCodeToScanCode[keyCodeComboEncoded] = this._keyCodeToScanCode[keyCodeComboEncoded] || [];
		this._keyCodeToScanCode[keyCodeComboEncoded].unshift(scanCodeComboEncoded);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
	}

	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;
	}

305
	public lookupScanCodeCombo(scanCodeCombo: ScanCodeCombo): KeyCodeCombo[] {
306
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
307 308 309 310 311 312 313 314
		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];
315

316 317 318 319
			const ctrlKey = (keyCodeComboEncoded & 0b001) ? true : false;
			const shiftKey = (keyCodeComboEncoded & 0b010) ? true : false;
			const altKey = (keyCodeComboEncoded & 0b100) ? true : false;
			const keyCode: KeyCode = (keyCodeComboEncoded >>> 3);
320

321 322 323
			result[i] = new KeyCodeCombo(ctrlKey, shiftKey, altKey, keyCode);
		}
		return result;
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
	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;
	}

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
	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;
	}
}

378 379
export class MacLinuxKeyboardMapper implements IKeyboardMapper {

380 381
	/**
	 * Is this the standard US keyboard layout?
382 383
	 */
	private readonly _isUSStandard: boolean;
A
Renames  
Alex Dima 已提交
384 385 386
	/**
	 * OS (can be Linux or Macintosh)
	 */
387
	private readonly _OS: OperatingSystem;
388 389 390
	/**
	 * used only for debug purposes.
	 */
391
	private readonly _codeInfo: IMacLinuxKeyMapping[];
A
Renames  
Alex Dima 已提交
392
	/**
393
	 * Maps ScanCode combos <-> KeyCode combos.
A
Renames  
Alex Dima 已提交
394
	 */
395
	private readonly _scanCodeKeyCodeMapper: ScanCodeKeyCodeMapper;
A
Renames  
Alex Dima 已提交
396 397 398
	/**
	 * UI label for a ScanCode.
	 */
399
	private readonly _scanCodeToLabel: Array<string | null> = [];
400
	/**
A
Renames  
Alex Dima 已提交
401
	 * Dispatching string for a ScanCode.
402
	 */
403
	private readonly _scanCodeToDispatch: Array<string | null> = [];
404

405
	constructor(isUSStandard: boolean, rawMappings: IMacLinuxKeyboardMapping, OS: OperatingSystem) {
406
		this._isUSStandard = isUSStandard;
407
		this._OS = OS;
408 409
		this._codeInfo = [];
		this._scanCodeKeyCodeMapper = new ScanCodeKeyCodeMapper();
A
Renames  
Alex Dima 已提交
410 411
		this._scanCodeToLabel = [];
		this._scanCodeToDispatch = [];
412

A
Alex Dima 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
		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
						);
					}
				}
			}
		};

436 437 438 439 440 441 442 443 444 445 446
		// 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 已提交
447 448 449
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			const keyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
			if (keyCode !== -1) {
A
Alex Dima 已提交
450
				_registerAllCombos(0, 0, 0, scanCode, keyCode);
A
Renames  
Alex Dima 已提交
451
				this._scanCodeToLabel[scanCode] = KeyCodeUtils.toString(keyCode);
A
Alex Dima 已提交
452

A
Renames  
Alex Dima 已提交
453 454
				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 已提交
455
				} else {
A
Renames  
Alex Dima 已提交
456
					this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
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
		// Try to identify keyboard layouts where characters A-Z are missing
		// and forcefully map them to their corresponding scan codes if that is the case
		const missingLatinLettersOverride: { [scanCode: string]: IMacLinuxKeyMapping; } = {};

		{
			let producesLatinLetter: boolean[] = [];
			for (let strScanCode in rawMappings) {
				if (rawMappings.hasOwnProperty(strScanCode)) {
					const scanCode = ScanCodeUtils.toEnum(strScanCode);
					if (scanCode === ScanCode.None) {
						continue;
					}
					if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
						continue;
					}

					const rawMapping = rawMappings[strScanCode];
					const value = MacLinuxKeyboardMapper.getCharCode(rawMapping.value);

					if (value >= CharCode.a && value <= CharCode.z) {
						const upperCaseValue = CharCode.A + (value - CharCode.a);
						producesLatinLetter[upperCaseValue] = true;
					}
				}
			}

			const _registerLetterIfMissing = (charCode: CharCode, scanCode: ScanCode, value: string, withShift: string): void => {
				if (!producesLatinLetter[charCode]) {
					missingLatinLettersOverride[ScanCodeUtils.toString(scanCode)] = {
						value: value,
						withShift: withShift,
						withAltGr: '',
						withShiftAltGr: ''
					};
				}
			};

			// Ensure letters are mapped
			_registerLetterIfMissing(CharCode.A, ScanCode.KeyA, 'a', 'A');
			_registerLetterIfMissing(CharCode.B, ScanCode.KeyB, 'b', 'B');
			_registerLetterIfMissing(CharCode.C, ScanCode.KeyC, 'c', 'C');
			_registerLetterIfMissing(CharCode.D, ScanCode.KeyD, 'd', 'D');
			_registerLetterIfMissing(CharCode.E, ScanCode.KeyE, 'e', 'E');
			_registerLetterIfMissing(CharCode.F, ScanCode.KeyF, 'f', 'F');
			_registerLetterIfMissing(CharCode.G, ScanCode.KeyG, 'g', 'G');
			_registerLetterIfMissing(CharCode.H, ScanCode.KeyH, 'h', 'H');
			_registerLetterIfMissing(CharCode.I, ScanCode.KeyI, 'i', 'I');
			_registerLetterIfMissing(CharCode.J, ScanCode.KeyJ, 'j', 'J');
			_registerLetterIfMissing(CharCode.K, ScanCode.KeyK, 'k', 'K');
			_registerLetterIfMissing(CharCode.L, ScanCode.KeyL, 'l', 'L');
			_registerLetterIfMissing(CharCode.M, ScanCode.KeyM, 'm', 'M');
			_registerLetterIfMissing(CharCode.N, ScanCode.KeyN, 'n', 'N');
			_registerLetterIfMissing(CharCode.O, ScanCode.KeyO, 'o', 'O');
			_registerLetterIfMissing(CharCode.P, ScanCode.KeyP, 'p', 'P');
			_registerLetterIfMissing(CharCode.Q, ScanCode.KeyQ, 'q', 'Q');
			_registerLetterIfMissing(CharCode.R, ScanCode.KeyR, 'r', 'R');
			_registerLetterIfMissing(CharCode.S, ScanCode.KeyS, 's', 'S');
			_registerLetterIfMissing(CharCode.T, ScanCode.KeyT, 't', 'T');
			_registerLetterIfMissing(CharCode.U, ScanCode.KeyU, 'u', 'U');
			_registerLetterIfMissing(CharCode.V, ScanCode.KeyV, 'v', 'V');
			_registerLetterIfMissing(CharCode.W, ScanCode.KeyW, 'w', 'W');
			_registerLetterIfMissing(CharCode.X, ScanCode.KeyX, 'x', 'X');
			_registerLetterIfMissing(CharCode.Y, ScanCode.KeyY, 'y', 'Y');
			_registerLetterIfMissing(CharCode.Z, ScanCode.KeyZ, 'z', 'Z');
		}

A
Renames  
Alex Dima 已提交
527 528 529 530 531
		let mappings: IScanCodeMapping[] = [], mappingsLen = 0;
		for (let strScanCode in rawMappings) {
			if (rawMappings.hasOwnProperty(strScanCode)) {
				const scanCode = ScanCodeUtils.toEnum(strScanCode);
				if (scanCode === ScanCode.None) {
532 533
					continue;
				}
A
Renames  
Alex Dima 已提交
534
				if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
535 536 537
					continue;
				}

538 539 540 541 542 543 544
				this._codeInfo[scanCode] = rawMappings[strScanCode];

				const rawMapping = missingLatinLettersOverride[strScanCode] || rawMappings[strScanCode];
				const value = MacLinuxKeyboardMapper.getCharCode(rawMapping.value);
				const withShift = MacLinuxKeyboardMapper.getCharCode(rawMapping.withShift);
				const withAltGr = MacLinuxKeyboardMapper.getCharCode(rawMapping.withAltGr);
				const withShiftAltGr = MacLinuxKeyboardMapper.getCharCode(rawMapping.withShiftAltGr);
545

A
Renames  
Alex Dima 已提交
546 547
				const mapping: IScanCodeMapping = {
					scanCode: scanCode,
548 549 550 551 552 553 554
					value: value,
					withShift: withShift,
					withAltGr: withAltGr,
					withShiftAltGr: withShiftAltGr,
				};
				mappings[mappingsLen++] = mapping;

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

557
				if (value >= CharCode.a && value <= CharCode.z) {
558 559 560 561
					const upperCaseValue = CharCode.A + (value - CharCode.a);
					this._scanCodeToLabel[scanCode] = String.fromCharCode(upperCaseValue);
				} else if (value >= CharCode.A && value <= CharCode.Z) {
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
562
				} else if (value) {
A
Renames  
Alex Dima 已提交
563
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
564
				} else {
A
Renames  
Alex Dima 已提交
565
					this._scanCodeToLabel[scanCode] = null;
566 567 568 569 570 571 572
				}
			}
		}

		// Handle all `withShiftAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
573
			const scanCode = mapping.scanCode;
574 575 576 577 578
			const withShiftAltGr = mapping.withShiftAltGr;
			if (withShiftAltGr === mapping.withAltGr || withShiftAltGr === mapping.withShift || withShiftAltGr === mapping.value) {
				// handled below
				continue;
			}
579 580 581 582 583 584 585
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShiftAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

586 587
			if (kbShiftKey) {
				// Ctrl+Shift+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
588
				_registerIfUnknown(1, 1, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
589 590
			} else {
				// Ctrl+Shift+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
591
				_registerIfUnknown(1, 1, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
592
			}
593 594 595 596
		}
		// Handle all `withAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
597
			const scanCode = mapping.scanCode;
598 599 600 601 602
			const withAltGr = mapping.withAltGr;
			if (withAltGr === mapping.withShift || withAltGr === mapping.value) {
				// handled below
				continue;
			}
603 604 605 606 607 608 609
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

610 611
			if (kbShiftKey) {
				// Ctrl+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
612
				_registerIfUnknown(1, 0, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
613 614
			} else {
				// Ctrl+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
615
				_registerIfUnknown(1, 0, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
616
			}
617 618 619 620
		}
		// Handle all `withShift` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
621
			const scanCode = mapping.scanCode;
622 623 624 625 626
			const withShift = mapping.withShift;
			if (withShift === mapping.value) {
				// handled below
				continue;
			}
627 628 629 630 631 632 633
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShift);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

634 635
			if (kbShiftKey) {
				// Shift+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
636 637 638 639
				_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
640 641
			} else {
				// Shift+ScanCode => KeyCode
A
Alex Dima 已提交
642 643 644 645 646 647 648 649
				_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
650
			}
651 652 653 654
		}
		// Handle all `value` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
655 656 657 658 659 660 661 662
			const scanCode = mapping.scanCode;
			const kb = MacLinuxKeyboardMapper._charCodeToKb(mapping.value);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

663 664
			if (kbShiftKey) {
				// ScanCode => Shift+KeyCode
A
Alex Dima 已提交
665 666 667 668
				_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
669 670
			} else {
				// ScanCode => KeyCode
A
Alex Dima 已提交
671 672 673 674 675 676 677 678
				_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
679
			}
680
		}
681
		// Handle all left-over available digits
A
Alex Dima 已提交
682 683 684 685 686 687 688 689 690 691
		_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 已提交
692

A
Alex Dima 已提交
693
		this._scanCodeKeyCodeMapper.registrationComplete();
694 695 696 697 698
	}

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

699 700 701 702 703
		let immutableSamples = [
			ScanCode.ArrowUp,
			ScanCode.Numpad0
		];

704
		let cnt = 0;
705
		result.push(`isUSStandard: ${this._isUSStandard}`);
706
		result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
A
Renames  
Alex Dima 已提交
707 708
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
709 710 711
				if (immutableSamples.indexOf(scanCode) === -1) {
					continue;
				}
712 713 714
			}

			if (cnt % 4 === 0) {
715 716
				result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
				result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
717 718 719
			}
			cnt++;

A
Renames  
Alex Dima 已提交
720
			const mapping = this._codeInfo[scanCode];
721 722

			for (let mod = 0; mod < 8; mod++) {
723 724 725
				const hwCtrlKey = (mod & 0b001) ? true : false;
				const hwShiftKey = (mod & 0b010) ? true : false;
				const hwAltKey = (mod & 0b100) ? true : false;
A
Alex Dima 已提交
726
				const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
727
				const resolvedKb = this.resolveKeyboardEvent({
A
Alex Dima 已提交
728 729 730
					ctrlKey: scanCodeCombo.ctrlKey,
					shiftKey: scanCodeCombo.shiftKey,
					altKey: scanCodeCombo.altKey,
731 732 733 734
					metaKey: false,
					keyCode: -1,
					code: ScanCodeUtils.toString(scanCode)
				});
735

A
Alex Dima 已提交
736 737 738 739 740 741 742 743
				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];

744 745 746
				const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false);
				const outWYSIWYG = (isWYSIWYG ? '       ' : '   NO  ');

A
Alex Dima 已提交
747
				const kbCombos = this._scanCodeKeyCodeMapper.lookupScanCodeCombo(scanCodeCombo);
748
				if (kbCombos.length === 0) {
749
					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} |`);
750 751 752
				} else {
					for (let i = 0, len = kbCombos.length; i < len; i++) {
						const kbCombo = kbCombos[i];
A
Alex Dima 已提交
753
						// find out the priority of this scan code for this key code
A
Alex Dima 已提交
754
						let colPriority: string;
A
Alex Dima 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770

						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 已提交
771
						const outKeybinding = kbCombo.toString();
A
Alex Dima 已提交
772
						if (i === 0) {
773
							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 已提交
774 775
						} else {
							// secondary keybindings
776
							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 已提交
777
						}
778 779
					}
				}
780 781

			}
782
			result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
783 784 785 786 787
		}

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

A
Alex Dima 已提交
788
	private _leftPad(str: string | null, cnt: number): string {
A
Alex Dima 已提交
789 790 791
		if (str === null) {
			str = 'null';
		}
792 793 794 795 796 797
		while (str.length < cnt) {
			str = ' ' + str;
		}
		return str;
	}

A
Alex Dima 已提交
798
	public simpleKeybindingToScanCodeBinding(keybinding: SimpleKeybinding): ScanCodeBinding[] {
799 800 801 802 803
		// 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)];
		}

804 805 806
		const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(
			new KeyCodeCombo(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.keyCode)
		);
807

A
Alex Dima 已提交
808
		let result: ScanCodeBinding[] = [];
809 810
		for (let i = 0, len = scanCodeCombos.length; i < len; i++) {
			const scanCodeCombo = scanCodeCombos[i];
A
Alex Dima 已提交
811
			result[i] = new ScanCodeBinding(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, keybinding.metaKey, scanCodeCombo.scanCode);
812 813 814 815
		}
		return result;
	}

A
Alex Dima 已提交
816
	public getUILabelForScanCodeBinding(binding: ScanCodeBinding | null): string | null {
817 818 819 820 821 822
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
823
		if (this._OS === OperatingSystem.Macintosh) {
824
			switch (binding.scanCode) {
A
Renames  
Alex Dima 已提交
825
				case ScanCode.ArrowLeft:
826
					return '';
A
Renames  
Alex Dima 已提交
827
				case ScanCode.ArrowUp:
828
					return '';
A
Renames  
Alex Dima 已提交
829
				case ScanCode.ArrowRight:
830
					return '';
A
Renames  
Alex Dima 已提交
831
				case ScanCode.ArrowDown:
832 833 834
					return '';
			}
		}
835
		return this._scanCodeToLabel[binding.scanCode];
836 837
	}

A
Alex Dima 已提交
838
	public getAriaLabelForScanCodeBinding(binding: ScanCodeBinding | null): string | null {
839 840 841 842 843 844 845
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._scanCodeToLabel[binding.scanCode];
846 847
	}

A
Alex Dima 已提交
848
	public getDispatchStrForScanCodeBinding(keypress: ScanCodeBinding): string | null {
A
Renames  
Alex Dima 已提交
849
		const codeDispatch = this._scanCodeToDispatch[keypress.scanCode];
A
Alex Dima 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
		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
Alex Dima 已提交
872
	public getUserSettingsLabelForScanCodeBinding(binding: ScanCodeBinding | null): string | null {
873 874 875 876 877 878 879 880
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}

		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[binding.scanCode];
881
		if (immutableKeyCode !== -1) {
882
			return KeyCodeUtils.toUserSettingsUS(immutableKeyCode).toLowerCase();
883 884
		}

A
Renames  
Alex Dima 已提交
885
		// Check if this scanCode always maps to the same keyCode and back
886
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(binding.scanCode);
887
		if (constantKeyCode !== -1) {
888 889 890 891 892
			// Verify that this is a good key code that can be mapped back to the same scan code
			let reverseBindings = this.simpleKeybindingToScanCodeBinding(new SimpleKeybinding(binding.ctrlKey, binding.shiftKey, binding.altKey, binding.metaKey, constantKeyCode));
			for (let i = 0, len = reverseBindings.length; i < len; i++) {
				const reverseBinding = reverseBindings[i];
				if (reverseBinding.scanCode === binding.scanCode) {
893
					return KeyCodeUtils.toUserSettingsUS(constantKeyCode).toLowerCase();
894 895
				}
			}
896 897
		}

898
		return this._scanCodeToDispatch[binding.scanCode];
899 900
	}

A
Alex Dima 已提交
901
	private _getElectronLabelForKeyCode(keyCode: KeyCode): string | null {
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
		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
Alex Dima 已提交
922
	public getElectronAcceleratorLabelForScanCodeBinding(binding: ScanCodeBinding | null): string | null {
923 924 925 926 927 928 929 930
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return null;
		}

		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[binding.scanCode];
931 932 933 934
		if (immutableKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(immutableKeyCode);
		}

A
Renames  
Alex Dima 已提交
935
		// Check if this scanCode always maps to the same keyCode and back
936
		const constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(binding.scanCode);
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

		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;
			}
		}

958 959 960 961 962 963 964
		if (constantKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(constantKeyCode);
		}

		return null;
	}

965
	public resolveKeybinding(keybinding: Keybinding): NativeResolvedKeybinding[] {
966 967 968 969
		let chordParts: ScanCodeBinding[][] = [];
		for (let part of keybinding.parts) {
			chordParts.push(this.simpleKeybindingToScanCodeBinding(part));
		}
970
		let result: NativeResolvedKeybinding[] = [];
A
Alex Dima 已提交
971
		this._generateResolvedKeybindings(chordParts, 0, [], result);
972 973
		return result;
	}
974

A
Alex Dima 已提交
975
	private _generateResolvedKeybindings(chordParts: ScanCodeBinding[][], currentIndex: number, previousParts: ScanCodeBinding[], result: NativeResolvedKeybinding[]) {
976 977 978 979 980 981 982
		const chordPart = chordParts[currentIndex];
		const isFinalIndex = currentIndex === chordParts.length - 1;
		for (let i = 0, len = chordPart.length; i < len; i++) {
			let chords = [...previousParts, chordPart[i]];
			if (isFinalIndex) {
				result.push(new NativeResolvedKeybinding(this, this._OS, chords));
			} else {
A
Alex Dima 已提交
983
				this._generateResolvedKeybindings(chordParts, currentIndex + 1, chords, result);
984 985 986 987
			}
		}
	}

988
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): NativeResolvedKeybinding {
989
		let code = ScanCodeUtils.toEnum(keyboardEvent.code);
990

991 992 993 994
		// Treat NumpadEnter as Enter
		if (code === ScanCode.NumpadEnter) {
			code = ScanCode.Enter;
		}
995

996 997
		const keyCode = keyboardEvent.keyCode;

998
		if (
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
			(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)
1009
		) {
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
			// "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;
					}
1038 1039 1040 1041
				}
			}
		}

1042
		const keypress = new ScanCodeBinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, code);
1043
		return new NativeResolvedKeybinding(this, this._OS, [keypress]);
1044 1045
	}

A
Alex Dima 已提交
1046
	private _resolveSimpleUserBinding(binding: SimpleKeybinding | ScanCodeBinding | null): ScanCodeBinding[] {
1047 1048 1049 1050 1051 1052 1053 1054 1055
		if (!binding) {
			return [];
		}
		if (binding instanceof ScanCodeBinding) {
			return [binding];
		}
		return this.simpleKeybindingToScanCodeBinding(binding);
	}

A
Alex Dima 已提交
1056
	public resolveUserBinding(_firstPart: SimpleKeybinding | ScanCodeBinding | null, _chordPart: SimpleKeybinding | ScanCodeBinding | null): ResolvedKeybinding[] {
A
Alex Dima 已提交
1057
		let parts: ScanCodeBinding[][] = [];
1058
		if (_firstPart) {
A
Alex Dima 已提交
1059
			parts.push(this._resolveSimpleUserBinding(_firstPart));
1060 1061
		}
		if (_chordPart) {
A
Alex Dima 已提交
1062
			parts.push(this._resolveSimpleUserBinding(_chordPart));
1063
		}
1064
		let result: NativeResolvedKeybinding[] = [];
A
Alex Dima 已提交
1065
		this._generateResolvedKeybindings(parts, 0, [], result);
1066 1067 1068
		return result;
	}

A
Alex Dima 已提交
1069
	private static _charCodeToKb(charCode: number): { keyCode: KeyCode; shiftKey: boolean } | null {
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
		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
	 */
1082
	public static getCharCode(char: string): number {
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 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 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
		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);
})();