extHostCommands.ts 9.5 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.
 *--------------------------------------------------------------------------------------------*/

J
Johannes Rieken 已提交
6
import { validateConstraint } from 'vs/base/common/types';
7
import { ICommandHandlerDescription } from 'vs/platform/commands/common/commands';
J
Johannes Rieken 已提交
8 9
import * as extHostTypes from 'vs/workbench/api/common/extHostTypes';
import * as extHostTypeConverter from 'vs/workbench/api/common/extHostTypeConverters';
J
Johannes Rieken 已提交
10
import { cloneAndChange } from 'vs/base/common/objects';
11
import { MainContext, MainThreadCommandsShape, ExtHostCommandsShape, ObjectIdentifier, ICommandDto } from './extHost.protocol';
12
import { isNonEmptyArray } from 'vs/base/common/arrays';
13
import * as modes from 'vs/editor/common/modes';
14
import type * as vscode from 'vscode';
J
Joao Moreno 已提交
15
import { ILogService } from 'vs/platform/log/common/log';
16
import { revive } from 'vs/base/common/marshalling';
17 18 19
import { Range } from 'vs/editor/common/core/range';
import { Position } from 'vs/editor/common/core/position';
import { URI } from 'vs/base/common/uri';
20
import { DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
21
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
22
import { IExtHostRpcService } from 'vs/workbench/api/common/extHostRpcService';
E
Erich Gamma 已提交
23

24 25 26
interface CommandHandler {
	callback: Function;
	thisArg: any;
M
Matt Bierner 已提交
27
	description?: ICommandHandlerDescription;
28 29
}

J
Joao Moreno 已提交
30 31 32 33
export interface ArgumentProcessor {
	processArgument(arg: any): any;
}

34
export class ExtHostCommands implements ExtHostCommandsShape {
J
Johannes Rieken 已提交
35

36
	readonly _serviceBrand: undefined;
37

38 39 40 41 42
	private readonly _commands = new Map<string, CommandHandler>();
	private readonly _proxy: MainThreadCommandsShape;
	private readonly _converter: CommandsConverter;
	private readonly _logService: ILogService;
	private readonly _argumentProcessors: ArgumentProcessor[];
E
Erich Gamma 已提交
43

44
	constructor(
45
		@IExtHostRpcService extHostRpc: IExtHostRpcService,
46
		@ILogService logService: ILogService
47
	) {
48
		this._proxy = extHostRpc.getProxy(MainContext.MainThreadCommands);
49
		this._logService = logService;
50
		this._converter = new CommandsConverter(this, logService);
51 52 53 54
		this._argumentProcessors = [
			{
				processArgument(a) {
					// URI, Regex
55
					return revive(a);
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
				}
			},
			{
				processArgument(arg) {
					return cloneAndChange(arg, function (obj) {
						// Reverse of https://github.com/Microsoft/vscode/blob/1f28c5fc681f4c01226460b6d1c7e91b8acb4a5b/src/vs/workbench/api/node/extHostCommands.ts#L112-L127
						if (Range.isIRange(obj)) {
							return extHostTypeConverter.Range.to(obj);
						}
						if (Position.isIPosition(obj)) {
							return extHostTypeConverter.Position.to(obj);
						}
						if (Range.isIRange((obj as modes.Location).range) && URI.isUri((obj as modes.Location).uri)) {
							return extHostTypeConverter.location.to(obj);
						}
						if (!Array.isArray(obj)) {
							return obj;
						}
					});
				}
			}
		];
78 79 80 81
	}

	get converter(): CommandsConverter {
		return this._converter;
E
Erich Gamma 已提交
82 83
	}

J
Joao Moreno 已提交
84 85 86 87
	registerArgumentProcessor(processor: ArgumentProcessor): void {
		this._argumentProcessors.push(processor);
	}

88
	registerCommand(global: boolean, id: string, callback: <T>(...args: any[]) => T | Thenable<T>, thisArg?: any, description?: ICommandHandlerDescription): extHostTypes.Disposable {
89
		this._logService.trace('ExtHostCommands#registerCommand', id);
E
Erich Gamma 已提交
90 91 92 93 94

		if (!id.trim().length) {
			throw new Error('invalid id');
		}

J
Johannes Rieken 已提交
95
		if (this._commands.has(id)) {
96
			throw new Error(`command '${id}' already exists`);
E
Erich Gamma 已提交
97 98
		}

J
Johannes Rieken 已提交
99
		this._commands.set(id, { callback, thisArg, description });
100 101 102
		if (global) {
			this._proxy.$registerCommand(id);
		}
E
Erich Gamma 已提交
103

J
Johannes Rieken 已提交
104
		return new extHostTypes.Disposable(() => {
J
Johannes Rieken 已提交
105
			if (this._commands.delete(id)) {
106 107 108
				if (global) {
					this._proxy.$unregisterCommand(id);
				}
J
Johannes Rieken 已提交
109 110
			}
		});
E
Erich Gamma 已提交
111 112
	}

J
Johannes Rieken 已提交
113
	executeCommand<T>(id: string, ...args: any[]): Promise<T> {
114
		this._logService.trace('ExtHostCommands#executeCommand', id);
115 116 117 118
		return this._doExecuteCommand(id, args, true);
	}

	private async _doExecuteCommand<T>(id: string, args: any[], retry: boolean): Promise<T> {
E
Erich Gamma 已提交
119

J
Johannes Rieken 已提交
120
		if (this._commands.has(id)) {
E
Erich Gamma 已提交
121 122
			// we stay inside the extension host and support
			// to pass any kind of parameters around
123
			return this._executeContributedCommand<T>(id, args);
E
Erich Gamma 已提交
124 125

		} else {
126
			// automagically convert some argument types
127
			const toArgs = cloneAndChange(args, function (value) {
128
				if (value instanceof extHostTypes.Position) {
129
					return extHostTypeConverter.Position.from(value);
130 131
				}
				if (value instanceof extHostTypes.Range) {
132
					return extHostTypeConverter.Range.from(value);
133 134 135 136 137 138 139 140
				}
				if (value instanceof extHostTypes.Location) {
					return extHostTypeConverter.location.from(value);
				}
				if (!Array.isArray(value)) {
					return value;
				}
			});
E
Erich Gamma 已提交
141

142 143
			try {
				const result = await this._proxy.$executeCommand<T>(id, toArgs, retry);
144
				return revive(result);
145 146 147 148 149 150 151 152 153 154
			} catch (e) {
				// Rerun the command when it wasn't known, had arguments, and when retry
				// is enabled. We do this because the command might be registered inside
				// the extension host now and can therfore accept the arguments as-is.
				if (e instanceof Error && e.message === '$executeCommand:retry') {
					return this._doExecuteCommand(id, args, false);
				} else {
					throw e;
				}
			}
E
Erich Gamma 已提交
155 156 157
		}
	}

J
Johannes Rieken 已提交
158
	private _executeContributedCommand<T>(id: string, args: any[]): Promise<T> {
159 160 161 162 163
		const command = this._commands.get(id);
		if (!command) {
			throw new Error('Unknown command');
		}
		let { callback, thisArg, description } = command;
164 165 166
		if (description) {
			for (let i = 0; i < description.args.length; i++) {
				try {
J
Johannes Rieken 已提交
167
					validateConstraint(args[i], description.args[i].constraint);
168
				} catch (err) {
169
					return Promise.reject(new Error(`Running the contributed command: '${id}' failed. Illegal argument '${description.args[i].name}' - ${description.args[i].description}`));
170 171
				}
			}
172 173 174
		}

		try {
175
			const result = callback.apply(thisArg, args);
176
			return Promise.resolve(result);
E
Erich Gamma 已提交
177
		} catch (err) {
178
			this._logService.error(err, id);
179
			return Promise.reject(new Error(`Running the contributed command: '${id}' failed.`));
E
Erich Gamma 已提交
180 181 182
		}
	}

J
Johannes Rieken 已提交
183
	$executeContributedCommand<T>(id: string, ...args: any[]): Promise<T> {
184 185
		this._logService.trace('ExtHostCommands#$executeContributedCommand', id);

186 187 188 189 190 191 192 193
		if (!this._commands.has(id)) {
			return Promise.reject(new Error(`Contributed command '${id}' does not exist.`));
		} else {
			args = args.map(arg => this._argumentProcessors.reduce((r, p) => p.processArgument(r), arg));
			return this._executeContributedCommand(id, args);
		}
	}

J
Johannes Rieken 已提交
194
	getCommands(filterUnderscoreCommands: boolean = false): Promise<string[]> {
195
		this._logService.trace('ExtHostCommands#getCommands', filterUnderscoreCommands);
J
Joao Moreno 已提交
196

197
		return this._proxy.$getCommands().then(result => {
198 199 200 201 202
			if (filterUnderscoreCommands) {
				result = result.filter(command => command[0] !== '_');
			}
			return result;
		});
E
Erich Gamma 已提交
203
	}
204

J
Johannes Rieken 已提交
205
	$getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription }> {
206
		const result: { [id: string]: string | ICommandHandlerDescription } = Object.create(null);
J
Johannes Rieken 已提交
207
		this._commands.forEach((command, id) => {
J
Johannes Rieken 已提交
208
			let { description } = command;
209 210 211
			if (description) {
				result[id] = description;
			}
J
Johannes Rieken 已提交
212
		});
213
		return Promise.resolve(result);
214
	}
E
Erich Gamma 已提交
215
}
216 217 218 219


export class CommandsConverter {

220
	private readonly _delegatingCommandId: string;
221 222
	private readonly _cache = new Map<number, vscode.Command>();
	private _cachIdPool = 0;
223 224

	// --- conversion between internal and api commands
225 226 227 228
	constructor(
		private readonly _commands: ExtHostCommands,
		private readonly _logService: ILogService
	) {
229
		this._delegatingCommandId = `_vscode_delegate_cmd_${Date.now().toString(36)}`;
230
		this._commands.registerCommand(true, this._delegatingCommandId, this._executeConvertedCommand, this);
231 232
	}

J
Johannes Rieken 已提交
233
	toInternal(command: vscode.Command | undefined, disposables: DisposableStore): ICommandDto | undefined {
234 235

		if (!command) {
M
Matt Bierner 已提交
236
			return undefined;
237 238
		}

J
Johannes Rieken 已提交
239
		const result: ICommandDto = {
240
			$ident: undefined,
241
			id: command.command,
242
			title: command.title,
243
			tooltip: command.tooltip
244 245
		};

246
		if (command.command && isNonEmptyArray(command.arguments)) {
247 248 249
			// we have a contributed command with arguments. that
			// means we don't want to send the arguments around

250 251
			const id = ++this._cachIdPool;
			this._cache.set(id, command);
252 253 254 255
			disposables.add(toDisposable(() => {
				this._cache.delete(id);
				this._logService.trace('CommandsConverter#DISPOSE', id);
			}));
256
			result.$ident = id;
257

258
			result.id = this._delegatingCommandId;
259 260
			result.arguments = [id];

261
			this._logService.trace('CommandsConverter#CREATE', command.command, id);
262 263
		}

264 265 266
		return result;
	}

267
	fromInternal(command: modes.Command): vscode.Command | undefined {
268 269 270

		const id = ObjectIdentifier.of(command);
		if (typeof id === 'number') {
271
			return this._cache.get(id);
272 273 274 275 276 277 278 279 280 281

		} else {
			return {
				command: command.id,
				title: command.title,
				arguments: command.arguments
			};
		}
	}

J
Johannes Rieken 已提交
282
	private _executeConvertedCommand<R>(...args: any[]): Promise<R> {
283
		const actualCmd = this._cache.get(args[0]);
284 285
		this._logService.trace('CommandsConverter#EXECUTE', args[0], actualCmd ? actualCmd.command : 'MISSING');

286 287 288
		if (!actualCmd) {
			return Promise.reject('actual command NOT FOUND');
		}
289
		return this._commands.executeCommand(actualCmd.command, ...(actualCmd.arguments || []));
290 291
	}

J
Johannes Rieken 已提交
292
}
293 294 295

export interface IExtHostCommands extends ExtHostCommands { }
export const IExtHostCommands = createDecorator<IExtHostCommands>('IExtHostCommands');