commandsHandler.ts 21.6 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';
E
Erich Gamma 已提交
35

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

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

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

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

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

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

	private configuredCommandsHistoryLength = 0;
54 55

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

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

		this.registerListeners();
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

128
		storageService.store(CommandsHistory.PREF_KEY_CACHE, JSON.stringify(serializedCache), StorageScope.GLOBAL);
B
Benjamin Pasero 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
		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);
149 150 151
	}
}

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

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

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

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

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

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

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

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

export class ClearCommandHistoryAction extends Action {

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

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

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

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

208 209 210 211
class CommandPaletteEditorAction extends EditorAction {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		// Use a timeout to give the quick open widget a chance to close itself first
317
		setTimeout(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
			}
338
		}, 50);
E
Erich Gamma 已提交
339
	}
340 341 342 343 344 345

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

B
Benjamin Pasero 已提交
346
		this.notificationService.error(error || localize('canNotRun', "Command '{0}' resulted in an error.", this.label));
347
	}
E
Erich Gamma 已提交
348 349 350 351 352
}

class EditorActionCommandEntry extends BaseCommandEntry {

	constructor(
B
Benjamin Pasero 已提交
353
		commandId: string,
B
Benjamin Pasero 已提交
354
		keybinding: ResolvedKeybinding | undefined,
355
		label: string,
B
Benjamin Pasero 已提交
356 357
		meta: string | undefined,
		highlights: { label: IHighlight[] | null, alias: IHighlight[] | null },
358 359
		private action: IEditorAction,
		onBeforeRun: (commandId: string) => void,
360
		@INotificationService notificationService: INotificationService,
E
Erich Gamma 已提交
361 362
		@ITelemetryService telemetryService: ITelemetryService
	) {
363
		super(commandId, keybinding, label, meta, highlights, onBeforeRun, notificationService, telemetryService);
E
Erich Gamma 已提交
364 365
	}

366 367
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
368 369 370 371 372 373
	}
}

class ActionCommandEntry extends BaseCommandEntry {

	constructor(
B
Benjamin Pasero 已提交
374
		commandId: string,
B
Benjamin Pasero 已提交
375
		keybinding: ResolvedKeybinding | undefined,
376
		label: string,
B
Benjamin Pasero 已提交
377 378
		alias: string | undefined,
		highlights: { label: IHighlight[] | null, alias: IHighlight[] | null },
379 380
		private action: Action,
		onBeforeRun: (commandId: string) => void,
381
		@INotificationService notificationService: INotificationService,
E
Erich Gamma 已提交
382 383
		@ITelemetryService telemetryService: ITelemetryService
	) {
384
		super(commandId, keybinding, label, alias, highlights, onBeforeRun, notificationService, telemetryService);
E
Erich Gamma 已提交
385 386
	}

387 388
	protected getAction(): Action | IEditorAction {
		return this.action;
E
Erich Gamma 已提交
389 390 391
	}
}

392 393
const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString);

394
export class CommandsHandler extends QuickOpenHandler implements IDisposable {
395

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

B
Benjamin Pasero 已提交
398
	private commandHistoryEnabled: boolean | undefined;
399 400 401
	private readonly commandsHistory: CommandsHistory;

	private readonly disposables = new DisposableStore();
402
	private readonly disposeOnClose = new DisposableStore();
403

B
Benjamin Pasero 已提交
404
	private waitedForExtensionsRegistered: boolean | undefined;
E
Erich Gamma 已提交
405 406

	constructor(
407 408 409 410 411 412
		@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 已提交
413 414
	) {
		super();
415

416
		this.commandsHistory = this.disposables.add(this.instantiationService.createInstance(CommandsHistory));
417

418
		this.extensionService.whenInstalledExtensionsRegistered().then(() => this.waitedForExtensionsRegistered = true);
419

420
		this.configurationService.onDidChangeConfiguration(e => this.updateConfiguration());
421
		this.updateConfiguration();
E
Erich Gamma 已提交
422 423
	}

424
	private updateConfiguration(): void {
B
Benjamin Pasero 已提交
425
		this.commandHistoryEnabled = CommandsHistory.getConfiguredCommandHistoryLength(this.configurationService) > 0;
E
Erich Gamma 已提交
426 427
	}

428
	async getResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
429
		if (this.waitedForExtensionsRegistered) {
430 431
			return this.doGetResults(searchValue, token);
		}
E
Erich Gamma 已提交
432

433 434 435 436
		// 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.
437 438
		await Promise.race([timeout(800).then(), this.extensionService.whenInstalledExtensionsRegistered()]);
		this.waitedForExtensionsRegistered = true;
439

440
		return this.doGetResults(searchValue, token);
441
	}
E
Erich Gamma 已提交
442

443 444 445 446
	private doGetResults(searchValue: string, token: CancellationToken): Promise<QuickOpenModel> {
		if (token.isCancellationRequested) {
			return Promise.resolve(new QuickOpenModel([]));
		}
B
Benjamin Pasero 已提交
447

448
		searchValue = searchValue.trim();
E
Erich Gamma 已提交
449

450 451
		// Remember as last command palette input
		lastCommandPaletteInput = searchValue;
E
Erich Gamma 已提交
452

453 454 455
		// Editor Actions
		const activeTextEditorWidget = this.editorService.activeTextEditorWidget;
		let editorActions: IEditorAction[] = [];
B
Benjamin Pasero 已提交
456
		if (activeTextEditorWidget && isFunction(activeTextEditorWidget.getSupportedActions)) {
457 458
			editorActions = activeTextEditorWidget.getSupportedActions();
		}
459

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

462 463 464 465 466
		// 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();
467
		this.disposeOnClose.add(toDisposable(() => dispose(menuActions)));
468

469 470
		// Concat
		let entries = [...editorEntries, ...commandEntries];
471

472
		// Remove duplicates
B
Benjamin Pasero 已提交
473
		entries = distinct(entries, entry => `${entry.getLabel()}${entry.getGroupLabel()}${entry.getCommandId()}`);
474 475 476 477 478 479 480 481 482 483 484

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

486 487 488 489
		// 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());
490

491 492 493
			if (counterA && counterB) {
				return counterA > counterB ? -1 : 1; // use more recently used command before older
			}
B
Benjamin Pasero 已提交
494

495 496 497
			if (counterA) {
				return -1; // first command was used, so it wins over the non used one
			}
B
Benjamin Pasero 已提交
498

499 500 501 502 503 504 505
			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());
		});
506

507 508 509 510
		// 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 已提交
511
			firstEntry.setGroupLabel(localize('recentlyUsed', "recently used"));
512 513 514 515
			for (let i = 1; i < entries.length; i++) {
				const entry = entries[i];
				if (!this.commandsHistory.peek(entry.getCommandId())) {
					entry.setShowBorder(true);
B
Benjamin Pasero 已提交
516
					entry.setGroupLabel(localize('morecCommands', "other commands"));
517
					break;
518 519
				}
			}
520
		}
E
Erich Gamma 已提交
521

522
		return Promise.resolve(new QuickOpenModel(entries));
E
Erich Gamma 已提交
523 524
	}

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

528
		for (const action of actions) {
B
Benjamin Pasero 已提交
529 530 531
			if (action.id === ShowAllCommandsAction.ID) {
				continue; // avoid duplicates
			}
E
Erich Gamma 已提交
532

B
Benjamin Pasero 已提交
533
			const label = action.label;
534
			if (label) {
535

536
				// Alias for non default languages
B
Benjamin Pasero 已提交
537
				const alias = !Language.isDefaultVariant() ? action.alias : undefined;
B
Benjamin Pasero 已提交
538 539
				const labelHighlights = wordFilter(searchValue, label);
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
540

541
				if (labelHighlights || aliasHighlights) {
542
					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 已提交
543 544 545 546 547 548 549
				}
			}
		}

		return entries;
	}

550 551 552 553 554 555
	private onBeforeRunCommand(commandId: string): void {

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

556
	private menuItemActionsToEntries(actions: MenuItemAction[], searchValue: string): ActionCommandEntry[] {
B
Benjamin Pasero 已提交
557
		const entries: ActionCommandEntry[] = [];
E
Erich Gamma 已提交
558 559

		for (let action of actions) {
560 561 562 563
			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 已提交
564
				label = localize('cat.title', "{0}: {1}", category, title);
565 566
			}

567 568
			if (label) {
				const labelHighlights = wordFilter(searchValue, label);
569

570
				// Add an 'alias' in original language when running in different locale
B
Benjamin Pasero 已提交
571 572
				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 已提交
573 574 575 576 577 578
				let alias;
				if (aliasTitle && category) {
					alias = aliasCategory ? `${aliasCategory}: ${aliasTitle}` : `${category}: ${aliasTitle}`;
				} else if (aliasTitle) {
					alias = aliasTitle;
				}
579
				const aliasHighlights = alias ? wordFilter(searchValue, alias) : null;
580

581
				if (labelHighlights || aliasHighlights) {
582
					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)));
583
				}
584
			}
E
Erich Gamma 已提交
585 586 587 588 589
		}

		return entries;
	}

B
Benjamin Pasero 已提交
590
	getAutoFocus(searchValue: string, context: { model: IModel<QuickOpenEntry>, quickNavigateConfiguration?: IQuickNavigateConfiguration }): IAutoFocus {
591
		let autoFocusPrefixMatch: string | undefined = searchValue.trim();
592 593 594

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

E
Erich Gamma 已提交
600 601
		return {
			autoFocusFirstEntry: true,
602
			autoFocusPrefixMatch
E
Erich Gamma 已提交
603 604 605
		};
	}

B
Benjamin Pasero 已提交
606
	getEmptyLabel(searchString: string): string {
B
Benjamin Pasero 已提交
607
		return localize('noCommandsMatching', "No commands matching");
E
Erich Gamma 已提交
608
	}
609

610 611 612 613 614 615
	onClose(canceled: boolean): void {
		super.onClose(canceled);

		this.disposeOnClose.clear();
	}

616 617
	dispose() {
		this.disposables.dispose();
618
		this.disposeOnClose.dispose();
619
	}
620
}
621

622
registerEditorAction(CommandPaletteEditorAction);