editor.ts 30.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 { TPromise } from 'vs/base/common/winjs.base';
M
Matt Bierner 已提交
8
import { Event, Emitter, once } from 'vs/base/common/event';
9
import * as objects from 'vs/base/common/objects';
10
import * as types from 'vs/base/common/types';
E
Erich Gamma 已提交
11
import URI from 'vs/base/common/uri';
S
Sandeep Somavarapu 已提交
12
import { IDisposable, dispose, Disposable } from 'vs/base/common/lifecycle';
13
import { IEditor as ICodeEditor, IEditorViewState, ScrollType, IDiffEditor } from 'vs/editor/common/editorCommon';
B
Benjamin Pasero 已提交
14
import { IEditorModel, IEditorOptions, ITextEditorOptions, IBaseResourceInput } from 'vs/platform/editor/common/editor';
J
Johannes Rieken 已提交
15
import { IInstantiationService, IConstructorSignature0 } from 'vs/platform/instantiation/common/instantiation';
16
import { RawContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
17
import { Registry } from 'vs/platform/registry/common/platform';
A
Alex Dima 已提交
18
import { ITextModel } from 'vs/editor/common/model';
19
import { Schemas } from 'vs/base/common/network';
20
import { LRUCache } from 'vs/base/common/map';
21
import { IEditorGroupsService, IEditorGroup } from 'vs/workbench/services/group/common/editorGroupsService';
B
Benjamin Pasero 已提交
22
import { ICompositeControl } from 'vs/workbench/common/composite';
23

24 25 26 27 28
export const EditorsVisibleContext = new RawContextKey<boolean>('editorIsOpen', false);
export const NoEditorsVisibleContext: ContextKeyExpr = EditorsVisibleContext.toNegated();
export const TextCompareEditorVisibleContext = new RawContextKey<boolean>('textCompareEditorVisible', false);
export const ActiveEditorGroupEmptyContext = new RawContextKey<boolean>('activeEditorGroupEmpty', false);
export const MultipleEditorGroupsContext = new RawContextKey<boolean>('multipleEditorGroups', false);
B
Benjamin Pasero 已提交
29
export const SingleEditorGroupsContext = MultipleEditorGroupsContext.toNegated();
30
export const InEditorZenModeContext = new RawContextKey<boolean>('inZenMode', false);
E
Erich Gamma 已提交
31

32 33 34 35 36 37 38 39 40 41
/**
 * Text diff editor id.
 */
export const TEXT_DIFF_EDITOR_ID = 'workbench.editors.textDiffEditor';

/**
 * Binary diff editor id.
 */
export const BINARY_DIFF_EDITOR_ID = 'workbench.editors.binaryResourceDiffEditor';

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
export interface IEditor {

	/**
	 * The assigned input of this editor.
	 */
	input: IEditorInput;

	/**
	 * The assigned options of this editor.
	 */
	options: IEditorOptions;

	/**
	 * The assigned group this editor is showing in.
	 */
57
	group: IEditorGroup;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

	/**
	 * Returns the unique identifier of this editor.
	 */
	getId(): string;

	/**
	 * Returns the underlying control of this editor.
	 */
	getControl(): IEditorControl;

	/**
	 * Asks the underlying control to focus.
	 */
	focus(): void;

	/**
	 * Finds out if this editor is visible or not.
	 */
	isVisible(): boolean;
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
export interface ITextEditor extends IEditor {

	/**
	 * Returns the underlying text editor widget of this editor.
	 */
	getControl(): ICodeEditor;
}

export interface ITextDiffEditor extends IEditor {

	/**
	 * Returns the underlying text editor widget of this editor.
	 */
	getControl(): IDiffEditor;
}

export interface ITextSideBySideEditor extends IEditor {

	/**
	 * Returns the underlying text editor widget of the master side
	 * of this side-by-side editor.
	 */
	getMasterEditor(): ITextEditor;

	/**
	 * Returns the underlying text editor widget of the details side
	 * of this side-by-side editor.
	 */
	getDetailsEditor(): ITextEditor;
}

111
/**
112
 * Marker interface for the base editor control
113
 */
B
Benjamin Pasero 已提交
114
export interface IEditorControl extends ICompositeControl { }
115

116
export interface IFileInputFactory {
117

118
	createFileInput(resource: URI, encoding: string, instantiationService: IInstantiationService): IFileEditorInput;
119 120

	isFileInput(obj: any): obj is IFileEditorInput;
121 122
}

123
export interface IEditorInputFactoryRegistry {
B
Benjamin Pasero 已提交
124 125

	/**
126
	 * Registers the file input factory to use for file inputs.
B
Benjamin Pasero 已提交
127
	 */
128
	registerFileInputFactory(factory: IFileInputFactory): void;
B
Benjamin Pasero 已提交
129 130

	/**
131
	 * Returns the file input factory to use for file inputs.
B
Benjamin Pasero 已提交
132
	 */
133
	getFileInputFactory(): IFileInputFactory;
B
Benjamin Pasero 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

	/**
	 * Registers a editor input factory for the given editor input to the registry. An editor input factory
	 * is capable of serializing and deserializing editor inputs from string data.
	 *
	 * @param editorInputId the identifier of the editor input
	 * @param factory the editor input factory for serialization/deserialization
	 */
	registerEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0<IEditorInputFactory>): void;

	/**
	 * Returns the editor input factory for the given editor input.
	 *
	 * @param editorInputId the identifier of the editor input
	 */
	getEditorInputFactory(editorInputId: string): IEditorInputFactory;

	setInstantiationService(service: IInstantiationService): void;
}

export interface IEditorInputFactory {

	/**
	 * Returns a string representation of the provided editor input that contains enough information
	 * to deserialize back to the original editor input from the deserialize() method.
	 */
	serialize(editorInput: EditorInput): string;

	/**
	 * Returns an editor input from the provided serialized form of the editor input. This form matches
	 * the value returned from the serialize() method.
	 */
	deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): EditorInput;
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
export interface IUntitledResourceInput extends IBaseResourceInput {

	/**
	 * Optional resource. If the resource is not provided a new untitled file is created.
	 */
	resource?: URI;

	/**
	 * Optional file path. Using the file resource will associate the file to the untitled resource.
	 */
	filePath?: string;

	/**
	 * Optional language of the untitled resource.
	 */
	language?: string;

	/**
	 * Optional contents of the untitled resource.
	 */
	contents?: string;

	/**
	 * Optional encoding of the untitled resource.
	 */
	encoding?: string;
}

export interface IResourceDiffInput extends IBaseResourceInput {

	/**
	 * The left hand side URI to open inside a diff editor.
	 */
	leftResource: URI;

	/**
	 * The right hand side URI to open inside a diff editor.
	 */
	rightResource: URI;
}

export interface IResourceSideBySideInput extends IBaseResourceInput {

	/**
	 * The right hand side URI to open inside a side by side editor.
	 */
	masterResource: URI;

	/**
	 * The left hand side URI to open inside a side by side editor.
	 */
	detailResource: URI;
}

export enum Verbosity {
	SHORT,
	MEDIUM,
	LONG
}

export interface IRevertOptions {

	/**
	 *  Forces to load the contents of the editor again even if the editor is not dirty.
	 */
	force?: boolean;

	/**
	 * A soft revert will clear dirty state of an editor but will not attempt to load it.
	 */
	soft?: boolean;
}

export interface IEditorInput extends IDisposable {

	/**
	 * Triggered when this input is disposed.
	 */
	onDispose: Event<void>;

	/**
	 * Returns the associated resource of this input.
	 */
	getResource(): URI;

	/**
	 * Returns the display name of this input.
	 */
	getName(): string;

	/**
	 * Returns the display description of this input.
	 */
	getDescription(verbosity?: Verbosity): string;

	/**
	 * Returns the display title of this input.
	 */
	getTitle(verbosity?: Verbosity): string;

	/**
	 * Resolves the input.
	 */
	resolve(): TPromise<IEditorModel>;

	/**
	 * Returns if this input is dirty or not.
	 */
	isDirty(): boolean;

	/**
	 * Reverts this input.
	 */
	revert(options?: IRevertOptions): TPromise<boolean>;

	/**
	 * Returns if the other object matches this input.
	 */
	matches(other: any): boolean;
}

E
Erich Gamma 已提交
290 291 292 293
/**
 * Editor inputs are lightweight objects that can be passed to the workbench API to open inside the editor part.
 * Each editor input is mapped to an editor that is capable of opening it through the Platform facade.
 */
294
export abstract class EditorInput implements IEditorInput {
M
Matt Bierner 已提交
295
	private readonly _onDispose: Emitter<void>;
296
	protected _onDidChangeDirty: Emitter<void>;
B
Benjamin Pasero 已提交
297
	protected _onDidChangeLabel: Emitter<void>;
298

E
Erich Gamma 已提交
299 300
	private disposed: boolean;

301
	constructor() {
302
		this._onDidChangeDirty = new Emitter<void>();
B
Benjamin Pasero 已提交
303
		this._onDidChangeLabel = new Emitter<void>();
304 305
		this._onDispose = new Emitter<void>();

306 307 308
		this.disposed = false;
	}

309 310 311 312 313 314 315
	/**
	 * Fired when the dirty state of this input changes.
	 */
	public get onDidChangeDirty(): Event<void> {
		return this._onDidChangeDirty.event;
	}

B
Benjamin Pasero 已提交
316 317 318 319 320 321 322
	/**
	 * Fired when the label this input changes.
	 */
	public get onDidChangeLabel(): Event<void> {
		return this._onDidChangeLabel.event;
	}

323 324 325 326 327 328 329
	/**
	 * Fired when the model gets disposed.
	 */
	public get onDispose(): Event<void> {
		return this._onDispose.event;
	}

B
Benjamin Pasero 已提交
330 331 332 333 334 335 336
	/**
	 * Returns the associated resource of this input if any.
	 */
	public getResource(): URI {
		return null;
	}

E
Erich Gamma 已提交
337 338 339 340 341 342 343 344 345 346 347 348
	/**
	 * Returns the name of this input that can be shown to the user. Examples include showing the name of the input
	 * above the editor area when the input is shown.
	 */
	public getName(): string {
		return null;
	}

	/**
	 * Returns the description of this input that can be shown to the user. Examples include showing the description of
	 * the input above the editor area to the side of the name of the input.
	 */
349
	public getDescription(verbosity?: Verbosity): string {
E
Erich Gamma 已提交
350 351 352
		return null;
	}

353 354 355 356
	public getTitle(verbosity?: Verbosity): string {
		return this.getName();
	}

357 358 359 360 361
	/**
	 * Returns the unique type identifier of this input.
	 */
	public abstract getTypeId(): string;

E
Erich Gamma 已提交
362 363 364 365 366 367 368 369 370 371 372 373
	/**
	 * Returns the preferred editor for this input. A list of candidate editors is passed in that whee registered
	 * for the input. This allows subclasses to decide late which editor to use for the input on a case by case basis.
	 */
	public getPreferredEditorId(candidates: string[]): string {
		if (candidates && candidates.length > 0) {
			return candidates[0];
		}

		return null;
	}

374 375 376 377 378
	/**
	 * Returns a descriptor suitable for telemetry events or null if none is available.
	 *
	 * Subclasses should extend if they can contribute.
	 */
B
Benjamin Pasero 已提交
379
	public getTelemetryDescriptor(): object {
K
kieferrm 已提交
380
		/* __GDPR__FRAGMENT__
K
kieferrm 已提交
381 382 383 384
			"EditorTelemetryDescriptor" : {
				"typeId" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
			}
		*/
385 386 387
		return { typeId: this.getTypeId() };
	}

E
Erich Gamma 已提交
388 389 390 391 392 393
	/**
	 * Returns a type of EditorModel that represents the resolved input. Subclasses should
	 * override to provide a meaningful model. The optional second argument allows to specify
	 * if the EditorModel should be refreshed before returning it. Depending on the implementation
	 * this could mean to refresh the editor model contents with the version from disk.
	 */
394
	public abstract resolve(refresh?: boolean): TPromise<IEditorModel>;
E
Erich Gamma 已提交
395

396 397 398 399 400 401 402 403 404 405
	/**
	 * An editor that is dirty will be asked to be saved once it closes.
	 */
	public isDirty(): boolean {
		return false;
	}

	/**
	 * Subclasses should bring up a proper dialog for the user if the editor is dirty and return the result.
	 */
406 407
	public confirmSave(): TPromise<ConfirmResult> {
		return TPromise.wrap(ConfirmResult.DONT_SAVE);
408 409 410 411 412 413 414 415 416 417 418 419
	}

	/**
	 * Saves the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation.
	 */
	public save(): TPromise<boolean> {
		return TPromise.as(true);
	}

	/**
	 * Reverts the editor if it is dirty. Subclasses return a promise with a boolean indicating the success of the operation.
	 */
420
	public revert(options?: IRevertOptions): TPromise<boolean> {
421 422 423 424
		return TPromise.as(true);
	}

	/**
425
	 * Called when this input is no longer opened in any editor. Subclasses can free resources as needed.
426 427
	 */
	public close(): void {
428 429 430
		this.dispose();
	}

431 432 433 434 435 436 437
	/**
	 * Subclasses can set this to false if it does not make sense to split the editor input.
	 */
	public supportsSplitEditor(): boolean {
		return true;
	}

438 439 440 441 442
	/**
	 * Returns true if this input is identical to the otherInput.
	 */
	public matches(otherInput: any): boolean {
		return this === otherInput;
443 444
	}

E
Erich Gamma 已提交
445 446 447 448 449 450
	/**
	 * Called when an editor input is no longer needed. Allows to free up any resources taken by
	 * resolving the editor input.
	 */
	public dispose(): void {
		this.disposed = true;
451
		this._onDispose.fire();
E
Erich Gamma 已提交
452

453
		this._onDidChangeDirty.dispose();
B
Benjamin Pasero 已提交
454
		this._onDidChangeLabel.dispose();
455
		this._onDispose.dispose();
E
Erich Gamma 已提交
456 457 458
	}

	/**
P
Pascal Borreli 已提交
459
	 * Returns whether this input was disposed or not.
E
Erich Gamma 已提交
460 461 462 463 464 465
	 */
	public isDisposed(): boolean {
		return this.disposed;
	}
}

B
Benjamin Pasero 已提交
466 467 468 469 470
export enum ConfirmResult {
	SAVE,
	DONT_SAVE,
	CANCEL
}
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
export enum EncodingMode {

	/**
	 * Instructs the encoding support to encode the current input with the provided encoding
	 */
	Encode,

	/**
	 * Instructs the encoding support to decode the current input with the provided encoding
	 */
	Decode
}

export interface IEncodingSupport {

	/**
	 * Gets the encoding of the input if known.
	 */
	getEncoding(): string;

	/**
	 * Sets the encoding for the input for saving.
	 */
	setEncoding(encoding: string, mode: EncodingMode): void;
}

/**
 * This is a tagging interface to declare an editor input being capable of dealing with files. It is only used in the editor registry
 * to register this kind of input to the platform.
 */
502
export interface IFileEditorInput extends IEditorInput, IEncodingSupport {
503

504 505 506 507
	/**
	 * Sets the preferred encodingt to use for this input.
	 */
	setPreferredEncoding(encoding: string): void;
508 509 510 511 512

	/**
	 * Forces this file input to open as binary instead of text.
	 */
	setForceOpenAsBinary(): void;
513 514
}

E
Erich Gamma 已提交
515
/**
S
Sandeep Somavarapu 已提交
516
 * Side by side editor inputs that have a master and details side.
E
Erich Gamma 已提交
517
 */
S
Sandeep Somavarapu 已提交
518
export class SideBySideEditorInput extends EditorInput {
E
Erich Gamma 已提交
519

M
Matt Bierner 已提交
520
	public static readonly ID: string = 'workbench.editorinputs.sidebysideEditorInput';
521

S
Sandeep Somavarapu 已提交
522
	private _toUnbind: IDisposable[];
E
Erich Gamma 已提交
523

S
Sandeep Somavarapu 已提交
524
	constructor(private name: string, private description: string, private _details: EditorInput, private _master: EditorInput) {
S
Sandeep Somavarapu 已提交
525 526 527
		super();
		this._toUnbind = [];
		this.registerListeners();
E
Erich Gamma 已提交
528 529
	}

S
Sandeep Somavarapu 已提交
530 531
	get master(): EditorInput {
		return this._master;
E
Erich Gamma 已提交
532 533
	}

S
Sandeep Somavarapu 已提交
534 535
	get details(): EditorInput {
		return this._details;
E
Erich Gamma 已提交
536 537
	}

538
	public isDirty(): boolean {
S
Sandeep Somavarapu 已提交
539
		return this.master.isDirty();
540 541
	}

542
	public confirmSave(): TPromise<ConfirmResult> {
S
Sandeep Somavarapu 已提交
543
		return this.master.confirmSave();
544 545 546
	}

	public save(): TPromise<boolean> {
S
Sandeep Somavarapu 已提交
547
		return this.master.save();
548 549 550
	}

	public revert(): TPromise<boolean> {
S
Sandeep Somavarapu 已提交
551
		return this.master.revert();
552
	}
553

B
Benjamin Pasero 已提交
554
	public getTelemetryDescriptor(): object {
S
Sandeep Somavarapu 已提交
555
		const descriptor = this.master.getTelemetryDescriptor();
556 557
		return objects.assign(descriptor, super.getTelemetryDescriptor());
	}
S
Sandeep Somavarapu 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

	private registerListeners(): void {

		// When the details or master input gets disposed, dispose this diff editor input
		const onceDetailsDisposed = once(this.details.onDispose);
		this._toUnbind.push(onceDetailsDisposed(() => {
			if (!this.isDisposed()) {
				this.dispose();
			}
		}));

		const onceMasterDisposed = once(this.master.onDispose);
		this._toUnbind.push(onceMasterDisposed(() => {
			if (!this.isDisposed()) {
				this.dispose();
			}
		}));

		// Reemit some events from the master side to the outside
		this._toUnbind.push(this.master.onDidChangeDirty(() => this._onDidChangeDirty.fire()));
		this._toUnbind.push(this.master.onDidChangeLabel(() => this._onDidChangeLabel.fire()));
	}

	public get toUnbind() {
		return this._toUnbind;
	}

	public resolve(refresh?: boolean): TPromise<EditorModel> {
		return TPromise.as(null);
	}

	getTypeId(): string {
590
		return SideBySideEditorInput.ID;
S
Sandeep Somavarapu 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	}

	public getName(): string {
		return this.name;
	}

	public getDescription(): string {
		return this.description;
	}

	public supportsSplitEditor(): boolean {
		return false;
	}

	public matches(otherInput: any): boolean {
		if (super.matches(otherInput) === true) {
			return true;
		}

		if (otherInput) {
			if (!(otherInput instanceof SideBySideEditorInput)) {
				return false;
			}

			const otherDiffInput = <SideBySideEditorInput>otherInput;
			return this.details.matches(otherDiffInput.details) && this.master.matches(otherDiffInput.master);
		}

		return false;
	}

	public dispose(): void {
		this._toUnbind = dispose(this._toUnbind);
		super.dispose();
	}
E
Erich Gamma 已提交
626 627
}

628
export interface ITextEditorModel extends IEditorModel {
A
Alex Dima 已提交
629
	textEditorModel: ITextModel;
630 631
}

E
Erich Gamma 已提交
632 633 634 635 636
/**
 * The editor model is the heavyweight counterpart of editor input. Depending on the editor input, it
 * connects to the disk to retrieve content and may allow for saving it back or reverting it. Editor models
 * are typically cached for some while because they are expensive to construct.
 */
S
Sandeep Somavarapu 已提交
637
export class EditorModel extends Disposable implements IEditorModel {
M
Matt Bierner 已提交
638
	private readonly _onDispose: Emitter<void>;
639 640

	constructor() {
S
Sandeep Somavarapu 已提交
641
		super();
642 643 644 645 646 647 648 649 650
		this._onDispose = new Emitter<void>();
	}

	/**
	 * Fired when the model gets disposed.
	 */
	public get onDispose(): Event<void> {
		return this._onDispose.event;
	}
E
Erich Gamma 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

	/**
	 * Causes this model to load returning a promise when loading is completed.
	 */
	public load(): TPromise<EditorModel> {
		return TPromise.as(this);
	}

	/**
	 * Returns whether this model was loaded or not.
	 */
	public isResolved(): boolean {
		return true;
	}

	/**
	 * Subclasses should implement to free resources that have been claimed through loading.
	 */
	public dispose(): void {
670 671
		this._onDispose.fire();
		this._onDispose.dispose();
S
Sandeep Somavarapu 已提交
672
		super.dispose();
E
Erich Gamma 已提交
673 674 675
	}
}

B
Benjamin Pasero 已提交
676 677
export interface IEditorInputWithOptions {
	editor: IEditorInput;
B
Benjamin Pasero 已提交
678
	options?: IEditorOptions | ITextEditorOptions;
B
Benjamin Pasero 已提交
679 680 681 682 683 684 685 686
}

export function isEditorInputWithOptions(obj: any): obj is IEditorInputWithOptions {
	const editorInputWithOptions = obj as IEditorInputWithOptions;

	return !!editorInputWithOptions && !!editorInputWithOptions.editor;
}

E
Erich Gamma 已提交
687 688 689 690 691 692 693 694
/**
 * The editor options is the base class of options that can be passed in when opening an editor.
 */
export class EditorOptions implements IEditorOptions {

	/**
	 * Helper to create EditorOptions inline.
	 */
695
	public static create(settings: IEditorOptions): EditorOptions {
696
		const options = new EditorOptions();
697

E
Erich Gamma 已提交
698 699
		options.preserveFocus = settings.preserveFocus;
		options.forceOpen = settings.forceOpen;
700
		options.revealIfVisible = settings.revealIfVisible;
701
		options.revealIfOpened = settings.revealIfOpened;
B
Benjamin Pasero 已提交
702 703
		options.pinned = settings.pinned;
		options.index = settings.index;
704
		options.inactive = settings.inactive;
E
Erich Gamma 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

		return options;
	}

	/**
	 * Tells the editor to not receive keyboard focus when the editor is being opened. By default,
	 * the editor will receive keyboard focus on open.
	 */
	public preserveFocus: boolean;

	/**
	 * Tells the editor to replace the editor input in the editor even if it is identical to the one
	 * already showing. By default, the editor will not replace the input if it is identical to the
	 * one showing.
	 */
	public forceOpen: boolean;

722
	/**
723
	 * Will reveal the editor if it is already opened and visible in any of the opened editor groups.
724
	 */
725
	public revealIfVisible: boolean;
726

727 728 729 730 731
	/**
	 * Will reveal the editor if it is already opened (even when not visible) in any of the opened editor groups.
	 */
	public revealIfOpened: boolean;

B
Benjamin Pasero 已提交
732
	/**
B
Benjamin Pasero 已提交
733 734
	 * An editor that is pinned remains in the editor stack even when another editor is being opened.
	 * An editor that is not pinned will always get replaced by another editor that is not pinned.
B
Benjamin Pasero 已提交
735 736
	 */
	public pinned: boolean;
B
Benjamin Pasero 已提交
737 738 739 740

	/**
	 * The index in the document stack where to insert the editor into when opening.
	 */
B
Benjamin Pasero 已提交
741
	public index: number;
742 743 744 745 746 747

	/**
	 * An active editor that is opened will show its contents directly. Set to true to open an editor
	 * in the background.
	 */
	public inactive: boolean;
E
Erich Gamma 已提交
748 749 750 751 752 753
}

/**
 * Base Text Editor Options.
 */
export class TextEditorOptions extends EditorOptions {
754 755 756 757
	private startLineNumber: number;
	private startColumn: number;
	private endLineNumber: number;
	private endColumn: number;
758

I
isidor 已提交
759
	private revealInCenterIfOutsideViewport: boolean;
E
Erich Gamma 已提交
760 761
	private editorViewState: IEditorViewState;

762
	public static from(input?: IBaseResourceInput): TextEditorOptions {
763 764 765 766
		if (!input || !input.options) {
			return null;
		}

767 768
		return TextEditorOptions.create(input.options);
	}
E
Erich Gamma 已提交
769

770 771 772 773 774
	/**
	 * Helper to convert options bag to real class
	 */
	public static create(options: ITextEditorOptions = Object.create(null)): TextEditorOptions {
		const textEditorOptions = new TextEditorOptions();
E
Erich Gamma 已提交
775

776 777 778
		if (options.selection) {
			const selection = options.selection;
			textEditorOptions.selection(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn);
779
		}
E
Erich Gamma 已提交
780

781 782
		if (options.viewState) {
			textEditorOptions.editorViewState = options.viewState as IEditorViewState;
783
		}
784

785 786
		if (options.forceOpen) {
			textEditorOptions.forceOpen = true;
787
		}
788

789 790
		if (options.revealIfVisible) {
			textEditorOptions.revealIfVisible = true;
791
		}
792

793 794
		if (options.revealIfOpened) {
			textEditorOptions.revealIfOpened = true;
795
		}
796

797 798
		if (options.preserveFocus) {
			textEditorOptions.preserveFocus = true;
799
		}
800

801 802
		if (options.revealInCenterIfOutsideViewport) {
			textEditorOptions.revealInCenterIfOutsideViewport = true;
803
		}
I
isidor 已提交
804

805 806
		if (options.pinned) {
			textEditorOptions.pinned = true;
807
		}
B
Benjamin Pasero 已提交
808

809 810
		if (options.inactive) {
			textEditorOptions.inactive = true;
E
Erich Gamma 已提交
811 812
		}

813 814
		if (typeof options.index === 'number') {
			textEditorOptions.index = options.index;
E
Erich Gamma 已提交
815 816
		}

817
		return textEditorOptions;
E
Erich Gamma 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
	}

	/**
	 * Returns if this options object has objects defined for the editor.
	 */
	public hasOptionsDefined(): boolean {
		return !!this.editorViewState || (!types.isUndefinedOrNull(this.startLineNumber) && !types.isUndefinedOrNull(this.startColumn));
	}

	/**
	 * Tells the editor to set show the given selection when the editor is being opened.
	 */
	public selection(startLineNumber: number, startColumn: number, endLineNumber: number = startLineNumber, endColumn: number = startColumn): EditorOptions {
		this.startLineNumber = startLineNumber;
		this.startColumn = startColumn;
		this.endLineNumber = endLineNumber;
		this.endColumn = endColumn;

		return this;
	}

	/**
840
	 * Create a TextEditorOptions inline to be used when the editor is opening.
E
Erich Gamma 已提交
841
	 */
842
	public static fromEditor(editor: ICodeEditor, settings?: IEditorOptions): TextEditorOptions {
843
		const options = TextEditorOptions.create(settings);
844 845

		// View state
846
		options.editorViewState = editor.saveViewState();
847

848
		return options;
E
Erich Gamma 已提交
849 850 851 852 853 854 855
	}

	/**
	 * Apply the view state or selection to the given editor.
	 *
	 * @return if something was applied
	 */
856
	public apply(editor: ICodeEditor, scrollType: ScrollType): boolean {
857 858

		// View state
859
		return this.applyViewState(editor, scrollType);
860 861
	}

862
	private applyViewState(editor: ICodeEditor, scrollType: ScrollType): boolean {
E
Erich Gamma 已提交
863 864 865 866
		let gotApplied = false;

		// First try viewstate
		if (this.editorViewState) {
867
			editor.restoreViewState(this.editorViewState);
E
Erich Gamma 已提交
868 869 870 871 872 873 874 875
			gotApplied = true;
		}

		// Otherwise check for selection
		else if (!types.isUndefinedOrNull(this.startLineNumber) && !types.isUndefinedOrNull(this.startColumn)) {

			// Select
			if (!types.isUndefinedOrNull(this.endLineNumber) && !types.isUndefinedOrNull(this.endColumn)) {
876
				const range = {
E
Erich Gamma 已提交
877 878 879 880 881
					startLineNumber: this.startLineNumber,
					startColumn: this.startColumn,
					endLineNumber: this.endLineNumber,
					endColumn: this.endColumn
				};
882
				editor.setSelection(range);
I
isidor 已提交
883
				if (this.revealInCenterIfOutsideViewport) {
884
					editor.revealRangeInCenterIfOutsideViewport(range, scrollType);
I
isidor 已提交
885
				} else {
886
					editor.revealRangeInCenter(range, scrollType);
I
isidor 已提交
887
				}
E
Erich Gamma 已提交
888 889 890 891
			}

			// Reveal
			else {
892
				const pos = {
E
Erich Gamma 已提交
893 894 895
					lineNumber: this.startLineNumber,
					column: this.startColumn
				};
896
				editor.setPosition(pos);
I
isidor 已提交
897
				if (this.revealInCenterIfOutsideViewport) {
898
					editor.revealPositionInCenterIfOutsideViewport(pos, scrollType);
I
isidor 已提交
899
				} else {
900
					editor.revealPositionInCenter(pos, scrollType);
I
isidor 已提交
901
				}
E
Erich Gamma 已提交
902 903 904 905 906 907 908 909 910
			}

			gotApplied = true;
		}

		return gotApplied;
	}
}

911
export interface IEditorIdentifier {
I
isidor 已提交
912
	groupId: GroupIdentifier;
I
isidor 已提交
913
	editor: IEditorInput;
914 915
}

B
Benjamin Pasero 已提交
916 917 918 919 920 921 922 923 924 925
/**
 * The editor commands context is used for editor commands (e.g. in the editor title)
 * and we must ensure that the context is serializable because it potentially travels
 * to the extension host!
 */
export interface IEditorCommandsContext {
	groupId: GroupIdentifier;
	editorIndex?: number;
}

B
Benjamin Pasero 已提交
926
export interface IEditorCloseEvent extends IEditorIdentifier {
927
	replaced: boolean;
928
	index: number;
929 930
}

931 932 933 934
export type GroupIdentifier = number;

export interface IWorkbenchEditorConfiguration {
	workbench: {
935
		editor: IWorkbenchEditorPartConfiguration,
B
Benjamin Pasero 已提交
936
		iconTheme: string;
937
	};
S
Sandeep Somavarapu 已提交
938 939
}

940 941 942 943 944 945 946 947 948
export interface IWorkbenchEditorPartConfiguration {
	showTabs?: boolean;
	tabCloseButton?: 'left' | 'right' | 'off';
	tabSizing?: 'fit' | 'shrink';
	showIcons?: boolean;
	enablePreview?: boolean;
	enablePreviewFromQuickOpen?: boolean;
	closeOnFileDelete?: boolean;
	openPositioning?: 'left' | 'right' | 'first' | 'last';
949 950
	openSideBySideDirection?: 'left' | 'right' | 'up' | 'down';
	closeEmptyGroups?: boolean;
951 952 953 954 955
	revealIfOpen?: boolean;
	swipeToNavigate?: boolean;
	labelFormat?: 'default' | 'short' | 'medium' | 'long';
}

956 957
export interface IResourceOptions {
	supportSideBySide?: boolean;
958
	filter?: string | string[];
959 960 961 962 963 964 965 966 967 968 969 970
}

export function toResource(editor: IEditorInput, options?: IResourceOptions): URI {
	if (!editor) {
		return null;
	}

	// Check for side by side if we are asked to
	if (options && options.supportSideBySide && editor instanceof SideBySideEditorInput) {
		editor = editor.master;
	}

B
Benjamin Pasero 已提交
971
	const resource = editor.getResource();
972 973 974 975 976 977 978 979 980 981 982
	if (!options || !options.filter) {
		return resource; // return early if no filter is specified
	}

	if (!resource) {
		return null;
	}

	let includeFiles: boolean;
	let includeUntitled: boolean;
	if (Array.isArray(options.filter)) {
983 984
		includeFiles = (options.filter.indexOf(Schemas.file) >= 0);
		includeUntitled = (options.filter.indexOf(Schemas.untitled) >= 0);
985
	} else {
986 987
		includeFiles = (options.filter === Schemas.file);
		includeUntitled = (options.filter === Schemas.untitled);
988 989
	}

990
	if (includeFiles && resource.scheme === Schemas.file) {
991 992 993
		return resource;
	}

994
	if (includeUntitled && resource.scheme === Schemas.untitled) {
995 996 997 998 999 1000
		return resource;
	}

	return null;
}

B
Benjamin Pasero 已提交
1001 1002 1003 1004 1005
export enum CloseDirection {
	LEFT,
	RIGHT
}

1006 1007
interface MapGroupToViewStates<T> {
	[group: number]: T;
1008 1009 1010
}

export class EditorViewStateMemento<T> {
1011 1012 1013
	private cache: LRUCache<string, MapGroupToViewStates<T>>;

	constructor(
1014
		private editorGroupService: IEditorGroupsService,
1015 1016 1017 1018 1019
		private memento: object,
		private key: string,
		private limit: number = 10
	) { }

1020 1021 1022
	public saveState(group: IEditorGroup, resource: URI, state: T): void;
	public saveState(group: IEditorGroup, editor: EditorInput, state: T): void;
	public saveState(group: IEditorGroup, resourceOrEditor: URI | EditorInput, state: T): void {
1023
		const resource = this.doGetResource(resourceOrEditor);
1024 1025 1026
		if (!resource || !group) {
			return; // we are not in a good state to save any viewstate for a resource
		}
1027

1028
		const cache = this.doLoad();
1029

1030 1031 1032 1033 1034
		let viewStates = cache.get(resource.toString());
		if (!viewStates) {
			viewStates = Object.create(null) as MapGroupToViewStates<T>;
			cache.set(resource.toString(), viewStates);
		}
1035

1036 1037 1038 1039 1040 1041 1042
		viewStates[group.id] = state;

		// Automatically clear when editor input gets disposed if any
		if (resourceOrEditor instanceof EditorInput) {
			once(resourceOrEditor.onDispose)(() => {
				this.clearState(resource);
			});
1043 1044 1045
		}
	}

1046 1047 1048
	public loadState(group: IEditorGroup, resource: URI): T;
	public loadState(group: IEditorGroup, editor: EditorInput): T;
	public loadState(group: IEditorGroup, resourceOrEditor: URI | EditorInput): T {
1049 1050 1051 1052 1053 1054
		const resource = this.doGetResource(resourceOrEditor);
		if (resource) {
			const cache = this.doLoad();

			const viewStates = cache.get(resource.toString());
			if (viewStates) {
1055
				return viewStates[group.id];
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
			}
		}

		return void 0;
	}

	public clearState(resource: URI): void;
	public clearState(editor: EditorInput): void;
	public clearState(resourceOrEditor: URI | EditorInput): void {
		const resource = this.doGetResource(resourceOrEditor);
		if (resource) {
			const cache = this.doLoad();
			cache.delete(resource.toString());
		}
	}

	private doGetResource(resourceOrEditor: URI | EditorInput): URI {
		if (resourceOrEditor instanceof EditorInput) {
			return resourceOrEditor.getResource();
		}

		return resourceOrEditor;
	}

1080
	private doLoad(): LRUCache<string, MapGroupToViewStates<T>> {
1081
		if (!this.cache) {
1082
			this.cache = new LRUCache<string, MapGroupToViewStates<T>>(this.limit);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

			// Restore from serialized map state
			const rawViewState = this.memento[this.key];
			if (Array.isArray(rawViewState)) {
				this.cache.fromJSON(rawViewState);
			}
		}

		return this.cache;
	}

	public save(): void {
		const cache = this.doLoad();

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
		// Remove groups from states that no longer exist
		cache.forEach((mapGroupToViewStates, resource) => {
			Object.keys(mapGroupToViewStates).forEach(group => {
				const groupId: GroupIdentifier = Number(group);
				if (!this.editorGroupService.getGroup(groupId)) {
					delete mapGroupToViewStates[groupId];

					if (types.isEmptyObject(mapGroupToViewStates)) {
						cache.delete(resource);
					}
				}
			});
		});

1111 1112 1113 1114
		this.memento[this.key] = cache.toJSON();
	}
}

1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
class EditorInputFactoryRegistry implements IEditorInputFactoryRegistry {
	private instantiationService: IInstantiationService;
	private fileInputFactory: IFileInputFactory;
	private editorInputFactoryConstructors: { [editorInputId: string]: IConstructorSignature0<IEditorInputFactory> } = Object.create(null);
	private editorInputFactoryInstances: { [editorInputId: string]: IEditorInputFactory } = Object.create(null);

	constructor() {
	}

	public setInstantiationService(service: IInstantiationService): void {
		this.instantiationService = service;

		for (let key in this.editorInputFactoryConstructors) {
			const element = this.editorInputFactoryConstructors[key];
			this.createEditorInputFactory(key, element);
		}

		this.editorInputFactoryConstructors = {};
	}

	private createEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0<IEditorInputFactory>): void {
		const instance = this.instantiationService.createInstance(ctor);
		this.editorInputFactoryInstances[editorInputId] = instance;
	}

	public registerFileInputFactory(factory: IFileInputFactory): void {
		this.fileInputFactory = factory;
	}

	public getFileInputFactory(): IFileInputFactory {
		return this.fileInputFactory;
	}

	public registerEditorInputFactory(editorInputId: string, ctor: IConstructorSignature0<IEditorInputFactory>): void {
		if (!this.instantiationService) {
			this.editorInputFactoryConstructors[editorInputId] = ctor;
		} else {
			this.createEditorInputFactory(editorInputId, ctor);
		}
	}

	public getEditorInputFactory(editorInputId: string): IEditorInputFactory {
		return this.editorInputFactoryInstances[editorInputId];
	}
}

export const Extensions = {
	EditorInputFactories: 'workbench.contributions.editor.inputFactories'
};

I
isidor 已提交
1165
Registry.add(Extensions.EditorInputFactories, new EditorInputFactoryRegistry());