commandsHandler.ts 20.9 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 7 8
import * as nls from 'vs/nls';
import * as arrays from 'vs/base/common/arrays';
import * as types from 'vs/base/common/types';
9
import { Language } from 'vs/base/common/platform';
10
import { Action, WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification } from 'vs/base/common/actions';
11 12
import { Mode, IEntryRunContext, IAutoFocus, IModel, IQuickNavigateConfiguration } from 'vs/base/parts/quickopen/common/quickOpen';
import { QuickOpenEntryGroup, IHighlight, QuickOpenModel, QuickOpenEntry } from 'vs/base/parts/quickopen/browser/quickOpenModel';
B
Benjamin Pasero 已提交
13
import { IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';
J
Joao Moreno 已提交
14
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
15
import { QuickOpenHandler, IWorkbenchQuickOpenConfiguration } from 'vs/workbench/browser/quickopen';
B
Benjamin Pasero 已提交
16
import { IEditorAction } from 'vs/editor/common/editorCommon';
J
Johannes Rieken 已提交
17
import { matchesWords, matchesPrefix, matchesContiguousSubString, or } from 'vs/base/common/filters';
18
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
19 20
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
J
Johannes Rieken 已提交
21
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
22
import { registerEditorAction, EditorAction } from 'vs/editor/browser/editorExtensions';
B
Benjamin Pasero 已提交
23
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
D
Dirk Baeumer 已提交
24
import { LRUCache } from 'vs/base/common/map';
B
Benjamin Pasero 已提交
25 26
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ResolvedKeybinding } from 'vs/base/common/keyCodes';
27
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
28
import { isPromiseCanceledError } from 'vs/base/common/errors';
29
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
30
import { INotificationService } from 'vs/platform/notification/common/notification';
31
import { CancellationToken } from 'vs/base/common/cancellation';
B
Benjamin Pasero 已提交
32
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
33
import { Disposable, DisposableStore, IDisposable, toDisposable, dispose } from 'vs/base/common/lifecycle';
34
import { timeout } from 'vs/base/common/async';
E
Erich Gamma 已提交
35

36
export const ALL_COMMANDS_PREFIX = '>';
E
Erich Gamma 已提交
37

38
let lastCommandPaletteInput: string;
D
Dirk Baeumer 已提交
39
let commandHistory: LRUCache<string, number>;
40 41
let commandCounter = 1;

D
Dirk Baeumer 已提交
42 43 44 45 46
interface ISerializedCommandHistory {
	usesLRU?: boolean;
	entries: { key: string; value: number }[];
}

47
function resolveCommandHistory(configurationService: IConfigurationService): number {
48
	const config = <IWorkbenchQuickOpenConfiguration>configurationService.getValue();
49 50 51 52 53 54 55 56 57

	let commandHistory = config.workbench && config.workbench.commandPalette && config.workbench.commandPalette.history;
	if (typeof commandHistory !== 'number') {
		commandHistory = CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH;
	}

	return commandHistory;
}

B
Benjamin Pasero 已提交
58
class CommandsHistory extends Disposable {
59

B
Benjamin Pasero 已提交
60
	static readonly DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
61 62 63 64

	private static readonly PREF_KEY_CACHE = 'commandPalette.mru.cache';
	private static readonly PREF_KEY_COUNTER = 'commandPalette.mru.counter';

B
Benjamin Pasero 已提交
65
	private commandHistoryLength = 0;
66 67

	constructor(
68 69
		@IStorageService private readonly storageService: IStorageService,
		@IConfigurationService private readonly configurationService: IConfigurationService
70
	) {
B
Benjamin Pasero 已提交
71 72
		super();

73 74 75 76 77 78
		this.updateConfiguration();
		this.load();

		this.registerListeners();
	}

B
Benjamin Pasero 已提交
79 80 81 82
	private registerListeners(): void {
		this._register(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration()));
	}

83 84 85
	private updateConfiguration(): void {
		this.commandHistoryLength = resolveCommandHistory(this.configurationService);

86
		if (commandHistory && commandHistory.limit !== this.commandHistoryLength) {
D
Dirk Baeumer 已提交
87
			commandHistory.limit = this.commandHistoryLength;
88 89

			CommandsHistory.saveState(this.storageService);
90 91 92 93
		}
	}

	private load(): void {
94
		const raw = this.storageService.get(CommandsHistory.PREF_KEY_CACHE, StorageScope.GLOBAL);
95
		let serializedCache: ISerializedCommandHistory | undefined;
96 97
		if (raw) {
			try {
D
Dirk Baeumer 已提交
98
				serializedCache = JSON.parse(raw);
99 100 101 102 103
			} catch (error) {
				// invalid data
			}
		}

D
Dirk Baeumer 已提交
104 105 106 107 108 109 110 111 112 113
		commandHistory = new LRUCache<string, number>(this.commandHistoryLength, 1);
		if (serializedCache) {
			let entries: { key: string; value: number }[];
			if (serializedCache.usesLRU) {
				entries = serializedCache.entries;
			} else {
				entries = serializedCache.entries.sort((a, b) => a.value - b.value);
			}
			entries.forEach(entry => commandHistory.set(entry.key, entry.value));
		}
114

115
		commandCounter = this.storageService.getNumber(CommandsHistory.PREF_KEY_COUNTER, StorageScope.GLOBAL, commandCounter);
116 117
	}

B
Benjamin Pasero 已提交
118 119
	push(commandId: string): void {
		commandHistory.set(commandId, commandCounter++); // set counter to command
120 121

		CommandsHistory.saveState(this.storageService);
B
Benjamin Pasero 已提交
122 123
	}

124
	peek(commandId: string): number | undefined {
B
Benjamin Pasero 已提交
125
		return commandHistory.peek(commandId);
126 127
	}

128
	static saveState(storageService: IStorageService): void {
129
		const serializedCache: ISerializedCommandHistory = { usesLRU: true, entries: [] };
D
Dirk Baeumer 已提交
130
		commandHistory.forEach((value, key) => serializedCache.entries.push({ key, value }));
B
Benjamin Pasero 已提交
131

132 133
		storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), StorageScope.GLOBAL);
		storageService.store(CommandsHistory.PREF_KEY_COUNTER, commandCounter, StorageScope.GLOBAL);
134 135 136 137
	}
}

export class ShowAllCommandsAction extends Action {
E
Erich Gamma 已提交
138

B
Benjamin Pasero 已提交
139 140
	static readonly ID = 'workbench.action.showCommands';
	static readonly LABEL = nls.localize('showTriggerActions', "Show All Commands");
141

142 143 144
	constructor(
		id: string,
		label: string,
145 146
		@IQuickOpenService private readonly quickOpenService: IQuickOpenService,
		@IConfigurationService private readonly configurationService: IConfigurationService
147 148 149 150
	) {
		super(id, label);
	}

151
	run(): Promise<void> {
152
		const config = <IWorkbenchQuickOpenConfiguration>this.configurationService.getValue();
153 154 155 156 157 158 159 160
		const restoreInput = config.workbench && config.workbench.commandPalette && config.workbench.commandPalette.preserveInput === true;

		// Show with last command palette input if any and configured
		let value = ALL_COMMANDS_PREFIX;
		if (restoreInput && lastCommandPaletteInput) {
			value = `${value}${lastCommandPaletteInput}`;
		}

R
Rob Lourens 已提交
161
		this.quickOpenService.show(value, { inputSelection: lastCommandPaletteInput ? { start: 1 /* after prefix */, end: value.length } : undefined });
162

R
Rob Lourens 已提交
163
		return Promise.resolve(undefined);
164 165 166 167 168
	}
}

export class ClearCommandHistoryAction extends Action {

B
Benjamin Pasero 已提交
169 170
	static readonly ID = 'workbench.action.clearCommandHistory';
	static readonly LABEL = nls.localize('clearCommandHistory', "Clear Command History");
171 172 173 174

	constructor(
		id: string,
		label: string,
175 176
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IStorageService private readonly storageService: IStorageService
177 178 179 180
	) {
		super(id, label);
	}

181
	run(): Promise<void> {
182 183
		const commandHistoryLength = resolveCommandHistory(this.configurationService);
		if (commandHistoryLength > 0) {
D
Dirk Baeumer 已提交
184
			commandHistory = new LRUCache<string, number>(commandHistoryLength);
185
			commandCounter = 1;
186 187

			CommandsHistory.saveState(this.storageService);
188 189
		}

R
Rob Lourens 已提交
190
		return Promise.resolve(undefined);
E
Erich Gamma 已提交
191 192 193
	}
}

194 195 196 197
class CommandPaletteEditorAction extends EditorAction {

	constructor() {
		super({
198
			id: ShowAllCommandsAction.ID,
199 200
			label: nls.localize('showCommands.label', "Command Palette..."),
			alias: 'Command Palette',
201
			precondition: undefined,
202
			menuOpts: {
B
Benjamin Pasero 已提交
203
				group: 'z_commands',
B
Benjamin Pasero 已提交
204
				order: 1
205
			}
206 207 208
		});
	}

J
Johannes Rieken 已提交
209
	run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
210 211 212 213 214
		const quickOpenService = accessor.get(IQuickOpenService);

		// Show with prefix
		quickOpenService.show(ALL_COMMANDS_PREFIX);

R
Rob Lourens 已提交
215
		return Promise.resolve(undefined);
216 217 218
	}
}

219
abstract class BaseCommandEntry extends QuickOpenEntryGroup {
B
Benjamin Pasero 已提交
220 221
	private description: string | undefined;
	private alias: string | undefined;
222
	private labelLowercase: string;
223
	private readonly keybindingAriaLabel?: string;
E
Erich Gamma 已提交
224 225

	constructor(
226 227 228
		private commandId: string,
		private keybinding: ResolvedKeybinding,
		private label: string,
229
		alias: string,
230
		highlights: { label: IHighlight[], alias?: IHighlight[] },
231
		private onBeforeRun: (commandId: string) => void,
232
		@INotificationService private readonly notificationService: INotificationService,
A
Alex Dima 已提交
233
		@ITelemetryService protected telemetryService: ITelemetryService
E
Erich Gamma 已提交
234 235 236
	) {
		super();

237
		this.labelLowercase = this.label.toLowerCase();
238
		this.keybindingAriaLabel = keybinding ? keybinding.getAriaLabel() || undefined : undefined;
239

240
		if (this.label !== alias) {
241 242
			this.alias = alias;
		} else {
243
			highlights.alias = undefined;
244 245
		}

246
		this.setHighlights(highlights.label, undefined, highlights.alias);
E
Erich Gamma 已提交
247 248
	}

B
Benjamin Pasero 已提交
249
	getCommandId(): string {
B
Benjamin Pasero 已提交
250 251 252
		return this.commandId;
	}

B
Benjamin Pasero 已提交
253
	getLabel(): string {
254 255 256
		return this.label;
	}

B
Benjamin Pasero 已提交
257
	getSortLabel(): string {
258 259 260
		return this.labelLowercase;
	}

B
Benjamin Pasero 已提交
261
	getDescription(): string | undefined {
262 263 264
		return this.description;
	}

B
Benjamin Pasero 已提交
265
	setDescription(description: string): void {
266 267 268
		this.description = description;
	}

B
Benjamin Pasero 已提交
269
	getKeybinding(): ResolvedKeybinding {
270 271 272
		return this.keybinding;
	}

B
Benjamin Pasero 已提交
273
	getDetail(): string | undefined {
274
		return this.alias;
E
Erich Gamma 已提交
275 276
	}

B
Benjamin Pasero 已提交
277
	getAriaLabel(): string {
278 279
		if (this.keybindingAriaLabel) {
			return nls.localize('entryAriaLabelWithKey', "{0}, {1}, commands", this.getLabel(), this.keybindingAriaLabel);
280 281
		}

282 283 284
		return nls.localize('entryAriaLabel', "{0}, commands", this.getLabel());
	}

B
Benjamin Pasero 已提交
285
	run(mode: Mode, context: IEntryRunContext): boolean {
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
		if (mode === Mode.OPEN) {
			this.runAction(this.getAction());

			return true;
		}

		return false;
	}

	protected abstract getAction(): Action | IEditorAction;

	protected runAction(action: Action | IEditorAction): void {

		// Indicate onBeforeRun
		this.onBeforeRun(this.commandId);
E
Erich Gamma 已提交
301 302

		// Use a timeout to give the quick open widget a chance to close itself first
303
		setTimeout(async () => {
304
			if (action && (!(action instanceof Action) || action.enabled)) {
E
Erich Gamma 已提交
305
				try {
306
					this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: action.id, from: 'quick open' });
307 308 309 310 311 312 313 314 315

					const promise = action.run();
					if (promise) {
						try {
							await promise;
						} finally {
							if (action instanceof Action) {
								action.dispose();
							}
316
						}
317
					}
E
Erich Gamma 已提交
318 319 320 321
				} catch (error) {
					this.onError(error);
				}
			} else {
322
				this.notificationService.info(nls.localize('actionNotEnabled', "Command '{0}' is not enabled in the current context.", this.getLabel()));
E
Erich Gamma 已提交
323
			}
324
		}, 50);
E
Erich Gamma 已提交
325
	}
326 327 328 329 330 331

	private onError(error?: Error): void {
		if (isPromiseCanceledError(error)) {
			return;
		}

332
		this.notificationService.error(error || nls.localize('canNotRun', "Command '{0}' resulted in an error.", this.label));
333
	}
E
Erich Gamma 已提交
334 335 336 337 338
}

class EditorActionCommandEntry extends BaseCommandEntry {

	constructor(
B
Benjamin Pasero 已提交
339
		commandId: string,
340
		keybinding: ResolvedKeybinding,
341 342
		label: string,
		meta: string,
343 344 345
		highlights: { label: IHighlight[], alias: IHighlight[] },
		private action: IEditorAction,
		onBeforeRun: (commandId: string) => void,
346
		@INotificationService notificationService: INotificationService,
E
Erich Gamma 已提交
347 348
		@ITelemetryService telemetryService: ITelemetryService
	) {
349
		super(commandId, keybinding, label, meta, highlights, onBeforeRun, notificationService, telemetryService);
E
Erich Gamma 已提交
350 351
	}

352 353
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
354 355 356 357 358 359
	}
}

class ActionCommandEntry extends BaseCommandEntry {

	constructor(
B
Benjamin Pasero 已提交
360
		commandId: string,
361
		keybinding: ResolvedKeybinding,
362
		label: string,
363
		alias: string,
364 365 366
		highlights: { label: IHighlight[], alias: IHighlight[] },
		private action: Action,
		onBeforeRun: (commandId: string) => void,
367
		@INotificationService notificationService: INotificationService,
E
Erich Gamma 已提交
368 369
		@ITelemetryService telemetryService: ITelemetryService
	) {
370
		super(commandId, keybinding, label, alias, highlights, onBeforeRun, notificationService, telemetryService);
E
Erich Gamma 已提交
371 372
	}

373 374
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
375 376 377
	}
}

378 379
const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString);

380
export class CommandsHandler extends QuickOpenHandler implements IDisposable {
381

B
Benjamin Pasero 已提交
382
	static readonly ID = 'workbench.picker.commands';
383

B
Benjamin Pasero 已提交
384
	private commandHistoryEnabled: boolean | undefined;
385 386 387
	private readonly commandsHistory: CommandsHistory;

	private readonly disposables = new DisposableStore();
388
	private readonly disposeOnClose = new DisposableStore();
389

B
Benjamin Pasero 已提交
390
	private waitedForExtensionsRegistered: boolean | undefined;
E
Erich Gamma 已提交
391 392

	constructor(
393 394 395 396 397 398
		@IEditorService private readonly editorService: IEditorService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IKeybindingService private readonly keybindingService: IKeybindingService,
		@IMenuService private readonly menuService: IMenuService,
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IExtensionService private readonly extensionService: IExtensionService
E
Erich Gamma 已提交
399 400
	) {
		super();
401

402
		this.commandsHistory = this.disposables.add(this.instantiationService.createInstance(CommandsHistory));
403

404
		this.extensionService.whenInstalledExtensionsRegistered().then(() => this.waitedForExtensionsRegistered = true);
405

406
		this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration());
407
		this.updateConfiguration();
E
Erich Gamma 已提交
408 409
	}

410 411
	private updateConfiguration(): void {
		this.commandHistoryEnabled = resolveCommandHistory(this.configurationService) > 0;
E
Erich Gamma 已提交
412 413
	}

414
	async getResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
415
		if (this.waitedForExtensionsRegistered) {
416 417
			return this.doGetResults(searchValue, token);
		}
E
Erich Gamma 已提交
418

419 420 421 422
		// If extensions are not yet registered, we wait for a little moment to give them
		// a chance to register so that the complete set of commands shows up as result
		// We do not want to delay functionality beyond that time though to keep the commands
		// functional.
423 424
		await Promise.race([timeout(800).then(), this.extensionService.whenInstalledExtensionsRegistered()]);
		this.waitedForExtensionsRegistered = true;
425

426
		return this.doGetResults(searchValue, token);
427
	}
E
Erich Gamma 已提交
428

429 430 431 432
	private doGetResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
		if (token.isCancellationRequested) {
			return Promise.resolve(new QuickOpenModel([]));
		}
B
Benjamin Pasero 已提交
433

434
		searchValue = searchValue.trim();
E
Erich Gamma 已提交
435

436 437
		// Remember as last command palette input
		lastCommandPaletteInput = searchValue;
E
Erich Gamma 已提交
438

439 440 441 442 443 444
		// Editor Actions
		const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
		let editorActions: IEditorAction[] = [];
		if (activeTextEditorWidget && types.isFunction(activeTextEditorWidget.getSupportedActions)) {
			editorActions = activeTextEditorWidget.getSupportedActions();
		}
445

446
		const editorEntries = this.editorActionsToEntries(editorActions, searchValue);
E
Erich Gamma 已提交
447

448 449 450 451 452
		// Other Actions
		const menu = this.editorService.invokeWithinEditorContext(accessor => this.menuService.createMenu(MenuId.CommandPalette, accessor.get(IContextKeyService)));
		const menuActions = menu.getActions().reduce((r, [, actions]) => [...r, ...actions], <MenuItemAction[]>[]).filter(action => action instanceof MenuItemAction) as MenuItemAction[];
		const commandEntries = this.menuItemActionsToEntries(menuActions, searchValue);
		menu.dispose();
453
		this.disposeOnClose.add(toDisposable(() => dispose(menuActions)));
454

455 456
		// Concat
		let entries = [...editorEntries, ...commandEntries];
457

458 459 460 461 462 463 464 465 466 467 468 469 470
		// Remove duplicates
		entries = arrays.distinct(entries, entry => `${entry.getLabel()}${entry.getGroupLabel()}${entry.getCommandId()}`);

		// Handle label clashes
		const commandLabels = new Set<string>();
		entries.forEach(entry => {
			const commandLabel = `${entry.getLabel()}${entry.getGroupLabel()}`;
			if (commandLabels.has(commandLabel)) {
				entry.setDescription(entry.getCommandId());
			} else {
				commandLabels.add(commandLabel);
			}
		});
471

472 473 474 475
		// Sort by MRU order and fallback to name otherwie
		entries = entries.sort((elementA, elementB) => {
			const counterA = this.commandsHistory.peek(elementA.getCommandId());
			const counterB = this.commandsHistory.peek(elementB.getCommandId());
476

477 478 479
			if (counterA && counterB) {
				return counterA > counterB ? -1 : 1; // use more recently used command before older
			}
B
Benjamin Pasero 已提交
480

481 482 483
			if (counterA) {
				return -1; // first command was used, so it wins over the non used one
			}
B
Benjamin Pasero 已提交
484

485 486 487 488 489 490 491
			if (counterB) {
				return 1; // other command was used so it wins over the command
			}

			// both commands were never used, so we sort by name
			return elementA.getSortLabel().localeCompare(elementB.getSortLabel());
		});
492

493 494 495 496 497 498 499 500 501 502 503
		// Introduce group marker border between recently used and others
		// only if we have recently used commands in the result set
		const firstEntry = entries[0];
		if (firstEntry && this.commandsHistory.peek(firstEntry.getCommandId())) {
			firstEntry.setGroupLabel(nls.localize('recentlyUsed', "recently used"));
			for (let i = 1; i < entries.length; i++) {
				const entry = entries[i];
				if (!this.commandsHistory.peek(entry.getCommandId())) {
					entry.setShowBorder(true);
					entry.setGroupLabel(nls.localize('morecCommands', "other commands"));
					break;
504 505
				}
			}
506
		}
E
Erich Gamma 已提交
507

508
		return Promise.resolve(new QuickOpenModel(entries));
E
Erich Gamma 已提交
509 510
	}

A
Alex Dima 已提交
511
	private editorActionsToEntries(actions: IEditorAction[], searchValue: string): EditorActionCommandEntry[] {
B
Benjamin Pasero 已提交
512
		const entries: EditorActionCommandEntry[] = [];
E
Erich Gamma 已提交
513

514
		for (const action of actions) {
B
Benjamin Pasero 已提交
515 516 517
			if (action.id === ShowAllCommandsAction.ID) {
				continue; // avoid duplicates
			}
E
Erich Gamma 已提交
518

B
Benjamin Pasero 已提交
519
			const label = action.label;
520
			if (label) {
521

522
				// Alias for non default languages
523
				const alias = !Language.isDefaultVariant() ? action.alias : null;
B
Benjamin Pasero 已提交
524 525
				const labelHighlights = wordFilter(searchValue, label);
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
526

527
				if (labelHighlights || aliasHighlights) {
528
					entries.push(this.instantiationService.createInstance(EditorActionCommandEntry, action.id, this.keybindingService.lookupKeybinding(action.id), label, alias, { label: labelHighlights, alias: aliasHighlights }, action, (id: string) => this.onBeforeRunCommand(id)));
E
Erich Gamma 已提交
529 530 531 532 533 534 535
				}
			}
		}

		return entries;
	}

536 537 538 539 540 541
	private onBeforeRunCommand(commandId: string): void {

		// Remember in commands history
		this.commandsHistory.push(commandId);
	}

542
	private menuItemActionsToEntries(actions: MenuItemAction[], searchValue: string): ActionCommandEntry[] {
B
Benjamin Pasero 已提交
543
		const entries: ActionCommandEntry[] = [];
E
Erich Gamma 已提交
544 545

		for (let action of actions) {
546 547 548 549 550 551 552
			const title = typeof action.item.title === 'string' ? action.item.title : action.item.title.value;
			let category, label = title;
			if (action.item.category) {
				category = typeof action.item.category === 'string' ? action.item.category : action.item.category.value;
				label = nls.localize('cat.title', "{0}: {1}", category, title);
			}

553 554
			if (label) {
				const labelHighlights = wordFilter(searchValue, label);
555

556
				// Add an 'alias' in original language when running in different locale
557 558
				const aliasTitle = (!Language.isDefaultVariant() && typeof action.item.title !== 'string') ? action.item.title.original : null;
				const aliasCategory = (!Language.isDefaultVariant() && category && action.item.category && typeof action.item.category !== 'string') ? action.item.category.original : null;
J
Johannes Rieken 已提交
559 560 561 562 563 564
				let alias;
				if (aliasTitle && category) {
					alias = aliasCategory ? `${aliasCategory}: ${aliasTitle}` : `${category}: ${aliasTitle}`;
				} else if (aliasTitle) {
					alias = aliasTitle;
				}
565
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
566

567
				if (labelHighlights || aliasHighlights) {
568
					entries.push(this.instantiationService.createInstance(ActionCommandEntry, action.id, this.keybindingService.lookupKeybinding(action.item.id), label, alias, { label: labelHighlights, alias: aliasHighlights }, action, (id: string) => this.onBeforeRunCommand(id)));
569
				}
570
			}
E
Erich Gamma 已提交
571 572 573 574 575
		}

		return entries;
	}

B
Benjamin Pasero 已提交
576
	getAutoFocus(searchValue: string, context: { model: IModel<QuickOpenEntry>, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus {
577
		let autoFocusPrefixMatch: string | undefined = searchValue.trim();
578 579 580

		if (autoFocusPrefixMatch && this.commandHistoryEnabled) {
			const firstEntry = context.model && context.model.entries[0];
D
Dirk Baeumer 已提交
581
			if (firstEntry instanceof BaseCommandEntry && this.commandsHistory.peek(firstEntry.getCommandId())) {
R
Rob Lourens 已提交
582
				autoFocusPrefixMatch = undefined; // keep focus on MRU element if we have history elements
583 584 585
			}
		}

E
Erich Gamma 已提交
586 587
		return {
			autoFocusFirstEntry: true,
588
			autoFocusPrefixMatch
E
Erich Gamma 已提交
589 590 591
		};
	}

B
Benjamin Pasero 已提交
592
	getEmptyLabel(searchString: string): string {
E
Erich Gamma 已提交
593 594
		return nls.localize('noCommandsMatching', "No commands matching");
	}
595

596 597 598 599 600 601
	onClose(canceled: boolean): void {
		super.onClose(canceled);

		this.disposeOnClose.clear();
	}

602 603
	dispose() {
		this.disposables.dispose();
604
		this.disposeOnClose.dispose();
605
	}
606
}
607

608
registerEditorAction(CommandPaletteEditorAction);