editorService.ts 23.5 KB
Newer Older
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.
 *--------------------------------------------------------------------------------------------*/

6
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
7
import { IResourceInput, ITextEditorOptions, IEditorOptions } from 'vs/platform/editor/common/editor';
8
import { IEditorInput, IEditor, GroupIdentifier, IFileEditorInput, IUntitledResourceInput, IResourceDiffInput, IResourceSideBySideInput, IEditorInputFactoryRegistry, Extensions as EditorExtensions, IFileInputFactory, EditorInput, SideBySideEditorInput, IEditorInputWithOptions, isEditorInputWithOptions, EditorOptions, TextEditorOptions, IEditorIdentifier, IEditorCloseEvent, ITextEditor, ITextDiffEditor, ITextSideBySideEditor, toResource } from 'vs/workbench/common/editor';
9 10 11 12 13 14 15
import { ResourceEditorInput } from 'vs/workbench/common/editor/resourceEditorInput';
import { DataUriEditorInput } from 'vs/workbench/common/editor/dataUriEditorInput';
import { Registry } from 'vs/platform/registry/common/platform';
import { ResourceMap } from 'vs/base/common/map';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IFileService } from 'vs/platform/files/common/files';
import { Schemas } from 'vs/base/common/network';
J
Joao Moreno 已提交
16
import { Event, Emitter } from 'vs/base/common/event';
17
import { URI } from 'vs/base/common/uri';
18 19 20
import { basename } from 'vs/base/common/paths';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { localize } from 'vs/nls';
21
import { IEditorGroupsService, IEditorGroup, GroupsOrder, IEditorReplacement, GroupChangeKind, preferredSideBySideGroupDirection } from 'vs/workbench/services/group/common/editorGroupsService';
B
Benjamin Pasero 已提交
22
import { IResourceEditor, ACTIVE_GROUP_TYPE, SIDE_GROUP_TYPE, SIDE_GROUP, IResourceEditorReplacement, IOpenEditorOverrideHandler } from 'vs/workbench/services/editor/common/editorService';
23
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
24
import { Disposable, IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
25
import { coalesce } from 'vs/base/common/arrays';
26
import { isCodeEditor, isDiffEditor, ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser';
B
Benjamin Pasero 已提交
27
import { IEditorGroupView, IEditorOpeningEvent, EditorGroupsServiceImpl, EditorServiceImpl } from 'vs/workbench/browser/parts/editor/editor';
I
isidor 已提交
28
import { ILabelService } from 'vs/platform/label/common/label';
29

30
type ICachedEditorInput = ResourceEditorInput | IFileEditorInput | DataUriEditorInput;
31

B
Benjamin Pasero 已提交
32
export class EditorService extends Disposable implements EditorServiceImpl {
33

34
	_serviceBrand: any;
35

36 37
	private static CACHE: ResourceMap<ICachedEditorInput> = new ResourceMap<ICachedEditorInput>();

38 39 40 41 42
	//#region events

	private _onDidActiveEditorChange: Emitter<void> = this._register(new Emitter<void>());
	get onDidActiveEditorChange(): Event<void> { return this._onDidActiveEditorChange.event; }

43 44 45
	private _onDidVisibleEditorsChange: Emitter<void> = this._register(new Emitter<void>());
	get onDidVisibleEditorsChange(): Event<void> { return this._onDidVisibleEditorsChange.event; }

B
Benjamin Pasero 已提交
46 47
	private _onDidCloseEditor: Emitter<IEditorCloseEvent> = this._register(new Emitter<IEditorCloseEvent>());
	get onDidCloseEditor(): Event<IEditorCloseEvent> { return this._onDidCloseEditor.event; }
48

49 50
	private _onDidOpenEditorFail: Emitter<IEditorIdentifier> = this._register(new Emitter<IEditorIdentifier>());
	get onDidOpenEditorFail(): Event<IEditorIdentifier> { return this._onDidOpenEditorFail.event; }
51

52 53
	//#endregion

54
	private fileInputFactory: IFileInputFactory;
55
	private openEditorHandlers: IOpenEditorOverrideHandler[] = [];
B
Benjamin Pasero 已提交
56

57
	private lastActiveEditor: IEditorInput;
B
Benjamin Pasero 已提交
58
	private lastActiveGroupId: GroupIdentifier;
59

60
	constructor(
B
Benjamin Pasero 已提交
61
		@IEditorGroupsService private editorGroupService: EditorGroupsServiceImpl,
62 63
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
I
isidor 已提交
64
		@ILabelService private labelService: ILabelService,
65 66
		@IFileService private fileService: IFileService,
		@IConfigurationService private configurationService: IConfigurationService
67
	) {
68 69
		super();

70
		this.fileInputFactory = Registry.as<IEditorInputFactoryRegistry>(EditorExtensions.EditorInputFactories).getFileInputFactory();
71 72 73 74 75

		this.registerListeners();
	}

	private registerListeners(): void {
76
		this.editorGroupService.whenRestored.then(() => this.onEditorsRestored());
77
		this.editorGroupService.onDidActiveGroupChange(group => this.handleActiveEditorChange(group));
78
		this.editorGroupService.onDidAddGroup(group => this.registerGroupListeners(group as IEditorGroupView));
79 80
	}

81 82 83 84 85 86 87 88 89 90 91 92
	private onEditorsRestored(): void {

		// Register listeners to each opened group
		this.editorGroupService.groups.forEach(group => this.registerGroupListeners(group as IEditorGroupView));

		// Fire initial set of editor events if there is an active editor
		if (this.activeEditor) {
			this.doEmitActiveEditorChangeEvent();
			this._onDidVisibleEditorsChange.fire();
		}
	}

93
	private handleActiveEditorChange(group: IEditorGroup): void {
94
		if (group !== this.editorGroupService.activeGroup) {
95
			return; // ignore if not the active group
96 97 98 99 100 101
		}

		if (!this.lastActiveEditor && !group.activeEditor) {
			return; // ignore if we still have no active editor
		}

B
Benjamin Pasero 已提交
102 103 104 105
		if (this.lastActiveGroupId === group.id && this.lastActiveEditor === group.activeEditor) {
			return; // ignore if the editor actually did not change
		}

106 107 108 109 110 111 112 113
		this.doEmitActiveEditorChangeEvent();
	}

	private doEmitActiveEditorChangeEvent(): void {
		const activeGroup = this.editorGroupService.activeGroup;

		this.lastActiveGroupId = activeGroup.id;
		this.lastActiveEditor = activeGroup.activeEditor;
114

115 116 117
		this._onDidActiveEditorChange.fire();
	}

118
	private registerGroupListeners(group: IEditorGroupView): void {
119 120
		const groupDisposeables: IDisposable[] = [];

121 122 123 124 125
		groupDisposeables.push(group.onDidGroupChange(e => {
			if (e.kind === GroupChangeKind.EDITOR_ACTIVE) {
				this.handleActiveEditorChange(group);
				this._onDidVisibleEditorsChange.fire();
			}
126 127
		}));

B
Benjamin Pasero 已提交
128 129
		groupDisposeables.push(group.onDidCloseEditor(event => {
			this._onDidCloseEditor.fire(event);
130 131
		}));

132 133
		groupDisposeables.push(group.onWillOpenEditor(event => {
			this.onGroupWillOpenEditor(group, event);
134 135 136
		}));

		groupDisposeables.push(group.onDidOpenEditorFail(editor => {
I
isidor 已提交
137
			this._onDidOpenEditorFail.fire({ editor, groupId: group.id });
138 139
		}));

J
Joao Moreno 已提交
140
		Event.once(group.onWillDispose)(() => {
141 142 143 144
			dispose(groupDisposeables);
		});
	}

145
	private onGroupWillOpenEditor(group: IEditorGroup, event: IEditorOpeningEvent): void {
146 147 148 149 150 151 152 153 154 155
		for (let i = 0; i < this.openEditorHandlers.length; i++) {
			const handler = this.openEditorHandlers[i];
			const result = handler(event.editor, event.options, group);
			if (result && result.override) {
				event.prevent((() => result.override));
				break;
			}
		}
	}

156
	get activeControl(): IEditor {
157
		const activeGroup = this.editorGroupService.activeGroup;
158

R
Rob Lourens 已提交
159
		return activeGroup ? activeGroup.activeControl : undefined;
160 161
	}

162
	get activeTextEditorWidget(): ICodeEditor | IDiffEditor {
163 164 165
		const activeControl = this.activeControl;
		if (activeControl) {
			const activeControlWidget = activeControl.getControl();
166
			if (isCodeEditor(activeControlWidget) || isDiffEditor(activeControlWidget)) {
167 168 169 170
				return activeControlWidget;
			}
		}

R
Rob Lourens 已提交
171
		return undefined;
172 173
	}

174 175
	get editors(): IEditorInput[] {
		const editors: IEditorInput[] = [];
176
		this.editorGroupService.groups.forEach(group => {
177 178 179 180 181 182
			editors.push(...group.editors);
		});

		return editors;
	}

183
	get activeEditor(): IEditorInput {
184
		const activeGroup = this.editorGroupService.activeGroup;
185

R
Rob Lourens 已提交
186
		return activeGroup ? activeGroup.activeEditor : undefined;
187 188
	}

189
	get visibleControls(): IEditor[] {
190
		return coalesce(this.editorGroupService.groups.map(group => group.activeControl));
191 192
	}

193
	get visibleTextEditorWidgets(): Array<ICodeEditor | IDiffEditor> {
194
		return this.visibleControls.map(control => control.getControl() as ICodeEditor | IDiffEditor).filter(widget => isCodeEditor(widget) || isDiffEditor(widget));
195 196
	}

197
	get visibleEditors(): IEditorInput[] {
198
		return coalesce(this.editorGroupService.groups.map(group => group.activeEditor));
199 200
	}

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
	//#region preventOpenEditor()

	overrideOpenEditor(handler: IOpenEditorOverrideHandler): IDisposable {
		this.openEditorHandlers.push(handler);

		return toDisposable(() => {
			const index = this.openEditorHandlers.indexOf(handler);
			if (index >= 0) {
				this.openEditorHandlers.splice(index, 1);
			}
		});
	}

	//#endregion

216 217
	//#region openEditor()

J
Johannes Rieken 已提交
218 219 220 221 222
	openEditor(editor: IEditorInput, options?: IEditorOptions | ITextEditorOptions, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<IEditor>;
	openEditor(editor: IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<ITextEditor>;
	openEditor(editor: IResourceDiffInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<ITextDiffEditor>;
	openEditor(editor: IResourceSideBySideInput, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<ITextSideBySideEditor>;
	openEditor(editor: IEditorInput | IResourceEditor, optionsOrGroup?: IEditorOptions | ITextEditorOptions | IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE, group?: GroupIdentifier): Promise<IEditor> {
223 224 225

		// Typed Editor Support
		if (editor instanceof EditorInput) {
226 227 228
			const editorOptions = this.toOptions(optionsOrGroup as IEditorOptions);
			const targetGroup = this.findTargetGroup(editor, editorOptions, group);

229
			return this.doOpenEditor(targetGroup, editor, editorOptions);
230 231 232 233 234 235
		}

		// Untyped Text Editor Support
		const textInput = <IResourceEditor>editor;
		const typedInput = this.createInput(textInput);
		if (typedInput) {
236
			const editorOptions = TextEditorOptions.from(textInput);
237
			const targetGroup = this.findTargetGroup(typedInput, editorOptions, optionsOrGroup as IEditorGroup | GroupIdentifier);
238

239
			return this.doOpenEditor(targetGroup, typedInput, editorOptions);
240 241
		}

B
Benjamin Pasero 已提交
242
		return Promise.resolve(null);
243
	}
244

J
Johannes Rieken 已提交
245
	protected doOpenEditor(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions): Promise<IEditor> {
246
		return group.openEditor(editor, options);
247 248
	}

249 250
	private findTargetGroup(input: IEditorInput, options?: IEditorOptions, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): IEditorGroup {
		let targetGroup: IEditorGroup;
251

B
Benjamin Pasero 已提交
252 253 254 255 256
		// Group: Instance of Group
		if (group && typeof group !== 'number') {
			return group;
		}

257
		// Group: Side by Side
B
Benjamin Pasero 已提交
258
		if (group === SIDE_GROUP) {
259
			targetGroup = this.findSideBySideGroup();
260 261
		}

262
		// Group: Specific Group
B
Benjamin Pasero 已提交
263
		else if (typeof group === 'number' && group >= 0) {
264
			targetGroup = this.editorGroupService.getGroup(group);
265 266
		}

267 268
		// Group: Unspecified without a specific index to open
		else if (!options || typeof options.index !== 'number') {
269
			const groupsByLastActive = this.editorGroupService.getGroups(GroupsOrder.MOST_RECENTLY_ACTIVE);
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

			// Respect option to reveal an editor if it is already visible in any group
			if (options && options.revealIfVisible) {
				for (let i = 0; i < groupsByLastActive.length; i++) {
					const group = groupsByLastActive[i];
					if (input.matches(group.activeEditor)) {
						targetGroup = group;
						break;
					}
				}
			}

			// Respect option to reveal an editor if it is open (not necessarily visible)
			if ((options && options.revealIfOpened) || this.configurationService.getValue<boolean>('workbench.editor.revealIfOpen')) {
				for (let i = 0; i < groupsByLastActive.length; i++) {
					const group = groupsByLastActive[i];
					if (group.isOpened(input)) {
						targetGroup = group;
						break;
					}
				}
			}
		}

		// Fallback to active group if target not valid
295
		if (!targetGroup) {
296
			targetGroup = this.editorGroupService.activeGroup;
297 298
		}

299 300 301
		return targetGroup;
	}

302
	private findSideBySideGroup(): IEditorGroup {
303
		const direction = preferredSideBySideGroupDirection(this.configurationService);
304

305
		let neighbourGroup = this.editorGroupService.findGroup({ direction });
306
		if (!neighbourGroup) {
307
			neighbourGroup = this.editorGroupService.addGroup(this.editorGroupService.activeGroup, direction);
308 309 310
		}

		return neighbourGroup;
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	}

	private toOptions(options?: IEditorOptions | EditorOptions): EditorOptions {
		if (!options || options instanceof EditorOptions) {
			return options as EditorOptions;
		}

		const textOptions: ITextEditorOptions = options;
		if (!!textOptions.selection) {
			return TextEditorOptions.create(options);
		}

		return EditorOptions.create(options);
	}

326 327
	//#endregion

328 329
	//#region openEditors()

J
Johannes Rieken 已提交
330 331
	openEditors(editors: IEditorInputWithOptions[], group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<IEditor[]>;
	openEditors(editors: IResourceEditor[], group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<IEditor[]>;
332
	openEditors(editors: Array<IEditorInputWithOptions | IResourceEditor>, group?: IEditorGroup | GroupIdentifier | SIDE_GROUP_TYPE | ACTIVE_GROUP_TYPE): Promise<IEditor[]> {
333 334 335 336 337 338 339 340 341 342 343 344

		// Convert to typed editors and options
		const typedEditors: IEditorInputWithOptions[] = [];
		editors.forEach(editor => {
			if (isEditorInputWithOptions(editor)) {
				typedEditors.push(editor);
			} else {
				typedEditors.push({ editor: this.createInput(editor), options: TextEditorOptions.from(editor) });
			}
		});

		// Find target groups to open
345
		const mapGroupToEditors = new Map<IEditorGroup, IEditorInputWithOptions[]>();
346
		if (group === SIDE_GROUP) {
347
			mapGroupToEditors.set(this.findSideBySideGroup(), typedEditors);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		} else {
			typedEditors.forEach(typedEditor => {
				const targetGroup = this.findTargetGroup(typedEditor.editor, typedEditor.options, group);

				let targetGroupEditors = mapGroupToEditors.get(targetGroup);
				if (!targetGroupEditors) {
					targetGroupEditors = [];
					mapGroupToEditors.set(targetGroup, targetGroupEditors);
				}

				targetGroupEditors.push(typedEditor);
			});
		}

		// Open in targets
J
Johannes Rieken 已提交
363
		const result: Promise<IEditor>[] = [];
364
		mapGroupToEditors.forEach((editorsWithOptions, group) => {
365
			result.push(group.openEditors(editorsWithOptions));
366
		});
367

B
Benjamin Pasero 已提交
368
		return Promise.all(result);
369 370 371 372
	}

	//#endregion

373 374
	//#region isOpen()

375
	isOpen(editor: IEditorInput | IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier): boolean {
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
		return !!this.doGetOpened(editor);
	}

	//#endregion

	//#region getOpend()

	getOpened(editor: IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier): IEditorInput {
		return this.doGetOpened(editor);
	}

	private doGetOpened(editor: IEditorInput | IResourceInput | IUntitledResourceInput, group?: IEditorGroup | GroupIdentifier): IEditorInput {
		if (!(editor instanceof EditorInput)) {
			const resourceInput = editor as IResourceInput | IUntitledResourceInput;
			if (!resourceInput.resource) {
R
Rob Lourens 已提交
391
				return undefined; // we need a resource at least
392 393 394
			}
		}

395
		let groups: IEditorGroup[] = [];
B
Benjamin Pasero 已提交
396
		if (typeof group === 'number') {
397
			groups.push(this.editorGroupService.getGroup(group));
B
Benjamin Pasero 已提交
398 399 400
		} else if (group) {
			groups.push(group);
		} else {
401
			groups = [...this.editorGroupService.groups];
B
Benjamin Pasero 已提交
402 403
		}

404 405 406 407 408
		// For each editor group
		for (let i = 0; i < groups.length; i++) {
			const group = groups[i];

			// Typed editor
409
			if (editor instanceof EditorInput) {
410 411 412
				if (group.isOpened(editor)) {
					return editor;
				}
413 414
			}

415 416 417 418 419
			// Resource editor
			else {
				for (let j = 0; j < group.editors.length; j++) {
					const editorInGroup = group.editors[j];
					const resource = toResource(editorInGroup, { supportSideBySide: true });
B
Benjamin Pasero 已提交
420 421 422
					if (!resource) {
						continue; // need a resource to compare with
					}
423

424 425 426 427 428 429 430
					const resourceInput = editor as IResourceInput | IUntitledResourceInput;
					if (resource.toString() === resourceInput.resource.toString()) {
						return editorInGroup;
					}
				}
			}
		}
431

R
Rob Lourens 已提交
432
		return undefined;
433 434 435 436
	}

	//#endregion

437 438
	//#region replaceEditors()

J
Johannes Rieken 已提交
439 440
	replaceEditors(editors: IResourceEditorReplacement[], group: IEditorGroup | GroupIdentifier): Promise<void>;
	replaceEditors(editors: IEditorReplacement[], group: IEditorGroup | GroupIdentifier): Promise<void>;
441
	replaceEditors(editors: Array<IEditorReplacement | IResourceEditorReplacement>, group: IEditorGroup | GroupIdentifier): Promise<void> {
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
		const typedEditors: IEditorReplacement[] = [];

		editors.forEach(replaceEditorArg => {
			if (replaceEditorArg.editor instanceof EditorInput) {
				typedEditors.push(replaceEditorArg as IEditorReplacement);
			} else {
				const editor = replaceEditorArg.editor as IResourceEditor;
				const typedEditor = this.createInput(editor);
				const replacementEditor = this.createInput(replaceEditorArg.replacement as IResourceEditor);

				typedEditors.push({
					editor: typedEditor,
					replacement: replacementEditor,
					options: this.toOptions(editor.options)
				});
			}
		});

460
		const targetGroup = typeof group === 'number' ? this.editorGroupService.getGroup(group) : group;
461 462 463 464 465
		return targetGroup.replaceEditors(typedEditors);
	}

	//#endregion

466 467 468
	//#region invokeWithinEditorContext()

	invokeWithinEditorContext<T>(fn: (accessor: ServicesAccessor) => T): T {
469 470 471
		const activeTextEditorWidget = this.activeTextEditorWidget;
		if (isCodeEditor(activeTextEditorWidget)) {
			return activeTextEditorWidget.invokeWithinContext(fn);
472 473
		}

474
		const activeGroup = this.editorGroupService.activeGroup;
475 476 477 478 479
		if (activeGroup) {
			return activeGroup.invokeWithinContext(fn);
		}

		return this.instantiationService.invokeFunction(fn);
480 481 482 483
	}

	//#endregion

484 485
	//#region createInput()

B
Benjamin Pasero 已提交
486
	createInput(input: IEditorInputWithOptions | IEditorInput | IResourceEditor): EditorInput {
487

488
		// Typed Editor Input Support (EditorInput)
489 490 491 492
		if (input instanceof EditorInput) {
			return input;
		}

493 494 495 496 497 498
		// Typed Editor Input Support (IEditorInputWithOptions)
		const editorInputWithOptions = input as IEditorInputWithOptions;
		if (editorInputWithOptions.editor instanceof EditorInput) {
			return editorInputWithOptions.editor;
		}

499 500 501
		// Side by Side Support
		const resourceSideBySideInput = <IResourceSideBySideInput>input;
		if (resourceSideBySideInput.masterResource && resourceSideBySideInput.detailResource) {
B
Benjamin Pasero 已提交
502 503
			const masterInput = this.createInput({ resource: resourceSideBySideInput.masterResource, forceFile: resourceSideBySideInput.forceFile });
			const detailInput = this.createInput({ resource: resourceSideBySideInput.detailResource, forceFile: resourceSideBySideInput.forceFile });
504 505 506 507 508 509 510 511 512 513 514 515

			return new SideBySideEditorInput(
				resourceSideBySideInput.label || masterInput.getName(),
				typeof resourceSideBySideInput.description === 'string' ? resourceSideBySideInput.description : masterInput.getDescription(),
				detailInput,
				masterInput
			);
		}

		// Diff Editor Support
		const resourceDiffInput = <IResourceDiffInput>input;
		if (resourceDiffInput.leftResource && resourceDiffInput.rightResource) {
B
Benjamin Pasero 已提交
516 517
			const leftInput = this.createInput({ resource: resourceDiffInput.leftResource, forceFile: resourceDiffInput.forceFile });
			const rightInput = this.createInput({ resource: resourceDiffInput.rightResource, forceFile: resourceDiffInput.forceFile });
518
			const label = resourceDiffInput.label || localize('compareLabels', "{0} ↔ {1}", this.toDiffLabel(leftInput), this.toDiffLabel(rightInput));
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

			return new DiffEditorInput(label, resourceDiffInput.description, leftInput, rightInput);
		}

		// Untitled file support
		const untitledInput = <IUntitledResourceInput>input;
		if (!untitledInput.resource || typeof untitledInput.filePath === 'string' || (untitledInput.resource instanceof URI && untitledInput.resource.scheme === Schemas.untitled)) {
			return this.untitledEditorService.createOrGet(
				untitledInput.filePath ? URI.file(untitledInput.filePath) : untitledInput.resource,
				untitledInput.language,
				untitledInput.contents,
				untitledInput.encoding
			);
		}

		// Resource Editor Support
		const resourceInput = <IResourceInput>input;
		if (resourceInput.resource instanceof URI) {
			let label = resourceInput.label;
			if (!label && resourceInput.resource.scheme !== Schemas.data) {
				label = basename(resourceInput.resource.fsPath); // derive the label from the path (but not for data URIs)
			}

B
Benjamin Pasero 已提交
542
			return this.createOrGet(resourceInput.resource, this.instantiationService, label, resourceInput.description, resourceInput.encoding, resourceInput.forceFile) as EditorInput;
543 544 545 546 547
		}

		return null;
	}

B
Benjamin Pasero 已提交
548
	private createOrGet(resource: URI, instantiationService: IInstantiationService, label: string, description: string, encoding?: string, forceFile?: boolean): ICachedEditorInput {
549 550
		if (EditorService.CACHE.has(resource)) {
			const input = EditorService.CACHE.get(resource);
551 552 553 554 555 556 557 558 559 560 561 562 563
			if (input instanceof ResourceEditorInput) {
				input.setName(label);
				input.setDescription(description);
			} else if (!(input instanceof DataUriEditorInput)) {
				input.setPreferredEncoding(encoding);
			}

			return input;
		}

		let input: ICachedEditorInput;

		// File
B
Benjamin Pasero 已提交
564
		if (forceFile /* fix for https://github.com/Microsoft/vscode/issues/48275 */ || this.fileService.canHandleResource(resource)) {
565 566 567 568 569 570 571 572 573 574 575 576 577
			input = this.fileInputFactory.createFileInput(resource, encoding, instantiationService);
		}

		// Data URI
		else if (resource.scheme === Schemas.data) {
			input = instantiationService.createInstance(DataUriEditorInput, label, description, resource);
		}

		// Resource
		else {
			input = instantiationService.createInstance(ResourceEditorInput, label, description, resource);
		}

578
		EditorService.CACHE.set(resource, input);
J
Joao Moreno 已提交
579
		Event.once(input.onDispose)(() => {
580
			EditorService.CACHE.delete(resource);
581 582 583 584 585
		});

		return input;
	}

586
	private toDiffLabel(input: EditorInput): string {
587 588 589 590 591 592 593 594
		const res = input.getResource();

		// Do not try to extract any paths from simple untitled editors
		if (res.scheme === Schemas.untitled && !this.untitledEditorService.hasAssociatedFilePath(res)) {
			return input.getName();
		}

		// Otherwise: for diff labels prefer to see the path as part of the label
595
		return this.labelService.getUriLabel(res, { relative: true });
596
	}
597 598

	//#endregion
599 600 601
}

export interface IEditorOpenHandler {
J
Johannes Rieken 已提交
602
	(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions | ITextEditorOptions): Promise<IEditor>;
603 604 605 606 607 608
}

/**
 * The delegating workbench editor service can be used to override the behaviour of the openEditor()
 * method by providing a IEditorOpenHandler.
 */
B
Benjamin Pasero 已提交
609
export class DelegatingEditorService extends EditorService {
610 611 612
	private editorOpenHandler: IEditorOpenHandler;

	constructor(
B
Benjamin Pasero 已提交
613
		@IEditorGroupsService editorGroupService: EditorGroupsServiceImpl,
614 615
		@IUntitledEditorService untitledEditorService: IUntitledEditorService,
		@IInstantiationService instantiationService: IInstantiationService,
I
isidor 已提交
616
		@ILabelService labelService: ILabelService,
617 618 619 620
		@IFileService fileService: IFileService,
		@IConfigurationService configurationService: IConfigurationService
	) {
		super(
621
			editorGroupService,
622 623
			untitledEditorService,
			instantiationService,
I
isidor 已提交
624
			labelService,
625 626 627 628 629 630 631 632 633
			fileService,
			configurationService
		);
	}

	setEditorOpenHandler(handler: IEditorOpenHandler): void {
		this.editorOpenHandler = handler;
	}

J
Johannes Rieken 已提交
634
	protected doOpenEditor(group: IEditorGroup, editor: IEditorInput, options?: IEditorOptions): Promise<IEditor> {
B
Benjamin Pasero 已提交
635 636 637
		if (!this.editorOpenHandler) {
			return super.doOpenEditor(group, editor, options);
		}
638

B
Benjamin Pasero 已提交
639
		return this.editorOpenHandler(group, editor, options).then(control => {
640
			if (control) {
B
Benjamin Pasero 已提交
641
				return control; // the opening was handled, so return early
642 643 644 645 646
			}

			return super.doOpenEditor(group, editor, options);
		});
	}
I
isidor 已提交
647
}