commandsHandler.ts 12.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./media/commandsHandler';
9
import {TPromise} from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
10 11 12 13 14 15
import nls = require('vs/nls');
import arrays = require('vs/base/common/arrays');
import types = require('vs/base/common/types');
import strings = require('vs/base/common/strings');
import {IAction, Action} from 'vs/base/common/actions';
import {toErrorMessage} from 'vs/base/common/errors';
16
import {Mode, IContext, IAutoFocus} from 'vs/base/parts/quickopen/common/quickOpen';
B
Benjamin Pasero 已提交
17
import {QuickOpenEntryGroup, IHighlight, QuickOpenModel} from 'vs/base/parts/quickopen/browser/quickOpenModel';
E
Erich Gamma 已提交
18
import {SyncActionDescriptor, IActionsService} from 'vs/platform/actions/common/actions';
19
import {IWorkbenchActionRegistry, Extensions as ActionExtensions} from 'vs/workbench/common/actionRegistry';
E
Erich Gamma 已提交
20
import {Registry} from 'vs/platform/platform';
B
Benjamin Pasero 已提交
21
import {QuickOpenHandler} from 'vs/workbench/browser/quickopen';
E
Erich Gamma 已提交
22
import {QuickOpenAction} from 'vs/workbench/browser/actions/quickOpenAction';
23
import {matchesWords, matchesPrefix, matchesContiguousSubString, or} from 'vs/base/common/filters';
E
Erich Gamma 已提交
24
import {ICommonCodeEditor, IEditorActionDescriptorData} from 'vs/editor/common/editorCommon';
A
Alex Dima 已提交
25 26
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
E
Erich Gamma 已提交
27 28 29 30 31
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService, Severity} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
32
import {IQuickOpenService} from 'vs/workbench/services/quickopen/common/quickOpenService';
E
Erich Gamma 已提交
33

34 35
export const ALL_COMMANDS_PREFIX = '>';
export const EDITOR_COMMANDS_PREFIX = '$';
E
Erich Gamma 已提交
36

37 38
const wordFilter = or(matchesPrefix, matchesWords, matchesContiguousSubString);

E
Erich Gamma 已提交
39 40
export class ShowAllCommandsAction extends QuickOpenAction {

41 42 43
	public static ID = 'workbench.action.showCommands';
	public static LABEL = nls.localize('showTriggerActions', "Show All Commands");

E
Erich Gamma 已提交
44 45 46 47 48 49
	constructor(actionId: string, actionLabel: string, @IQuickOpenService quickOpenService: IQuickOpenService) {
		super(actionId, actionLabel, ALL_COMMANDS_PREFIX, quickOpenService);
	}
}

class BaseCommandEntry extends QuickOpenEntryGroup {
50 51
	private keyLabel: string;
	private keyAriaLabel: string;
E
Erich Gamma 已提交
52 53 54
	private description: string;

	constructor(
55 56
		keyLabel: string,
		keyAriaLabel: string,
E
Erich Gamma 已提交
57 58 59 60 61 62 63
		description: string,
		highlights: IHighlight[],
		@IMessageService protected messageService: IMessageService,
		@ITelemetryService private telemetryService: ITelemetryService
	) {
		super();

64 65
		this.keyLabel = keyLabel;
		this.keyAriaLabel = keyAriaLabel;
E
Erich Gamma 已提交
66 67 68 69 70 71 72 73
		this.description = description;
		this.setHighlights(highlights);
	}

	public getLabel(): string {
		return this.description;
	}

74
	public getAriaLabel(): string {
75
		if (this.keyAriaLabel) {
B
Benjamin Pasero 已提交
76
			return nls.localize('entryAriaLabelWithKey', "{0}, {1}, commands", this.getLabel(), this.keyAriaLabel);
77 78
		}

79 80 81
		return nls.localize('entryAriaLabel', "{0}, commands", this.getLabel());
	}

E
Erich Gamma 已提交
82
	public getGroupLabel(): string {
83
		return this.keyLabel;
E
Erich Gamma 已提交
84 85 86 87 88 89 90 91 92 93 94
	}

	protected onError(error?: Error): void {
		let message = !error ? nls.localize('canNotRun', "Command '{0}' can not be run from here.", this.description) : toErrorMessage(error);

		this.messageService.show(Severity.Error, message);
	}

	protected runAction(action: IAction): void {

		// Use a timeout to give the quick open widget a chance to close itself first
95
		TPromise.timeout(50).done(() => {
E
Erich Gamma 已提交
96 97 98
			if (action && action.enabled) {
				try {
					this.telemetryService.publicLog('workbenchActionExecuted', { id: action.id, from: 'quick open' });
A
Alex Dima 已提交
99
					(action.run() || TPromise.as(null)).done(() => {
E
Erich Gamma 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
						action.dispose();
					}, (err) => this.onError(err));
				} catch (error) {
					this.onError(error);
				}
			} else {
				this.messageService.show(Severity.Info, nls.localize('actionNotEnabled', "Command '{0}' is not enabled in the current context.", this.getLabel()));
			}
		}, (err) => this.onError(err));
	}
}

class CommandEntry extends BaseCommandEntry {
	private actionDescriptor: SyncActionDescriptor;

	constructor(
116 117
		keyLabel: string,
		keyAriaLabel: string,
E
Erich Gamma 已提交
118 119 120 121 122 123 124 125
		description: string,
		highlights: IHighlight[],
		actionDescriptor: SyncActionDescriptor,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService messageService: IMessageService,
		@ITelemetryService telemetryService: ITelemetryService
	) {
126
		super(keyLabel, keyAriaLabel, description, highlights, messageService, telemetryService);
E
Erich Gamma 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

		this.actionDescriptor = actionDescriptor;
	}

	public run(mode: Mode, context: IContext): boolean {
		if (mode === Mode.OPEN) {
			let action = <Action>this.instantiationService.createInstance(this.actionDescriptor.syncDescriptor);
			this.runAction(action);

			return true;
		}

		return false;
	}
}

class EditorActionCommandEntry extends BaseCommandEntry {
	private action: IAction;

	constructor(
147 148
		keyLabel: string,
		keyAriaLabel: string,
E
Erich Gamma 已提交
149 150 151 152 153 154 155
		description: string,
		highlights: IHighlight[],
		action: IAction,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IMessageService messageService: IMessageService,
		@ITelemetryService telemetryService: ITelemetryService
	) {
156
		super(keyLabel, keyAriaLabel, description, highlights, messageService, telemetryService);
E
Erich Gamma 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

		this.action = action;
	}

	public run(mode: Mode, context: IContext): boolean {
		if (mode === Mode.OPEN) {
			this.runAction(this.action);

			return true;
		}

		return false;
	}
}


class ActionCommandEntry extends BaseCommandEntry {
	private action: IAction;

	constructor(
177 178
		keyLabel: string,
		keyAriaLabel: string,
E
Erich Gamma 已提交
179 180 181 182 183 184
		description: string,
		highlights: IHighlight[],
		action: IAction,
		@IMessageService messageService: IMessageService,
		@ITelemetryService telemetryService: ITelemetryService
	) {
185
		super(keyLabel, keyAriaLabel, description, highlights, messageService, telemetryService);
E
Erich Gamma 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

		this.action = action;
	}

	public run(mode: Mode, context: IContext): boolean {
		if (mode === Mode.OPEN) {
			this.runAction(this.action);

			return true;
		}

		return false;
	}
}

export class CommandsHandler extends QuickOpenHandler {

	constructor(
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService private messageService: IMessageService,
		@IKeybindingService private keybindingService: IKeybindingService,
B
Benjamin Pasero 已提交
208
		@IActionsService private actionsService: IActionsService
E
Erich Gamma 已提交
209 210 211 212 213 214 215 216 217
	) {
		super();
	}

	protected includeWorkbenchCommands(): boolean {
		return true;
	}

	public getResults(searchValue: string): TPromise<QuickOpenModel> {
218
		searchValue = searchValue.trim();
E
Erich Gamma 已提交
219 220 221 222 223 224 225 226 227 228 229 230

		// Workbench Actions (if prefix asks for all commands)
		let workbenchEntries: CommandEntry[] = [];
		if (this.includeWorkbenchCommands()) {
			let workbenchActions = (<IWorkbenchActionRegistry>Registry.as(ActionExtensions.WorkbenchActions)).getWorkbenchActions();
			workbenchEntries = this.actionDescriptorsToEntries(workbenchActions, searchValue);
		}

		// Editor Actions
		let activeEditor = this.editorService.getActiveEditor();
		let activeEditorControl = <any>(activeEditor ? activeEditor.getControl() : null);

231
		let editorActions: EditorAction[] = [];
E
Erich Gamma 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
		if (activeEditorControl && types.isFunction(activeEditorControl.getActions)) {
			editorActions = activeEditorControl.getActions();
		}

		let editorEntries = this.editorActionsToEntries(editorActions, searchValue);

		// Other Actions
		let otherActions = this.actionsService.getActions();
		let otherEntries = this.otherActionsToEntries(otherActions, searchValue);

		// Concat
		let entries = [...workbenchEntries, ...editorEntries, ...otherEntries];

		// Remove duplicates
		entries = arrays.distinct(entries, (entry) => entry.getLabel() + entry.getGroupLabel());

248 249
		// Sort by name
		entries = entries.sort((elementA, elementB) => strings.localeCompare(elementA.getLabel().toLowerCase(), elementB.getLabel().toLowerCase()));
E
Erich Gamma 已提交
250 251 252 253 254 255

		return TPromise.as(new QuickOpenModel(entries));
	}

	private actionDescriptorsToEntries(actionDescriptors: SyncActionDescriptor[], searchValue: string): CommandEntry[] {
		let entries: CommandEntry[] = [];
256
		let registry = Registry.as<IWorkbenchActionRegistry>(ActionExtensions.WorkbenchActions);
E
Erich Gamma 已提交
257 258 259

		for (let i = 0; i < actionDescriptors.length; i++) {
			let actionDescriptor = actionDescriptors[i];
260 261 262
			let keys = this.keybindingService.lookupKeybindings(actionDescriptor.id);
			let keyLabel = keys.map(k => this.keybindingService.getLabelFor(k));
			let keyAriaLabel = keys.map(k => this.keybindingService.getAriaLabelFor(k));
E
Erich Gamma 已提交
263 264 265 266 267 268 269 270

			if (actionDescriptor.label) {
				let label = actionDescriptor.label;
				let category = registry.getCategory(actionDescriptor.id);
				if (category) {
					label = nls.localize('commandLabel', "{0}: {1}", category, label);
				}

271 272 273 274 275 276 277
				let searchTarget = label;
				let keywords = registry.getKeywords(actionDescriptor.id);
				if (keywords) {
					searchTarget = [searchTarget, ...keywords].join(' ');
				}

				let highlights = wordFilter(searchValue, searchTarget);
E
Erich Gamma 已提交
278
				if (highlights) {
279
					entries.push(this.instantiationService.createInstance(CommandEntry, keyLabel.length > 0 ? keyLabel.join(', ') : '', keyAriaLabel.length > 0 ? keyAriaLabel.join(', ') : '', label, highlights, actionDescriptor));
E
Erich Gamma 已提交
280 281 282 283 284 285 286
				}
			}
		}

		return entries;
	}

287
	private editorActionsToEntries(actions: EditorAction[], searchValue: string): EditorActionCommandEntry[] {
E
Erich Gamma 已提交
288 289 290 291 292 293 294 295 296 297
		let entries: EditorActionCommandEntry[] = [];

		for (let i = 0; i < actions.length; i++) {
			let action = actions[i];

			let editorAction = <EditorAction>action;
			if (!editorAction.isSupported()) {
				continue; // do not show actions that are not supported in this context
			}

298 299 300
			let keys = this.keybindingService.lookupKeybindings(editorAction.id);
			let keyLabel = keys.map(k => this.keybindingService.getLabelFor(k));
			let keyAriaLabel = keys.map(k => this.keybindingService.getAriaLabelFor(k));
E
Erich Gamma 已提交
301 302

			if (action.label) {
303 304 305 306 307 308 309 310
				let searchTarget = action.label;

				let keywords = action.getKeywords();
				if (keywords) {
					searchTarget = [searchTarget, ...keywords].join(' ');
				}

				let highlights = wordFilter(searchValue, searchTarget);
E
Erich Gamma 已提交
311
				if (highlights) {
312
					entries.push(this.instantiationService.createInstance(EditorActionCommandEntry, keyLabel.length > 0 ? keyLabel.join(', ') : '', keyAriaLabel.length > 0 ? keyAriaLabel.join(', ') : '', action.label, highlights, action));
E
Erich Gamma 已提交
313 314 315 316 317 318 319 320 321 322 323
				}
			}
		}

		return entries;
	}

	private otherActionsToEntries(actions: IAction[], searchValue: string): ActionCommandEntry[] {
		let entries: ActionCommandEntry[] = [];

		for (let action of actions) {
324 325 326
			let keys = this.keybindingService.lookupKeybindings(action.id);
			let keyLabel = keys.map(k => this.keybindingService.getLabelFor(k));
			let keyAriaLabel = keys.map(k => this.keybindingService.getAriaLabelFor(k));
327
			let highlights = wordFilter(searchValue, action.label);
E
Erich Gamma 已提交
328
			if (highlights) {
329
				entries.push(this.instantiationService.createInstance(ActionCommandEntry, keyLabel.join(', '), keyAriaLabel.join(', '), action.label, highlights, action));
E
Erich Gamma 已提交
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 365 366 367 368 369 370 371 372 373 374 375 376
			}
		}

		return entries;
	}

	public getAutoFocus(searchValue: string): IAutoFocus {
		return {
			autoFocusFirstEntry: true,
			autoFocusPrefixMatch: searchValue.trim()
		};
	}

	public getClass(): string {
		return 'commands-handler';
	}

	public getEmptyLabel(searchString: string): string {
		return nls.localize('noCommandsMatching', "No commands matching");
	}
}

export class EditorCommandsHandler extends CommandsHandler {

	protected includeWorkbenchCommands(): boolean {
		return false;
	}
}

export class QuickCommandsEditorAction extends EditorAction {

	public static ID = 'editor.action.quickCommand';

	constructor(
		descriptor: IEditorActionDescriptorData,
		editor: ICommonCodeEditor,
		@IQuickOpenService private quickOpenService: IQuickOpenService
	) {
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.ShowInContextMenu);

		this.label = nls.localize('QuickCommandsAction.label', "Show Editor Commands");
	}

	public getGroupId(): string {
		return '4_tools/1_commands';
	}

377
	public run(): TPromise<any> {
E
Erich Gamma 已提交
378 379 380 381 382 383 384 385 386

		// Pass focus to editor first before running quick open action
		this.editor.focus();

		// Show with prefix
		this.quickOpenService.show('$');

		return super.run();
	}
387
}