keybindingService.ts 13.7 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';
J
Johannes Rieken 已提交
19
import { ICommandService } from 'vs/platform/commands/common/commands';
20
import { IKeybindingEvent, IKeybindingItem, IUserFriendlyKeybinding, KeybindingSource } from 'vs/platform/keybinding/common/keybinding';
21
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
J
Johannes Rieken 已提交
22 23
import { IKeybindingRule, KeybindingsRegistry } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Registry } from 'vs/platform/platform';
24 25
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { keybindingsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
A
Alex Dima 已提交
26
import { getCurrentKeyboardLayout, getNativeUIKeyCodeLabelProvider, getNativeAriaKeyCodeLabelProvider } from 'vs/workbench/services/keybinding/electron-browser/nativeKeymap';
J
Johannes Rieken 已提交
27 28 29
import { IMessageService } from 'vs/platform/message/common/message';
import { ConfigWatcher } from 'vs/base/node/config';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
30 31
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
32
import { NormalizedKeybindingItem } from 'vs/platform/keybinding/common/normalizedKeybindingItem';
A
Alex Dima 已提交
33
import { KeybindingIO } from 'vs/platform/keybinding/common/keybindingIO';
E
Erich Gamma 已提交
34 35 36 37 38 39 40 41 42 43

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

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

80
let keybindingType: IJSONSchema = {
E
Erich Gamma 已提交
81 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
	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 已提交
111
let keybindingsExtPoint = ExtensionsRegistry.registerExtensionPoint<ContributedKeyBinding | ContributedKeyBinding[]>('keybindings', [], {
E
Erich Gamma 已提交
112 113 114 115 116 117 118 119 120 121
	description: nls.localize('vscode.extension.contributes.keybindings', "Contributes keybindings."),
	oneOf: [
		keybindingType,
		{
			type: 'array',
			items: keybindingType
		}
	]
});

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

	private readonly _actual: Keybinding;

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

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
160
		let usLabel = usResolvedKeybinding.getLabel();
A
Alex Dima 已提交
161 162 163 164 165 166 167
		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 已提交
168
		return usResolvedKeybinding.getElectronAccelerator();
A
Alex Dima 已提交
169
	}
170 171

	public getUserSettingsLabel(): string {
A
Alex Dima 已提交
172
		return KeybindingIO.writeKeybinding(this._actual, OS);
173
	}
A
Alex Dima 已提交
174 175
}

176 177 178 179
export class WorkbenchKeybindingService extends AbstractKeybindingService {

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

182
	constructor(
B
Benjamin Pasero 已提交
183
		windowElement: Window,
184
		@IContextKeyService contextKeyService: IContextKeyService,
185
		@ICommandService commandService: ICommandService,
186
		@ITelemetryService private telemetryService: ITelemetryService,
187
		@IMessageService messageService: IMessageService,
188
		@IEnvironmentService environmentService: IEnvironmentService,
189
		@IStatusbarService statusBarService: IStatusbarService
190
	) {
191
		super(contextKeyService, commandService, messageService, statusBarService);
192

193 194 195
		this._cachedResolver = null;
		this._firstTimeComputingResolver = true;

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

E
Erich Gamma 已提交
199 200 201 202 203 204 205 206
		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 已提交
207
				this.updateResolver({ source: KeybindingSource.Default });
E
Erich Gamma 已提交
208 209
			}
		});
210

C
Christof Marti 已提交
211 212 213 214
		this.toDispose.push(this.userKeybindings.onDidUpdateConfiguration(event => this.updateResolver({
			source: KeybindingSource.User,
			keybindings: event.config
		})));
215

B
Benjamin Pasero 已提交
216
		this.toDispose.push(dom.addDisposableListener(windowElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
217 218 219 220 221 222 223
			let keyEvent = new StandardKeyboardEvent(e);
			let shouldPreventDefault = this._dispatch(keyEvent.toKeybinding(), keyEvent.target);
			if (shouldPreventDefault) {
				keyEvent.preventDefault();
			}
		}));

C
Christof Marti 已提交
224
		keybindingsTelemetry(telemetryService, this);
A
Alex Dima 已提交
225
		let data = getCurrentKeyboardLayout();
A
Alex Dima 已提交
226 227 228
		telemetryService.publicLog('keyboardLayout', {
			currentKeyboardLayout: data
		});
E
Erich Gamma 已提交
229 230
	}

231 232 233 234 235 236 237 238
	private _safeGetConfig(): IUserFriendlyKeybinding[] {
		let rawConfig = this.userKeybindings.getConfig();
		if (Array.isArray(rawConfig)) {
			return rawConfig;
		}
		return [];
	}

239
	public customKeybindingsCount(): number {
240
		let userKeybindings = this._safeGetConfig();
241 242

		return userKeybindings.length;
243 244
	}

245 246 247 248 249 250 251
	private updateResolver(event: IKeybindingEvent): void {
		this._cachedResolver = null;
		this._onDidUpdateKeybindings.fire(event);
	}

	protected _getResolver(): KeybindingResolver {
		if (!this._cachedResolver) {
252 253 254
			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);
255 256 257 258 259 260
			this._firstTimeComputingResolver = false;
		}
		return this._cachedResolver;
	}

	private _getExtraKeybindings(isFirstTime: boolean): IKeybindingItem[] {
261
		let extraUserKeybindings: IUserFriendlyKeybinding[] = this._safeGetConfig();
262 263
		if (!isFirstTime) {
			let cnt = extraUserKeybindings.length;
264

265 266 267
			this.telemetryService.publicLog('customKeybindingsChanged', {
				keyCount: cnt
			});
268
		}
269

A
Alex Dima 已提交
270
		return extraUserKeybindings.map((k, i) => KeybindingIO.readKeybindingItem(k, i, OS));
271 272
	}

A
Alex Dima 已提交
273 274 275 276
	protected _createResolvedKeybinding(kb: Keybinding): ResolvedKeybinding {
		return new FancyResolvedKeybinding(kb);
	}

277
	private _handleKeybindingsExtensionPointUser(isBuiltin: boolean, keybindings: ContributedKeyBinding | ContributedKeyBinding[], collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
278 279 280 281 282 283 284 285 286 287 288
		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);
		}
	}

289
	private _handleKeybinding(isBuiltin: boolean, idx: number, keybindings: ContributedKeyBinding, collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
290 291 292 293 294 295 296

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

		if (isValidContributedKeyBinding(keybindings, rejects)) {
			let rule = this._asCommandRule(isBuiltin, idx++, keybindings);
			if (rule) {
A
Alex Dima 已提交
297
				KeybindingsRegistry.registerKeybindingRule(rule);
E
Erich Gamma 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
				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 已提交
314
	private _asCommandRule(isBuiltin: boolean, idx: number, binding: ContributedKeyBinding): IKeybindingRule {
E
Erich Gamma 已提交
315 316 317 318 319 320 321 322 323 324 325 326

		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,
327
			when: ContextKeyExpr.deserialize(when),
E
Erich Gamma 已提交
328
			weight: weight,
A
Alex Dima 已提交
329 330 331 332
			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 已提交
333
		};
E
Erich Gamma 已提交
334 335

		if (!desc.primary && !desc.mac && !desc.linux && !desc.win) {
336
			return undefined;
E
Erich Gamma 已提交
337 338 339 340
		}

		return desc;
	}
341
}
342

343
let schemaId = 'vscode://schemas/keybindings';
344
let schema: IJSONSchema = {
345 346 347 348 349 350
	'id': schemaId,
	'type': 'array',
	'title': nls.localize('keybindings.json.title', "Keybindings configuration"),
	'items': {
		'required': ['key'],
		'type': 'object',
351
		'defaultSnippets': [{ 'body': { 'key': '$1', 'command': '$2', 'when': '$3' } }],
352 353 354
		'properties': {
			'key': {
				'type': 'string',
355
				'description': nls.localize('keybindings.json.key', "Key or key sequence (separated by space)"),
356 357
			},
			'command': {
358
				'description': nls.localize('keybindings.json.command', "Name of the command to execute"),
359 360 361
			},
			'when': {
				'type': 'string',
362 363 364 365
				'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.")
366 367 368 369 370
			}
		}
	}
};

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