macLinuxKeyboardMapper.ts 45.2 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, NO_MODIFIERS } from 'vs/platform/keybinding/common/keybindingLabels';
13
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
14
import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
15

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

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

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

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

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

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

export class NativeResolvedKeybinding extends ResolvedKeybinding {

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

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

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

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

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

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

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

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

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

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

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

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

164
	public getUserSettingsLabel(): string {
165 166
		let firstPart = this._getUserSettingsLabelForScanCodeBinding(this._firstPart);
		let chordPart = this._getUserSettingsLabelForScanCodeBinding(this._chordPart);
167
		return UserSettingsLabelProvider.toLabel(this._firstPart, firstPart, this._chordPart, chordPart, this._OS);
168 169
	}

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
	private _isWYSIWYG(scanCode: ScanCode): boolean {
		if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
			return true;
		}
		let a = this._mapper.getAriaLabelForScanCode(scanCode);
		let b = this._mapper.getUserSettingsLabel(scanCode);

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

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

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

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

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

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

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

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	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)
		);
245 246
	}

247
	public getDispatchParts(): [string, string] {
A
Alex Dima 已提交
248 249
		let firstPart = this._firstPart ? this._mapper.getDispatchStrForScanCodeBinding(this._firstPart) : null;
		let chordPart = this._chordPart ? this._mapper.getDispatchStrForScanCodeBinding(this._chordPart) : null;
250
		return [firstPart, chordPart];
251 252 253
	}
}

A
Renames  
Alex Dima 已提交
254 255
interface IScanCodeMapping {
	scanCode: ScanCode;
256 257 258 259 260 261
	value: number;
	withShift: number;
	withAltGr: number;
	withShiftAltGr: number;
}

262 263 264 265 266 267 268 269 270 271 272 273
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 已提交
274 275 276 277 278

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

A
Alex Dima 已提交
279 280 281 282 283 284 285 286 287
	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 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
	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) + '  ';
	}
315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

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 已提交
329 330 331 332

	public toString(): string {
		return `${this.ctrlKey ? 'Ctrl+' : ''}${this.shiftKey ? 'Shift+' : ''}${this.altKey ? 'Alt+' : ''}${KeyCodeUtils.toString(this.keyCode)}`;
	}
333 334 335 336 337 338 339 340
}

class ScanCodeKeyCodeMapper {

	/**
	 * ScanCode combination => KeyCode combination.
	 * Only covers relevant modifiers ctrl, shift, alt (since meta does not influence the mappings).
	 */
341
	private readonly _scanCodeToKeyCode: number[][] = [];
342 343 344 345 346 347 348 349 350 351 352 353
	/**
	 * 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 已提交
354
	public registrationComplete(): void {
355 356 357 358 359 360 361 362 363 364
		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 已提交
365 366

		// IntlHash and IntlBackslash are rare keys, so ensure they don't end up being the preferred...
367 368
		this._moveToEnd(ScanCode.IntlHash);
		this._moveToEnd(ScanCode.IntlBackslash);
A
Alex Dima 已提交
369 370
	}

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
	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;
					}
				}
			}
		}
	}
396 397

	public registerIfUnknown(scanCodeCombo: ScanCodeCombo, keyCodeCombo: KeyCodeCombo): void {
398 399 400
		if (keyCodeCombo.keyCode === KeyCode.Unknown) {
			return;
		}
401 402 403
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
		const keyCodeComboEncoded = this._encodeKeyCodeCombo(keyCodeCombo);

A
Alex Dima 已提交
404 405 406
		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 已提交
407
		const existingKeyCodeCombos = this._scanCodeToKeyCode[scanCodeComboEncoded];
A
Alex Dima 已提交
408 409 410 411

		// 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 已提交
412 413 414
			if (existingKeyCodeCombos) {
				for (let i = 0, len = existingKeyCodeCombos.length; i < len; i++) {
					if (existingKeyCodeCombos[i] === keyCodeComboEncoded) {
A
Alex Dima 已提交
415 416 417 418 419 420 421
						// avoid duplicates
						return;
					}
				}
			}
		} else {
			// Don't allow multiples
A
Alex Dima 已提交
422
			if (existingKeyCodeCombos && existingKeyCodeCombos.length !== 0) {
A
Alex Dima 已提交
423 424
				return;
			}
425 426
		}

427 428
		this._scanCodeToKeyCode[scanCodeComboEncoded] = this._scanCodeToKeyCode[scanCodeComboEncoded] || [];
		this._scanCodeToKeyCode[scanCodeComboEncoded].unshift(keyCodeComboEncoded);
429

430 431
		this._keyCodeToScanCode[keyCodeComboEncoded] = this._keyCodeToScanCode[keyCodeComboEncoded] || [];
		this._keyCodeToScanCode[keyCodeComboEncoded].unshift(scanCodeComboEncoded);
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
	}

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

455
	public lookupScanCodeCombo(scanCodeCombo: ScanCodeCombo): KeyCodeCombo[] {
456
		const scanCodeComboEncoded = this._encodeScanCodeCombo(scanCodeCombo);
457 458 459 460 461 462 463 464
		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];
465

466 467 468 469
			const ctrlKey = (keyCodeComboEncoded & 0b001) ? true : false;
			const shiftKey = (keyCodeComboEncoded & 0b010) ? true : false;
			const altKey = (keyCodeComboEncoded & 0b100) ? true : false;
			const keyCode: KeyCode = (keyCodeComboEncoded >>> 3);
470

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

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	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;
	}
}

528 529
export class MacLinuxKeyboardMapper implements IKeyboardMapper {

530
	/**
531 532 533 534 535
	 * Is the keyboard type ISO (on Mac)
	 */
	private readonly _isISOKeyboard: boolean;
	/**
	 * Is this the standard US keyboard layout?
536 537
	 */
	private readonly _isUSStandard: boolean;
A
Renames  
Alex Dima 已提交
538 539 540
	/**
	 * OS (can be Linux or Macintosh)
	 */
541
	private readonly _OS: OperatingSystem;
542 543 544
	/**
	 * used only for debug purposes.
	 */
A
Renames  
Alex Dima 已提交
545 546
	private readonly _codeInfo: IScanCodeMapping[];
	/**
547
	 * Maps ScanCode combos <-> KeyCode combos.
A
Renames  
Alex Dima 已提交
548
	 */
549
	private readonly _scanCodeKeyCodeMapper: ScanCodeKeyCodeMapper;
A
Renames  
Alex Dima 已提交
550 551 552 553
	/**
	 * UI label for a ScanCode.
	 */
	private readonly _scanCodeToLabel: string[] = [];
554
	/**
A
Renames  
Alex Dima 已提交
555
	 * Dispatching string for a ScanCode.
556
	 */
A
Renames  
Alex Dima 已提交
557
	private readonly _scanCodeToDispatch: string[] = [];
558

559 560
	constructor(isISOKeyboard: boolean, isUSStandard: boolean, rawMappings: IMacLinuxKeyboardMapping, OS: OperatingSystem) {
		this._isISOKeyboard = isISOKeyboard;
561
		this._isUSStandard = isUSStandard;
562
		this._OS = OS;
563 564
		this._codeInfo = [];
		this._scanCodeKeyCodeMapper = new ScanCodeKeyCodeMapper();
A
Renames  
Alex Dima 已提交
565 566
		this._scanCodeToLabel = [];
		this._scanCodeToDispatch = [];
567

A
Alex Dima 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
		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);
			}
		};


599 600 601 602 603 604 605 606 607 608 609
		// 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 已提交
610 611 612
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			const keyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
			if (keyCode !== -1) {
A
Alex Dima 已提交
613
				_registerAllCombos(0, 0, 0, scanCode, keyCode);
A
Renames  
Alex Dima 已提交
614
				this._scanCodeToLabel[scanCode] = KeyCodeUtils.toString(keyCode);
A
Alex Dima 已提交
615

A
Renames  
Alex Dima 已提交
616 617
				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 已提交
618
				} else {
A
Renames  
Alex Dima 已提交
619
					this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
620
				}
621 622 623
			}
		}

A
Renames  
Alex Dima 已提交
624 625 626 627 628 629
		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.`);
630 631
					continue;
				}
A
Renames  
Alex Dima 已提交
632
				if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
633 634 635
					continue;
				}

A
Renames  
Alex Dima 已提交
636
				const rawMapping = rawMappings[strScanCode];
637 638 639 640 641
				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 已提交
642 643
				const mapping: IScanCodeMapping = {
					scanCode: scanCode,
644 645 646 647 648 649
					value: value,
					withShift: withShift,
					withAltGr: withAltGr,
					withShiftAltGr: withShiftAltGr,
				};
				mappings[mappingsLen++] = mapping;
A
Renames  
Alex Dima 已提交
650
				this._codeInfo[scanCode] = mapping;
651

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

654
				if (value >= CharCode.a && value <= CharCode.z) {
655 656 657 658 659 660
					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);
661
				} else if (value) {
A
Renames  
Alex Dima 已提交
662
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
663
				} else {
A
Renames  
Alex Dima 已提交
664
					this._scanCodeToLabel[scanCode] = null;
665 666 667 668 669 670 671
				}
			}
		}

		// Handle all `withShiftAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
672
			const scanCode = mapping.scanCode;
673 674 675 676 677
			const withShiftAltGr = mapping.withShiftAltGr;
			if (withShiftAltGr === mapping.withAltGr || withShiftAltGr === mapping.withShift || withShiftAltGr === mapping.value) {
				// handled below
				continue;
			}
678 679 680 681 682 683 684
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShiftAltGr);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

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

709 710
			if (kbShiftKey) {
				// Ctrl+Alt+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
711
				_registerIfUnknown(1, 0, 1, scanCode, 0, 1, 0, keyCode); //       Ctrl+Alt+ScanCode =>          Shift+KeyCode
712 713
			} else {
				// Ctrl+Alt+ScanCode => KeyCode
A
Alex Dima 已提交
714
				_registerIfUnknown(1, 0, 1, scanCode, 0, 0, 0, keyCode); //       Ctrl+Alt+ScanCode =>                KeyCode
715
			}
716 717 718 719
		}
		// Handle all `withShift` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
720
			const scanCode = mapping.scanCode;
721 722 723 724 725
			const withShift = mapping.withShift;
			if (withShift === mapping.value) {
				// handled below
				continue;
			}
726 727 728 729 730 731 732
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShift);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

733 734
			if (kbShiftKey) {
				// Shift+ScanCode => Shift+KeyCode
A
Alex Dima 已提交
735 736 737 738
				_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
739 740
			} else {
				// Shift+ScanCode => KeyCode
A
Alex Dima 已提交
741 742 743 744 745 746 747 748
				_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
749
			}
750 751 752 753
		}
		// Handle all `value` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
754 755 756 757 758 759 760 761
			const scanCode = mapping.scanCode;
			const kb = MacLinuxKeyboardMapper._charCodeToKb(mapping.value);
			if (!kb) {
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

762 763
			if (kbShiftKey) {
				// ScanCode => Shift+KeyCode
A
Alex Dima 已提交
764 765 766 767
				_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
768 769
			} else {
				// ScanCode => KeyCode
A
Alex Dima 已提交
770 771 772 773 774 775 776 777
				_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
778
			}
779
		}
780
		// Handle all left-over available digits
A
Alex Dima 已提交
781 782 783 784 785 786 787 788 789 790
		_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 已提交
791

792
		// Ensure letters are mapped
A
Alex Dima 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
		_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);
819

A
Alex Dima 已提交
820
		this._scanCodeKeyCodeMapper.registrationComplete();
821 822 823 824 825
	}

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

826 827 828 829 830
		let immutableSamples = [
			ScanCode.ArrowUp,
			ScanCode.Numpad0
		];

831
		let cnt = 0;
832
		result.push(`isUSStandard: ${this._isUSStandard}`);
833
		result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
A
Renames  
Alex Dima 已提交
834 835
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
836 837 838
				if (immutableSamples.indexOf(scanCode) === -1) {
					continue;
				}
839 840 841
			}

			if (cnt % 4 === 0) {
842 843
				result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
				result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
844 845 846
			}
			cnt++;

A
Renames  
Alex Dima 已提交
847
			const mapping = this._codeInfo[scanCode];
848 849

			for (let mod = 0; mod < 8; mod++) {
850 851 852
				const hwCtrlKey = (mod & 0b001) ? true : false;
				const hwShiftKey = (mod & 0b010) ? true : false;
				const hwAltKey = (mod & 0b100) ? true : false;
A
Alex Dima 已提交
853
				const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
854
				const resolvedKb = this.resolveKeyboardEvent({
A
Alex Dima 已提交
855 856 857
					ctrlKey: scanCodeCombo.ctrlKey,
					shiftKey: scanCodeCombo.shiftKey,
					altKey: scanCodeCombo.altKey,
858 859 860 861
					metaKey: false,
					keyCode: -1,
					code: ScanCodeUtils.toString(scanCode)
				});
862

A
Alex Dima 已提交
863 864 865 866 867 868 869 870
				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];

871 872 873
				const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false);
				const outWYSIWYG = (isWYSIWYG ? '       ' : '   NO  ');

A
Alex Dima 已提交
874
				const kbCombos = this._scanCodeKeyCodeMapper.lookupScanCodeCombo(scanCodeCombo);
875
				if (kbCombos.length === 0) {
876
					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} |`);
877 878 879
				} else {
					for (let i = 0, len = kbCombos.length; i < len; i++) {
						const kbCombo = kbCombos[i];
A
Alex Dima 已提交
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
						// 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 已提交
898
						const outKeybinding = kbCombo.toString();
A
Alex Dima 已提交
899
						if (i === 0) {
900
							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 已提交
901 902
						} else {
							// secondary keybindings
903
							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 已提交
904
						}
905 906
					}
				}
907 908

			}
909
			result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
910 911 912 913 914 915
		}

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

	private _leftPad(str: string, cnt: number): string {
A
Alex Dima 已提交
916 917 918
		if (str === null) {
			str = 'null';
		}
919 920 921 922 923 924
		while (str.length < cnt) {
			str = ' ' + str;
		}
		return str;
	}

A
Alex Dima 已提交
925
	public simpleKeybindingToScanCodeBinding(keybinding: SimpleKeybinding): ScanCodeBinding[] {
926 927 928 929 930
		// 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)];
		}

931 932 933
		const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(
			new KeyCodeCombo(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.keyCode)
		);
934

A
Alex Dima 已提交
935
		let result: ScanCodeBinding[] = [];
936 937
		for (let i = 0, len = scanCodeCombos.length; i < len; i++) {
			const scanCodeCombo = scanCodeCombos[i];
A
Alex Dima 已提交
938
			result[i] = new ScanCodeBinding(scanCodeCombo.ctrlKey, scanCodeCombo.shiftKey, scanCodeCombo.altKey, keybinding.metaKey, scanCodeCombo.scanCode);
939 940 941 942
		}
		return result;
	}

A
Renames  
Alex Dima 已提交
943
	public getUILabelForScanCode(scanCode: ScanCode): string {
944
		if (this._OS === OperatingSystem.Macintosh) {
A
Renames  
Alex Dima 已提交
945 946
			switch (scanCode) {
				case ScanCode.ArrowLeft:
947
					return '';
A
Renames  
Alex Dima 已提交
948
				case ScanCode.ArrowUp:
949
					return '';
A
Renames  
Alex Dima 已提交
950
				case ScanCode.ArrowRight:
951
					return '';
A
Renames  
Alex Dima 已提交
952
				case ScanCode.ArrowDown:
953 954 955
					return '';
			}
		}
A
Renames  
Alex Dima 已提交
956
		return this._scanCodeToLabel[scanCode];
957 958
	}

A
Renames  
Alex Dima 已提交
959 960
	public getAriaLabelForScanCode(scanCode: ScanCode): string {
		return this._scanCodeToLabel[scanCode];
961 962
	}

A
Alex Dima 已提交
963
	public getDispatchStrForScanCodeBinding(keypress: ScanCodeBinding): string {
A
Renames  
Alex Dima 已提交
964
		const codeDispatch = this._scanCodeToDispatch[keypress.scanCode];
A
Alex Dima 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
		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 已提交
987 988
	public getUserSettingsLabel(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
989 990 991 992
		if (immutableKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(immutableKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
993
		// Check if this scanCode always maps to the same keyCode and back
994
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
995 996 997 998
		if (constantKeyCode !== -1) {
			return USER_SETTINGS.fromKeyCode(constantKeyCode).toLowerCase();
		}

A
Renames  
Alex Dima 已提交
999
		return this._scanCodeToDispatch[scanCode];
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
	}

	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 已提交
1023 1024
	public getElectronLabelForScanCode(scanCode: ScanCode): string {
		const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
1025 1026 1027 1028
		if (immutableKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(immutableKeyCode);
		}

A
Renames  
Alex Dima 已提交
1029
		// Check if this scanCode always maps to the same keyCode and back
1030
		let constantKeyCode: KeyCode = this._scanCodeKeyCodeMapper.guessStableKeyCode(scanCode);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

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

1052 1053 1054 1055 1056 1057 1058
		if (constantKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(constantKeyCode);
		}

		return null;
	}

1059 1060 1061 1062
	public resolveKeybinding(keybinding: Keybinding): NativeResolvedKeybinding[] {
		let result: NativeResolvedKeybinding[] = [], resultLen = 0;

		if (keybinding.type === KeybindingType.Chord) {
A
Alex Dima 已提交
1063 1064
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding.firstPart);
			const chordParts = this.simpleKeybindingToScanCodeBinding(keybinding.chordPart);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

			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 已提交
1075
			const firstParts = this.simpleKeybindingToScanCodeBinding(keybinding);
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

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

1087
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): NativeResolvedKeybinding {
1088
		let code = ScanCodeUtils.toEnum(keyboardEvent.code);
1089

1090 1091 1092 1093
		// Treat NumpadEnter as Enter
		if (code === ScanCode.NumpadEnter) {
			code = ScanCode.Enter;
		}
1094

1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
		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;
			}
		}

1110 1111
		const keyCode = keyboardEvent.keyCode;

1112
		if (
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
			(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)
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
			// "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;
					}
1152 1153 1154 1155
				}
			}
		}

1156
		const keypress = new ScanCodeBinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, code);
1157 1158 1159
		return new NativeResolvedKeybinding(this, this._OS, keypress, null);
	}

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	private _resolveSimpleUserBinding(binding: SimpleKeybinding | ScanCodeBinding): ScanCodeBinding[] {
		if (!binding) {
			return [];
		}
		if (binding instanceof ScanCodeBinding) {
			return [binding];
		}
		return this.simpleKeybindingToScanCodeBinding(binding);
	}

A
Alex Dima 已提交
1170 1171 1172
	public resolveUserBinding(_firstPart: SimpleKeybinding | ScanCodeBinding, _chordPart: SimpleKeybinding | ScanCodeBinding): ResolvedKeybinding[] {
		const firstParts = this._resolveSimpleUserBinding(_firstPart);
		const chordParts = this._resolveSimpleUserBinding(_chordPart);
1173 1174 1175 1176

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

A
Alex Dima 已提交
1181 1182 1183 1184
					result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, chordPart);
				}
			} else {
				result[resultLen++] = new NativeResolvedKeybinding(this, this._OS, firstPart, null);
1185 1186 1187 1188 1189
			}
		}
		return result;
	}

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
	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);
})();