macLinuxKeyboardMapper.ts 44.1 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, ResolvedKeybindingPart } 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 } 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 112 113 114 115
	private _getAriaLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._mapper.getAriaLabelForScanCode(binding.scanCode);
	}

116
	public getAriaLabel(): string {
117 118
		let firstPart = this._getAriaLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getAriaLabelForScanCodeBinding(this._chordPart);
119 120 121
		return AriaLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
	}

122 123 124 125 126 127 128 129 130 131
	private _getElectronAcceleratorLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return null;
		}
		return this._mapper.getElectronLabelForScanCode(binding.scanCode);
	}

132
	public getElectronAccelerator(): string {
133 134 135 136 137
		if (this._chordPart !== null) {
			// Electron cannot handle chords
			return null;
		}

138
		let firstPart = this._getElectronAcceleratorLabelForScanCodeBinding(this._firstPart);
139
		return ElectronAcceleratorLabelProvider.toLabel(this._firstPart, firstPart, null, null, this._OS);
140 141
	}

142 143 144 145 146 147 148 149 150 151
	private _getUserSettingsLabelForScanCodeBinding(binding: ScanCodeBinding): string {
		if (!binding) {
			return null;
		}
		if (binding.isDuplicateModifierCase()) {
			return '';
		}
		return this._mapper.getUserSettingsLabel(binding.scanCode);
	}

152
	public getUserSettingsLabel(): string {
153 154
		let firstPart = this._getUserSettingsLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getUserSettingsLabelForScanCodeBinding(this._chordPart);
155
		return UserSettingsLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
156 157
	}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
	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;
	}

181
	public isChord(): boolean {
A
Alex Dima 已提交
182
		return (this._chordPart ? true : false);
183 184
	}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
	public getParts(): [ResolvedKeybindingPart, ResolvedKeybindingPart] {
		return [
			this._toResolvedKeybindingPart(this._firstPart),
			this._toResolvedKeybindingPart(this._chordPart)
		];
	}

	private _toResolvedKeybindingPart(binding: ScanCodeBinding): ResolvedKeybindingPart {
		if (!binding) {
			return null;
		}

		return new ResolvedKeybindingPart(
			binding.ctrlKey,
			binding.shiftKey,
			binding.altKey,
			binding.metaKey,
			this._getUILabelForScanCodeBinding(binding),
			this._getAriaLabelForScanCodeBinding(binding)
		);
205 206
	}

207
	public getDispatchParts(): [string, string] {
A
Alex Dima 已提交
208 209
		let firstPart = this._firstPart ? this._mapper.getDispatchStrForScanCodeBinding(this._firstPart) : null;
		let chordPart = this._chordPart ? this._mapper.getDispatchStrForScanCodeBinding(this._chordPart) : null;
210
		return [firstPart, chordPart];
211 212 213
	}
}

A
Renames  
Alex Dima 已提交
214 215
interface IScanCodeMapping {
	scanCode: ScanCode;
216 217 218 219 220 221
	value: number;
	withShift: number;
	withAltGr: number;
	withShiftAltGr: number;
}

222 223 224 225 226 227 228 229 230 231 232 233
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 已提交
234 235 236 237 238

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

A
Alex Dima 已提交
239 240 241 242 243 244 245 246 247
	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 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
	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) + '  ';
	}
275 276 277 278 279 280 281 282 283 284 285 286 287 288
}

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 已提交
289 290 291 292

	public toString(): string {
		return `${this.ctrlKey ? 'Ctrl+' : ''}${this.shiftKey ? 'Shift+' : ''}${this.altKey ? 'Alt+' : ''}${KeyCodeUtils.toString(this.keyCode)}`;
	}
293 294 295 296 297 298 299 300
}

class ScanCodeKeyCodeMapper {

	/**
	 * ScanCode combination => KeyCode combination.
	 * Only covers relevant modifiers ctrl, shift, alt (since meta does not influence the mappings).
	 */
301
	private readonly _scanCodeToKeyCode: number[][] = [];
302 303 304 305 306 307 308 309 310 311 312 313
	/**
	 * 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 已提交
314
	public registrationComplete(): void {
315 316 317 318 319 320 321 322 323 324
		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 已提交
325 326

		// IntlHash and IntlBackslash are rare keys, so ensure they don't end up being the preferred...
327 328
		this._moveToEnd(ScanCode.IntlHash);
		this._moveToEnd(ScanCode.IntlBackslash);
A
Alex Dima 已提交
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
	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;
					}
				}
			}
		}
	}
356 357

	public registerIfUnknown(scanCodeCombo: ScanCodeCombo, keyCodeCombo: KeyCodeCombo): void {
358 359 360
		if (keyCodeCombo.keyCode === KeyCode.Unknown) {
			return;
		}
361 362 363
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
		const keyCodeComboEncoded = this._encodeKeyCodeCombo(keyCodeCombo);

A
Alex Dima 已提交
364 365 366
		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 已提交
367
		const existingKeyCodeCombos = this._scanCodeToKeyCode[scanCodeComboEncoded];
A
Alex Dima 已提交
368 369 370 371

		// 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 已提交
372 373 374
			if (existingKeyCodeCombos) {
				for (let i = 0, len = existingKeyCodeCombos.length; i < len; i++) {
					if (existingKeyCodeCombos[i] === keyCodeComboEncoded) {
A
Alex Dima 已提交
375 376 377 378 379 380 381
						// avoid duplicates
						return;
					}
				}
			}
		} else {
			// Don't allow multiples
A
Alex Dima 已提交
382
			if (existingKeyCodeCombos && existingKeyCodeCombos.length !== 0) {
A
Alex Dima 已提交
383 384
				return;
			}
385 386
		}

387 388
		this._scanCodeToKeyCode[scanCodeComboEncoded] = this._scanCodeToKeyCode[scanCodeComboEncoded] || [];
		this._scanCodeToKeyCode[scanCodeComboEncoded].unshift(keyCodeComboEncoded);
389

390 391
		this._keyCodeToScanCode[keyCodeComboEncoded] = this._keyCodeToScanCode[keyCodeComboEncoded] || [];
		this._keyCodeToScanCode[keyCodeComboEncoded].unshift(scanCodeComboEncoded);
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	}

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

415
	public lookupScanCodeCombo(scanCodeCombo: ScanCodeCombo): KeyCodeCombo[] {
416
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
417 418 419 420 421 422 423 424
		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];
425

426 427 428 429
			const ctrlKey = (keyCodeComboEncoded & 0b001) ? true : false;
			const shiftKey = (keyCodeComboEncoded & 0b010) ? true : false;
			const altKey = (keyCodeComboEncoded & 0b100) ? true : false;
			const keyCode: KeyCode = (keyCodeComboEncoded >>> 3);
430

431 432 433
			result[i] = new KeyCodeCombo(ctrlKey, shiftKey, altKey, keyCode);
		}
		return result;
434 435
	}

436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
	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;
	}

470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	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;
	}
}

488 489
export class MacLinuxKeyboardMapper implements IKeyboardMapper {

490
	/**
491 492 493 494 495
	 * Is the keyboard type ISO (on Mac)
	 */
	private readonly _isISOKeyboard: boolean;
	/**
	 * Is this the standard US keyboard layout?
496 497
	 */
	private readonly _isUSStandard: boolean;
A
Renames  
Alex Dima 已提交
498 499 500
	/**
	 * OS (can be Linux or Macintosh)
	 */
501
	private readonly _OS: OperatingSystem;
502 503 504
	/**
	 * used only for debug purposes.
	 */
A
Renames  
Alex Dima 已提交
505 506
	private readonly _codeInfo: IScanCodeMapping[];
	/**
507
	 * Maps ScanCode combos <-> KeyCode combos.
A
Renames  
Alex Dima 已提交
508
	 */
509
	private readonly _scanCodeKeyCodeMapper: ScanCodeKeyCodeMapper;
A
Renames  
Alex Dima 已提交
510 511 512 513
	/**
	 * UI label for a ScanCode.
	 */
	private readonly _scanCodeToLabel: string[] = [];
514
	/**
A
Renames  
Alex Dima 已提交
515
	 * Dispatching string for a ScanCode.
516
	 */
A
Renames  
Alex Dima 已提交
517
	private readonly _scanCodeToDispatch: string[] = [];
518

519 520
	constructor(isISOKeyboard: boolean, isUSStandard: boolean, rawMappings: IMacLinuxKeyboardMapping, OS: OperatingSystem) {
		this._isISOKeyboard = isISOKeyboard;
521
		this._isUSStandard = isUSStandard;
522
		this._OS = OS;
523 524
		this._codeInfo = [];
		this._scanCodeKeyCodeMapper = new ScanCodeKeyCodeMapper();
A
Renames  
Alex Dima 已提交
525 526
		this._scanCodeToLabel = [];
		this._scanCodeToDispatch = [];
527

A
Alex Dima 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
		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);
			}
		};


559 560 561 562 563 564 565 566 567 568 569
		// 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 已提交
570 571 572
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			const keyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
			if (keyCode !== -1) {
A
Alex Dima 已提交
573
				_registerAllCombos(0, 0, 0, scanCode, keyCode);
A
Renames  
Alex Dima 已提交
574
				this._scanCodeToLabel[scanCode] = KeyCodeUtils.toString(keyCode);
A
Alex Dima 已提交
575

A
Renames  
Alex Dima 已提交
576 577
				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 已提交
578
				} else {
A
Renames  
Alex Dima 已提交
579
					this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
580
				}
581 582 583
			}
		}

A
Renames  
Alex Dima 已提交
584 585 586 587 588 589
		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.`);
590 591
					continue;
				}
A
Renames  
Alex Dima 已提交
592
				if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
593 594 595
					continue;
				}

A
Renames  
Alex Dima 已提交
596
				const rawMapping = rawMappings[strScanCode];
597 598 599 600 601
				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 已提交
602 603
				const mapping: IScanCodeMapping = {
					scanCode: scanCode,
604 605 606 607 608 609
					value: value,
					withShift: withShift,
					withAltGr: withAltGr,
					withShiftAltGr: withShiftAltGr,
				};
				mappings[mappingsLen++] = mapping;
A
Renames  
Alex Dima 已提交
610
				this._codeInfo[scanCode] = mapping;
611

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

614
				if (value >= CharCode.a && value <= CharCode.z) {
615 616 617 618 619 620
					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);
621
				} else if (value) {
A
Renames  
Alex Dima 已提交
622
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
623
				} else {
A
Renames  
Alex Dima 已提交
624
					this._scanCodeToLabel[scanCode] = null;
625 626 627 628 629 630 631
				}
			}
		}

		// Handle all `withShiftAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
632
			const scanCode = mapping.scanCode;
633 634 635 636 637
			const withShiftAltGr = mapping.withShiftAltGr;
			if (withShiftAltGr === mapping.withAltGr || withShiftAltGr === mapping.withShift || withShiftAltGr === mapping.value) {
				// handled below
				continue;
			}
638 639 640 641 642 643 644
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShiftAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

645 646
			if (kbShiftKey) {
				// Ctrl+Shift+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
647
				_registerIfUnknown(1, 1, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
648 649
			} else {
				// Ctrl+Shift+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
650
				_registerIfUnknown(1, 1, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
651
			}
652 653 654 655
		}
		// Handle all `withAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
656
			const scanCode = mapping.scanCode;
657 658 659 660 661
			const withAltGr = mapping.withAltGr;
			if (withAltGr === mapping.withShift || withAltGr === mapping.value) {
				// handled below
				continue;
			}
662 663 664 665 666 667 668
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

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

693 694
			if (kbShiftKey) {
				// Shift+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
695 696 697 698
				_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
699 700
			} else {
				// Shift+ScanCode => KeyCode
A
Alex Dima 已提交
701 702 703 704 705 706 707 708
				_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
709
			}
710 711 712 713
		}
		// Handle all `value` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
714 715 716 717 718 719 720 721
			const scanCode = mapping.scanCode;
			const kb = MacLinuxKeyboardMapper._charCodeToKb(mapping.value);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

722 723
			if (kbShiftKey) {
				// ScanCode => Shift+KeyCode
A
Alex Dima 已提交
724 725 726 727
				_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
728 729
			} else {
				// ScanCode => KeyCode
A
Alex Dima 已提交
730 731 732 733 734 735 736 737
				_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
738
			}
739
		}
740
		// Handle all left-over available digits
A
Alex Dima 已提交
741 742 743 744 745 746 747 748 749 750
		_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 已提交
751

752
		// Ensure letters are mapped
A
Alex Dima 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
		_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);
779

A
Alex Dima 已提交
780
		this._scanCodeKeyCodeMapper.registrationComplete();
781 782 783 784 785
	}

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

786 787 788 789 790
		let immutableSamples = [
			ScanCode.ArrowUp,
			ScanCode.Numpad0
		];

791
		let cnt = 0;
792
		result.push(`isUSStandard: ${this._isUSStandard}`);
793
		result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
A
Renames  
Alex Dima 已提交
794 795
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
796 797 798
				if (immutableSamples.indexOf(scanCode) === -1) {
					continue;
				}
799 800 801
			}

			if (cnt % 4 === 0) {
802 803
				result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
				result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
804 805 806
			}
			cnt++;

A
Renames  
Alex Dima 已提交
807
			const mapping = this._codeInfo[scanCode];
808 809

			for (let mod = 0; mod < 8; mod++) {
810 811 812
				const hwCtrlKey = (mod & 0b001) ? true : false;
				const hwShiftKey = (mod & 0b010) ? true : false;
				const hwAltKey = (mod & 0b100) ? true : false;
A
Alex Dima 已提交
813
				const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
814
				const resolvedKb = this.resolveKeyboardEvent({
A
Alex Dima 已提交
815 816 817
					ctrlKey: scanCodeCombo.ctrlKey,
					shiftKey: scanCodeCombo.shiftKey,
					altKey: scanCodeCombo.altKey,
818 819 820 821
					metaKey: false,
					keyCode: -1,
					code: ScanCodeUtils.toString(scanCode)
				});
822

A
Alex Dima 已提交
823 824 825 826 827 828 829 830
				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];

831 832 833
				const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false);
				const outWYSIWYG = (isWYSIWYG ? '       ' : '   NO  ');

A
Alex Dima 已提交
834
				const kbCombos = this._scanCodeKeyCodeMapper.lookupScanCodeCombo(scanCodeCombo);
835
				if (kbCombos.length === 0) {
836
					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} |`);
837 838 839
				} else {
					for (let i = 0, len = kbCombos.length; i < len; i++) {
						const kbCombo = kbCombos[i];
A
Alex Dima 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
						// 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 已提交
858
						const outKeybinding = kbCombo.toString();
A
Alex Dima 已提交
859
						if (i === 0) {
860
							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 已提交
861 862
						} else {
							// secondary keybindings
863
							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 已提交
864
						}
865 866
					}
				}
867 868

			}
869
			result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
870 871 872 873 874 875
		}

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

	private _leftPad(str: string, cnt: number): string {
A
Alex Dima 已提交
876 877 878
		if (str === null) {
			str = 'null';
		}
879 880 881 882 883 884
		while (str.length < cnt) {
			str = ' ' + str;
		}
		return str;
	}

A
Alex Dima 已提交
885
	public simpleKeybindingToScanCodeBinding(keybinding: SimpleKeybinding): ScanCodeBinding[] {
886 887 888 889 890
		// 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)];
		}

891 892 893
		const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(
			new KeyCodeCombo(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.keyCode)
		);
894

A
Alex Dima 已提交
895
		let result: ScanCodeBinding[] = [];
896 897
		for (let i = 0, len = scanCodeCombos.length; i < len; i++) {
			const scanCodeCombo = scanCodeCombos[i];
A
Alex Dima 已提交
898
			result[i] = new ScanCodeBinding(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, keybinding.metaKey, scanCodeCombo.scanCode);
899 900 901 902
		}
		return result;
	}

A
Renames  
Alex Dima 已提交
903
	public getUILabelForScanCode(scanCode: ScanCode): string {
904
		if (this._OS === OperatingSystem.Macintosh) {
A
Renames  
Alex Dima 已提交
905 906
			switch (scanCode) {
				case ScanCode.ArrowLeft:
907
					return '';
A
Renames  
Alex Dima 已提交
908
				case ScanCode.ArrowUp:
909
					return '';
A
Renames  
Alex Dima 已提交
910
				case ScanCode.ArrowRight:
911
					return '';
A
Renames  
Alex Dima 已提交
912
				case ScanCode.ArrowDown:
913 914 915
					return '';
			}
		}
A
Renames  
Alex Dima 已提交
916
		return this._scanCodeToLabel[scanCode];
917 918
	}

A
Renames  
Alex Dima 已提交
919 920
	public getAriaLabelForScanCode(scanCode: ScanCode): string {
		return this._scanCodeToLabel[scanCode];
921 922
	}

A
Alex Dima 已提交
923
	public getDispatchStrForScanCodeBinding(keypress: ScanCodeBinding): string {
A
Renames  
Alex Dima 已提交
924
		const codeDispatch = this._scanCodeToDispatch[keypress.scanCode];
A
Alex Dima 已提交
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
		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 已提交
947 948
	public getUserSettingsLabel(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
949 950 951 952
		if (immutableKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(immutableKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
953
		// Check if this scanCode always maps to the same keyCode and back
954
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
955 956 957 958
		if (constantKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(constantKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
959
		return this._scanCodeToDispatch[scanCode];
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
	}

	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 已提交
983 984
	public getElectronLabelForScanCode(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
985 986 987 988
		if (immutableKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(immutableKeyCode);
		}

A
Renames  
Alex Dima 已提交
989
		// Check if this scanCode always maps to the same keyCode and back
990
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

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

1012 1013 1014 1015 1016 1017 1018
		if (constantKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(constantKeyCode);
		}

		return null;
	}

1019 1020 1021 1022
	public resolveKeybinding(keybinding: Keybinding): NativeResolvedKeybinding[] {
		let result: NativeResolvedKeybinding[] = [], resultLen = 0;

		if (keybinding.type === KeybindingType.Chord) {
A
Alex Dima 已提交
1023 1024
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding.firstPart);
			const chordParts = this.simpleKeybindingToScanCodeBinding(keybinding.chordPart);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

			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 已提交
1035
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding);
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046

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

1047
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): NativeResolvedKeybinding {
1048
		let code = ScanCodeUtils.toEnum(keyboardEvent.code);
1049

1050 1051 1052 1053
		// Treat NumpadEnter as Enter
		if (code === ScanCode.NumpadEnter) {
			code = ScanCode.Enter;
		}
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
		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;
			}
		}

1070 1071
		const keyCode = keyboardEvent.keyCode;

1072
		if (
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
			(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)
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
			// "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;
					}
1112 1113 1114 1115
				}
			}
		}

1116
		const keypress = new ScanCodeBinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, code);
1117 1118 1119
		return new NativeResolvedKeybinding(this, this._OS, keypress, null);
	}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
	private _resolveSimpleUserBinding(binding: SimpleKeybinding | ScanCodeBinding): ScanCodeBinding[] {
		if (!binding) {
			return [];
		}
		if (binding instanceof ScanCodeBinding) {
			return [binding];
		}
		return this.simpleKeybindingToScanCodeBinding(binding);
	}

A
Alex Dima 已提交
1130 1131 1132
	public resolveUserBinding(_firstPart: SimpleKeybinding | ScanCodeBinding, _chordPart: SimpleKeybinding | ScanCodeBinding): ResolvedKeybinding[] {
		const firstParts = this._resolveSimpleUserBinding(_firstPart);
		const chordParts = this._resolveSimpleUserBinding(_chordPart);
1133 1134 1135 1136

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

A
Alex Dima 已提交
1141 1142 1143 1144
					result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, chordPart);
				}
			} else {
				result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, null);
1145 1146 1147 1148 1149
			}
		}
		return result;
	}

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 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
	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);
})();