keybindingService.ts 21.5 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
import { IJSONSchema } from 'vs/base/common/jsonSchema';
9
import { ResolvedKeybinding, Keybinding } from 'vs/base/common/keyCodes';
A
Alex Dima 已提交
10
import { OS, OperatingSystem } from 'vs/base/common/platform';
J
Johannes Rieken 已提交
11
import { toDisposable } from 'vs/base/common/lifecycle';
12
import { ExtensionMessageCollector, ExtensionsRegistry } from 'vs/platform/extensions/common/extensionsRegistry';
J
Johannes Rieken 已提交
13
import { Extensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
14
import { AbstractKeybindingService } from 'vs/platform/keybinding/common/abstractKeybindingService';
J
Johannes Rieken 已提交
15
import { IStatusbarService } from 'vs/platform/statusbar/common/statusbar';
A
Alex Dima 已提交
16
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
S
Sandeep Somavarapu 已提交
17
import { ICommandService } from 'vs/platform/commands/common/commands';
18
import { IKeybindingEvent, IUserFriendlyKeybinding, KeybindingSource, IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
19
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
20
import { IKeybindingItem, KeybindingsRegistry, IKeybindingRule2 } from 'vs/platform/keybinding/common/keybindingsRegistry';
J
Johannes Rieken 已提交
21
import { Registry } from 'vs/platform/platform';
22 23
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { keybindingsTelemetry } from 'vs/platform/telemetry/common/telemetryUtils';
J
Johannes Rieken 已提交
24 25 26
import { IMessageService } from 'vs/platform/message/common/message';
import { ConfigWatcher } from 'vs/base/node/config';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
27 28
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
29
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
30
import { KeybindingIO, OutputBuilder, IUserKeybindingItem } from 'vs/workbench/services/keybinding/common/keybindingIO';
31 32
import * as nativeKeymap from 'native-keymap';
import { IKeyboardMapper } from 'vs/workbench/services/keybinding/common/keyboardMapper';
A
Alex Dima 已提交
33 34
import { WindowsKeyboardMapper, IWindowsKeyboardMapping, windowsKeyboardMappingEquals } from 'vs/workbench/services/keybinding/common/windowsKeyboardMapper';
import { IMacLinuxKeyboardMapping, MacLinuxKeyboardMapper, macLinuxKeyboardMappingEquals } from 'vs/workbench/services/keybinding/common/macLinuxKeyboardMapper';
35
import { MacLinuxFallbackKeyboardMapper } from 'vs/workbench/services/keybinding/common/macLinuxFallbackKeyboardMapper';
A
Alex Dima 已提交
36
import Event, { Emitter } from 'vs/base/common/event';
37 38 39 40
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { Action } from 'vs/base/common/actions';
import { TPromise } from 'vs/base/common/winjs.base';
import Severity from 'vs/base/common/severity';
41

A
Alex Dima 已提交
42 43 44 45 46 47
export class KeyboardMapperFactory {
	public static INSTANCE = new KeyboardMapperFactory();

	private _layoutInfo: nativeKeymap.IKeyboardLayoutInfo;
	private _rawMapping: nativeKeymap.IKeyboardMapping;
	private _keyboardMapper: IKeyboardMapper;
A
Alex Dima 已提交
48
	private _initialized: boolean;
A
Alex Dima 已提交
49 50 51 52 53 54 55 56

	private _onDidChangeKeyboardMapper: Emitter<void> = new Emitter<void>();
	public onDidChangeKeyboardMapper: Event<void> = this._onDidChangeKeyboardMapper.event;

	private constructor() {
		this._layoutInfo = null;
		this._rawMapping = null;
		this._keyboardMapper = null;
A
Alex Dima 已提交
57
		this._initialized = false;
58
	}
A
Alex Dima 已提交
59 60

	public _onKeyboardLayoutChanged(): void {
A
Alex Dima 已提交
61
		if (this._initialized) {
A
Alex Dima 已提交
62 63 64 65 66
			this._setKeyboardData(nativeKeymap.getCurrentKeyboardLayout(), nativeKeymap.getKeyMap());
		}
	}

	public getKeyboardMapper(): IKeyboardMapper {
A
Alex Dima 已提交
67
		if (!this._initialized) {
A
Alex Dima 已提交
68 69 70 71 72
			this._setKeyboardData(nativeKeymap.getCurrentKeyboardLayout(), nativeKeymap.getKeyMap());
		}
		return this._keyboardMapper;
	}

A
Alex Dima 已提交
73 74 75 76 77 78 79
	public getCurrentKeyboardLayout(): nativeKeymap.IKeyboardLayoutInfo {
		if (!this._initialized) {
			this._setKeyboardData(nativeKeymap.getCurrentKeyboardLayout(), nativeKeymap.getKeyMap());
		}
		return this._layoutInfo;
	}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	public isUSStandard(): boolean {
		let _kbInfo = this.getCurrentKeyboardLayout();

		if (OS === OperatingSystem.Linux) {
			const kbInfo = <nativeKeymap.ILinuxKeyboardLayoutInfo>_kbInfo;
			return (kbInfo && kbInfo.layout === 'us');
		}

		if (OS === OperatingSystem.Macintosh) {
			const kbInfo = <nativeKeymap.IMacKeyboardLayoutInfo>_kbInfo;
			return (kbInfo && kbInfo.id === 'com.apple.keylayout.US');
		}

		if (OS === OperatingSystem.Windows) {
			const kbInfo = <nativeKeymap.IWindowsKeyboardLayoutInfo>_kbInfo;
			return (kbInfo && kbInfo.name === '00000409');
		}

		return false;
	}

A
Alex Dima 已提交
101 102 103 104 105 106 107
	public getRawKeyboardMapping(): nativeKeymap.IKeyboardMapping {
		if (!this._initialized) {
			this._setKeyboardData(nativeKeymap.getCurrentKeyboardLayout(), nativeKeymap.getKeyMap());
		}
		return this._rawMapping;
	}

A
Alex Dima 已提交
108 109 110
	private _setKeyboardData(layoutInfo: nativeKeymap.IKeyboardLayoutInfo, rawMapping: nativeKeymap.IKeyboardMapping): void {
		this._layoutInfo = layoutInfo;

A
Alex Dima 已提交
111
		if (this._initialized && KeyboardMapperFactory._equals(this._rawMapping, rawMapping)) {
A
Alex Dima 已提交
112 113 114 115
			// nothing to do...
			return;
		}

A
Alex Dima 已提交
116 117
		this._initialized = true;

A
Alex Dima 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
		this._rawMapping = rawMapping;
		this._keyboardMapper = KeyboardMapperFactory._createKeyboardMapper(this._rawMapping);
		this._onDidChangeKeyboardMapper.fire();
	}

	private static _createKeyboardMapper(rawMapping: nativeKeymap.IKeyboardMapping): IKeyboardMapper {
		if (OS === OperatingSystem.Windows) {
			return new WindowsKeyboardMapper(<IWindowsKeyboardMapping>rawMapping);
		}

		if (Object.keys(rawMapping).length === 0) {
			// Looks like reading the mappings failed (most likely Mac + Japanese/Chinese keyboard layouts)
			return new MacLinuxFallbackKeyboardMapper(<IMacLinuxKeyboardMapping>rawMapping, OS);
		}

		return new MacLinuxKeyboardMapper(<IMacLinuxKeyboardMapping>rawMapping, OS);
	}

	private static _equals(a: nativeKeymap.IKeyboardMapping, b: nativeKeymap.IKeyboardMapping): boolean {
		if (OS === OperatingSystem.Windows) {
			return windowsKeyboardMappingEquals(<IWindowsKeyboardMapping>a, <IWindowsKeyboardMapping>b);
		}

		return macLinuxKeyboardMappingEquals(<IMacLinuxKeyboardMapping>a, <IMacLinuxKeyboardMapping>b);
142
	}
143
}
E
Erich Gamma 已提交
144 145 146 147 148 149 150 151 152 153

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

154
function isContributedKeyBindingsArray(thing: ContributedKeyBinding | ContributedKeyBinding[]): thing is ContributedKeyBinding[] {
E
Erich Gamma 已提交
155 156 157 158 159 160 161 162 163
	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 已提交
164
		rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'command'));
E
Erich Gamma 已提交
165 166 167
		return false;
	}
	if (typeof keyBinding.key !== 'string') {
B
Benjamin Pasero 已提交
168
		rejects.push(nls.localize('requirestring', "property `{0}` is mandatory and must be of type `string`", 'key'));
E
Erich Gamma 已提交
169 170 171
		return false;
	}
	if (keyBinding.when && typeof keyBinding.when !== 'string') {
B
Benjamin Pasero 已提交
172
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'when'));
E
Erich Gamma 已提交
173 174 175
		return false;
	}
	if (keyBinding.mac && typeof keyBinding.mac !== 'string') {
B
Benjamin Pasero 已提交
176
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'mac'));
E
Erich Gamma 已提交
177 178 179
		return false;
	}
	if (keyBinding.linux && typeof keyBinding.linux !== 'string') {
B
Benjamin Pasero 已提交
180
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'linux'));
E
Erich Gamma 已提交
181 182 183
		return false;
	}
	if (keyBinding.win && typeof keyBinding.win !== 'string') {
B
Benjamin Pasero 已提交
184
		rejects.push(nls.localize('optstring', "property `{0}` can be omitted or must be of type `string`", 'win'));
E
Erich Gamma 已提交
185 186 187 188 189
		return false;
	}
	return true;
}

190
let keybindingType: IJSONSchema = {
E
Erich Gamma 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
	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 已提交
221
let keybindingsExtPoint = ExtensionsRegistry.registerExtensionPoint<ContributedKeyBinding | ContributedKeyBinding[]>('keybindings', [], {
E
Erich Gamma 已提交
222 223 224 225 226 227 228 229 230 231
	description: nls.localize('vscode.extension.contributes.keybindings', "Contributes keybindings."),
	oneOf: [
		keybindingType,
		{
			type: 'array',
			items: keybindingType
		}
	]
});

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
interface IStorageData {
	dontShowPrompt: boolean;
}

class KeybindingsMigrationsStorage {
	private static KEY = 'keybindingsMigration';

	private _storageService: IStorageService;
	private _value: IStorageData;

	constructor(storageService: IStorageService) {
		this._storageService = storageService;
		this._value = this._read();
	}

	private _read(): IStorageData {
		let jsonValue = this._storageService.get(KeybindingsMigrationsStorage.KEY, StorageScope.GLOBAL);
		if (!jsonValue) {
			return null;
		}
		try {
			return JSON.parse(jsonValue);
		} catch (err) {
			return null;
		}
	}

	public get(): IStorageData {
		return this._value;
	}

	public set(data: IStorageData): void {
		this._value = data;
		this._storageService.store(KeybindingsMigrationsStorage.KEY, JSON.stringify(this._value), StorageScope.GLOBAL);
	}
}

269 270
export class WorkbenchKeybindingService extends AbstractKeybindingService {

271
	private _keyboardMapper: IKeyboardMapper;
272 273
	private _cachedResolver: KeybindingResolver;
	private _firstTimeComputingResolver: boolean;
274
	private userKeybindings: ConfigWatcher<IUserFriendlyKeybinding[]>;
E
Erich Gamma 已提交
275

276
	constructor(
B
Benjamin Pasero 已提交
277
		windowElement: Window,
278
		@IContextKeyService contextKeyService: IContextKeyService,
279
		@ICommandService commandService: ICommandService,
280
		@ITelemetryService private telemetryService: ITelemetryService,
281
		@IMessageService private messageService: IMessageService,
282
		@IEnvironmentService environmentService: IEnvironmentService,
283
		@IStorageService private storageService: IStorageService,
284
		@IStatusbarService statusBarService: IStatusbarService
285
	) {
286
		super(contextKeyService, commandService, messageService, statusBarService);
287

A
Alex Dima 已提交
288 289 290 291 292
		this._keyboardMapper = KeyboardMapperFactory.INSTANCE.getKeyboardMapper();
		KeyboardMapperFactory.INSTANCE.onDidChangeKeyboardMapper(() => {
			this._keyboardMapper = KeyboardMapperFactory.INSTANCE.getKeyboardMapper();
			this.updateResolver({ source: KeybindingSource.Default });
		});
293 294 295
		this._cachedResolver = null;
		this._firstTimeComputingResolver = true;

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

E
Erich Gamma 已提交
299 300 301 302 303 304 305 306
		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 已提交
307
				this.updateResolver({ source: KeybindingSource.Default });
E
Erich Gamma 已提交
308 309
			}
		});
310

C
Christof Marti 已提交
311 312 313 314
		this.toDispose.push(this.userKeybindings.onDidUpdateConfiguration(event => this.updateResolver({
			source: KeybindingSource.User,
			keybindings: event.config
		})));
315

B
Benjamin Pasero 已提交
316
		this.toDispose.push(dom.addDisposableListener(windowElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
317
			let keyEvent = new StandardKeyboardEvent(e);
318
			let shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
319 320 321 322 323
			if (shouldPreventDefault) {
				keyEvent.preventDefault();
			}
		}));

C
Christof Marti 已提交
324
		keybindingsTelemetry(telemetryService, this);
A
Alex Dima 已提交
325
		let data = KeyboardMapperFactory.INSTANCE.getCurrentKeyboardLayout();
A
Alex Dima 已提交
326 327 328
		telemetryService.publicLog('keyboardLayout', {
			currentKeyboardLayout: data
		});
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

		if (OS === OperatingSystem.Macintosh || OS === OperatingSystem.Linux) {
			const isUSStandard = KeyboardMapperFactory.INSTANCE.isUSStandard();
			if (!isUSStandard) {
				this._promptIfNeeded();
			}
		}
	}

	private _promptIfNeeded(): void {
		const storage = new KeybindingsMigrationsStorage(this.storageService);
		const storedData = storage.get();
		if (storedData && storedData.dontShowPrompt) {
			// Do not prompt stored
			return;
		}

		storage.set({
			dontShowPrompt: true
		});

		this._prompt();
	}

	private _prompt(): void {
		const okAction = new Action(
			'keybindingMigration.ok',
			nls.localize('keybindingMigration.ok', "OK"),
			null,
			true,
			() => TPromise.as(true)
		);
		this.messageService.show(Severity.Info, {
			message: nls.localize('keybindingMigration.prompt', "Some keyboard shortcuts have changed for your keyboard layout."),
			actions: [okAction]
		});
E
Erich Gamma 已提交
365 366
	}

A
Alex Dima 已提交
367
	public dumpDebugInfo(): string {
A
Alex Dima 已提交
368 369 370 371
		const layoutInfo = JSON.stringify(KeyboardMapperFactory.INSTANCE.getCurrentKeyboardLayout(), null, '\t');
		const mapperInfo = this._keyboardMapper.dumpDebugInfo();
		const rawMapping = JSON.stringify(KeyboardMapperFactory.INSTANCE.getRawKeyboardMapping(), null, '\t');
		return `Layout info:\n${layoutInfo}\n${mapperInfo}\n\nRaw mapping:\n${rawMapping}`;
A
Alex Dima 已提交
372 373
	}

374 375 376 377 378 379 380 381
	private _safeGetConfig(): IUserFriendlyKeybinding[] {
		let rawConfig = this.userKeybindings.getConfig();
		if (Array.isArray(rawConfig)) {
			return rawConfig;
		}
		return [];
	}

382
	public customKeybindingsCount(): number {
383
		let userKeybindings = this._safeGetConfig();
384 385

		return userKeybindings.length;
386 387
	}

388 389 390 391 392 393 394
	private updateResolver(event: IKeybindingEvent): void {
		this._cachedResolver = null;
		this._onDidUpdateKeybindings.fire(event);
	}

	protected _getResolver(): KeybindingResolver {
		if (!this._cachedResolver) {
395 396
			const defaults = this._resolveKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
			const overrides = this._resolveUserKeybindingItems(this._getExtraKeybindings(this._firstTimeComputingResolver), false);
397
			this._cachedResolver = new KeybindingResolver(defaults, overrides);
398 399 400
			this._firstTimeComputingResolver = false;
		}
		return this._cachedResolver;
401 402
	}

403
	private _resolveKeybindingItems(items: IKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
404
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
405 406 407
		for (let i = 0, len = items.length; i < len; i++) {
			const item = items[i];
			const when = (item.when ? item.when.normalize() : null);
A
Alex Dima 已提交
408
			const keybinding = item.keybinding;
409 410 411 412 413 414 415 416 417
			if (!keybinding) {
				// This might be a removal keybinding item in user settings => accept it
				result[resultLen++] = new ResolvedKeybindingItem(null, item.command, item.commandArgs, when, isDefault);
			} else {
				const resolvedKeybindings = this.resolveKeybinding(keybinding);
				for (let j = 0; j < resolvedKeybindings.length; j++) {
					result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybindings[j], item.command, item.commandArgs, when, isDefault);
				}
			}
418 419 420
		}

		return result;
421 422
	}

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
	private _resolveUserKeybindingItems(items: IUserKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
		for (let i = 0, len = items.length; i < len; i++) {
			const item = items[i];
			const when = (item.when ? item.when.normalize() : null);
			const firstPart = item.firstPart;
			const chordPart = item.chordPart;
			if (!firstPart) {
				// This might be a removal keybinding item in user settings => accept it
				result[resultLen++] = new ResolvedKeybindingItem(null, item.command, item.commandArgs, when, isDefault);
			} else {
				const resolvedKeybindings = this._keyboardMapper.resolveUserBinding(firstPart, chordPart);
				for (let j = 0; j < resolvedKeybindings.length; j++) {
					result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybindings[j], item.command, item.commandArgs, when, isDefault);
				}
			}
		}

		return result;
	}

	private _getExtraKeybindings(isFirstTime: boolean): IUserKeybindingItem[] {
445
		let extraUserKeybindings: IUserFriendlyKeybinding[] = this._safeGetConfig();
446 447
		if (!isFirstTime) {
			let cnt = extraUserKeybindings.length;
448

449 450 451
			this.telemetryService.publicLog('customKeybindingsChanged', {
				keyCount: cnt
			});
452
		}
453

454
		return extraUserKeybindings.map((k) => KeybindingIO.readUserKeybindingItem(k, OS));
455 456
	}

457
	public resolveKeybinding(kb: Keybinding): ResolvedKeybinding[] {
458
		return this._keyboardMapper.resolveKeybinding(kb);
A
Alex Dima 已提交
459 460
	}

461
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding {
462
		return this._keyboardMapper.resolveKeyboardEvent(keyboardEvent);
463 464
	}

465 466 467 468 469
	public resolveUserBinding(userBinding: string): ResolvedKeybinding[] {
		const [firstPart, chordPart] = KeybindingIO._readUserBinding(userBinding);
		return this._keyboardMapper.resolveUserBinding(firstPart, chordPart);
	}

470
	private _handleKeybindingsExtensionPointUser(isBuiltin: boolean, keybindings: ContributedKeyBinding | ContributedKeyBinding[], collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
471 472 473 474 475 476 477 478 479 480 481
		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);
		}
	}

482
	private _handleKeybinding(isBuiltin: boolean, idx: number, keybindings: ContributedKeyBinding, collector: ExtensionMessageCollector): boolean {
E
Erich Gamma 已提交
483 484 485 486 487 488 489

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

		if (isValidContributedKeyBinding(keybindings, rejects)) {
			let rule = this._asCommandRule(isBuiltin, idx++, keybindings);
			if (rule) {
490
				KeybindingsRegistry.registerKeybindingRule2(rule);
E
Erich Gamma 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
				commandAdded = true;
			}
		}

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

		return commandAdded;
	}

507
	private _asCommandRule(isBuiltin: boolean, idx: number, binding: ContributedKeyBinding): IKeybindingRule2 {
E
Erich Gamma 已提交
508

509
		let { command, when, key, mac, linux, win } = binding;
E
Erich Gamma 已提交
510 511 512 513 514 515 516 517 518 519

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

		let desc = {
			id: command,
520
			when: ContextKeyExpr.deserialize(when),
E
Erich Gamma 已提交
521
			weight: weight,
A
Alex Dima 已提交
522 523 524 525
			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 已提交
526
		};
E
Erich Gamma 已提交
527 528

		if (!desc.primary && !desc.mac && !desc.linux && !desc.win) {
529
			return undefined;
E
Erich Gamma 已提交
530 531 532 533
		}

		return desc;
	}
A
Alex Dima 已提交
534

S
Sandeep Somavarapu 已提交
535
	public getDefaultKeybindingsContent(): string {
A
Alex Dima 已提交
536 537 538 539 540 541 542 543 544 545
		const resolver = this._getResolver();
		const defaultKeybindings = resolver.getDefaultKeybindings();
		const boundCommands = resolver.getDefaultBoundCommands();
		return (
			WorkbenchKeybindingService._getDefaultKeybindings(defaultKeybindings)
			+ '\n\n'
			+ WorkbenchKeybindingService._getAllCommandsAsComment(boundCommands)
		);
	}

546
	private static _getDefaultKeybindings(defaultKeybindings: ResolvedKeybindingItem[]): string {
A
Alex Dima 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
		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 {
S
Sandeep Somavarapu 已提交
564
		const unboundCommands = KeybindingResolver.getAllUnboundCommands(boundCommands);
A
Alex Dima 已提交
565 566 567
		let pretty = unboundCommands.sort().join('\n// - ');
		return '// ' + nls.localize('unboundCommands', "Here are other available commands: ") + '\n// - ' + pretty;
	}
568
}
569

570
let schemaId = 'vscode://schemas/keybindings';
571
let schema: IJSONSchema = {
572 573 574 575 576 577
	'id': schemaId,
	'type': 'array',
	'title': nls.localize('keybindings.json.title', "Keybindings configuration"),
	'items': {
		'required': ['key'],
		'type': 'object',
578
		'defaultSnippets': [{ 'body': { 'key': '$1', 'command': '$2', 'when': '$3' } }],
579 580 581
		'properties': {
			'key': {
				'type': 'string',
582
				'description': nls.localize('keybindings.json.key', "Key or key sequence (separated by space)"),
583 584
			},
			'command': {
585
				'description': nls.localize('keybindings.json.command', "Name of the command to execute"),
586 587 588
			},
			'when': {
				'type': 'string',
589 590 591 592
				'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.")
593 594 595 596 597
			}
		}
	}
};

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