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

7
import * as nls from 'vs/nls';
J
Johannes Rieken 已提交
8 9
import { IHTMLContentElement } from 'vs/base/common/htmlContent';
import { IJSONSchema } from 'vs/base/common/jsonSchema';
10
import { ResolvedKeybinding, Keybinding } from 'vs/base/common/keyCodes';
A
Alex Dima 已提交
11 12
import { PrintableKeypress, UILabelProvider, AriaLabelProvider } from 'vs/platform/keybinding/common/keybindingLabels';
import { OS, OperatingSystem } from 'vs/base/common/platform';
J
Johannes Rieken 已提交
13
import { toDisposable } from 'vs/base/common/lifecycle';
14
import { ExtensionMessageCollector, ExtensionsRegistry } from 'vs/platform/extensions/common/extensionsRegistry';
J
Johannes Rieken 已提交
15
import { Extensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
A
Alex Dima 已提交
16
import { AbstractKeybindingService, USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/abstractKeybindingService';
J
Johannes Rieken 已提交
17
import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar';
A
Alex Dima 已提交
18
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
A
Alex Dima 已提交
19 20
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { ICommandService, CommandsRegistry, ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
21
import { IKeybindingEvent, IKeybindingItem, IUserFriendlyKeybinding, KeybindingSource } from 'vs/platform/keybinding/common/keybinding';
22
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
J
Johannes Rieken 已提交
23 24
import { IKeybindingRule, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Registry } from 'vs/platform/platform';
25 26
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { keybindingsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
A
Alex Dima 已提交
27
import { getCurrentKeyboardLayout, getNativeUIKeyCodeLabelProvider, getNativeAriaKeyCodeLabelProvider } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymap';
J
Johannes Rieken 已提交
28 29 30
import { IMessageService } from 'vs/platform/message/common/message';
import { ConfigWatcher } from 'vs/base/node/config';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
31 32
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
33
import { NormalizedKeybindingItem } from 'vs/platform/keybinding/common/normalizedKeybindingItem';
A
Alex Dima 已提交
34
import { KeybindingIO, OutputBuilder } from 'vs/workbench/services/keybinding/common/keybindingIO';
E
Erich Gamma 已提交
35 36 37 38 39 40 41 42 43 44

interface ContributedKeyBinding {
	command: string;
	key: string;
	when?: string;
	mac?: string;
	linux?: string;
	win?: string;
}

45
function isContributedKeyBindingsArray(thing: ContributedKeyBinding | ContributedKeyBinding[]): thing is ContributedKeyBinding[] {
E
Erich Gamma 已提交
46 47 48 49 50 51 52 53 54
	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 已提交
55
		rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command'));
E
Erich Gamma 已提交
56 57 58
		return false;
	}
	if (typeof keyBinding.key !== 'string') {
B
Benjamin Pasero 已提交
59
		rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'key'));
E
Erich Gamma 已提交
60 61 62
		return false;
	}
	if (keyBinding.when && typeof keyBinding.when !== 'string') {
B
Benjamin Pasero 已提交
63
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when'));
E
Erich Gamma 已提交
64 65 66
		return false;
	}
	if (keyBinding.mac && typeof keyBinding.mac !== 'string') {
B
Benjamin Pasero 已提交
67
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'mac'));
E
Erich Gamma 已提交
68 69 70
		return false;
	}
	if (keyBinding.linux && typeof keyBinding.linux !== 'string') {
B
Benjamin Pasero 已提交
71
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'linux'));
E
Erich Gamma 已提交
72 73 74
		return false;
	}
	if (keyBinding.win && typeof keyBinding.win !== 'string') {
B
Benjamin Pasero 已提交
75
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'win'));
E
Erich Gamma 已提交
76 77 78 79 80
		return false;
	}
	return true;
}

81
let keybindingType: IJSONSchema = {
E
Erich Gamma 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	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'
		},
		key: {
			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'),
			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'
		}
	}
};

A
Alex Dima 已提交
112
let keybindingsExtPoint = ExtensionsRegistry.registerExtensionPoint<ContributedKeyBinding | ContributedKeyBinding[]>('keybindings', [], {
E
Erich Gamma 已提交
113 114 115 116 117 118 119 120 121 122
	description: nls.localize('vscode.extension.contributes.keybindings', "Contributes keybindings."),
	oneOf: [
		keybindingType,
		{
			type: 'array',
			items: keybindingType
		}
	]
});

A
Alex Dima 已提交
123 124 125 126 127 128 129 130 131 132
export class FancyResolvedKeybinding extends ResolvedKeybinding {

	private readonly _actual: Keybinding;

	constructor(actual: Keybinding) {
		super();
		this._actual = actual;
	}

	public getLabel(): string {
A
Alex Dima 已提交
133
		const keyCodeLabelProvider = getNativeUIKeyCodeLabelProvider();
134
		const [firstPart, chordPart] = PrintableKeypress.fromKeybinding(this._actual, keyCodeLabelProvider, OS);
A
Alex Dima 已提交
135

A
Alex Dima 已提交
136
		return UILabelProvider.toLabel2(firstPart, chordPart, OS);
A
Alex Dima 已提交
137 138 139
	}

	public getAriaLabel(): string {
A
Alex Dima 已提交
140
		const keyCodeLabelProvider = getNativeAriaKeyCodeLabelProvider();
141
		const [firstPart, chordPart] = PrintableKeypress.fromKeybinding(this._actual, keyCodeLabelProvider, OS);
A
Alex Dima 已提交
142

A
Alex Dima 已提交
143
		return AriaLabelProvider.toLabel2(firstPart, chordPart, OS);
A
Alex Dima 已提交
144 145 146
	}

	public getHTMLLabel(): IHTMLContentElement[] {
A
Alex Dima 已提交
147
		const keyCodeLabelProvider = getNativeUIKeyCodeLabelProvider();
148
		const [firstPart, chordPart] = PrintableKeypress.fromKeybinding(this._actual, keyCodeLabelProvider, OS);
A
Alex Dima 已提交
149

A
Alex Dima 已提交
150
		return UILabelProvider.toHTMLLabel2(firstPart, chordPart, OS);
A
Alex Dima 已提交
151 152 153
	}

	public getElectronAccelerator(): string {
A
Alex Dima 已提交
154 155 156
		const usResolvedKeybinding = new USLayoutResolvedKeybinding(this._actual, OS);

		if (OS === OperatingSystem.Windows) {
A
Alex Dima 已提交
157
			// electron menus always do the correct rendering on Windows
A
Alex Dima 已提交
158
			return usResolvedKeybinding.getElectronAccelerator();
A
Alex Dima 已提交
159 160
		}

A
Alex Dima 已提交
161
		let usLabel = usResolvedKeybinding.getLabel();
A
Alex Dima 已提交
162 163 164 165 166 167 168
		let label = this.getLabel();
		if (usLabel !== label) {
			// electron menus are incorrect in rendering (linux) and in rendering and interpreting (mac)
			// for non US standard keyboard layouts
			return null;
		}

A
Alex Dima 已提交
169
		return usResolvedKeybinding.getElectronAccelerator();
A
Alex Dima 已提交
170
	}
171 172

	public getUserSettingsLabel(): string {
A
Alex Dima 已提交
173
		return KeybindingIO.writeKeybinding(this._actual, OS);
174
	}
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

	public isChord(): boolean {
		return this._actual.isChord();
	}

	public hasCtrlModifier(): boolean {
		if (this._actual.isChord()) {
			return false;
		}
		if (OS === OperatingSystem.Macintosh) {
			return this._actual.hasWinCtrl();
		} else {
			return this._actual.hasCtrlCmd();
		}
	}

	public hasShiftModifier(): boolean {
		if (this._actual.isChord()) {
			return false;
		}
		return this._actual.hasShift();
	}

	public hasAltModifier(): boolean {
		if (this._actual.isChord()) {
			return false;
		}
		return this._actual.hasAlt();
	}

	public hasMetaModifier(): boolean {
		if (this._actual.isChord()) {
			return false;
		}
		if (OS === OperatingSystem.Macintosh) {
			return this._actual.hasCtrlCmd();
		} else {
			return this._actual.hasWinCtrl();
		}
	}
A
Alex Dima 已提交
215 216
}

217 218 219 220
export class WorkbenchKeybindingService extends AbstractKeybindingService {

	private _cachedResolver: KeybindingResolver;
	private _firstTimeComputingResolver: boolean;
221
	private userKeybindings: ConfigWatcher<IUserFriendlyKeybinding[]>;
E
Erich Gamma 已提交
222

223
	constructor(
B
Benjamin Pasero 已提交
224
		windowElement: Window,
225
		@IContextKeyService contextKeyService: IContextKeyService,
226
		@ICommandService commandService: ICommandService,
227
		@ITelemetryService private telemetryService: ITelemetryService,
228
		@IMessageService messageService: IMessageService,
229
		@IEnvironmentService environmentService: IEnvironmentService,
230
		@IStatusbarService statusBarService: IStatusbarService
231
	) {
232
		super(contextKeyService, commandService, messageService, statusBarService);
233

234 235 236
		this._cachedResolver = null;
		this._firstTimeComputingResolver = true;

237
		this.userKeybindings = new ConfigWatcher(environmentService.appKeybindingsPath, { defaultConfig: [] });
B
Benjamin Pasero 已提交
238
		this.toDispose.push(toDisposable(() => this.userKeybindings.dispose()));
239

E
Erich Gamma 已提交
240 241 242 243 244 245 246 247
		keybindingsExtPoint.setHandler((extensions) => {
			let commandAdded = false;

			for (let extension of extensions) {
				commandAdded = this._handleKeybindingsExtensionPointUser(extension.description.isBuiltin, extension.value, extension.collector) || commandAdded;
			}

			if (commandAdded) {
C
Christof Marti 已提交
248
				this.updateResolver({ source: KeybindingSource.Default });
E
Erich Gamma 已提交
249 250
			}
		});
251

C
Christof Marti 已提交
252 253 254 255
		this.toDispose.push(this.userKeybindings.onDidUpdateConfiguration(event => this.updateResolver({
			source: KeybindingSource.User,
			keybindings: event.config
		})));
256

B
Benjamin Pasero 已提交
257
		this.toDispose.push(dom.addDisposableListener(windowElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
258 259 260 261 262 263 264
			let keyEvent = new StandardKeyboardEvent(e);
			let shouldPreventDefault = this._dispatch(keyEvent.toKeybinding(), keyEvent.target);
			if (shouldPreventDefault) {
				keyEvent.preventDefault();
			}
		}));

C
Christof Marti 已提交
265
		keybindingsTelemetry(telemetryService, this);
A
Alex Dima 已提交
266
		let data = getCurrentKeyboardLayout();
A
Alex Dima 已提交
267 268 269
		telemetryService.publicLog('keyboardLayout', {
			currentKeyboardLayout: data
		});
E
Erich Gamma 已提交
270 271
	}

272 273 274 275 276 277 278 279
	private _safeGetConfig(): IUserFriendlyKeybinding[] {
		let rawConfig = this.userKeybindings.getConfig();
		if (Array.isArray(rawConfig)) {
			return rawConfig;
		}
		return [];
	}

280
	public customKeybindingsCount(): number {
281
		let userKeybindings = this._safeGetConfig();
282 283

		return userKeybindings.length;
284 285
	}

286 287 288 289 290 291 292
	private updateResolver(event: IKeybindingEvent): void {
		this._cachedResolver = null;
		this._onDidUpdateKeybindings.fire(event);
	}

	protected _getResolver(): KeybindingResolver {
		if (!this._cachedResolver) {
293 294 295
			const defaults = KeybindingsRegistry.getDefaultKeybindings().map(k => NormalizedKeybindingItem.fromKeybindingItem(k, true));
			const overrides = this._getExtraKeybindings(this._firstTimeComputingResolver).map(k => NormalizedKeybindingItem.fromKeybindingItem(k, false));
			this._cachedResolver = new KeybindingResolver(defaults, overrides);
296 297 298 299 300 301
			this._firstTimeComputingResolver = false;
		}
		return this._cachedResolver;
	}

	private _getExtraKeybindings(isFirstTime: boolean): IKeybindingItem[] {
302
		let extraUserKeybindings: IUserFriendlyKeybinding[] = this._safeGetConfig();
303 304
		if (!isFirstTime) {
			let cnt = extraUserKeybindings.length;
305

306 307 308
			this.telemetryService.publicLog('customKeybindingsChanged', {
				keyCount: cnt
			});
309
		}
310

A
Alex Dima 已提交
311
		return extraUserKeybindings.map((k, i) => KeybindingIO.readKeybindingItem(k, i, OS));
312 313
	}

A
Alex Dima 已提交
314 315 316 317
	protected _createResolvedKeybinding(kb: Keybinding): ResolvedKeybinding {
		return new FancyResolvedKeybinding(kb);
	}

318
	private _handleKeybindingsExtensionPointUser(isBuiltin: boolean, keybindings: ContributedKeyBinding | ContributedKeyBinding[], collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
319 320 321 322 323 324 325 326 327 328 329
		if (isContributedKeyBindingsArray(keybindings)) {
			let commandAdded = false;
			for (let i = 0, len = keybindings.length; i < len; i++) {
				commandAdded = this._handleKeybinding(isBuiltin, i + 1, keybindings[i], collector) || commandAdded;
			}
			return commandAdded;
		} else {
			return this._handleKeybinding(isBuiltin, 1, keybindings, collector);
		}
	}

330
	private _handleKeybinding(isBuiltin: boolean, idx: number, keybindings: ContributedKeyBinding, collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
331 332 333 334 335 336 337

		let rejects: string[] = [];
		let commandAdded = false;

		if (isValidContributedKeyBinding(keybindings, rejects)) {
			let rule = this._asCommandRule(isBuiltin, idx++, keybindings);
			if (rule) {
A
Alex Dima 已提交
338
				KeybindingsRegistry.registerKeybindingRule(rule);
E
Erich Gamma 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
				commandAdded = true;
			}
		}

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

		return commandAdded;
	}

A
Alex Dima 已提交
355
	private _asCommandRule(isBuiltin: boolean, idx: number, binding: ContributedKeyBinding): IKeybindingRule {
E
Erich Gamma 已提交
356 357 358 359 360 361 362 363 364 365 366 367

		let {command, when, key, mac, linux, win} = binding;

		let weight: number;
		if (isBuiltin) {
			weight = KeybindingsRegistry.WEIGHT.builtinExtension(idx);
		} else {
			weight = KeybindingsRegistry.WEIGHT.externalExtension(idx);
		}

		let desc = {
			id: command,
368
			when: ContextKeyExpr.deserialize(when),
E
Erich Gamma 已提交
369
			weight: weight,
A
Alex Dima 已提交
370 371 372 373
			primary: KeybindingIO.readKeybinding(key, OS),
			mac: mac && { primary: KeybindingIO.readKeybinding(mac, OS) },
			linux: linux && { primary: KeybindingIO.readKeybinding(linux, OS) },
			win: win && { primary: KeybindingIO.readKeybinding(win, OS) }
B
Benjamin Pasero 已提交
374
		};
E
Erich Gamma 已提交
375 376

		if (!desc.primary && !desc.mac && !desc.linux && !desc.win) {
377
			return undefined;
E
Erich Gamma 已提交
378 379 380 381
		}

		return desc;
	}
A
Alex Dima 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

	public getDefaultKeybindings(): string {
		const resolver = this._getResolver();
		const defaultKeybindings = resolver.getDefaultKeybindings();
		const boundCommands = resolver.getDefaultBoundCommands();
		return (
			WorkbenchKeybindingService._getDefaultKeybindings(defaultKeybindings)
			+ '\n\n'
			+ WorkbenchKeybindingService._getAllCommandsAsComment(boundCommands)
		);
	}

	private static _getDefaultKeybindings(defaultKeybindings: NormalizedKeybindingItem[]): string {
		let out = new OutputBuilder();
		out.writeLine('[');

		let lastIndex = defaultKeybindings.length - 1;
		defaultKeybindings.forEach((k, index) => {
			KeybindingIO.writeKeybindingItem(out, k, OS);
			if (index !== lastIndex) {
				out.writeLine(',');
			} else {
				out.writeLine();
			}
		});
		out.writeLine(']');
		return out.toString();
	}

	private static _getAllCommandsAsComment(boundCommands: Map<string, boolean>): string {
		const commands = CommandsRegistry.getCommands();
		const unboundCommands: string[] = [];

		for (let id in commands) {
			if (id[0] === '_' || id.indexOf('vscode.') === 0) { // private command
				continue;
			}
			if (typeof commands[id].description === 'object'
				&& !isFalsyOrEmpty((<ICommandHandlerDescription>commands[id].description).args)) { // command with args
				continue;
			}
			if (boundCommands.get(id) === true) {
				continue;
			}
			unboundCommands.push(id);
		}

		let pretty = unboundCommands.sort().join('\n// - ');

		return '// ' + nls.localize('unboundCommands', "Here are other available commands: ") + '\n// - ' + pretty;
	}
433
}
434

435
let schemaId = 'vscode://schemas/keybindings';
436
let schema: IJSONSchema = {
437 438 439 440 441 442
	'id': schemaId,
	'type': 'array',
	'title': nls.localize('keybindings.json.title', "Keybindings configuration"),
	'items': {
		'required': ['key'],
		'type': 'object',
443
		'defaultSnippets': [{ 'body': { 'key': '$1', 'command': '$2', 'when': '$3' } }],
444 445 446
		'properties': {
			'key': {
				'type': 'string',
447
				'description': nls.localize('keybindings.json.key', "Key or key sequence (separated by space)"),
448 449
			},
			'command': {
450
				'description': nls.localize('keybindings.json.command', "Name of the command to execute"),
451 452 453
			},
			'when': {
				'type': 'string',
454 455 456 457
				'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.")
458 459 460 461 462
			}
		}
	}
};

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