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

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 14
import * as modes from 'vs/editor/common/modes';
import * 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 37
	readonly _serviceBrand: any;

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);
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
		this._argumentProcessors = [
			{
				processArgument(a) {
					// URI, Regex
					return revive(a, 0);
				}
			},
			{
				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);
E
Erich Gamma 已提交
115

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

		} else {
122 123
			// automagically convert some argument types

J
Johannes Rieken 已提交
124
			args = cloneAndChange(args, function (value) {
125
				if (value instanceof extHostTypes.Position) {
126
					return extHostTypeConverter.Position.from(value);
127 128
				}
				if (value instanceof extHostTypes.Range) {
129
					return extHostTypeConverter.Range.from(value);
130 131 132 133 134 135 136 137
				}
				if (value instanceof extHostTypes.Location) {
					return extHostTypeConverter.location.from(value);
				}
				if (!Array.isArray(value)) {
					return value;
				}
			});
E
Erich Gamma 已提交
138

H
Harry Hedger 已提交
139
			return this._proxy.$executeCommand<T>(id, args).then(result => revive(result, 0));
E
Erich Gamma 已提交
140 141 142
		}
	}

J
Johannes Rieken 已提交
143
	private _executeContributedCommand<T>(id: string, args: any[]): Promise<T> {
144 145 146 147 148
		const command = this._commands.get(id);
		if (!command) {
			throw new Error('Unknown command');
		}
		let { callback, thisArg, description } = command;
149 150 151
		if (description) {
			for (let i = 0; i < description.args.length; i++) {
				try {
J
Johannes Rieken 已提交
152
					validateConstraint(args[i], description.args[i].constraint);
153
				} catch (err) {
154
					return Promise.reject(new Error(`Running the contributed command: '${id}' failed. Illegal argument '${description.args[i].name}' - ${description.args[i].description}`));
155 156
				}
			}
157 158 159
		}

		try {
160
			const result = callback.apply(thisArg, args);
161
			return Promise.resolve(result);
E
Erich Gamma 已提交
162
		} catch (err) {
163
			this._logService.error(err, id);
164
			return Promise.reject(new Error(`Running the contributed command: '${id}' failed.`));
E
Erich Gamma 已提交
165 166 167
		}
	}

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

171 172 173 174 175 176 177 178
		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 已提交
179
	getCommands(filterUnderscoreCommands: boolean = false): Promise<string[]> {
180
		this._logService.trace('ExtHostCommands#getCommands', filterUnderscoreCommands);
J
Joao Moreno 已提交
181

182
		return this._proxy.$getCommands().then(result => {
183 184 185 186 187
			if (filterUnderscoreCommands) {
				result = result.filter(command => command[0] !== '_');
			}
			return result;
		});
E
Erich Gamma 已提交
188
	}
189

J
Johannes Rieken 已提交
190
	$getContributedCommandHandlerDescriptions(): Promise<{ [id: string]: string | ICommandHandlerDescription }> {
191
		const result: { [id: string]: string | ICommandHandlerDescription } = Object.create(null);
J
Johannes Rieken 已提交
192
		this._commands.forEach((command, id) => {
J
Johannes Rieken 已提交
193
			let { description } = command;
194 195 196
			if (description) {
				result[id] = description;
			}
J
Johannes Rieken 已提交
197
		});
198
		return Promise.resolve(result);
199
	}
E
Erich Gamma 已提交
200
}
201 202 203 204


export class CommandsConverter {

205
	private readonly _delegatingCommandId: string;
206 207 208
	private readonly _commands: ExtHostCommands;
	private readonly _cache = new Map<number, vscode.Command>();
	private _cachIdPool = 0;
209 210

	// --- conversion between internal and api commands
211
	constructor(commands: ExtHostCommands) {
212
		this._delegatingCommandId = `_vscode_delegate_cmd_${Date.now().toString(36)}`;
213
		this._commands = commands;
214
		this._commands.registerCommand(true, this._delegatingCommandId, this._executeConvertedCommand, this);
215 216
	}

J
Johannes Rieken 已提交
217
	toInternal(command: vscode.Command | undefined, disposables: DisposableStore): ICommandDto | undefined {
218 219

		if (!command) {
M
Matt Bierner 已提交
220
			return undefined;
221 222
		}

J
Johannes Rieken 已提交
223
		const result: ICommandDto = {
224
			$ident: undefined,
225
			id: command.command,
226
			title: command.title,
227
			tooltip: command.tooltip
228 229
		};

230
		if (command.command && isNonEmptyArray(command.arguments)) {
231 232 233
			// we have a contributed command with arguments. that
			// means we don't want to send the arguments around

234 235 236
			const id = ++this._cachIdPool;
			this._cache.set(id, command);
			disposables.add(toDisposable(() => this._cache.delete(id)));
237
			result.$ident = id;
238

239
			result.id = this._delegatingCommandId;
240 241
			result.arguments = [id];

242 243
		}

244 245 246
		return result;
	}

247
	fromInternal(command: modes.Command): vscode.Command | undefined {
248 249 250

		const id = ObjectIdentifier.of(command);
		if (typeof id === 'number') {
251
			return this._cache.get(id);
252 253 254 255 256 257 258 259 260 261

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

J
Johannes Rieken 已提交
262
	private _executeConvertedCommand<R>(...args: any[]): Promise<R> {
263 264 265 266
		const actualCmd = this._cache.get(args[0]);
		if (!actualCmd) {
			return Promise.reject('actual command NOT FOUND');
		}
267
		return this._commands.executeCommand(actualCmd.command, ...(actualCmd.arguments || []));
268 269
	}

J
Johannes Rieken 已提交
270
}
271 272 273

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