fileEditorInput.ts 11.9 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';

7
import {TPromise} from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
8 9 10 11 12 13 14 15
import {Registry} from 'vs/platform/platform';
import types = require('vs/base/common/types');
import paths = require('vs/base/common/paths');
import {guessMimeTypes} from 'vs/base/common/mime';
import labels = require('vs/base/common/labels');
import URI from 'vs/base/common/uri';
import strings = require('vs/base/common/strings');
import assert = require('vs/base/common/assert');
B
Benjamin Pasero 已提交
16
import {IEditorRegistry, Extensions, EditorModel, EncodingMode, ConfirmResult, IEditorDescriptor} from 'vs/workbench/common/editor';
17
import {BinaryEditorModel} from 'vs/workbench/common/editor/binaryEditorModel';
18
import {IFileOperationResult, FileOperationResult} from 'vs/platform/files/common/files';
19
import {ITextFileService, BINARY_FILE_EDITOR_ID, FILE_EDITOR_INPUT_ID, FileEditorInput as CommonFileEditorInput, AutoSaveMode, ModelState, EventType as FileEventType, TextFileChangeEvent, IFileEditorDescriptor} from 'vs/workbench/parts/files/common/files';
B
Benjamin Pasero 已提交
20
import {CACHE, TextFileEditorModel} from 'vs/workbench/parts/files/common/editors/textFileEditorModel';
21
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
22
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
23 24
import {IDisposable, dispose} from 'vs/base/common/lifecycle';
import {IEventService} from 'vs/platform/event/common/event';
E
Erich Gamma 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

/**
 * A file editor input is the input type for the file editor of file system resources.
 */
export class FileEditorInput extends CommonFileEditorInput {

	// Do ref counting for all inputs that resolved to a model to be able to dispose when count = 0
	private static FILE_EDITOR_MODEL_CLIENTS: { [resource: string]: FileEditorInput[]; } = Object.create(null);

	// Keep promises that load a file editor model to avoid loading the same model twice
	private static FILE_EDITOR_MODEL_LOADERS: { [resource: string]: TPromise<EditorModel>; } = Object.create(null);

	private resource: URI;
	private mime: string;
	private preferredEncoding: string;

	private name: string;
	private description: string;
	private verboseDescription: string;

45 46
	private toUnbind: IDisposable[];

E
Erich Gamma 已提交
47
	/**
48
	 * An editor input who's contents are retrieved from file services.
E
Erich Gamma 已提交
49 50 51 52 53
	 */
	constructor(
		resource: URI,
		mime: string,
		preferredEncoding: string,
54
		@IEventService private eventService: IEventService,
E
Erich Gamma 已提交
55
		@IInstantiationService private instantiationService: IInstantiationService,
56 57
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@ITextFileService private textFileService: ITextFileService
E
Erich Gamma 已提交
58 59 60
	) {
		super();

61 62
		this.toUnbind = [];

E
Erich Gamma 已提交
63 64 65 66 67
		if (resource) {
			this.setResource(resource);
			this.setMime(mime || guessMimeTypes(this.resource.fsPath).join(', '));
			this.preferredEncoding = preferredEncoding;
		}
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

		this.registerListeners();
	}

	private registerListeners(): void {
		this.toUnbind.push(this.eventService.addListener2(FileEventType.FILE_DIRTY, (e: TextFileChangeEvent) => this.onDirtyStateChange(e)));
		this.toUnbind.push(this.eventService.addListener2(FileEventType.FILE_SAVE_ERROR, (e: TextFileChangeEvent) => this.onDirtyStateChange(e)));
		this.toUnbind.push(this.eventService.addListener2(FileEventType.FILE_SAVED, (e: TextFileChangeEvent) => this.onDirtyStateChange(e)));
		this.toUnbind.push(this.eventService.addListener2(FileEventType.FILE_REVERTED, (e: TextFileChangeEvent) => this.onDirtyStateChange(e)));
	}

	private onDirtyStateChange(e: TextFileChangeEvent): void {
		if (e.resource.toString() === this.resource.toString()) {
			this._onDidChangeDirty.fire();
		}
E
Erich Gamma 已提交
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 111
	}

	public setResource(resource: URI): void {
		if (resource.scheme !== 'file') {
			throw new Error('FileEditorInput can only handle file:// resources.');
		}

		this.resource = resource;

		// Reset resource dependent properties
		this.name = null;
		this.description = null;
		this.verboseDescription = null;
	}

	public getResource(): URI {
		return this.resource;
	}

	public getMime(): string {
		return this.mime;
	}

	public setMime(mime: string): void {
		assert.ok(mime, 'Editor input needs mime type');

		this.mime = mime;
	}

112 113 114 115
	public setPreferredEncoding(encoding: string): void {
		this.preferredEncoding = encoding;
	}

E
Erich Gamma 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	public getEncoding(): string {
		let textModel = CACHE.get(this.resource);
		if (textModel) {
			return textModel.getEncoding();
		}

		return this.preferredEncoding;
	}

	public setEncoding(encoding: string, mode: EncodingMode): void {
		this.preferredEncoding = encoding;

		let textModel = CACHE.get(this.resource);
		if (textModel) {
			textModel.setEncoding(encoding, mode);
		}
	}

134
	public getTypeId(): string {
E
Erich Gamma 已提交
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
		return FILE_EDITOR_INPUT_ID;
	}

	public getName(): string {
		if (!this.name) {
			this.name = paths.basename(this.resource.fsPath);
		}

		return this.name;
	}

	public getDescription(verbose?: boolean): string {
		if (!verbose) {
			if (!this.description) {
				this.description = labels.getPathLabel(paths.dirname(this.resource.fsPath), this.contextService);
			}

			return this.description;
		}

		if (!this.verboseDescription) {
			this.verboseDescription = labels.getPathLabel(this.resource.fsPath);
		}

		return this.verboseDescription;
	}

162
	public isDirty(): boolean {
B
Benjamin Pasero 已提交
163 164 165 166 167 168 169 170 171 172
		const model = CACHE.get(this.resource);
		if (!model) {
			return false;
		}

		const state = model.getState();
		if (state === ModelState.CONFLICT || state === ModelState.ERROR) {
			return true; // always indicate dirty state if we are in conflict or error state
		}

B
Benjamin Pasero 已提交
173
		if (this.textFileService.getAutoSaveMode() === AutoSaveMode.AFTER_SHORT_DELAY) {
B
Benjamin Pasero 已提交
174
			return false; // fast auto save enabled so we do not declare dirty
B
Benjamin Pasero 已提交
175 176
		}

B
Benjamin Pasero 已提交
177
		return model.isDirty();
178 179 180 181 182 183 184 185 186 187 188 189 190 191
	}

	public confirmSave(): ConfirmResult {
		return this.textFileService.confirmSave([this.resource]);
	}

	public save(): TPromise<boolean> {
		return this.textFileService.save(this.resource);
	}

	public revert(): TPromise<boolean> {
		return this.textFileService.revert(this.resource);
	}

E
Erich Gamma 已提交
192 193 194 195
	public getPreferredEditorId(candidates: string[]): string {
		let editorRegistry = (<IEditorRegistry>Registry.as(Extensions.Editors));

		// Lookup Editor by Mime
B
Benjamin Pasero 已提交
196
		let descriptor: IEditorDescriptor;
E
Erich Gamma 已提交
197 198 199 200 201 202 203
		let mimes = this.mime.split(',');
		for (let m = 0; m < mimes.length; m++) {
			let mime = strings.trim(mimes[m]);

			for (let i = 0; i < candidates.length; i++) {
				descriptor = editorRegistry.getEditorById(candidates[i]);

204 205
				if (types.isFunction((<IFileEditorDescriptor>descriptor).getMimeTypes)) {
					let mimetypes = (<IFileEditorDescriptor>descriptor).getMimeTypes();
E
Erich Gamma 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
					for (let j = 0; j < mimetypes.length; j++) {
						let mimetype = mimetypes[j];

						// Check for direct mime match
						if (mime === mimetype) {
							return descriptor.getId();
						}

						// Otherwise check for wildcard mime matches
						if (strings.endsWith(mimetype, '/*') && strings.startsWith(mime, mimetype.substring(0, mimetype.length - 1))) {
							return descriptor.getId();
						}
					}
				}
			}
		}

		// Otherwise use default editor
		return BINARY_FILE_EDITOR_ID;
	}

	public resolve(refresh?: boolean): TPromise<EditorModel> {
		let modelPromise: TPromise<EditorModel>;
B
Benjamin Pasero 已提交
229
		let resource = this.resource.toString();
E
Erich Gamma 已提交
230 231

		// Keep clients who resolved the input to support proper disposal
B
Benjamin Pasero 已提交
232
		let clients = FileEditorInput.FILE_EDITOR_MODEL_CLIENTS[resource];
E
Erich Gamma 已提交
233
		if (types.isUndefinedOrNull(clients)) {
B
Benjamin Pasero 已提交
234
			FileEditorInput.FILE_EDITOR_MODEL_CLIENTS[resource] = [this];
E
Erich Gamma 已提交
235
		} else if (this.indexOfClient() === -1) {
B
Benjamin Pasero 已提交
236
			FileEditorInput.FILE_EDITOR_MODEL_CLIENTS[resource].push(this);
E
Erich Gamma 已提交
237 238 239
		}

		// Check for running loader to ensure the model is only ever loaded once
B
Benjamin Pasero 已提交
240 241
		if (FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource]) {
			return FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource];
E
Erich Gamma 已提交
242 243 244 245 246 247 248 249 250 251 252
		}

		// Use Cached Model if present
		let cachedModel = CACHE.get(this.resource);
		if (cachedModel && !refresh) {
			modelPromise = TPromise.as<EditorModel>(cachedModel);
		}

		// Refresh Cached Model if present
		else if (cachedModel && refresh) {
			modelPromise = cachedModel.load();
B
Benjamin Pasero 已提交
253
			FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource] = modelPromise;
E
Erich Gamma 已提交
254 255 256 257
		}

		// Otherwise Create Model and Load
		else {
258
			modelPromise = this.createAndLoadModel();
B
Benjamin Pasero 已提交
259
			FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource] = modelPromise;
E
Erich Gamma 已提交
260 261
		}

262
		return modelPromise.then((resolvedModel: TextFileEditorModel | BinaryEditorModel) => {
E
Erich Gamma 已提交
263 264 265
			if (resolvedModel instanceof TextFileEditorModel) {
				CACHE.add(this.resource, resolvedModel); // Store into the text model cache unless this file is binary
			}
B
Benjamin Pasero 已提交
266
			FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource] = null; // Remove from pending loaders
E
Erich Gamma 已提交
267 268 269

			return resolvedModel;
		}, (error) => {
B
Benjamin Pasero 已提交
270
			FileEditorInput.FILE_EDITOR_MODEL_LOADERS[resource] = null; // Remove from pending loaders in case of an error
E
Erich Gamma 已提交
271

272
			return TPromise.wrapError(error);
E
Erich Gamma 已提交
273 274 275 276
		});
	}

	private indexOfClient(): number {
277 278 279 280
		const inputs = FileEditorInput.FILE_EDITOR_MODEL_CLIENTS[this.resource.toString()];
		if (inputs) {
			for (let i = 0; i < inputs.length; i++) {
				let client = inputs[i];
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289
				if (client === this) {
					return i;
				}
			}
		}

		return -1;
	}

290
	private createAndLoadModel(): TPromise<EditorModel> {
E
Erich Gamma 已提交
291 292 293 294 295
		let descriptor = (<IEditorRegistry>Registry.as(Extensions.Editors)).getEditor(this);
		if (!descriptor) {
			throw new Error('Unable to find an editor in the registry for this input.');
		}

296 297 298
		// Optimistically create a text model assuming that the file is not binary
		let textModel = this.instantiationService.createInstance(TextFileEditorModel, this.resource, this.preferredEncoding);
		return textModel.load().then(() => textModel, (error) => {
E
Erich Gamma 已提交
299

300 301
			// In case of an error that indicates that the file is binary or too large, just return with the binary editor model
			if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_IS_BINARY || (<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_TOO_LARGE) {
302
				textModel.dispose();
E
Erich Gamma 已提交
303

304
				return this.instantiationService.createInstance(BinaryEditorModel, this.resource, this.getName()).load();
305 306 307
			}

			// Bubble any other error up
308
			return TPromise.wrapError(error);
309
		});
E
Erich Gamma 已提交
310 311
	}

312
	public dispose(): void {
E
Erich Gamma 已提交
313

314 315 316
		// Listeners
		dispose(this.toUnbind);

317 318 319 320
		// Clear from our input cache
		const index = this.indexOfClient();
		if (index >= 0) {
			FileEditorInput.FILE_EDITOR_MODEL_CLIENTS[this.resource.toString()].splice(index, 1);
E
Erich Gamma 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
		}

		super.dispose();
	}

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

		if (otherInput) {

			// Note that we can not test for the mime type here because we cache resolved file editor input models by resource. And
			// these models have a fixed mode association that can not be changed afterwards. As such, we always treat this input
			// equal if the resource is equal so that there is always just one text editor model (with undo hisotry etc.) around.
			//
			// !!! DO NOT CHANGE THIS ASSUMPTION !!!
			//
			return otherInput instanceof FileEditorInput && (<FileEditorInput>otherInput).resource.toString() === this.resource.toString();
		}

		return false;
	}

	/**
	 * Exposed so that other internal file API can access the list of all file editor inputs
	 * that have been loaded during the session.
	 */
	public static getAll(desiredFileOrFolderResource: URI): FileEditorInput[] {
		let inputsContainingResource: FileEditorInput[] = [];

		let clients = FileEditorInput.FILE_EDITOR_MODEL_CLIENTS;
		for (let resource in clients) {
			let inputs = clients[resource];

			// Check if path is identical or path is a folder that the content is inside
			if (paths.isEqualOrParent(resource, desiredFileOrFolderResource.toString())) {
				inputsContainingResource.push(...inputs);
			}
		}

		return inputsContainingResource;
	}
}