keybindingService.ts 27.5 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as nls from 'vs/nls';
P
Peng Lyu 已提交
7
import * as browser from 'vs/base/browser/browser';
A
Alex Dima 已提交
8 9 10
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { Emitter, Event } from 'vs/base/common/event';
J
Johannes Rieken 已提交
11
import { IJSONSchema } from 'vs/base/common/jsonSchema';
P
Peng Lyu 已提交
12
import { Keybinding, ResolvedKeybinding, KeyCode, KeyMod } from 'vs/base/common/keyCodes';
A
Alex Dima 已提交
13
import { KeybindingParser } from 'vs/base/common/keybindingParser';
P
Peng Lyu 已提交
14
import { OS, OperatingSystem, isWeb } from 'vs/base/common/platform';
15
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
A
Alex Dima 已提交
16 17 18 19
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { Extensions as ConfigExtensions, IConfigurationNode, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry';
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
J
Johannes Rieken 已提交
20
import { Extensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
21
import { AbstractKeybindingService } from 'vs/platform/keybinding/common/abstractKeybindingService';
P
Peng Lyu 已提交
22
import { IKeyboardEvent, IUserFriendlyKeybinding, KeybindingSource, IKeybindingService, IKeybindingEvent } from 'vs/platform/keybinding/common/keybinding';
A
Alex Dima 已提交
23
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
24
import { IKeybindingItem, IKeybindingRule2, KeybindingWeight, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
A
Alex Dima 已提交
25 26
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
import { INotificationService } from 'vs/platform/notification/common/notification';
27
import { Registry } from 'vs/platform/registry/common/platform';
28 29
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { keybindingsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
A
Alex Dima 已提交
30 31
import { ExtensionMessageCollector, ExtensionsRegistry } from 'vs/workbench/services/extensions/common/extensionsRegistry';
import { IUserKeybindingItem, KeybindingIO, OutputBuilder } from 'vs/workbench/services/keybinding/common/keybindingIO';
P
Peng Lyu 已提交
32
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
33
import { IWindowService } from 'vs/platform/windows/common/windows';
A
Alex Dima 已提交
34
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
35
import { MenuRegistry } from 'vs/platform/actions/common/actions';
36
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
P
Peng Lyu 已提交
37
// tslint:disable-next-line: import-patterns
38
import { commandsExtensionPoint } from 'vs/workbench/api/common/menusExtensionPoint';
39 40 41 42 43 44 45
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { URI } from 'vs/base/common/uri';
import { IFileService, FileChangesEvent, FileChangeType } from 'vs/platform/files/common/files';
import { dirname, isEqual } from 'vs/base/common/resources';
import { parse } from 'vs/base/common/json';
import * as objects from 'vs/base/common/objects';
P
Peng Lyu 已提交
46 47
import { IKeymapService } from 'vs/workbench/services/keybinding/common/keymapService';
import { getDispatchConfig } from 'vs/workbench/services/keybinding/common/dispatchConfig';
S
Sandeep Somavarapu 已提交
48
import { isArray } from 'vs/base/common/types';
P
Peng Lyu 已提交
49
import { INavigatorWithKeyboard } from 'vs/workbench/services/keybinding/common/navigatorKeyboard';
E
Erich Gamma 已提交
50 51 52

interface ContributedKeyBinding {
	command: string;
J
Johannes Rieken 已提交
53
	args?: any;
E
Erich Gamma 已提交
54 55 56 57 58 59 60
	key: string;
	when?: string;
	mac?: string;
	linux?: string;
	win?: string;
}

61
function isContributedKeyBindingsArray(thing: ContributedKeyBinding | ContributedKeyBinding[]): thing is ContributedKeyBinding[] {
E
Erich Gamma 已提交
62 63 64 65 66 67 68 69 70
	return Array.isArray(thing);
}

function isValidContributedKeyBinding(keyBinding: ContributedKeyBinding, rejects: string[]): boolean {
	if (!keyBinding) {
		rejects.push(nls.localize('nonempty', "expected non-empty value."));
		return false;
	}
	if (typeof keyBinding.command !== 'string') {
B
Benjamin Pasero 已提交
71
		rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command'));
E
Erich Gamma 已提交
72 73
		return false;
	}
A
Alex Dima 已提交
74 75
	if (keyBinding.key && typeof keyBinding.key !== 'string') {
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'key'));
E
Erich Gamma 已提交
76 77 78
		return false;
	}
	if (keyBinding.when && typeof keyBinding.when !== 'string') {
B
Benjamin Pasero 已提交
79
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when'));
E
Erich Gamma 已提交
80 81 82
		return false;
	}
	if (keyBinding.mac && typeof keyBinding.mac !== 'string') {
B
Benjamin Pasero 已提交
83
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'mac'));
E
Erich Gamma 已提交
84 85 86
		return false;
	}
	if (keyBinding.linux && typeof keyBinding.linux !== 'string') {
B
Benjamin Pasero 已提交
87
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'linux'));
E
Erich Gamma 已提交
88 89 90
		return false;
	}
	if (keyBinding.win && typeof keyBinding.win !== 'string') {
B
Benjamin Pasero 已提交
91
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'win'));
E
Erich Gamma 已提交
92 93 94 95 96
		return false;
	}
	return true;
}

97
let keybindingType: IJSONSchema = {
E
Erich Gamma 已提交
98 99 100 101 102 103 104
	type: 'object',
	default: { command: '', key: '' },
	properties: {
		command: {
			description: nls.localize('vscode.extension.contributes.keybindings.command', 'Identifier of the command to run when keybinding is triggered.'),
			type: 'string'
		},
J
Johannes Rieken 已提交
105
		args: {
106
			description: nls.localize('vscode.extension.contributes.keybindings.args', "Arguments to pass to the command to execute.")
J
Johannes Rieken 已提交
107
		},
E
Erich Gamma 已提交
108
		key: {
109
			description: nls.localize('vscode.extension.contributes.keybindings.key', 'Key or key sequence (separate keys with plus-sign and sequences with space, e.g. Ctrl+O and Ctrl+L L for a chord).'),
E
Erich Gamma 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
			type: 'string'
		},
		mac: {
			description: nls.localize('vscode.extension.contributes.keybindings.mac', 'Mac specific key or key sequence.'),
			type: 'string'
		},
		linux: {
			description: nls.localize('vscode.extension.contributes.keybindings.linux', 'Linux specific key or key sequence.'),
			type: 'string'
		},
		win: {
			description: nls.localize('vscode.extension.contributes.keybindings.win', 'Windows specific key or key sequence.'),
			type: 'string'
		},
		when: {
			description: nls.localize('vscode.extension.contributes.keybindings.when', 'Condition when the key is active.'),
			type: 'string'
J
Johannes Rieken 已提交
127
		},
E
Erich Gamma 已提交
128 129 130
	}
};

131 132
const keybindingsExtPoint = ExtensionsRegistry.registerExtensionPoint<ContributedKeyBinding | ContributedKeyBinding[]>({
	extensionPoint: 'keybindings',
133
	deps: [commandsExtensionPoint],
134 135 136 137 138 139 140 141 142 143
	jsonSchema: {
		description: nls.localize('vscode.extension.contributes.keybindings', "Contributes keybindings."),
		oneOf: [
			keybindingType,
			{
				type: 'array',
				items: keybindingType
			}
		]
	}
E
Erich Gamma 已提交
144 145
});

146 147
export class WorkbenchKeybindingService extends AbstractKeybindingService {

148
	private _keyboardMapper: IKeyboardMapper;
A
Alex Dima 已提交
149
	private _cachedResolver: KeybindingResolver | null;
150
	private userKeybindings: UserKeybindings;
E
Erich Gamma 已提交
151

152
	constructor(
153
		@IContextKeyService contextKeyService: IContextKeyService,
154
		@ICommandService commandService: ICommandService,
155
		@ITelemetryService telemetryService: ITelemetryService,
156
		@INotificationService notificationService: INotificationService,
157
		@IEnvironmentService environmentService: IEnvironmentService,
158
		@IConfigurationService configurationService: IConfigurationService,
A
Alex Dima 已提交
159
		@IWindowService private readonly windowService: IWindowService,
160
		@IExtensionService extensionService: IExtensionService,
P
Peng Lyu 已提交
161
		@IFileService fileService: IFileService,
P
Peng Lyu 已提交
162
		@IKeymapService private readonly keymapService: IKeymapService
163
	) {
164
		super(contextKeyService, commandService, telemetryService, notificationService);
165

166 167
		updateSchema();

168
		let dispatchConfig = getDispatchConfig(configurationService);
169
		configurationService.onDidChangeConfiguration((e) => {
170 171 172 173 174 175
			let newDispatchConfig = getDispatchConfig(configurationService);
			if (dispatchConfig === newDispatchConfig) {
				return;
			}

			dispatchConfig = newDispatchConfig;
P
Peng Lyu 已提交
176
			this._keyboardMapper = this.keymapService.getKeyboardMapper(dispatchConfig);
177 178 179
			this.updateResolver({ source: KeybindingSource.Default });
		});

P
Peng Lyu 已提交
180 181 182
		this._keyboardMapper = this.keymapService.getKeyboardMapper(dispatchConfig);
		this.keymapService.onDidChangeKeyboardMapper(() => {
			this._keyboardMapper = this.keymapService.getKeyboardMapper(dispatchConfig);
A
Alex Dima 已提交
183 184
			this.updateResolver({ source: KeybindingSource.Default });
		});
185

186 187
		this._cachedResolver = null;

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		this.userKeybindings = this._register(new UserKeybindings(environmentService.keybindingsResource, fileService));
		this.userKeybindings.initialize().then(() => {
			if (this.userKeybindings.keybindings.length) {
				this.updateResolver({ source: KeybindingSource.User });
			}
		});
		this._register(this.userKeybindings.onDidChange(() => {
			/* __GDPR__
				"customKeybindingsChanged" : {
					"keyCount" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
				}
			*/
			this._telemetryService.publicLog('customKeybindingsChanged', {
				keyCount: this.userKeybindings.keybindings.length
			});
			this.updateResolver({
				source: KeybindingSource.User,
				keybindings: this.userKeybindings.keybindings
			});
		}));
208

E
Erich Gamma 已提交
209 210
		keybindingsExtPoint.setHandler((extensions) => {

211
			let keybindings: IKeybindingRule2[] = [];
E
Erich Gamma 已提交
212
			for (let extension of extensions) {
213
				this._handleKeybindingsExtensionPointUser(extension.description.isBuiltin, extension.value, extension.collector, keybindings);
E
Erich Gamma 已提交
214 215
			}

216 217
			KeybindingsRegistry.setExtensionKeybindings(keybindings);
			this.updateResolver({ source: KeybindingSource.Default });
E
Erich Gamma 已提交
218
		});
219

A
Alex Dima 已提交
220 221 222
		updateSchema();
		this._register(extensionService.onDidRegisterExtensions(() => updateSchema()));

223
		this._register(dom.addDisposableListener(window, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
224
			let keyEvent = new StandardKeyboardEvent(e);
225
			let shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
226 227 228 229 230
			if (shouldPreventDefault) {
				keyEvent.preventDefault();
			}
		}));

C
Christof Marti 已提交
231
		keybindingsTelemetry(telemetryService, this);
P
Peng Lyu 已提交
232
		let data = this.keymapService.getCurrentKeyboardLayout();
K
kieferrm 已提交
233
		/* __GDPR__
K
kieferrm 已提交
234 235 236 237
			"keyboardLayout" : {
				"currentKeyboardLayout": { "${inline}": [ "${IKeyboardLayoutInfo}" ] }
			}
		*/
A
Alex Dima 已提交
238 239 240
		telemetryService.publicLog('keyboardLayout', {
			currentKeyboardLayout: data
		});
P
Peng Lyu 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

		this._register(browser.onDidChangeFullscreen(() => {
			const keyboard = (<INavigatorWithKeyboard>navigator).keyboard;

			if (!keyboard) {
				return;
			}

			if (browser.isFullscreen()) {
				keyboard.lock(['Escape']);
			} else {
				keyboard.unlock();
			}

			// update resolver which will bring back all unbound keyboard shortcuts
			this._cachedResolver = null;
			this._onDidUpdateKeybindings.fire({ source: KeybindingSource.User });
		}));
E
Erich Gamma 已提交
259 260
	}

261
	public _dumpDebugInfo(): string {
P
Peng Lyu 已提交
262
		const layoutInfo = JSON.stringify(this.keymapService.getCurrentKeyboardLayout(), null, '\t');
A
Alex Dima 已提交
263
		const mapperInfo = this._keyboardMapper.dumpDebugInfo();
P
Peng Lyu 已提交
264
		const rawMapping = JSON.stringify(this.keymapService.getRawKeyboardMapping(), null, '\t');
A
Alex Dima 已提交
265
		return `Layout info:\n${layoutInfo}\n${mapperInfo}\n\nRaw mapping:\n${rawMapping}`;
A
Alex Dima 已提交
266 267
	}

P
Peng Lyu 已提交
268 269 270 271 272 273 274 275
	public _dumpDebugInfoJSON(): string {
		const info = {
			layout: this.keymapService.getCurrentKeyboardLayout(),
			rawMapping: this.keymapService.getRawKeyboardMapping()
		};
		return JSON.stringify(info, null, '\t');
	}

276
	public customKeybindingsCount(): number {
277
		return this.userKeybindings.keybindings.length;
278 279
	}

280 281 282 283 284 285 286
	private updateResolver(event: IKeybindingEvent): void {
		this._cachedResolver = null;
		this._onDidUpdateKeybindings.fire(event);
	}

	protected _getResolver(): KeybindingResolver {
		if (!this._cachedResolver) {
287
			const defaults = this._resolveKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
288
			const overrides = this._resolveUserKeybindingItems(this.userKeybindings.keybindings.map((k) => KeybindingIO.readUserKeybindingItem(k)), false);
289
			this._cachedResolver = new KeybindingResolver(defaults, overrides);
290 291
		}
		return this._cachedResolver;
292 293
	}

294
	protected _documentHasFocus(): boolean {
295 296 297 298
		// it is possible that the document has lost focus, but the
		// window is still focused, e.g. when a <webview> element
		// has focus
		return this.windowService.hasFocus;
299 300
	}

301
	private _resolveKeybindingItems(items: IKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
302
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
303
		for (const item of items) {
304
			const when = (item.when ? item.when.normalize() : undefined);
A
Alex Dima 已提交
305
			const keybinding = item.keybinding;
306 307
			if (!keybinding) {
				// This might be a removal keybinding item in user settings => accept it
308
				result[resultLen++] = new ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault);
309
			} else {
310 311 312 313
				if (this._assertBrowserConflicts(keybinding, item.command)) {
					continue;
				}

314
				const resolvedKeybindings = this.resolveKeybinding(keybinding);
315 316
				for (const resolvedKeybinding of resolvedKeybindings) {
					result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault);
317 318
				}
			}
319 320 321
		}

		return result;
322 323
	}

324 325
	private _resolveUserKeybindingItems(items: IUserKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
326
		for (const item of items) {
327
			const when = (item.when ? item.when.normalize() : undefined);
A
Alex Dima 已提交
328 329
			const parts = item.parts;
			if (parts.length === 0) {
330
				// This might be a removal keybinding item in user settings => accept it
331
				result[resultLen++] = new ResolvedKeybindingItem(undefined, item.command, item.commandArgs, when, isDefault);
332
			} else {
333
				const resolvedKeybindings = this._keyboardMapper.resolveUserBinding(parts);
334 335
				for (const resolvedKeybinding of resolvedKeybindings) {
					result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault);
336 337 338 339 340 341 342
				}
			}
		}

		return result;
	}

343
	private _assertBrowserConflicts(kb: Keybinding, commandId: string): boolean {
P
Peng Lyu 已提交
344 345 346 347
		if (!isWeb) {
			return false;
		}

348 349 350 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
		if (browser.isFullscreen() && (<any>navigator).keyboard) {
			return false;
		}

		for (let part of kb.parts) {
			if (!part.metaKey && !part.altKey && !part.ctrlKey && !part.shiftKey) {
				continue;
			}

			const modifiersMask = KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift;

			let partModifiersMask = 0;
			if (part.metaKey) {
				partModifiersMask |= KeyMod.CtrlCmd;
			}

			if (part.shiftKey) {
				partModifiersMask |= KeyMod.Shift;
			}

			if (part.altKey) {
				partModifiersMask |= KeyMod.Alt;
			}

			if (part.ctrlKey && OS === OperatingSystem.Macintosh) {
				partModifiersMask |= KeyMod.WinCtrl;
			}

			if ((partModifiersMask & modifiersMask) === KeyMod.CtrlCmd && part.keyCode === KeyCode.KEY_W) {
P
Peng Lyu 已提交
377
				// console.warn('Ctrl/Cmd+W keybindings should not be used by default in web. Offender: ', kb.getHashCode(), ' for ', commandId);
378 379 380 381 382

				return true;
			}

			if ((partModifiersMask & modifiersMask) === KeyMod.CtrlCmd && part.keyCode === KeyCode.KEY_N) {
P
Peng Lyu 已提交
383
				// console.warn('Ctrl/Cmd+N keybindings should not be used by default in web. Offender: ', kb.getHashCode(), ' for ', commandId);
384 385 386 387 388

				return true;
			}

			if ((partModifiersMask & modifiersMask) === KeyMod.CtrlCmd && part.keyCode === KeyCode.KEY_T) {
P
Peng Lyu 已提交
389
				// console.warn('Ctrl/Cmd+T keybindings should not be used by default in web. Offender: ', kb.getHashCode(), ' for ', commandId);
390 391 392 393 394

				return true;
			}

			if ((partModifiersMask & modifiersMask) === (KeyMod.CtrlCmd | KeyMod.Alt) && (part.keyCode === KeyCode.LeftArrow || part.keyCode === KeyCode.RightArrow)) {
P
Peng Lyu 已提交
395
				// console.warn('Ctrl/Cmd+Arrow keybindings should not be used by default in web. Offender: ', kb.getHashCode(), ' for ', commandId);
396 397 398 399 400

				return true;
			}

			if ((partModifiersMask & modifiersMask) === KeyMod.CtrlCmd && part.keyCode >= KeyCode.KEY_0 && part.keyCode <= KeyCode.KEY_9) {
P
Peng Lyu 已提交
401
				// console.warn('Ctrl/Cmd+Num keybindings should not be used by default in web. Offender: ', kb.getHashCode(), ' for ', commandId);
402 403 404 405 406 407 408 409

				return true;
			}
		}

		return false;
	}

410
	public resolveKeybinding(kb: Keybinding): ResolvedKeybinding[] {
411
		return this._keyboardMapper.resolveKeybinding(kb);
A
Alex Dima 已提交
412 413
	}

414
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding {
P
Peng Lyu 已提交
415
		this.keymapService.validateCurrentKeyboardMapping(keyboardEvent);
416
		return this._keyboardMapper.resolveKeyboardEvent(keyboardEvent);
417 418
	}

419
	public resolveUserBinding(userBinding: string): ResolvedKeybinding[] {
420 421
		const parts = KeybindingParser.parseUserBinding(userBinding);
		return this._keyboardMapper.resolveUserBinding(parts);
422 423
	}

424
	private _handleKeybindingsExtensionPointUser(isBuiltin: boolean, keybindings: ContributedKeyBinding | ContributedKeyBinding[], collector: ExtensionMessageCollector, result: IKeybindingRule2[]): void {
E
Erich Gamma 已提交
425 426
		if (isContributedKeyBindingsArray(keybindings)) {
			for (let i = 0, len = keybindings.length; i < len; i++) {
427
				this._handleKeybinding(isBuiltin, i + 1, keybindings[i], collector, result);
E
Erich Gamma 已提交
428 429
			}
		} else {
430
			this._handleKeybinding(isBuiltin, 1, keybindings, collector, result);
E
Erich Gamma 已提交
431 432 433
		}
	}

434
	private _handleKeybinding(isBuiltin: boolean, idx: number, keybindings: ContributedKeyBinding, collector: ExtensionMessageCollector, result: IKeybindingRule2[]): void {
E
Erich Gamma 已提交
435 436 437 438 439 440

		let rejects: string[] = [];

		if (isValidContributedKeyBinding(keybindings, rejects)) {
			let rule = this._asCommandRule(isBuiltin, idx++, keybindings);
			if (rule) {
441
				result.push(rule);
E
Erich Gamma 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454
			}
		}

		if (rejects.length > 0) {
			collector.error(nls.localize(
				'invalid.keybindings',
				"Invalid `contributes.{0}`: {1}",
				keybindingsExtPoint.name,
				rejects.join('\n')
			));
		}
	}

A
Alex Dima 已提交
455
	private _asCommandRule(isBuiltin: boolean, idx: number, binding: ContributedKeyBinding): IKeybindingRule2 | undefined {
E
Erich Gamma 已提交
456

J
Johannes Rieken 已提交
457
		let { command, args, when, key, mac, linux, win } = binding;
E
Erich Gamma 已提交
458 459 460

		let weight: number;
		if (isBuiltin) {
461
			weight = KeybindingWeight.BuiltinExtension + idx;
E
Erich Gamma 已提交
462
		} else {
463
			weight = KeybindingWeight.ExternalExtension + idx;
E
Erich Gamma 已提交
464 465
		}

466 467 468 469 470 471 472 473 474 475 476
		let commandAction = MenuRegistry.getCommand(command);
		let precondition = commandAction && commandAction.precondition;
		let fullWhen: ContextKeyExpr | undefined;
		if (when && precondition) {
			fullWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(when));
		} else if (when) {
			fullWhen = ContextKeyExpr.deserialize(when);
		} else if (precondition) {
			fullWhen = precondition;
		}

A
Alex Dima 已提交
477
		let desc: IKeybindingRule2 = {
E
Erich Gamma 已提交
478
			id: command,
J
Johannes Rieken 已提交
479
			args,
480
			when: fullWhen,
E
Erich Gamma 已提交
481
			weight: weight,
J
Joao Moreno 已提交
482
			primary: KeybindingParser.parseKeybinding(key, OS),
A
Alex Dima 已提交
483 484 485
			mac: mac ? { primary: KeybindingParser.parseKeybinding(mac, OS) } : null,
			linux: linux ? { primary: KeybindingParser.parseKeybinding(linux, OS) } : null,
			win: win ? { primary: KeybindingParser.parseKeybinding(win, OS) } : null
B
Benjamin Pasero 已提交
486
		};
E
Erich Gamma 已提交
487 488

		if (!desc.primary && !desc.mac && !desc.linux && !desc.win) {
489
			return undefined;
E
Erich Gamma 已提交
490 491 492 493
		}

		return desc;
	}
A
Alex Dima 已提交
494

S
Sandeep Somavarapu 已提交
495
	public getDefaultKeybindingsContent(): string {
A
Alex Dima 已提交
496 497 498 499 500 501 502 503 504 505
		const resolver = this._getResolver();
		const defaultKeybindings = resolver.getDefaultKeybindings();
		const boundCommands = resolver.getDefaultBoundCommands();
		return (
			WorkbenchKeybindingService._getDefaultKeybindings(defaultKeybindings)
			+ '\n\n'
			+ WorkbenchKeybindingService._getAllCommandsAsComment(boundCommands)
		);
	}

506
	private static _getDefaultKeybindings(defaultKeybindings: ResolvedKeybindingItem[]): string {
A
Alex Dima 已提交
507 508 509 510 511
		let out = new OutputBuilder();
		out.writeLine('[');

		let lastIndex = defaultKeybindings.length - 1;
		defaultKeybindings.forEach((k, index) => {
A
Alex Dima 已提交
512
			KeybindingIO.writeKeybindingItem(out, k);
A
Alex Dima 已提交
513 514 515 516 517 518 519 520 521 522 523
			if (index !== lastIndex) {
				out.writeLine(',');
			} else {
				out.writeLine();
			}
		});
		out.writeLine(']');
		return out.toString();
	}

	private static _getAllCommandsAsComment(boundCommands: Map<string, boolean>): string {
S
Sandeep Somavarapu 已提交
524
		const unboundCommands = KeybindingResolver.getAllUnboundCommands(boundCommands);
A
Alex Dima 已提交
525 526 527
		let pretty = unboundCommands.sort().join('\n// - ');
		return '// ' + nls.localize('unboundCommands', "Here are other available commands: ") + '\n// - ' + pretty;
	}
528 529 530 531 532 533 534 535

	mightProducePrintableCharacter(event: IKeyboardEvent): boolean {
		if (event.ctrlKey || event.metaKey) {
			// ignore ctrl/cmd-combination but not shift/alt-combinatios
			return false;
		}
		// consult the KeyboardMapperFactory to check the given event for
		// a printable value.
P
Peng Lyu 已提交
536
		const mapping = this.keymapService.getRawKeyboardMapping();
537 538 539 540 541 542 543
		if (!mapping) {
			return false;
		}
		const keyInfo = mapping[event.code];
		if (!keyInfo) {
			return false;
		}
544 545
		if (!keyInfo.value || /\s/.test(keyInfo.value)) {
			return false;
546
		}
547
		return true;
548
	}
549
}
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
class UserKeybindings extends Disposable {

	private _keybindings: IUserFriendlyKeybinding[] = [];
	get keybindings(): IUserFriendlyKeybinding[] { return this._keybindings; }
	private readonly reloadConfigurationScheduler: RunOnceScheduler;
	protected readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
	readonly onDidChange: Event<void> = this._onDidChange.event;

	private fileWatcherDisposable: IDisposable = Disposable.None;
	private directoryWatcherDisposable: IDisposable = Disposable.None;

	constructor(
		private readonly keybindingsResource: URI,
		private readonly fileService: IFileService
	) {
		super();

		this._register(fileService.onFileChanges(e => this.handleFileEvents(e)));
		this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.reload().then(changed => {
			if (changed) {
				this._onDidChange.fire();
			}
		}), 50));
		this._register(toDisposable(() => {
			this.stopWatchingResource();
			this.stopWatchingDirectory();
		}));
	}

	private watchResource(): void {
		this.fileWatcherDisposable = this.fileService.watch(this.keybindingsResource);
	}

	private stopWatchingResource(): void {
		this.fileWatcherDisposable.dispose();
		this.fileWatcherDisposable = Disposable.None;
	}

	private watchDirectory(): void {
		const directory = dirname(this.keybindingsResource);
		this.directoryWatcherDisposable = this.fileService.watch(directory);
	}

	private stopWatchingDirectory(): void {
		this.directoryWatcherDisposable.dispose();
		this.directoryWatcherDisposable = Disposable.None;
	}

	async initialize(): Promise<void> {
		const exists = await this.fileService.exists(this.keybindingsResource);
		this.onResourceExists(exists);
		await this.reload();
	}

	private async reload(): Promise<boolean> {
		const existing = this._keybindings;
		try {
			const content = await this.fileService.readFile(this.keybindingsResource);
S
Sandeep Somavarapu 已提交
609 610
			const value = parse(content.value.toString());
			this._keybindings = isArray(value) ? value : [];
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
		} catch (e) {
			this._keybindings = [];
		}
		return existing ? !objects.equals(existing, this._keybindings) : true;
	}

	private async handleFileEvents(event: FileChangesEvent): Promise<void> {
		const events = event.changes;

		let affectedByChanges = false;

		// Find changes that affect the resource
		for (const event of events) {
			affectedByChanges = isEqual(this.keybindingsResource, event.resource);
			if (affectedByChanges) {
				if (event.type === FileChangeType.ADDED) {
					this.onResourceExists(true);
				} else if (event.type === FileChangeType.DELETED) {
					this.onResourceExists(false);
				}
				break;
			}
		}

		if (affectedByChanges) {
			this.reloadConfigurationScheduler.schedule();
		}
	}

	private onResourceExists(exists: boolean): void {
		if (exists) {
			this.stopWatchingDirectory();
			this.watchResource();
		} else {
			this.stopWatchingResource();
			this.watchDirectory();
		}
	}
}

651
let schemaId = 'vscode://schemas/keybindings';
A
Alex Dima 已提交
652
let commandsSchemas: IJSONSchema[] = [];
653
let commandsEnum: string[] = [];
654
let commandsEnumDescriptions: (string | undefined)[] = [];
655
let schema: IJSONSchema = {
656 657 658
	'id': schemaId,
	'type': 'array',
	'title': nls.localize('keybindings.json.title', "Keybindings configuration"),
659
	'definitions': {
660
		'editorGroupsSchema': {
661 662 663 664 665
			'type': 'array',
			'items': {
				'type': 'object',
				'properties': {
					'groups': {
666
						'$ref': '#/definitions/editorGroupsSchema',
667 668 669 670 671 672 673 674 675 676
						'default': [{}, {}]
					},
					'size': {
						'type': 'number',
						'default': 0.5
					}
				}
			}
		}
	},
677 678 679
	'items': {
		'required': ['key'],
		'type': 'object',
680
		'defaultSnippets': [{ 'body': { 'key': '$1', 'command': '$2', 'when': '$3' } }],
681 682 683
		'properties': {
			'key': {
				'type': 'string',
684
				'description': nls.localize('keybindings.json.key', "Key or key sequence (separated by space)"),
685 686
			},
			'command': {
A
al 已提交
687
				'type': 'string',
688
				'enum': commandsEnum,
A
Alex Dima 已提交
689
				'enumDescriptions': <any>commandsEnumDescriptions,
690
				'description': nls.localize('keybindings.json.command', "Name of the command to execute"),
691 692 693
			},
			'when': {
				'type': 'string',
694 695 696 697
				'description': nls.localize('keybindings.json.when', "Condition when the key is active.")
			},
			'args': {
				'description': nls.localize('keybindings.json.args', "Arguments to pass to the command to execute.")
698
			}
699
		},
A
Alex Dima 已提交
700
		'allOf': commandsSchemas
701 702 703 704 705 706 707
	}
};

let schemaRegistry = Registry.as<IJSONContributionRegistry>(Extensions.JSONContribution);
schemaRegistry.registerSchema(schemaId, schema);

function updateSchema() {
A
Alex Dima 已提交
708 709 710 711
	commandsSchemas.length = 0;
	commandsEnum.length = 0;
	commandsEnumDescriptions.length = 0;

712
	const knownCommands = new Set<string>();
713
	const addKnownCommand = (commandId: string, description?: string | undefined) => {
714 715 716 717 718 719 720 721 722 723 724 725 726 727
		if (!/^_/.test(commandId)) {
			if (!knownCommands.has(commandId)) {
				knownCommands.add(commandId);

				commandsEnum.push(commandId);
				commandsEnumDescriptions.push(description);

				// Also add the negative form for keybinding removal
				commandsEnum.push(`-${commandId}`);
				commandsEnumDescriptions.push(description);
			}
		}
	};

728 729 730
	const allCommands = CommandsRegistry.getCommands();
	for (let commandId in allCommands) {
		const commandDescription = allCommands[commandId].description;
731

732
		addKnownCommand(commandId, commandDescription ? commandDescription.description : undefined);
733

734 735 736 737 738
		if (!commandDescription || !commandDescription.args || commandDescription.args.length !== 1 || !commandDescription.args[0].schema) {
			continue;
		}

		const argsSchema = commandDescription.args[0].schema;
739
		const argsRequired = Array.isArray(argsSchema.required) && argsSchema.required.length > 0;
740
		const addition = {
741 742
			'if': {
				'properties': {
743
					'command': { 'const': commandId }
744 745 746
				}
			},
			'then': {
A
Alex Dima 已提交
747
				'required': (<string[]>[]).concat(argsRequired ? ['args'] : []),
748
				'properties': {
749
					'args': argsSchema
750 751
				}
			}
752
		};
753

A
Alex Dima 已提交
754
		commandsSchemas.push(addition);
755
	}
756 757 758 759 760

	const menuCommands = MenuRegistry.getCommands();
	for (let commandId in menuCommands) {
		addKnownCommand(commandId);
	}
761
}
762

763
const configurationRegistry = Registry.as<IConfigurationRegistry>(ConfigExtensions.Configuration);
764 765 766 767 768 769 770 771 772 773 774
const keyboardConfiguration: IConfigurationNode = {
	'id': 'keyboard',
	'order': 15,
	'type': 'object',
	'title': nls.localize('keyboardConfigurationTitle', "Keyboard"),
	'overridable': true,
	'properties': {
		'keyboard.dispatch': {
			'type': 'string',
			'enum': ['code', 'keyCode'],
			'default': 'code',
775
			'markdownDescription': nls.localize('dispatch', "Controls the dispatching logic for key presses to use either `code` (recommended) or `keyCode`."),
776
			'included': OS === OperatingSystem.Macintosh || OS === OperatingSystem.Linux
777
		}
P
Peng Lyu 已提交
778
		// no touch bar support
779 780
	}
};
781

782
configurationRegistry.registerConfiguration(keyboardConfiguration);
783

784
registerSingleton(IKeybindingService, WorkbenchKeybindingService);