commandsHandler.ts 21.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.
 *--------------------------------------------------------------------------------------------*/

B
Benjamin Pasero 已提交
6 7 8
import { localize } from 'vs/nls';
import { distinct } from 'vs/base/common/arrays';
import { withNullAsUndefined, isFunction } 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';
B
Benjamin Pasero 已提交
35
import { isFirefox } from 'vs/base/browser/browser';
E
Erich Gamma 已提交
36

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

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

B
Benjamin Pasero 已提交
44
class CommandsHistory extends Disposable {
45

B
Benjamin Pasero 已提交
46
	static readonly DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
47 48 49 50

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

B
Benjamin Pasero 已提交
51 52 53 54
	private static cache: LRUCache<string, number> | undefined;
	private static counter = 1;

	private configuredCommandsHistoryLength = 0;
55 56

	constructor(
57 58
		@IStorageService private readonly storageService: IStorageService,
		@IConfigurationService private readonly configurationService: IConfigurationService
59
	) {
B
Benjamin Pasero 已提交
60 61
		super();

62 63 64 65 66 67
		this.updateConfiguration();
		this.load();

		this.registerListeners();
	}

B
Benjamin Pasero 已提交
68 69 70 71
	private registerListeners(): void {
		this._register(this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration()));
	}

72
	private updateConfiguration(): void {
B
Benjamin Pasero 已提交
73
		this.configuredCommandsHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService);
74

B
Benjamin Pasero 已提交
75 76
		if (CommandsHistory.cache && CommandsHistory.cache.limit !== this.configuredCommandsHistoryLength) {
			CommandsHistory.cache.limit = this.configuredCommandsHistoryLength;
77 78

			CommandsHistory.saveState(this.storageService);
79 80 81 82
		}
	}

	private load(): void {
83
		const raw = this.storageService.get(CommandsHistory.PREF_KEY_CACHE, StorageScope.GLOBAL);
84
		let serializedCache: ISerializedCommandHistory | undefined;
85 86
		if (raw) {
			try {
D
Dirk Baeumer 已提交
87
				serializedCache = JSON.parse(raw);
88 89 90 91 92
			} catch (error) {
				// invalid data
			}
		}

B
Benjamin Pasero 已提交
93
		const cache = CommandsHistory.cache = new LRUCache<string, number>(this.configuredCommandsHistoryLength, 1);
D
Dirk Baeumer 已提交
94 95 96 97 98 99 100
		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);
			}
B
Benjamin Pasero 已提交
101
			entries.forEach(entry => cache.set(entry.key, entry.value));
D
Dirk Baeumer 已提交
102
		}
103

B
Benjamin Pasero 已提交
104
		CommandsHistory.counter = this.storageService.getNumber(CommandsHistory.PREF_KEY_COUNTER, StorageScope.GLOBAL, CommandsHistory.counter);
105 106
	}

B
Benjamin Pasero 已提交
107
	push(commandId: string): void {
B
Benjamin Pasero 已提交
108 109 110 111 112
		if (!CommandsHistory.cache) {
			return;
		}

		CommandsHistory.cache.set(commandId, CommandsHistory.counter++); // set counter to command
113 114

		CommandsHistory.saveState(this.storageService);
B
Benjamin Pasero 已提交
115 116
	}

117
	peek(commandId: string): number | undefined {
B
Benjamin Pasero 已提交
118
		return CommandsHistory.cache?.peek(commandId);
119 120
	}

121
	static saveState(storageService: IStorageService): void {
B
Benjamin Pasero 已提交
122 123 124 125
		if (!CommandsHistory.cache) {
			return;
		}

126
		const serializedCache: ISerializedCommandHistory = { usesLRU: true, entries: [] };
B
Benjamin Pasero 已提交
127
		CommandsHistory.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
B
Benjamin Pasero 已提交
128

129
		storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), StorageScope.GLOBAL);
B
Benjamin Pasero 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
		storageService.store(CommandsHistory.PREF_KEY_COUNTER, CommandsHistory.counter, StorageScope.GLOBAL);
	}

	static getConfiguredCommandHistoryLength(configurationService: IConfigurationService): number {
		const config = <IWorkbenchQuickOpenConfiguration>configurationService.getValue();

		const configuredCommandHistoryLength = config.workbench?.commandPalette?.history;
		if (typeof configuredCommandHistoryLength === 'number') {
			return configuredCommandHistoryLength;
		}

		return CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH;
	}

	static clearHistory(configurationService: IConfigurationService, storageService: IStorageService): void {
		const commandHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(configurationService);
		CommandsHistory.cache = new LRUCache<string, number>(commandHistoryLength);
		CommandsHistory.counter = 1;

		CommandsHistory.saveState(storageService);
150 151 152
	}
}

B
Benjamin Pasero 已提交
153 154
let lastCommandPaletteInput: string | undefined = undefined;

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

B
Benjamin Pasero 已提交
157
	static readonly ID = 'workbench.action.showCommands';
B
Benjamin Pasero 已提交
158
	static readonly LABEL = localize('showTriggerActions', "Show All Commands");
159

160 161 162
	constructor(
		id: string,
		label: string,
163 164
		@IQuickOpenService private readonly quickOpenService: IQuickOpenService,
		@IConfigurationService private readonly configurationService: IConfigurationService
165 166 167 168
	) {
		super(id, label);
	}

169
	run(): Promise<void> {
170
		const config = <IWorkbenchQuickOpenConfiguration>this.configurationService.getValue();
B
Benjamin Pasero 已提交
171
		const restoreInput = config.workbench?.commandPalette?.preserveInput === true;
172 173 174 175 176 177 178

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

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

R
Rob Lourens 已提交
181
		return Promise.resolve(undefined);
182 183 184 185 186
	}
}

export class ClearCommandHistoryAction extends Action {

B
Benjamin Pasero 已提交
187
	static readonly ID = 'workbench.action.clearCommandHistory';
B
Benjamin Pasero 已提交
188
	static readonly LABEL = localize('clearCommandHistory', "Clear Command History");
189 190 191 192

	constructor(
		id: string,
		label: string,
193 194
		@IConfigurationService private readonly configurationService: IConfigurationService,
		@IStorageService private readonly storageService: IStorageService
195 196 197 198
	) {
		super(id, label);
	}

199
	run(): Promise<void> {
B
Benjamin Pasero 已提交
200
		const commandHistoryLength = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService);
201
		if (commandHistoryLength > 0) {
B
Benjamin Pasero 已提交
202
			CommandsHistory.clearHistory(this.configurationService, this.storageService);
203 204
		}

R
Rob Lourens 已提交
205
		return Promise.resolve(undefined);
E
Erich Gamma 已提交
206 207 208
	}
}

209 210 211 212
class CommandPaletteEditorAction extends EditorAction {

	constructor() {
		super({
213
			id: ShowAllCommandsAction.ID,
B
Benjamin Pasero 已提交
214
			label: localize('showCommands.label', "Command Palette..."),
215
			alias: 'Command Palette',
216
			precondition: undefined,
217
			contextMenuOpts: {
B
Benjamin Pasero 已提交
218
				group: 'z_commands',
B
Benjamin Pasero 已提交
219
				order: 1
220
			}
221 222 223
		});
	}

J
Johannes Rieken 已提交
224
	run(accessor: ServicesAccessor, editor: ICodeEditor): Promise<void> {
225 226 227 228 229
		const quickOpenService = accessor.get(IQuickOpenService);

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

R
Rob Lourens 已提交
230
		return Promise.resolve(undefined);
231 232 233
	}
}

234
abstract class BaseCommandEntry extends QuickOpenEntryGroup {
B
Benjamin Pasero 已提交
235 236
	private description: string | undefined;
	private alias: string | undefined;
237
	private labelLowercase: string;
238
	private readonly keybindingAriaLabel?: string;
E
Erich Gamma 已提交
239 240

	constructor(
241
		private commandId: string,
B
Benjamin Pasero 已提交
242
		private keybinding: ResolvedKeybinding | undefined,
243
		private label: string,
B
Benjamin Pasero 已提交
244 245
		alias: string | undefined,
		highlights: { label: IHighlight[] | null, alias: IHighlight[] | null },
246
		private onBeforeRun: (commandId: string) => void,
247
		@INotificationService private readonly notificationService: INotificationService,
A
Alex Dima 已提交
248
		@ITelemetryService protected telemetryService: ITelemetryService
E
Erich Gamma 已提交
249 250 251
	) {
		super();

252
		this.labelLowercase = this.label.toLowerCase();
253
		this.keybindingAriaLabel = keybinding ? keybinding.getAriaLabel() || undefined : undefined;
254

255
		if (this.label !== alias) {
256 257
			this.alias = alias;
		} else {
B
Benjamin Pasero 已提交
258
			highlights.alias = null;
259 260
		}

B
Benjamin Pasero 已提交
261
		this.setHighlights(withNullAsUndefined(highlights.label), undefined, withNullAsUndefined(highlights.alias));
E
Erich Gamma 已提交
262 263
	}

B
Benjamin Pasero 已提交
264
	getCommandId(): string {
B
Benjamin Pasero 已提交
265 266 267
		return this.commandId;
	}

B
Benjamin Pasero 已提交
268
	getLabel(): string {
269 270 271
		return this.label;
	}

B
Benjamin Pasero 已提交
272
	getSortLabel(): string {
273 274 275
		return this.labelLowercase;
	}

B
Benjamin Pasero 已提交
276
	getDescription(): string | undefined {
277 278 279
		return this.description;
	}

B
Benjamin Pasero 已提交
280
	setDescription(description: string): void {
281 282 283
		this.description = description;
	}

B
Benjamin Pasero 已提交
284
	getKeybinding(): ResolvedKeybinding | undefined {
285 286 287
		return this.keybinding;
	}

B
Benjamin Pasero 已提交
288
	getDetail(): string | undefined {
289
		return this.alias;
E
Erich Gamma 已提交
290 291
	}

B
Benjamin Pasero 已提交
292
	getAriaLabel(): string {
293
		if (this.keybindingAriaLabel) {
B
Benjamin Pasero 已提交
294
			return localize('entryAriaLabelWithKey', "{0}, {1}, commands", this.getLabel(), this.keybindingAriaLabel);
295 296
		}

B
Benjamin Pasero 已提交
297
		return localize('entryAriaLabel', "{0}, commands", this.getLabel());
298 299
	}

B
Benjamin Pasero 已提交
300
	run(mode: Mode, context: IEntryRunContext): boolean {
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
		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 已提交
316

B
Benjamin Pasero 已提交
317
		const commandRunner = (async () => {
318
			if (action && (!(action instanceof Action) || action.enabled)) {
E
Erich Gamma 已提交
319
				try {
320
					this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: action.id, from: 'quick open' });
321 322 323 324 325 326 327 328 329

					const promise = action.run();
					if (promise) {
						try {
							await promise;
						} finally {
							if (action instanceof Action) {
								action.dispose();
							}
330
						}
331
					}
E
Erich Gamma 已提交
332 333 334 335
				} catch (error) {
					this.onError(error);
				}
			} else {
B
Benjamin Pasero 已提交
336
				this.notificationService.info(localize('actionNotEnabled', "Command '{0}' is not enabled in the current context.", this.getLabel()));
E
Erich Gamma 已提交
337
			}
B
Benjamin Pasero 已提交
338 339 340 341 342 343 344 345 346 347
		});

		// Use a timeout to give the quick open widget a chance to close itself first
		// Firefox: since the browser is quite picky for certain commands, we do not
		// use a timeout (https://github.com/microsoft/vscode/issues/83288)
		if (!isFirefox) {
			setTimeout(() => commandRunner(), 50);
		} else {
			commandRunner();
		}
E
Erich Gamma 已提交
348
	}
349 350 351 352 353 354

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

B
Benjamin Pasero 已提交
355
		this.notificationService.error(error || localize('canNotRun', "Command '{0}' resulted in an error.", this.label));
356
	}
E
Erich Gamma 已提交
357 358 359 360 361
}

class EditorActionCommandEntry extends BaseCommandEntry {

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

375 376
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
377 378 379 380 381 382
	}
}

class ActionCommandEntry extends BaseCommandEntry {

	constructor(
B
Benjamin Pasero 已提交
383
		commandId: string,
B
Benjamin Pasero 已提交
384
		keybinding: ResolvedKeybinding | undefined,
385
		label: string,
B
Benjamin Pasero 已提交
386 387
		alias: string | undefined,
		highlights: { label: IHighlight[] | null, alias: IHighlight[] | null },
388 389
		private action: Action,
		onBeforeRun: (commandId: string) => void,
390
		@INotificationService notificationService: INotificationService,
E
Erich Gamma 已提交
391 392
		@ITelemetryService telemetryService: ITelemetryService
	) {
393
		super(commandId, keybinding, label, alias, highlights, onBeforeRun, notificationService, telemetryService);
E
Erich Gamma 已提交
394 395
	}

396 397
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
398 399 400
	}
}

401 402
const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString);

403
export class CommandsHandler extends QuickOpenHandler implements IDisposable {
404

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

B
Benjamin Pasero 已提交
407
	private commandHistoryEnabled: boolean | undefined;
408 409 410
	private readonly commandsHistory: CommandsHistory;

	private readonly disposables = new DisposableStore();
411
	private readonly disposeOnClose = new DisposableStore();
412

B
Benjamin Pasero 已提交
413
	private waitedForExtensionsRegistered: boolean | undefined;
E
Erich Gamma 已提交
414 415

	constructor(
416 417 418 419 420 421
		@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 已提交
422 423
	) {
		super();
424

425
		this.commandsHistory = this.disposables.add(this.instantiationService.createInstance(CommandsHistory));
426

427
		this.extensionService.whenInstalledExtensionsRegistered().then(() => this.waitedForExtensionsRegistered = true);
428

429
		this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration());
430
		this.updateConfiguration();
E
Erich Gamma 已提交
431 432
	}

433
	private updateConfiguration(): void {
B
Benjamin Pasero 已提交
434
		this.commandHistoryEnabled = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService) > 0;
E
Erich Gamma 已提交
435 436
	}

437
	async getResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
438
		if (this.waitedForExtensionsRegistered) {
439 440
			return this.doGetResults(searchValue, token);
		}
E
Erich Gamma 已提交
441

442 443 444 445
		// 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.
446 447
		await Promise.race([timeout(800).then(), this.extensionService.whenInstalledExtensionsRegistered()]);
		this.waitedForExtensionsRegistered = true;
448

449
		return this.doGetResults(searchValue, token);
450
	}
E
Erich Gamma 已提交
451

452 453 454 455
	private doGetResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
		if (token.isCancellationRequested) {
			return Promise.resolve(new QuickOpenModel([]));
		}
B
Benjamin Pasero 已提交
456

457
		searchValue = searchValue.trim();
E
Erich Gamma 已提交
458

459 460
		// Remember as last command palette input
		lastCommandPaletteInput = searchValue;
E
Erich Gamma 已提交
461

462 463 464
		// Editor Actions
		const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
		let editorActions: IEditorAction[] = [];
B
Benjamin Pasero 已提交
465
		if (activeTextEditorWidget && isFunction(activeTextEditorWidget.getSupportedActions)) {
466 467
			editorActions = activeTextEditorWidget.getSupportedActions();
		}
468

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

471 472 473 474 475
		// 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();
476
		this.disposeOnClose.add(toDisposable(() => dispose(menuActions)));
477

478 479
		// Concat
		let entries = [...editorEntries, ...commandEntries];
480

481
		// Remove duplicates
B
Benjamin Pasero 已提交
482
		entries = distinct(entries, entry => `${entry.getLabel()}${entry.getGroupLabel()}${entry.getCommandId()}`);
483 484 485 486 487 488 489 490 491 492 493

		// 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);
			}
		});
494

495 496 497 498
		// 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());
499

500 501 502
			if (counterA && counterB) {
				return counterA > counterB ? -1 : 1; // use more recently used command before older
			}
B
Benjamin Pasero 已提交
503

504 505 506
			if (counterA) {
				return -1; // first command was used, so it wins over the non used one
			}
B
Benjamin Pasero 已提交
507

508 509 510 511 512 513 514
			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());
		});
515

516 517 518 519
		// 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())) {
B
Benjamin Pasero 已提交
520
			firstEntry.setGroupLabel(localize('recentlyUsed', "recently used"));
521 522 523 524
			for (let i = 1; i < entries.length; i++) {
				const entry = entries[i];
				if (!this.commandsHistory.peek(entry.getCommandId())) {
					entry.setShowBorder(true);
B
Benjamin Pasero 已提交
525
					entry.setGroupLabel(localize('morecCommands', "other commands"));
526
					break;
527 528
				}
			}
529
		}
E
Erich Gamma 已提交
530

531
		return Promise.resolve(new QuickOpenModel(entries));
E
Erich Gamma 已提交
532 533
	}

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

537
		for (const action of actions) {
B
Benjamin Pasero 已提交
538 539 540
			if (action.id === ShowAllCommandsAction.ID) {
				continue; // avoid duplicates
			}
E
Erich Gamma 已提交
541

B
Benjamin Pasero 已提交
542
			const label = action.label;
543
			if (label) {
544

545
				// Alias for non default languages
B
Benjamin Pasero 已提交
546
				const alias = !Language.isDefaultVariant() ? action.alias : undefined;
B
Benjamin Pasero 已提交
547 548
				const labelHighlights = wordFilter(searchValue, label);
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
549

550
				if (labelHighlights || aliasHighlights) {
551
					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 已提交
552 553 554 555 556 557 558
				}
			}
		}

		return entries;
	}

559 560 561 562 563 564
	private onBeforeRunCommand(commandId: string): void {

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

565
	private menuItemActionsToEntries(actions: MenuItemAction[], searchValue: string): ActionCommandEntry[] {
B
Benjamin Pasero 已提交
566
		const entries: ActionCommandEntry[] = [];
E
Erich Gamma 已提交
567 568

		for (let action of actions) {
569 570 571 572
			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;
B
Benjamin Pasero 已提交
573
				label = localize('cat.title', "{0}: {1}", category, title);
574 575
			}

576 577
			if (label) {
				const labelHighlights = wordFilter(searchValue, label);
578

579
				// Add an 'alias' in original language when running in different locale
B
Benjamin Pasero 已提交
580 581
				const aliasTitle = (!Language.isDefaultVariant() && typeof action.item.title !== 'string') ? action.item.title.original : undefined;
				const aliasCategory = (!Language.isDefaultVariant() && category && action.item.category && typeof action.item.category !== 'string') ? action.item.category.original : undefined;
J
Johannes Rieken 已提交
582 583 584 585 586 587
				let alias;
				if (aliasTitle && category) {
					alias = aliasCategory ? `${aliasCategory}: ${aliasTitle}` : `${category}: ${aliasTitle}`;
				} else if (aliasTitle) {
					alias = aliasTitle;
				}
588
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
589

590
				if (labelHighlights || aliasHighlights) {
591
					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)));
592
				}
593
			}
E
Erich Gamma 已提交
594 595 596 597 598
		}

		return entries;
	}

B
Benjamin Pasero 已提交
599
	getAutoFocus(searchValue: string, context: { model: IModel<QuickOpenEntry>, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus {
600
		let autoFocusPrefixMatch: string | undefined = searchValue.trim();
601 602 603

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

E
Erich Gamma 已提交
609 610
		return {
			autoFocusFirstEntry: true,
611
			autoFocusPrefixMatch
E
Erich Gamma 已提交
612 613 614
		};
	}

B
Benjamin Pasero 已提交
615
	getEmptyLabel(searchString: string): string {
B
Benjamin Pasero 已提交
616
		return localize('noCommandsMatching', "No commands matching");
E
Erich Gamma 已提交
617
	}
618

619 620 621 622 623 624
	onClose(canceled: boolean): void {
		super.onClose(canceled);

		this.disposeOnClose.clear();
	}

625 626
	dispose() {
		this.disposables.dispose();
627
		this.disposeOnClose.dispose();
628
	}
629
}
630

631
registerEditorAction(CommandPaletteEditorAction);