textFileServices.ts 14.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*---------------------------------------------------------------------------------------------
 *  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 nls = require('vs/nls');
import {Promise, TPromise} from 'vs/base/common/winjs.base';
import {Registry} from 'vs/platform/platform';
import {IEditorModesRegistry, Extensions as ModesExtensions} from 'vs/editor/common/modes/modesRegistry';
import paths = require('vs/base/common/paths');
import strings = require('vs/base/common/strings');
14
import {isWindows} from 'vs/base/common/platform';
E
Erich Gamma 已提交
15 16
import URI from 'vs/base/common/uri';
import {Action} from 'vs/base/common/actions';
17
import {UntitledEditorModel} from 'vs/workbench/common/editor/untitledEditorModel';
18
import {IEventService} from 'vs/platform/event/common/event';
B
naming  
Benjamin Pasero 已提交
19
import {TextFileService as AbstractTextFileService} from 'vs/workbench/parts/files/browser/textFileServices';
20
import {CACHE, TextFileEditorModel} from 'vs/workbench/parts/files/common/editors/textFileEditorModel';
21
import {ITextFileOperationResult, ConfirmResult, AutoSaveMode} from 'vs/workbench/parts/files/common/files';
22
import {IWorkbenchActionRegistry, Extensions as ActionExtensions} from 'vs/workbench/common/actionRegistry';
E
Erich Gamma 已提交
23
import {SyncActionDescriptor} from 'vs/platform/actions/common/actions';
24
import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService';
E
Erich Gamma 已提交
25 26 27 28
import {IFileService} from 'vs/platform/files/common/files';
import {IInstantiationService, INullService} from 'vs/platform/instantiation/common/instantiation';
import {IWorkspaceContextService} from 'vs/workbench/services/workspace/common/contextService';
import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle';
29
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
30
import {IConfigurationService, IConfigurationServiceEvent, ConfigurationServiceEventTypes} from 'vs/platform/configuration/common/configuration';
E
Erich Gamma 已提交
31

32
import {remote} from 'electron';
E
Erich Gamma 已提交
33

B
naming  
Benjamin Pasero 已提交
34
export class TextFileService extends AbstractTextFileService {
E
Erich Gamma 已提交
35 36 37

	constructor(
		@IWorkspaceContextService contextService: IWorkspaceContextService,
38
		@IInstantiationService instantiationService: IInstantiationService,
E
Erich Gamma 已提交
39 40
		@IFileService private fileService: IFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
41
		@ILifecycleService lifecycleService: ILifecycleService,
42
		@ITelemetryService telemetryService: ITelemetryService,
43 44
		@IConfigurationService configurationService: IConfigurationService,
		@IEventService eventService: IEventService
E
Erich Gamma 已提交
45
	) {
46
		super(contextService, instantiationService, configurationService, telemetryService, lifecycleService, eventService);
B
Benjamin Pasero 已提交
47 48

		this.init();
E
Erich Gamma 已提交
49 50 51 52 53 54 55 56
	}

	public beforeShutdown(): boolean | TPromise<boolean> {
		super.beforeShutdown();

		// Dirty files need treatment on shutdown
		if (this.getDirty().length) {

57
			// If auto save is enabled, save all files and then check again for dirty files
58
			if (this.getAutoSaveMode() !== AutoSaveMode.OFF) {
59 60 61
				return this.saveAll(false /* files only */).then(() => {
					if (this.getDirty().length) {
						return this.confirmBeforeShutdown(); // we still have dirty files around, so confirm normally
E
Erich Gamma 已提交
62 63
					}

64
					return false; // all good, no veto
E
Erich Gamma 已提交
65 66 67
				});
			}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
			// Otherwise just confirm what to do
			return this.confirmBeforeShutdown();
		}

		return false; // no veto
	}

	private confirmBeforeShutdown(): boolean | TPromise<boolean> {
		let confirm = this.confirmSave();

		// Save
		if (confirm === ConfirmResult.SAVE) {
			return this.saveAll(true /* includeUntitled */).then((result) => {
				if (result.results.some((r) => !r.success)) {
					return true; // veto if some saves failed
				}

E
Erich Gamma 已提交
85
				return false; // no veto
86 87
			});
		}
E
Erich Gamma 已提交
88

89 90 91
		// Don't Save
		else if (confirm === ConfirmResult.DONT_SAVE) {
			return false; // no veto
E
Erich Gamma 已提交
92 93
		}

94 95 96 97
		// Cancel
		else if (confirm === ConfirmResult.CANCEL) {
			return true; // veto
		}
E
Erich Gamma 已提交
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
	}

	public revertAll(resources?: URI[], force?: boolean): TPromise<ITextFileOperationResult> {

		// Revert files
		return super.revertAll(resources, force).then((r) => {

			// Revert untitled
			let untitledInputs = this.untitledEditorService.getAll(resources);
			untitledInputs.forEach((input) => {
				if (input) {
					input.dispose();

					r.results.push({
						source: input.getResource(),
						success: true
					});
				}
			});

			return r;
		});
	}

	public getDirty(resource?: URI): URI[] {

		// Collect files
		let dirty = super.getDirty(resource);

		// Add untitled ones
		if (!resource) {
			dirty.push(...this.untitledEditorService.getDirty());
		} else {
			let input = this.untitledEditorService.get(resource);
			if (input && input.isDirty()) {
				dirty.push(input.getResource());
			}
		}

		return dirty;
	}

	public isDirty(resource?: URI): boolean {
		if (super.isDirty(resource)) {
			return true;
		}

		return this.untitledEditorService.getDirty().some((dirty) => !resource || dirty.toString() === resource.toString());
	}

	public confirmSave(resource?: URI): ConfirmResult {
149 150 151 152
		if (!!this.contextService.getConfiguration().env.pluginDevelopmentPath) {
			return ConfirmResult.DONT_SAVE; // no veto when we are in plugin dev mode because we cannot assum we run interactive (e.g. tests)
		}

E
Erich Gamma 已提交
153 154 155 156 157 158 159 160 161 162 163
		let resourcesToConfirm = this.getDirty(resource);
		if (resourcesToConfirm.length === 0) {
			return ConfirmResult.DONT_SAVE;
		}

		let message = [
			resourcesToConfirm.length === 1 ? nls.localize('saveChangesMessage', "Do you want to save the changes you made to {0}?", paths.basename(resourcesToConfirm[0].fsPath)) : nls.localize('saveChangesMessages', "Do you want to save the changes to the following files?")
		];

		if (resourcesToConfirm.length > 1) {
			message.push('');
164
			message.push(...resourcesToConfirm.map((r) => paths.basename(r.fsPath)));
E
Erich Gamma 已提交
165 166 167
			message.push('');
		}

168 169
		// Button order
		// Windows: Save | Don't Save | Cancel
170
		// Mac/Linux: Save | Cancel | Don't
171

172 173
		const save = { label: resourcesToConfirm.length > 1 ? this.mnemonicLabel(nls.localize('saveAll', "&&Save All")) : this.mnemonicLabel(nls.localize('save', "&&Save")), result: ConfirmResult.SAVE };
		const dontSave = { label: this.mnemonicLabel(nls.localize('dontSave', "Do&&n't Save")), result: ConfirmResult.DONT_SAVE };
174 175
		const cancel = { label: nls.localize('cancel', "Cancel"), result: ConfirmResult.CANCEL };

176
		const buttons = [save];
177
		if (isWindows) {
178
			buttons.push(dontSave, cancel);
179
		} else {
180
			buttons.push(cancel, dontSave);
181
		}
182

183
		let opts: Electron.Dialog.ShowMessageBoxOptions = {
E
Erich Gamma 已提交
184 185 186 187
			title: this.contextService.getConfiguration().env.appName,
			message: message.join('\n'),
			type: 'warning',
			detail: nls.localize('saveChangesDetail', "Your changes will be lost if you don't save them."),
188
			buttons: buttons.map(b => b.label),
E
Erich Gamma 已提交
189
			noLink: true,
190
			cancelId: buttons.indexOf(cancel)
E
Erich Gamma 已提交
191 192
		};

193
		const choice = remote.dialog.showMessageBox(remote.getCurrentWindow(), opts);
E
Erich Gamma 已提交
194

195
		return buttons[choice].result;
E
Erich Gamma 已提交
196 197
	}

198 199 200 201 202 203 204 205
	private mnemonicLabel(label: string): string {
		if (!isWindows) {
			return label.replace(/&&/g, ''); // no mnemonic support on mac/linux in buttons yet
		}

		return label.replace(/&&/g, '&');
	}

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 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	public saveAll(includeUntitled?: boolean): TPromise<ITextFileOperationResult>;
	public saveAll(resources: URI[]): TPromise<ITextFileOperationResult>;
	public saveAll(arg1?: any): TPromise<ITextFileOperationResult> {

		// get all dirty
		let toSave: URI[] = [];
		if (Array.isArray(arg1)) {
			(<URI[]>arg1).forEach((r) => {
				toSave.push(...this.getDirty(r));
			});
		} else {
			toSave = this.getDirty();
		}

		// split up between files and untitled
		let filesToSave: URI[] = [];
		let untitledToSave: URI[] = [];
		toSave.forEach((s) => {
			if (s.scheme === 'file') {
				filesToSave.push(s);
			} else if ((Array.isArray(arg1) || arg1 === true /* includeUntitled */) && s.scheme === 'untitled') {
				untitledToSave.push(s);
			}
		});

		return this.doSaveAll(filesToSave, untitledToSave);
	}

	private doSaveAll(fileResources: URI[], untitledResources: URI[]): TPromise<ITextFileOperationResult> {

		// Preflight for untitled to handle cancellation from the dialog
		let targetsForUntitled: URI[] = [];
		for (let i = 0; i < untitledResources.length; i++) {
			let untitled = this.untitledEditorService.get(untitledResources[i]);
			if (untitled) {
				let targetPath: string;

243
				// Untitled with associated file path don't need to prompt
E
Erich Gamma 已提交
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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
				if (this.untitledEditorService.hasAssociatedFilePath(untitled.getResource())) {
					targetPath = untitled.getResource().fsPath;
				}

				// Otherwise ask user
				else {
					targetPath = this.promptForPathSync(this.suggestFileName(untitledResources[i]));
					if (!targetPath) {
						return Promise.as({
							results: [...fileResources, ...untitledResources].map((r) => {
								return {
									source: r
								};
							})
						});
					}
				}

				targetsForUntitled.push(URI.file(targetPath));
			}
		}

		// Handle files
		return super.saveAll(fileResources).then((result) => {

			// Handle untitled
			let untitledSaveAsPromises: Promise[] = [];
			targetsForUntitled.forEach((target, index) => {
				let untitledSaveAsPromise = this.saveAs(untitledResources[index], target).then((uri) => {
					result.results.push({
						source: untitledResources[index],
						target: uri,
						success: !!uri
					});
				});

				untitledSaveAsPromises.push(untitledSaveAsPromise);
			});

			return Promise.join(untitledSaveAsPromises).then(() => {
				return result;
			});
		});
	}

	public saveAs(resource: URI, target?: URI): TPromise<URI> {

		// Get to target resource
		let targetPromise: TPromise<URI>;
		if (target) {
			targetPromise = Promise.as(target);
		} else {
			let dialogPath = resource.fsPath;
			if (resource.scheme === 'untitled') {
				dialogPath = this.suggestFileName(resource);
			}

			targetPromise = this.promptForPathAsync(dialogPath).then((path) => path ? URI.file(path) : null);
		}

		return targetPromise.then((target) => {
			if (!target) {
				return null; // user canceled
			}

			// Just save if target is same as models own resource
			if (resource.toString() === target.toString()) {
				return this.save(resource).then(() => resource);
			}

			// Do it
			return this.doSaveAs(resource, target);
		});
	}

	private doSaveAs(resource: URI, target?: URI): TPromise<URI> {

		// Retrieve text model from provided resource if any
		let modelPromise: TPromise<TextFileEditorModel | UntitledEditorModel> = TPromise.as(null);
		if (resource.scheme === 'file') {
			modelPromise = TPromise.as(CACHE.get(resource));
		} else if (resource.scheme === 'untitled') {
			let untitled = this.untitledEditorService.get(resource);
			if (untitled) {
				modelPromise = untitled.resolve();
			}
		}

		return modelPromise.then((model) => {

			// We have a model: Use it (can be null e.g. if this file is binary and not a text file or was never opened before)
			if (model) {
336
				return this.fileService.updateContent(target, model.getValue(), { charset: model.getEncoding() });
E
Erich Gamma 已提交
337 338 339
			}

			// Otherwise we can only copy
340 341 342 343 344 345 346 347 348 349 350 351
			return this.fileService.copyFile(resource, target);
		}).then(() => {

			// Add target to working files because this is an operation that indicates activity
			this.getWorkingFilesModel().addEntry(target);

			// Revert the source
			return this.revert(resource).then(() => {

				// Done: return target
				return target;
			});
E
Erich Gamma 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365
		});
	}

	private suggestFileName(untitledResource: URI): string {
		let workspace = this.contextService.getWorkspace();
		if (workspace) {
			return URI.file(paths.join(workspace.resource.fsPath, this.untitledEditorService.get(untitledResource).suggestFileName())).fsPath;
		}

		return this.untitledEditorService.get(untitledResource).suggestFileName();
	}

	private promptForPathAsync(defaultPath?: string): TPromise<string> {
		return new TPromise<string>((c, e) => {
366
			remote.dialog.showSaveDialog(remote.getCurrentWindow(), this.getSaveDialogOptions(defaultPath ? paths.normalize(defaultPath, true) : void 0), (path) => {
E
Erich Gamma 已提交
367 368 369 370 371 372
				c(path);
			});
		});
	}

	private promptForPathSync(defaultPath?: string): string {
373
		return remote.dialog.showSaveDialog(remote.getCurrentWindow(), this.getSaveDialogOptions(defaultPath ? paths.normalize(defaultPath, true) : void 0));
E
Erich Gamma 已提交
374 375
	}

376 377
	private getSaveDialogOptions(defaultPath?: string): Electron.Dialog.SaveDialogOptions {
		let options: Electron.Dialog.SaveDialogOptions = {
E
Erich Gamma 已提交
378 379 380
			defaultPath: defaultPath
		};

381 382 383 384
		// Filters are working flaky in Electron and there are bugs. On Windows they are working
		// somewhat but we see issues:
		// - https://github.com/atom/electron/issues/3556
		// - https://github.com/Microsoft/vscode/issues/451
385
		// - Bug on Windows: When "All Files" is picked, the path gets an extra ".*"
386 387
		// Until these issues are resolved, we disable the dialog file extension filtering.
		if (true) {
E
Erich Gamma 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
			return options;
		}

		interface IFilter { name: string, extensions: string[] };

		// Build the file filter by using our known languages
		let ext: string = paths.extname(defaultPath);
		let matchingFilter: IFilter;
		let modesRegistry = <IEditorModesRegistry>Registry.as(ModesExtensions.EditorModes);
		let filters: IFilter[] = modesRegistry.getRegisteredLanguageNames().map(languageName => {
			let extensions = modesRegistry.getExtensions(languageName);
			if (!extensions || !extensions.length) {
				return null;
			}

			let filter: IFilter = { name: languageName, extensions: extensions.map(e => strings.trim(e, '.')) };

			if (ext && extensions.indexOf(ext) >= 0) {
				matchingFilter = filter;

				return null; // matching filter will be added last to the top
			}

			return filter;
		}).filter(f => !!f);

		// Filters are a bit weird on Windows, based on having a match or not:
		// Match: we put the matching filter first so that it shows up selected and the all files last
		// No match: we put the all files filter first
		let allFilesFilter = { name: nls.localize('allFiles', "All Files"), extensions: ['*'] };
		if (matchingFilter) {
			filters.unshift(matchingFilter);
			filters.push(allFilesFilter);
		} else {
			filters.unshift(allFilesFilter);
		}

		options.filters = filters;

		return options;
	}
}