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

J
Johannes Rieken 已提交
7
import { Schemas } from 'vs/base/common/network';
E
Erich Gamma 已提交
8
import Severity from 'vs/base/common/severity';
9
import URI from 'vs/base/common/uri';
J
Johannes Rieken 已提交
10
import { TPromise } from 'vs/base/common/winjs.base';
B
Benjamin Pasero 已提交
11
import { IConfigurationService, IConfigurationServiceEvent, IConfigurationValue, getConfigurationValue, IConfigurationKeys } from 'vs/platform/configuration/common/configuration';
J
Joao Moreno 已提交
12
import { IEditor, IEditorInput, IEditorOptions, IEditorService, IResourceInput, Position } from 'vs/platform/editor/common/editor';
13
import { ICommandService, ICommand, ICommandEvent, ICommandHandler, CommandsRegistry } from 'vs/platform/commands/common/commands';
14 15
import { AbstractKeybindingService } from 'vs/platform/keybinding/common/abstractKeybindingService';
import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding';
16
import { KeybindingResolver } from 'vs/platform/keybinding/common/keybindingResolver';
17
import { IKeybindingEvent, KeybindingSource, IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding';
18
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
J
Johannes Rieken 已提交
19
import { IConfirmation, IMessageService } from 'vs/platform/message/common/message';
A
Alex Dima 已提交
20
import * as editorCommon from 'vs/editor/common/editorCommon';
J
Johannes Rieken 已提交
21 22 23 24 25 26
import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
import { Selection } from 'vs/editor/common/core/selection';
import Event, { Emitter } from 'vs/base/common/event';
import { getDefaultValues as getDefaultConfiguration } from 'vs/platform/configuration/common/model';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgressService, IProgressRunner } from 'vs/platform/progress/common/progress';
J
Joao Moreno 已提交
27
import { ITextModelResolverService, ITextModelContentProvider, ITextEditorModel } from 'vs/editor/common/services/resolverService';
28
import { IDisposable, IReference, ImmortalReference, combinedDisposable } from 'vs/base/common/lifecycle';
29 30
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
A
Renames  
Alex Dima 已提交
31
import { KeybindingsRegistry, IKeybindingItem } from 'vs/platform/keybinding/common/keybindingsRegistry';
32
import { MenuId, IMenu, IMenuService } from 'vs/platform/actions/common/actions';
A
Alex Dima 已提交
33
import { Menu } from 'vs/platform/actions/common/menu';
34
import { ITelemetryService, ITelemetryExperiments, ITelemetryInfo } from 'vs/platform/telemetry/common/telemetry';
35
import { ResolvedKeybinding, Keybinding, createKeybinding, SimpleKeybinding } from 'vs/base/common/keyCodes';
36
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
A
Alex Dima 已提交
37
import { OS } from 'vs/base/common/platform';
E
Erich Gamma 已提交
38 39 40

export class SimpleEditor implements IEditor {

J
Johannes Rieken 已提交
41 42 43
	public input: IEditorInput;
	public options: IEditorOptions;
	public position: Position;
E
Erich Gamma 已提交
44

J
Johannes Rieken 已提交
45
	public _widget: editorCommon.IEditor;
E
Erich Gamma 已提交
46

J
Johannes Rieken 已提交
47
	constructor(editor: editorCommon.IEditor) {
E
Erich Gamma 已提交
48 49 50
		this._widget = editor;
	}

J
Johannes Rieken 已提交
51 52 53 54 55
	public getId(): string { return 'editor'; }
	public getControl(): editorCommon.IEditor { return this._widget; }
	public getSelection(): Selection { return this._widget.getSelection(); }
	public focus(): void { this._widget.focus(); }
	public isVisible(): boolean { return true; }
E
Erich Gamma 已提交
56

J
Johannes Rieken 已提交
57
	public withTypedEditor<T>(codeEditorCallback: (editor: ICodeEditor) => T, diffEditorCallback: (editor: IDiffEditor) => T): T {
A
Alex Dima 已提交
58
		if (editorCommon.isCommonCodeEditor(this._widget)) {
E
Erich Gamma 已提交
59
			// Single Editor
A
Alex Dima 已提交
60
			return codeEditorCallback(<ICodeEditor>this._widget);
E
Erich Gamma 已提交
61 62
		} else {
			// Diff Editor
A
Alex Dima 已提交
63
			return diffEditorCallback(<IDiffEditor>this._widget);
E
Erich Gamma 已提交
64 65 66 67
		}
	}
}

J
Johannes Rieken 已提交
68
export class SimpleModel implements ITextEditorModel {
E
Erich Gamma 已提交
69

J
Johannes Rieken 已提交
70
	private model: editorCommon.IModel;
71
	private _onDispose: Emitter<void>;
E
Erich Gamma 已提交
72

J
Johannes Rieken 已提交
73
	constructor(model: editorCommon.IModel) {
E
Erich Gamma 已提交
74
		this.model = model;
75 76 77 78 79
		this._onDispose = new Emitter<void>();
	}

	public get onDispose(): Event<void> {
		return this._onDispose.event;
E
Erich Gamma 已提交
80 81
	}

82 83 84 85
	public load(): TPromise<SimpleModel> {
		return TPromise.as(this);
	}

J
Johannes Rieken 已提交
86
	public get textEditorModel(): editorCommon.IModel {
E
Erich Gamma 已提交
87 88
		return this.model;
	}
89 90 91 92

	public dispose(): void {
		this._onDispose.fire();
	}
E
Erich Gamma 已提交
93 94 95
}

export interface IOpenEditorDelegate {
J
Johannes Rieken 已提交
96
	(url: string): boolean;
E
Erich Gamma 已提交
97 98 99
}

export class SimpleEditorService implements IEditorService {
100
	public _serviceBrand: any;
E
Erich Gamma 已提交
101

J
Johannes Rieken 已提交
102 103
	private editor: SimpleEditor;
	private openEditorDelegate: IOpenEditorDelegate;
E
Erich Gamma 已提交
104 105 106 107 108

	constructor() {
		this.openEditorDelegate = null;
	}

J
Johannes Rieken 已提交
109
	public setEditor(editor: editorCommon.IEditor): void {
E
Erich Gamma 已提交
110 111 112
		this.editor = new SimpleEditor(editor);
	}

J
Johannes Rieken 已提交
113
	public setOpenEditorDelegate(openEditorDelegate: IOpenEditorDelegate): void {
E
Erich Gamma 已提交
114 115 116
		this.openEditorDelegate = openEditorDelegate;
	}

J
Johannes Rieken 已提交
117
	public openEditor(typedData: IResourceInput, sideBySide?: boolean): TPromise<IEditor> {
E
Erich Gamma 已提交
118 119 120 121 122 123 124 125 126
		return TPromise.as(this.editor.withTypedEditor(
			(editor) => this.doOpenEditor(editor, typedData),
			(diffEditor) => (
				this.doOpenEditor(diffEditor.getOriginalEditor(), typedData) ||
				this.doOpenEditor(diffEditor.getModifiedEditor(), typedData)
			)
		));
	}

J
Johannes Rieken 已提交
127
	private doOpenEditor(editor: editorCommon.ICommonCodeEditor, data: IResourceInput): IEditor {
A
Alex Dima 已提交
128
		let model = this.findModel(editor, data);
E
Erich Gamma 已提交
129 130 131 132 133 134
		if (!model) {
			if (data.resource) {
				if (this.openEditorDelegate) {
					this.openEditorDelegate(data.resource.toString());
					return null;
				} else {
A
Alex Dima 已提交
135
					let schema = data.resource.scheme;
A
Alex Dima 已提交
136
					if (schema === Schemas.http || schema === Schemas.https) {
E
Erich Gamma 已提交
137 138 139 140 141 142 143 144 145
						// This is a fully qualified http or https URL
						window.open(data.resource.toString());
						return this.editor;
					}
				}
			}
			return null;
		}

A
Alex Dima 已提交
146
		let selection = <editorCommon.IRange>data.options.selection;
E
Erich Gamma 已提交
147 148 149
		if (selection) {
			if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') {
				editor.setSelection(selection);
A
Alex Dima 已提交
150
				editor.revealRangeInCenter(selection);
E
Erich Gamma 已提交
151
			} else {
A
Alex Dima 已提交
152
				let pos = {
E
Erich Gamma 已提交
153 154 155 156 157 158 159 160 161 162 163
					lineNumber: selection.startLineNumber,
					column: selection.startColumn
				};
				editor.setPosition(pos);
				editor.revealPositionInCenter(pos);
			}
		}

		return this.editor;
	}

J
Johannes Rieken 已提交
164
	private findModel(editor: editorCommon.ICommonCodeEditor, data: IResourceInput): editorCommon.IModel {
A
Alex Dima 已提交
165
		let model = editor.getModel();
J
Johannes Rieken 已提交
166
		if (model.uri.toString() !== data.resource.toString()) {
E
Erich Gamma 已提交
167 168 169 170 171 172 173
			return null;
		}

		return model;
	}
}

174 175 176 177 178 179 180 181 182
export class SimpleEditorModelResolverService implements ITextModelResolverService {
	public _serviceBrand: any;

	private editor: SimpleEditor;

	public setEditor(editor: editorCommon.IEditor): void {
		this.editor = new SimpleEditor(editor);
	}

J
Joao Moreno 已提交
183
	public createModelReference(resource: URI): TPromise<IReference<ITextEditorModel>> {
184 185 186 187 188 189 190 191
		let model: editorCommon.IModel;

		model = this.editor.withTypedEditor(
			(editor) => this.findModel(editor, resource),
			(diffEditor) => this.findModel(diffEditor.getOriginalEditor(), resource) || this.findModel(diffEditor.getModifiedEditor(), resource)
		);

		if (!model) {
J
Joao Moreno 已提交
192
			return TPromise.as(new ImmortalReference(null));
193 194
		}

J
Joao Moreno 已提交
195
		return TPromise.as(new ImmortalReference(new SimpleModel(model)));
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	}

	public registerTextModelContentProvider(scheme: string, provider: ITextModelContentProvider): IDisposable {
		return {
			dispose: function () { /* no op */ }
		};
	}

	private findModel(editor: editorCommon.ICommonCodeEditor, resource: URI): editorCommon.IModel {
		let model = editor.getModel();
		if (model.uri.toString() !== resource.toString()) {
			return null;
		}

		return model;
	}
}

214 215 216
export class SimpleProgressService implements IProgressService {
	_serviceBrand: any;

J
Johannes Rieken 已提交
217 218 219 220
	private static NULL_PROGRESS_RUNNER: IProgressRunner = {
		done: () => { },
		total: () => { },
		worked: () => { }
221 222 223 224 225 226 227 228 229 230 231 232 233
	};

	show(infinite: boolean, delay?: number): IProgressRunner;
	show(total: number, delay?: number): IProgressRunner;
	show(): IProgressRunner {
		return SimpleProgressService.NULL_PROGRESS_RUNNER;
	}

	showWhile(promise: TPromise<any>, delay?: number): TPromise<void> {
		return null;
	}
}

E
Erich Gamma 已提交
234
export class SimpleMessageService implements IMessageService {
235
	public _serviceBrand: any;
E
Erich Gamma 已提交
236

J
Johannes Rieken 已提交
237
	private static Empty = function () { /* nothing */ };
E
Erich Gamma 已提交
238

J
Johannes Rieken 已提交
239
	public show(sev: Severity, message: any): () => void {
E
Erich Gamma 已提交
240

J
Johannes Rieken 已提交
241
		switch (sev) {
E
Erich Gamma 已提交
242
			case Severity.Error:
243
				console.error(message);
E
Erich Gamma 已提交
244 245 246 247 248 249 250 251 252 253 254 255
				break;
			case Severity.Warning:
				console.warn(message);
				break;
			default:
				console.log(message);
				break;
		}

		return SimpleMessageService.Empty;
	}

J
Johannes Rieken 已提交
256
	public hideAll(): void {
E
Erich Gamma 已提交
257 258 259
		// No-op
	}

J
Johannes Rieken 已提交
260
	public confirm(confirmation: IConfirmation): boolean {
A
Alex Dima 已提交
261
		let messageText = confirmation.message;
E
Erich Gamma 已提交
262 263 264 265 266 267
		if (confirmation.detail) {
			messageText = messageText + '\n\n' + confirmation.detail;
		}

		return window.confirm(messageText);
	}
A
Alex Dima 已提交
268 269
}

A
Alex Dima 已提交
270 271
export class StandaloneCommandService implements ICommandService {
	_serviceBrand: any;
272

A
Alex Dima 已提交
273
	private readonly _instantiationService: IInstantiationService;
274 275
	private _dynamicCommands: { [id: string]: ICommand; };

276 277 278
	private _onWillExecuteCommand: Emitter<ICommandEvent> = new Emitter<ICommandEvent>();
	public readonly onWillExecuteCommand: Event<ICommandEvent> = this._onWillExecuteCommand.event;

A
Alex Dima 已提交
279 280
	constructor(instantiationService: IInstantiationService) {
		this._instantiationService = instantiationService;
281 282 283
		this._dynamicCommands = Object.create(null);
	}

284
	public addCommand(id: string, command: ICommand): IDisposable {
285
		this._dynamicCommands[id] = command;
286 287 288 289 290
		return {
			dispose: () => {
				delete this._dynamicCommands[id];
			}
		};
291 292
	}

A
Alex Dima 已提交
293 294 295 296 297 298 299
	public executeCommand<T>(id: string, ...args: any[]): TPromise<T> {
		const command = (CommandsRegistry.getCommand(id) || this._dynamicCommands[id]);
		if (!command) {
			return TPromise.wrapError(new Error(`command '${id}' not found`));
		}

		try {
300
			this._onWillExecuteCommand.fire({ commandId: id });
A
Alex Dima 已提交
301 302 303 304 305
			const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(args));
			return TPromise.as(result);
		} catch (err) {
			return TPromise.wrapError(err);
		}
306 307 308
	}
}

309 310
export class StandaloneKeybindingService extends AbstractKeybindingService {
	private _cachedResolver: KeybindingResolver;
E
Erich Gamma 已提交
311 312
	private _dynamicKeybindings: IKeybindingItem[];

A
Alex Dima 已提交
313
	constructor(
314
		contextKeyService: IContextKeyService,
A
Alex Dima 已提交
315 316 317 318
		commandService: ICommandService,
		messageService: IMessageService,
		domNode: HTMLElement
	) {
319
		super(contextKeyService, commandService, messageService);
320

321
		this._cachedResolver = null;
E
Erich Gamma 已提交
322
		this._dynamicKeybindings = [];
323

324 325
		this.toDispose.push(dom.addDisposableListener(domNode, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
			let keyEvent = new StandardKeyboardEvent(e);
326
			let shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
327 328 329 330
			if (shouldPreventDefault) {
				keyEvent.preventDefault();
			}
		}));
E
Erich Gamma 已提交
331 332
	}

333
	public addDynamicKeybinding(commandId: string, keybinding: number, handler: ICommandHandler, when: ContextKeyExpr): IDisposable {
334 335
		let toDispose: IDisposable[] = [];

E
Erich Gamma 已提交
336
		this._dynamicKeybindings.push({
A
Renames  
Alex Dima 已提交
337
			keybinding: createKeybinding(keybinding, OS),
E
Erich Gamma 已提交
338
			command: commandId,
339
			when: when,
E
Erich Gamma 已提交
340 341 342
			weight1: 1000,
			weight2: 0
		});
343

344 345 346 347 348 349 350 351 352 353 354 355 356
		toDispose.push({
			dispose: () => {
				for (let i = 0; i < this._dynamicKeybindings.length; i++) {
					let kb = this._dynamicKeybindings[i];
					if (kb.command === commandId) {
						this._dynamicKeybindings.splice(i, 1);
						this.updateResolver({ source: KeybindingSource.Default });
						return;
					}
				}
			}
		});

357 358
		let commandService = this._commandService;
		if (commandService instanceof StandaloneCommandService) {
359
			toDispose.push(commandService.addCommand(commandId, {
360
				handler: handler
361
			}));
362 363 364
		} else {
			throw new Error('Unknown command service!');
		}
C
Christof Marti 已提交
365
		this.updateResolver({ source: KeybindingSource.Default });
366

367
		return combinedDisposable(toDispose);
E
Erich Gamma 已提交
368 369
	}

370 371 372 373 374 375 376
	private updateResolver(event: IKeybindingEvent): void {
		this._cachedResolver = null;
		this._onDidUpdateKeybindings.fire(event);
	}

	protected _getResolver(): KeybindingResolver {
		if (!this._cachedResolver) {
377 378
			const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
			const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
379
			this._cachedResolver = new KeybindingResolver(defaults, overrides);
380 381 382 383
		}
		return this._cachedResolver;
	}

384 385
	private _toNormalizedKeybindingItems(items: IKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
386 387 388
		for (let i = 0, len = items.length; i < len; i++) {
			const item = items[i];
			const when = (item.when ? item.when.normalize() : null);
A
Alex Dima 已提交
389
			const keybinding = item.keybinding;
390

391 392 393 394 395 396 397 398 399
			if (!keybinding) {
				// This might be a removal keybinding item in user settings => accept it
				result[resultLen++] = new ResolvedKeybindingItem(null, item.command, item.commandArgs, when, isDefault);
			} else {
				const resolvedKeybindings = this.resolveKeybinding(keybinding);
				for (let j = 0; j < resolvedKeybindings.length; j++) {
					result[resultLen++] = new ResolvedKeybindingItem(resolvedKeybindings[j], item.command, item.commandArgs, when, isDefault);
				}
			}
400 401 402 403 404
		}

		return result;
	}

405 406
	public resolveKeybinding(keybinding: Keybinding): ResolvedKeybinding[] {
		return [new USLayoutResolvedKeybinding(keybinding, OS)];
A
Alex Dima 已提交
407 408
	}

409 410 411 412 413 414 415 416
	public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): ResolvedKeybinding {
		let keybinding = new SimpleKeybinding(
			keyboardEvent.ctrlKey,
			keyboardEvent.shiftKey,
			keyboardEvent.altKey,
			keyboardEvent.metaKey,
			keyboardEvent.keyCode
		);
417
		return new USLayoutResolvedKeybinding(keybinding, OS);
418
	}
419 420 421 422

	public resolveUserBinding(userBinding: string): ResolvedKeybinding[] {
		return [];
	}
E
Erich Gamma 已提交
423 424
}

425
export class SimpleConfigurationService implements IConfigurationService {
426

427 428
	_serviceBrand: any;

429 430
	private _onDidUpdateConfiguration = new Emitter<IConfigurationServiceEvent>();
	public onDidUpdateConfiguration: Event<IConfigurationServiceEvent> = this._onDidUpdateConfiguration.event;
431

432
	private _config: any;
433

434 435
	constructor() {
		this._config = getDefaultConfiguration();
436 437
	}

438
	public getConfiguration<T>(section?: any): T {
439
		return this._config;
440 441
	}

442
	public reloadConfiguration<T>(section?: string): TPromise<T> {
443
		return TPromise.as(this.getConfiguration(section));
444
	}
B
Benjamin Pasero 已提交
445 446 447 448 449 450 451 452

	public lookup<C>(key: string): IConfigurationValue<C> {
		return {
			value: getConfigurationValue<C>(this.getConfiguration(), key),
			default: getConfigurationValue<C>(this.getConfiguration(), key),
			user: getConfigurationValue<C>(this.getConfiguration(), key)
		};
	}
B
Benjamin Pasero 已提交
453 454 455 456

	public keys(): IConfigurationKeys {
		return { default: [], user: [] };
	}
457
}
A
Alex Dima 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

export class SimpleMenuService implements IMenuService {

	_serviceBrand: any;

	private readonly _commandService: ICommandService;

	constructor(commandService: ICommandService) {
		this._commandService = commandService;
	}

	public createMenu(id: MenuId, contextKeyService: IContextKeyService): IMenu {
		return new Menu(id, TPromise.as(true), this._commandService, contextKeyService);
	}
}
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

export class StandaloneTelemetryService implements ITelemetryService {
	_serviceBrand: void;

	public isOptedIn = false;

	public publicLog(eventName: string, data?: any): TPromise<void> {
		return TPromise.as<void>(null);
	}

	public getTelemetryInfo(): TPromise<ITelemetryInfo> {
		return null;
	}

	public getExperiments(): ITelemetryExperiments {
		return null;
	}
}