simpleServices.ts 15.4 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';
A
Alex Dima 已提交
38
import { IRange } from "vs/editor/common/core/range";
E
Erich Gamma 已提交
39 40 41

export class SimpleEditor implements IEditor {

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

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

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

J
Johannes Rieken 已提交
52 53 54 55 56
	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 已提交
57

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

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

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

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

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

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

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

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

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

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

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

	constructor() {
		this.openEditorDelegate = null;
	}

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

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

J
Johannes Rieken 已提交
118
	public openEditor(typedData: IResourceInput, sideBySide?: boolean): TPromise<IEditor> {
E
Erich Gamma 已提交
119 120 121 122 123 124 125 126 127
		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 已提交
128
	private doOpenEditor(editor: editorCommon.ICommonCodeEditor, data: IResourceInput): IEditor {
A
Alex Dima 已提交
129
		let model = this.findModel(editor, data);
E
Erich Gamma 已提交
130 131 132 133 134 135
		if (!model) {
			if (data.resource) {
				if (this.openEditorDelegate) {
					this.openEditorDelegate(data.resource.toString());
					return null;
				} else {
A
Alex Dima 已提交
136
					let schema = data.resource.scheme;
A
Alex Dima 已提交
137
					if (schema === Schemas.http || schema === Schemas.https) {
E
Erich Gamma 已提交
138 139 140 141 142 143 144 145 146
						// This is a fully qualified http or https URL
						window.open(data.resource.toString());
						return this.editor;
					}
				}
			}
			return null;
		}

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

		return this.editor;
	}

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

		return model;
	}
}

175 176 177 178 179 180 181 182 183
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 已提交
184
	public createModelReference(resource: URI): TPromise<IReference<ITextEditorModel>> {
185 186 187 188 189 190 191 192
		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 已提交
193
			return TPromise.as(new ImmortalReference(null));
194 195
		}

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

	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;
	}
}

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

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

	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 已提交
235
export class SimpleMessageService implements IMessageService {
236
	public _serviceBrand: any;
E
Erich Gamma 已提交
237

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

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

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

		return SimpleMessageService.Empty;
	}

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

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

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

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

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

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

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

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

A
Alex Dima 已提交
294 295 296 297 298 299 300
	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 {
301
			this._onWillExecuteCommand.fire({ commandId: id });
A
Alex Dima 已提交
302 303 304 305 306
			const result = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler].concat(args));
			return TPromise.as(result);
		} catch (err) {
			return TPromise.wrapError(err);
		}
307 308 309
	}
}

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

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

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

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

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

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

345 346 347 348 349 350 351 352 353 354 355 356 357
		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;
					}
				}
			}
		});

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

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

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

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

385 386
	private _toNormalizedKeybindingItems(items: IKeybindingItem[], isDefault: boolean): ResolvedKeybindingItem[] {
		let result: ResolvedKeybindingItem[] = [], resultLen = 0;
387 388 389
		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 已提交
390
			const keybinding = item.keybinding;
391

392 393 394 395 396 397 398 399 400
			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);
				}
			}
401 402 403 404 405
		}

		return result;
	}

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

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

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

426
export class SimpleConfigurationService implements IConfigurationService {
427

428 429
	_serviceBrand: any;

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

433
	private _config: any;
434

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

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

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

	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 已提交
454 455 456 457

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

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);
	}
}
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

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;
	}
}