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

'use strict';

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

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

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

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

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

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

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

export class NativeResolvedKeybinding extends ResolvedKeybinding {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
	private getProducedCharCode(mapping: IScanCodeMapping): number {
		if (!mapping) {
			return 0;
		}
		if (this.ctrlKey && this.shiftKey && this.altKey) {
			return mapping.withShiftAltGr;
		}
		if (this.ctrlKey && this.altKey) {
			return mapping.withAltGr;
		}
		if (this.shiftKey) {
			return mapping.withShift;
		}
		return mapping.value;
	}

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

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

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

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

class ScanCodeKeyCodeMapper {

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

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

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

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

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
	private _moveToEnd(scanCode: ScanCode): void {
		for (let mod = 0; mod < 8; mod++) {
			const encodedKeyCodeCombos = this._scanCodeToKeyCode[(scanCode << 3) + mod];
			if (!encodedKeyCodeCombos) {
				continue;
			}
			for (let i = 0, len = encodedKeyCodeCombos.length; i < len; i++) {
				const encodedScanCodeCombos = this._keyCodeToScanCode[encodedKeyCodeCombos[i]];
				if (encodedScanCodeCombos.length === 1) {
					continue;
				}
				for (let j = 0, len = encodedScanCodeCombos.length; j < len; j++) {
					const entry = encodedScanCodeCombos[j];
					const entryScanCode = (entry >>> 3);
					if (entryScanCode === scanCode) {
						// Move this entry to the end
						for (let k = j + 1; k < len; k++) {
							encodedScanCodeCombos[k - 1] = encodedScanCodeCombos[k];
						}
						encodedScanCodeCombos[len - 1] = entry;
					}
				}
			}
		}
	}
378 379

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

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

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

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

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

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

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

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

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

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

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

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

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

453 454 455
			result[i] = new KeyCodeCombo(ctrlKey, shiftKey, altKey, keyCode);
		}
		return result;
456 457
	}

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
	public guessStableKeyCode(scanCode: ScanCode): KeyCode {
		if (scanCode >= ScanCode.Digit1 && scanCode <= ScanCode.Digit0) {
			// digits are ok
			switch (scanCode) {
				case ScanCode.Digit1: return KeyCode.KEY_1;
				case ScanCode.Digit2: return KeyCode.KEY_2;
				case ScanCode.Digit3: return KeyCode.KEY_3;
				case ScanCode.Digit4: return KeyCode.KEY_4;
				case ScanCode.Digit5: return KeyCode.KEY_5;
				case ScanCode.Digit6: return KeyCode.KEY_6;
				case ScanCode.Digit7: return KeyCode.KEY_7;
				case ScanCode.Digit8: return KeyCode.KEY_8;
				case ScanCode.Digit9: return KeyCode.KEY_9;
				case ScanCode.Digit0: return KeyCode.KEY_0;
			}
		}

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

		return -1;
	}

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

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

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

510 511
export class MacLinuxKeyboardMapper implements IKeyboardMapper {

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

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

550 551 552 553 554 555 556 557 558 559 560
		// 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 已提交
561 562 563 564 565
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			const keyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
			if (keyCode !== -1) {
				this._registerAllCombos1(false, false, false, scanCode, keyCode);
				this._scanCodeToLabel[scanCode] = KeyCodeUtils.toString(keyCode);
A
Alex Dima 已提交
566

A
Renames  
Alex Dima 已提交
567 568
				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 已提交
569
				} else {
A
Renames  
Alex Dima 已提交
570
					this._scanCodeToDispatch[scanCode] = `[${ScanCodeUtils.toString(scanCode)}]`;
A
Alex Dima 已提交
571
				}
572 573 574
			}
		}

A
Renames  
Alex Dima 已提交
575
		let mappings: IScanCodeMapping[] = [], mappingsLen = 0;
576
		let producesLetter: boolean[] = [];
A
Renames  
Alex Dima 已提交
577 578 579 580 581
		for (let strScanCode in rawMappings) {
			if (rawMappings.hasOwnProperty(strScanCode)) {
				const scanCode = ScanCodeUtils.toEnum(strScanCode);
				if (scanCode === ScanCode.None) {
					log(`Unknown ScanCode ${strScanCode} in mapping.`);
582 583
					continue;
				}
A
Renames  
Alex Dima 已提交
584
				if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
585 586 587
					continue;
				}

A
Renames  
Alex Dima 已提交
588
				const rawMapping = rawMappings[strScanCode];
589 590 591 592 593
				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 已提交
594 595
				const mapping: IScanCodeMapping = {
					scanCode: scanCode,
596 597 598 599 600 601
					value: value,
					withShift: withShift,
					withAltGr: withAltGr,
					withShiftAltGr: withShiftAltGr,
				};
				mappings[mappingsLen++] = mapping;
A
Renames  
Alex Dima 已提交
602
				this._codeInfo[scanCode] = mapping;
603

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

606
				if (value >= CharCode.a && value <= CharCode.z) {
607 608 609 610 611 612
					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);
613
				} else if (value) {
A
Renames  
Alex Dima 已提交
614
					this._scanCodeToLabel[scanCode] = String.fromCharCode(value);
615
				} else {
A
Renames  
Alex Dima 已提交
616
					this._scanCodeToLabel[scanCode] = null;
617 618 619 620 621 622 623
				}
			}
		}

		// Handle all `withShiftAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
624
			const scanCode = mapping.scanCode;
625 626 627 628 629
			const withShiftAltGr = mapping.withShiftAltGr;
			if (withShiftAltGr === mapping.withAltGr || withShiftAltGr === mapping.withShift || withShiftAltGr === mapping.value) {
				// handled below
				continue;
			}
630 631 632 633 634 635 636 637 638 639 640 641
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShiftAltGr);
			if (!kb) {
				this._registerAllCombos1(true, true, true, scanCode, KeyCode.Unknown);
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

			this._registerAllCombos2(
				true, true, true, scanCode,
				kbShiftKey, keyCode
			);
642 643 644 645
		}
		// Handle all `withAltGr` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
646
			const scanCode = mapping.scanCode;
647 648 649 650 651
			const withAltGr = mapping.withAltGr;
			if (withAltGr === mapping.withShift || withAltGr === mapping.value) {
				// handled below
				continue;
			}
652 653 654 655 656 657 658 659 660 661 662 663
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withAltGr);
			if (!kb) {
				this._registerAllCombos1(true, false, true, scanCode, KeyCode.Unknown);
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

			this._registerAllCombos2(
				true, false, true, scanCode,
				kbShiftKey, keyCode
			);
664 665 666 667
		}
		// Handle all `withShift` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
668
			const scanCode = mapping.scanCode;
669 670 671 672 673
			const withShift = mapping.withShift;
			if (withShift === mapping.value) {
				// handled below
				continue;
			}
674 675 676 677 678 679 680 681 682 683 684 685
			const kb = MacLinuxKeyboardMapper._charCodeToKb(withShift);
			if (!kb) {
				this._registerAllCombos1(false, true, false, scanCode, KeyCode.Unknown);
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

			this._registerAllCombos2(
				false, true, false, scanCode,
				kbShiftKey, keyCode
			);
686 687 688 689
		}
		// Handle all `value` entries
		for (let i = mappings.length - 1; i >= 0; i--) {
			const mapping = mappings[i];
690 691 692 693 694 695 696 697 698 699 700 701 702
			const scanCode = mapping.scanCode;
			const kb = MacLinuxKeyboardMapper._charCodeToKb(mapping.value);
			if (!kb) {
				this._registerAllCombos1(false, false, false, scanCode, KeyCode.Unknown);
				continue;
			}
			const kbShiftKey = kb.shiftKey;
			const keyCode = kb.keyCode;

			this._registerAllCombos2(
				false, false, false, scanCode,
				kbShiftKey, keyCode
			);
703
		}
704
		// Handle all left-over available digits
A
Renames  
Alex Dima 已提交
705 706 707 708 709 710 711 712 713 714 715
		this._registerAllCombos1(false, false, false, ScanCode.Digit1, KeyCode.KEY_1);
		this._registerAllCombos1(false, false, false, ScanCode.Digit2, KeyCode.KEY_2);
		this._registerAllCombos1(false, false, false, ScanCode.Digit3, KeyCode.KEY_3);
		this._registerAllCombos1(false, false, false, ScanCode.Digit4, KeyCode.KEY_4);
		this._registerAllCombos1(false, false, false, ScanCode.Digit5, KeyCode.KEY_5);
		this._registerAllCombos1(false, false, false, ScanCode.Digit6, KeyCode.KEY_6);
		this._registerAllCombos1(false, false, false, ScanCode.Digit7, KeyCode.KEY_7);
		this._registerAllCombos1(false, false, false, ScanCode.Digit8, KeyCode.KEY_8);
		this._registerAllCombos1(false, false, false, ScanCode.Digit9, KeyCode.KEY_9);
		this._registerAllCombos1(false, false, false, ScanCode.Digit0, KeyCode.KEY_0);

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
		// Ensure letters are mapped
		this._registerLetterIfMissing(producesLetter, CharCode.A, ScanCode.KeyA, KeyCode.KEY_A);
		this._registerLetterIfMissing(producesLetter, CharCode.B, ScanCode.KeyB, KeyCode.KEY_B);
		this._registerLetterIfMissing(producesLetter, CharCode.C, ScanCode.KeyC, KeyCode.KEY_C);
		this._registerLetterIfMissing(producesLetter, CharCode.D, ScanCode.KeyD, KeyCode.KEY_D);
		this._registerLetterIfMissing(producesLetter, CharCode.E, ScanCode.KeyE, KeyCode.KEY_E);
		this._registerLetterIfMissing(producesLetter, CharCode.F, ScanCode.KeyF, KeyCode.KEY_F);
		this._registerLetterIfMissing(producesLetter, CharCode.G, ScanCode.KeyG, KeyCode.KEY_G);
		this._registerLetterIfMissing(producesLetter, CharCode.H, ScanCode.KeyH, KeyCode.KEY_H);
		this._registerLetterIfMissing(producesLetter, CharCode.I, ScanCode.KeyI, KeyCode.KEY_I);
		this._registerLetterIfMissing(producesLetter, CharCode.J, ScanCode.KeyJ, KeyCode.KEY_J);
		this._registerLetterIfMissing(producesLetter, CharCode.K, ScanCode.KeyK, KeyCode.KEY_K);
		this._registerLetterIfMissing(producesLetter, CharCode.L, ScanCode.KeyL, KeyCode.KEY_L);
		this._registerLetterIfMissing(producesLetter, CharCode.M, ScanCode.KeyM, KeyCode.KEY_M);
		this._registerLetterIfMissing(producesLetter, CharCode.N, ScanCode.KeyN, KeyCode.KEY_N);
		this._registerLetterIfMissing(producesLetter, CharCode.O, ScanCode.KeyO, KeyCode.KEY_O);
		this._registerLetterIfMissing(producesLetter, CharCode.P, ScanCode.KeyP, KeyCode.KEY_P);
		this._registerLetterIfMissing(producesLetter, CharCode.Q, ScanCode.KeyQ, KeyCode.KEY_Q);
		this._registerLetterIfMissing(producesLetter, CharCode.R, ScanCode.KeyR, KeyCode.KEY_R);
		this._registerLetterIfMissing(producesLetter, CharCode.S, ScanCode.KeyS, KeyCode.KEY_S);
		this._registerLetterIfMissing(producesLetter, CharCode.T, ScanCode.KeyT, KeyCode.KEY_T);
		this._registerLetterIfMissing(producesLetter, CharCode.U, ScanCode.KeyU, KeyCode.KEY_U);
		this._registerLetterIfMissing(producesLetter, CharCode.V, ScanCode.KeyV, KeyCode.KEY_V);
		this._registerLetterIfMissing(producesLetter, CharCode.W, ScanCode.KeyW, KeyCode.KEY_W);
		this._registerLetterIfMissing(producesLetter, CharCode.X, ScanCode.KeyX, KeyCode.KEY_X);
		this._registerLetterIfMissing(producesLetter, CharCode.Y, ScanCode.KeyY, KeyCode.KEY_Y);
		this._registerLetterIfMissing(producesLetter, CharCode.Z, ScanCode.KeyZ, KeyCode.KEY_Z);

A
Alex Dima 已提交
744
		this._scanCodeKeyCodeMapper.registrationComplete();
745 746
	}

747 748 749 750 751 752
	private _registerLetterIfMissing(producesLetter: boolean[], charCode: CharCode, scanCode: ScanCode, keyCode: KeyCode): void {
		if (!producesLetter[charCode]) {
			this._registerAllCombos1(false, false, false, scanCode, keyCode);
		}
	}

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

756 757 758 759 760
		let immutableSamples = [
			ScanCode.ArrowUp,
			ScanCode.Numpad0
		];

761
		let cnt = 0;
762
		result.push(`isUSStandard: ${this._isUSStandard}`);
763
		result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
A
Renames  
Alex Dima 已提交
764 765
		for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) {
			if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== -1) {
766 767 768
				if (immutableSamples.indexOf(scanCode) === -1) {
					continue;
				}
769 770 771
			}

			if (cnt % 4 === 0) {
772 773
				result.push(`|       HW Code combination      |  Key  |    KeyCode combination    | Pri |          UI label         |         User settings          |    Electron accelerator   |       Dispatching string       | WYSIWYG |`);
				result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
774 775 776
			}
			cnt++;

A
Renames  
Alex Dima 已提交
777
			const mapping = this._codeInfo[scanCode];
778 779

			for (let mod = 0; mod < 8; mod++) {
780 781 782
				const hwCtrlKey = (mod & 0b001) ? true : false;
				const hwShiftKey = (mod & 0b010) ? true : false;
				const hwAltKey = (mod & 0b100) ? true : false;
A
Alex Dima 已提交
783
				const scanCodeCombo = new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode);
784
				const resolvedKb = this.resolveKeyboardEvent({
A
Alex Dima 已提交
785 786 787
					ctrlKey: scanCodeCombo.ctrlKey,
					shiftKey: scanCodeCombo.shiftKey,
					altKey: scanCodeCombo.altKey,
788 789 790 791
					metaKey: false,
					keyCode: -1,
					code: ScanCodeUtils.toString(scanCode)
				});
792

A
Alex Dima 已提交
793 794 795 796 797 798 799 800
				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];

801 802 803
				const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false);
				const outWYSIWYG = (isWYSIWYG ? '       ' : '   NO  ');

A
Alex Dima 已提交
804
				const kbCombos = this._scanCodeKeyCodeMapper.lookupScanCodeCombo(scanCodeCombo);
805
				if (kbCombos.length === 0) {
806
					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} |`);
807 808 809
				} else {
					for (let i = 0, len = kbCombos.length; i < len; i++) {
						const kbCombo = kbCombos[i];
A
Alex Dima 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
						// 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 已提交
828
						const outKeybinding = kbCombo.toString();
A
Alex Dima 已提交
829
						if (i === 0) {
830
							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 已提交
831 832
						} else {
							// secondary keybindings
833
							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 已提交
834
						}
835 836
					}
				}
837 838

			}
839
			result.push(`----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------`);
840 841 842 843 844 845
		}

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

	private _leftPad(str: string, cnt: number): string {
A
Alex Dima 已提交
846 847 848
		if (str === null) {
			str = 'null';
		}
849 850 851 852 853 854 855
		while (str.length < cnt) {
			str = ' ' + str;
		}
		return str;
	}

	private _registerIfUnknown(
A
Renames  
Alex Dima 已提交
856
		hwCtrlKey: boolean, hwShiftKey: boolean, hwAltKey: boolean, scanCode: ScanCode,
857 858
		kbCtrlKey: boolean, kbShiftKey: boolean, kbAltKey: boolean, keyCode: KeyCode,
	): void {
859 860 861 862
		this._scanCodeKeyCodeMapper.registerIfUnknown(
			new ScanCodeCombo(hwCtrlKey, hwShiftKey, hwAltKey, scanCode),
			new KeyCodeCombo(kbCtrlKey, kbShiftKey, kbAltKey, keyCode)
		);
863 864 865
	}

	private _registerAllCombos1(
A
Renames  
Alex Dima 已提交
866
		_ctrlKey: boolean, _shiftKey: boolean, _altKey: boolean, scanCode: ScanCode,
867 868 869 870 871 872 873 874 875
		keyCode: KeyCode,
	): void {
		for (let _ctrl = (_ctrlKey ? 1 : 0); _ctrl <= 1; _ctrl++) {
			const ctrlKey = (_ctrl ? true : false);
			for (let _shift = (_shiftKey ? 1 : 0); _shift <= 1; _shift++) {
				const shiftKey = (_shift ? true : false);
				for (let _alt = (_altKey ? 1 : 0); _alt <= 1; _alt++) {
					const altKey = (_alt ? true : false);
					this._registerIfUnknown(
A
Renames  
Alex Dima 已提交
876
						ctrlKey, shiftKey, altKey, scanCode,
877 878 879 880 881 882 883 884
						ctrlKey, shiftKey, altKey, keyCode
					);
				}
			}
		}
	}

	private _registerAllCombos2(
A
Renames  
Alex Dima 已提交
885
		hwCtrlKey: boolean, hwShiftKey: boolean, hwAltKey: boolean, scanCode: ScanCode,
886 887 888
		kbShiftKey: boolean, keyCode: KeyCode,
	): void {
		this._registerIfUnknown(
A
Renames  
Alex Dima 已提交
889
			hwCtrlKey, hwShiftKey, hwAltKey, scanCode,
890 891 892 893 894 895 896 897 898
			false, kbShiftKey, false, keyCode
		);

		if (!kbShiftKey) {
			for (let _ctrl = (hwCtrlKey ? 1 : 0); _ctrl <= 1; _ctrl++) {
				const ctrlKey = (_ctrl ? true : false);
				for (let _alt = (hwAltKey ? 1 : 0); _alt <= 1; _alt++) {
					const altKey = (_alt ? true : false);
					this._registerIfUnknown(
A
Renames  
Alex Dima 已提交
899
						ctrlKey, hwShiftKey, altKey, scanCode,
900 901 902
						ctrlKey, kbShiftKey, altKey, keyCode
					);
					this._registerIfUnknown(
A
Renames  
Alex Dima 已提交
903
						ctrlKey, true, altKey, scanCode,
904 905 906 907 908 909 910 911 912 913
						ctrlKey, true, altKey, keyCode
					);
				}
			}
		} else {
			for (let _ctrl = (hwCtrlKey ? 1 : 0); _ctrl <= 1; _ctrl++) {
				const ctrlKey = (_ctrl ? true : false);
				for (let _alt = (hwAltKey ? 1 : 0); _alt <= 1; _alt++) {
					const altKey = (_alt ? true : false);
					this._registerIfUnknown(
A
Renames  
Alex Dima 已提交
914
						ctrlKey, hwShiftKey, altKey, scanCode,
915 916 917 918 919 920 921
						ctrlKey, kbShiftKey, altKey, keyCode
					);
				}
			}
		}
	}

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

928 929 930
		const scanCodeCombos = this._scanCodeKeyCodeMapper.lookupKeyCodeCombo(
			new KeyCodeCombo(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.keyCode)
		);
931

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

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

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

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

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

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

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

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

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

1049 1050 1051 1052 1053 1054 1055
		if (constantKeyCode !== -1) {
			return this._getElectronLabelForKeyCode(constantKeyCode);
		}

		return null;
	}

1056 1057 1058 1059
	public resolveKeybinding(keybinding: Keybinding): NativeResolvedKeybinding[] {
		let result: NativeResolvedKeybinding[] = [], resultLen = 0;

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

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

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

1084
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): NativeResolvedKeybinding {
1085
		let code = ScanCodeUtils.toEnum(keyboardEvent.code);
1086

1087 1088 1089 1090
		// Treat NumpadEnter as Enter
		if (code === ScanCode.NumpadEnter) {
			code = ScanCode.Enter;
		}
1091

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
		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;
			}
		}

1107 1108
		const keyCode = keyboardEvent.keyCode;

1109
		if (
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
			(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)
1120
		) {
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
			// "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;
					}
1149 1150 1151 1152
				}
			}
		}

1153
		const keypress = new ScanCodeBinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, code);
1154 1155 1156
		return new NativeResolvedKeybinding(this, this._OS, keypress, null);
	}

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

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

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

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

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