quickFixCommands.ts 8.6 KB
Newer Older
J
Johannes Rieken 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  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 * as nls from 'vs/nls';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
12
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
J
Johannes Rieken 已提交
13
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
14
import { optional } from 'vs/platform/instantiation/common/instantiation';
J
Johannes Rieken 已提交
15
import { IMarkerService } from 'vs/platform/markers/common/markers';
16
import { IEditorContribution } from 'vs/editor/common/editorCommon';
17
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
M
Matt Bierner 已提交
18
import { registerEditorAction, registerEditorContribution, ServicesAccessor, EditorAction, EditorCommand, registerEditorCommand } from 'vs/editor/browser/editorExtensions';
J
Johannes Rieken 已提交
19 20 21 22
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { QuickFixContextMenu } from './quickFixWidget';
import { LightBulbWidget } from './lightBulbWidget';
import { QuickFixModel, QuickFixComputeEvent } from './quickFixModel';
M
Matt Bierner 已提交
23
import { CodeActionKind, CodeActionAutoApply } from './codeActionTrigger';
24 25
import { TPromise } from 'vs/base/common/winjs.base';
import { CodeAction } from 'vs/editor/common/modes';
26
import { BulkEdit } from 'vs/editor/browser/services/bulkEdit';
27 28
import { IFileService } from 'vs/platform/files/common/files';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
J
Johannes Rieken 已提交
29 30 31

export class QuickFixController implements IEditorContribution {

32
	private static readonly ID = 'editor.contrib.quickFixController';
J
Johannes Rieken 已提交
33

34
	public static get(editor: ICodeEditor): QuickFixController {
J
Johannes Rieken 已提交
35 36 37 38 39
		return editor.getContribution<QuickFixController>(QuickFixController.ID);
	}

	private _editor: ICodeEditor;
	private _model: QuickFixModel;
40 41
	private _quickFixContextMenu: QuickFixContextMenu;
	private _lightBulbWidget: LightBulbWidget;
J
Johannes Rieken 已提交
42 43
	private _disposables: IDisposable[] = [];

44
	constructor(editor: ICodeEditor,
J
Johannes Rieken 已提交
45
		@IMarkerService markerService: IMarkerService,
46
		@IContextKeyService contextKeyService: IContextKeyService,
47
		@ICommandService private readonly _commandService: ICommandService,
48
		@IContextMenuService contextMenuService: IContextMenuService,
49 50
		@IKeybindingService private readonly _keybindingService: IKeybindingService,
		@ITextModelService private readonly _textModelService: ITextModelService,
51
		@optional(IFileService) private _fileService: IFileService
J
Johannes Rieken 已提交
52 53 54
	) {
		this._editor = editor;
		this._model = new QuickFixModel(this._editor, markerService);
55
		this._quickFixContextMenu = new QuickFixContextMenu(editor, contextMenuService, action => this._onApplyCodeAction(action));
56 57 58
		this._lightBulbWidget = new LightBulbWidget(editor);

		this._updateLightBulbTitle();
J
Johannes Rieken 已提交
59 60

		this._disposables.push(
M
Matt Bierner 已提交
61
			this._quickFixContextMenu.onDidExecuteCodeAction(_ => this._model.trigger({ type: 'auto' })),
62 63 64
			this._lightBulbWidget.onClick(this._handleLightBulbSelect, this),
			this._model.onDidChangeFixes(e => this._onQuickFixEvent(e)),
			this._keybindingService.onDidUpdateKeybindings(this._updateLightBulbTitle, this)
J
Johannes Rieken 已提交
65 66 67 68 69 70 71 72 73
		);
	}

	public dispose(): void {
		this._model.dispose();
		dispose(this._disposables);
	}

	private _onQuickFixEvent(e: QuickFixComputeEvent): void {
M
Matt Bierner 已提交
74 75 76 77 78 79 80 81 82 83 84 85
		if (e && e.trigger.kind) {
			// Triggered for specific scope
			// Apply if we only have one action or requested autoApply, otherwise show menu
			e.fixes.then(fixes => {
				if (e.trigger.autoApply === CodeActionAutoApply.First || (e.trigger.autoApply === CodeActionAutoApply.IfSingle && fixes.length === 1)) {
					this._onApplyCodeAction(fixes[0]);
				} else {
					this._quickFixContextMenu.show(e.fixes, e.position);
				}
			});
			return;
		}
86

M
Matt Bierner 已提交
87 88
		if (e && e.trigger.type === 'manual') {
			this._quickFixContextMenu.show(e.fixes, e.position);
J
Johannes Rieken 已提交
89 90 91 92
		} else if (e && e.fixes) {
			// auto magically triggered
			// * update an existing list of code actions
			// * manage light bulb
93 94
			if (this._quickFixContextMenu.isVisible) {
				this._quickFixContextMenu.show(e.fixes, e.position);
J
Johannes Rieken 已提交
95
			} else {
96
				this._lightBulbWidget.model = e;
J
Johannes Rieken 已提交
97 98
			}
		} else {
99
			this._lightBulbWidget.hide();
J
Johannes Rieken 已提交
100 101 102 103 104 105 106 107
		}
	}

	public getId(): string {
		return QuickFixController.ID;
	}

	private _handleLightBulbSelect(coords: { x: number, y: number }): void {
108
		this._quickFixContextMenu.show(this._lightBulbWidget.model.fixes, coords);
J
Johannes Rieken 已提交
109 110 111
	}

	public triggerFromEditorSelection(): void {
M
Matt Bierner 已提交
112 113 114 115 116
		this._model.trigger({ type: 'manual' });
	}

	public triggerCodeActionFromEditorSelection(kind?: CodeActionKind, autoApply?: CodeActionAutoApply): void {
		this._model.trigger({ type: 'manual', kind, autoApply });
J
Johannes Rieken 已提交
117 118 119 120 121 122 123 124 125 126
	}

	private _updateLightBulbTitle(): void {
		const kb = this._keybindingService.lookupKeybinding(QuickFixAction.Id);
		let title: string;
		if (kb) {
			title = nls.localize('quickFixWithKb', "Show Fixes ({0})", kb.getLabel());
		} else {
			title = nls.localize('quickFix', "Show Fixes");
		}
127
		this._lightBulbWidget.title = title;
J
Johannes Rieken 已提交
128
	}
129 130

	private async _onApplyCodeAction(action: CodeAction): TPromise<void> {
131
		if (action.edit) {
132
			await BulkEdit.perform(action.edit.edits, this._textModelService, this._fileService, this._editor);
133 134 135 136 137 138
		}

		if (action.command) {
			await this._commandService.executeCommand(action.command.id, ...action.command.arguments);
		}
	}
J
Johannes Rieken 已提交
139 140 141 142
}

export class QuickFixAction extends EditorAction {

143
	static readonly Id = 'editor.action.quickFix';
J
Johannes Rieken 已提交
144 145 146 147 148 149

	constructor() {
		super({
			id: QuickFixAction.Id,
			label: nls.localize('quickfix.trigger.label', "Quick Fix"),
			alias: 'Quick Fix',
150
			precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
J
Johannes Rieken 已提交
151
			kbOpts: {
152
				kbExpr: EditorContextKeys.editorTextFocus,
J
Johannes Rieken 已提交
153 154 155 156 157
				primary: KeyMod.CtrlCmd | KeyCode.US_DOT
			}
		});
	}

158
	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
J
Johannes Rieken 已提交
159 160 161 162 163 164
		let controller = QuickFixController.get(editor);
		if (controller) {
			controller.triggerFromEditorSelection();
		}
	}
}
165

M
Matt Bierner 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

class CodeActionCommandArgs {
	public static fromUser(arg: any): CodeActionCommandArgs {
		if (!arg || typeof arg !== 'object') {
			return new CodeActionCommandArgs(CodeActionKind.Empty, CodeActionAutoApply.IfSingle);
		}
		return new CodeActionCommandArgs(
			CodeActionCommandArgs.getKindFromUser(arg),
			CodeActionCommandArgs.getApplyFromUser(arg));
	}

	private static getApplyFromUser(arg: any) {
		switch (typeof arg.apply === 'string' ? arg.apply.toLowerCase() : '') {
			case 'first':
				return CodeActionAutoApply.First;

			case 'never':
				return CodeActionAutoApply.Never;

			case 'ifsingle':
			default:
				return CodeActionAutoApply.IfSingle;
		}
	}

	private static getKindFromUser(arg: any) {
		return typeof arg.kind === 'string'
			? new CodeActionKind(arg.kind)
			: CodeActionKind.Empty;
	}

	private constructor(
		public readonly kind: CodeActionKind,
		public readonly apply: CodeActionAutoApply
	) { }
}

export class CodeActionCommand extends EditorCommand {

	static readonly Id = 'editor.action.codeAction';

	constructor() {
		super({
			id: CodeActionCommand.Id,
			precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider)
		});
	}

	public runEditorCommand(accessor: ServicesAccessor, editor: ICodeEditor, userArg: any) {
		const controller = QuickFixController.get(editor);
		if (controller) {
			const args = CodeActionCommandArgs.fromUser(userArg);
			controller.triggerCodeActionFromEditorSelection(args.kind, args.apply);
		}
	}
}

M
Matt Bierner 已提交
223 224 225 226 227 228 229 230 231 232

export class RefactorAction extends EditorAction {

	static readonly Id = 'editor.action.refactor';

	constructor() {
		super({
			id: RefactorAction.Id,
			label: nls.localize('refactor.label', "Refactor"),
			alias: 'Refactor',
M
Matt Bierner 已提交
233 234
			precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
			kbOpts: {
235
				kbExpr: EditorContextKeys.editorTextFocus,
M
Matt Bierner 已提交
236 237
				primary: KeyMod.WinCtrl | KeyMod.Shift | KeyCode.KEY_R
			}
M
Matt Bierner 已提交
238 239 240 241 242 243 244 245 246 247 248 249
		});
	}

	public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
		const controller = QuickFixController.get(editor);
		if (controller) {
			controller.triggerCodeActionFromEditorSelection(CodeActionKind.Refactor, CodeActionAutoApply.Never);
		}
	}
}


250
registerEditorContribution(QuickFixController);
251
registerEditorAction(QuickFixAction);
M
Matt Bierner 已提交
252
registerEditorAction(RefactorAction);
M
Matt Bierner 已提交
253
registerEditorCommand(new CodeActionCommand());