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

import {TPromise, Promise} from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
9 10
import errors = require('vs/base/common/errors');
import {ListenerUnbind} from 'vs/base/common/eventEmitter';
E
Erich Gamma 已提交
11 12
import {FileEditorInput} from 'vs/workbench/parts/files/browser/editors/fileEditorInput';
import {CACHE, TextFileEditorModel} from 'vs/workbench/parts/files/browser/editors/textFileEditorModel';
13
import {IResult, ITextFileOperationResult, ConfirmResult, ITextFileService, IAutoSaveConfiguration} from 'vs/workbench/parts/files/common/files';
14
import {EventType} from 'vs/workbench/common/events';
E
Erich Gamma 已提交
15 16
import {WorkingFilesModel} from 'vs/workbench/parts/files/browser/workingFilesModel';
import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
17
import {IFilesConfiguration, IFileOperationResult, FileOperationResult} from 'vs/platform/files/common/files';
E
Erich Gamma 已提交
18 19
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
20
import {IConfigurationService, IConfigurationServiceEvent, ConfigurationServiceEventTypes} from 'vs/platform/configuration/common/configuration';
E
Erich Gamma 已提交
21 22 23 24 25 26 27 28 29

/**
 * The workbench file service implementation implements the raw file service spec and adds additional methods on top.
 *
 * It also adds diagnostics and logging around file system operations.
 */
export abstract class TextFileService implements ITextFileService {
	public serviceId = ITextFileService;

30 31 32 33
	private listenerToUnbind: ListenerUnbind[];
	private _workingFilesModel: WorkingFilesModel;

	private configuredAutoSaveDelay: number;
E
Erich Gamma 已提交
34 35 36

	constructor(
		@IWorkspaceContextService protected contextService: IWorkspaceContextService,
37 38
		@IInstantiationService private instantiationService: IInstantiationService,
		@IConfigurationService private configurationService: IConfigurationService,
E
Erich Gamma 已提交
39 40
		@ILifecycleService private lifecycleService: ILifecycleService
	) {
41
		this.listenerToUnbind = [];
E
Erich Gamma 已提交
42 43

		this.registerListeners();
44
		this.loadConfiguration();
E
Erich Gamma 已提交
45 46
	}

47 48 49
	private get workingFilesModel(): WorkingFilesModel {
		if (!this._workingFilesModel) {
			this._workingFilesModel = this.instantiationService.createInstance(WorkingFilesModel);
E
Erich Gamma 已提交
50
		}
51 52 53 54 55 56 57

		return this._workingFilesModel;
	}

	private registerListeners(): void {
		this.lifecycleService.addBeforeShutdownParticipant(this);
		this.lifecycleService.onShutdown(this.dispose, this);
58

59
		this.listenerToUnbind.push(this.configurationService.addListener(ConfigurationServiceEventTypes.UPDATED, (e: IConfigurationServiceEvent) => this.onConfigurationChange(e.config)));
E
Erich Gamma 已提交
60 61
	}

62 63 64 65 66 67 68
	private loadConfiguration(): void {
		this.configurationService.loadConfiguration().done((configuration: IFilesConfiguration) => {
			this.onConfigurationChange(configuration);
		}, errors.onUnexpectedError);
	}

	private onConfigurationChange(configuration: IFilesConfiguration): void {
69 70
		const wasAutoSaveEnabled = this.isAutoSaveEnabled();

71 72 73 74
		this.configuredAutoSaveDelay = configuration && configuration.files && configuration.files.autoSaveAfterDelay;

		const autoSaveConfig = this.getAutoSaveConfiguration();
		CACHE.getAll().forEach((model) => model.updateAutoSaveConfiguration(autoSaveConfig));
75 76 77 78

		if (!wasAutoSaveEnabled && this.isAutoSaveEnabled()) {
			this.saveAll().done(null, errors.onUnexpectedError); // save all dirty when enabling auto save
		}
E
Erich Gamma 已提交
79 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 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 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
	}

	public getDirty(resource?: URI): URI[] {
		return this.getDirtyFileModels(resource).map((m) => m.getResource());
	}

	public isDirty(resource?: URI): boolean {
		return CACHE
			.getAll(resource)
			.some((model) => model.isDirty());
	}

	public save(resource: URI): TPromise<boolean> {
		return this.saveAll([resource]).then((result) => result.results.length === 1 && result.results[0].success);
	}

	public saveAll(arg1?: any /* URI[] */): TPromise<ITextFileOperationResult> {
		let dirtyFileModels = this.getDirtyFileModels(Array.isArray(arg1) ? arg1 : void 0 /* Save All */);

		let mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		dirtyFileModels.forEach((m) => {
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

		return Promise.join(dirtyFileModels.map((model) => {
			return model.save().then(() => {
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
			});
		})).then((r) => {
			return {
				results: Object.keys(mapResourceToResult).map((k) => mapResourceToResult[k])
			};
		});
	}

	private getFileModels(resources?: URI[]): TextFileEditorModel[];
	private getFileModels(resource?: URI): TextFileEditorModel[];
	private getFileModels(arg1?: any): TextFileEditorModel[] {
		if (Array.isArray(arg1)) {
			let models: TextFileEditorModel[] = [];
			(<URI[]>arg1).forEach((resource) => {
				models.push(...this.getFileModels(resource));
			});

			return models;
		}

		return CACHE.getAll(<URI>arg1);
	}

	private getDirtyFileModels(resources?: URI[]): TextFileEditorModel[];
	private getDirtyFileModels(resource?: URI): TextFileEditorModel[];
	private getDirtyFileModels(arg1?: any): TextFileEditorModel[] {
		return this.getFileModels(arg1).filter((model) => model.isDirty());
	}

	public abstract saveAs(resource: URI, targetResource?: URI): TPromise<URI>;

	public confirmSave(resource?: URI): ConfirmResult {
		throw new Error('Unsupported');
	}

	public revert(resource: URI, force?: boolean): TPromise<boolean> {
		return this.revertAll([resource], force).then((result) => result.results.length === 1 && result.results[0].success);
	}

	public revertAll(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> {
		let fileModels = force ? this.getFileModels(resources) : this.getDirtyFileModels(resources);

		let mapResourceToResult: { [resource: string]: IResult } = Object.create(null);
		fileModels.forEach((m) => {
			mapResourceToResult[m.getResource().toString()] = {
				source: m.getResource()
			};
		});

		return Promise.join(fileModels.map((model) => {
			return model.revert().then(() => {
				if (!model.isDirty()) {
					mapResourceToResult[model.getResource().toString()].success = true;
				}
			}, (error) => {

				// FileNotFound means the file got deleted meanwhile, so dispose this model
				if ((<IFileOperationResult>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
					let clients = FileEditorInput.getAll(model.getResource());
					clients.forEach((input) => input.dispose(true));

					// also make sure to have it removed from any working files
					this.workingFilesModel.removeEntry(model.getResource());

					// store as successful revert
					mapResourceToResult[model.getResource().toString()].success = true;
				}

				// Otherwise bubble up the error
				else {
					return Promise.wrapError(error);
				}
			});
		})).then((r) => {
			return {
				results: Object.keys(mapResourceToResult).map((k) => mapResourceToResult[k])
			};
		});
	}

	public beforeShutdown(): boolean | TPromise<boolean> {

		// Propagate to working files model
		this.workingFilesModel.shutdown();

		return false; // no veto
	}

	public getWorkingFilesModel(): WorkingFilesModel {
		return this.workingFilesModel;
	}

202 203 204 205 206 207 208 209 210 211
	public isAutoSaveEnabled(): boolean {
		return this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0;
	}

	public getAutoSaveConfiguration(): IAutoSaveConfiguration {
		return {
			autoSaveAfterDelay: this.configuredAutoSaveDelay && this.configuredAutoSaveDelay > 0 ? this.configuredAutoSaveDelay : void 0
		}
	}

E
Erich Gamma 已提交
212
	public dispose(): void {
213 214 215
		while (this.listenerToUnbind.length) {
			this.listenerToUnbind.pop()();
		}
E
Erich Gamma 已提交
216 217 218 219 220 221 222

		this.workingFilesModel.dispose();

		// Clear all caches
		CACHE.clear();
	}
}