fileActions.ts 53.8 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 'vs/css!./media/fileactions';
J
Johannes Rieken 已提交
9
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
10
import nls = require('vs/nls');
J
Johannes Rieken 已提交
11 12
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
import { sequence, ITask } from 'vs/base/common/async';
E
Erich Gamma 已提交
13 14 15
import paths = require('vs/base/common/paths');
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
16
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
17
import strings = require('vs/base/common/strings');
18
import { EventType as CommonEventType } from 'vs/base/common/events';
19
import severity from 'vs/base/common/severity';
E
Erich Gamma 已提交
20
import diagnostics = require('vs/base/common/diagnostics');
J
Johannes Rieken 已提交
21 22 23 24 25
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
26
import labels = require('vs/base/common/labels');
27 28
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
29
import { toResource, IEditorIdentifier, EditorInput } from 'vs/workbench/common/editor';
J
Johannes Rieken 已提交
30 31 32 33 34 35 36
import { FileStat, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerViewModel';
import { ExplorerView } from 'vs/workbench/parts/files/browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/browser/explorerViewlet';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
B
Benjamin Pasero 已提交
37
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
J
Johannes Rieken 已提交
38
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
J
Johannes Rieken 已提交
39
import { IQuickOpenService, IFilePickOpenEntry } from 'vs/platform/quickOpen/common/quickOpen';
40
import { IHistoryService } from 'vs/workbench/services/history/common/history';
B
Benjamin Pasero 已提交
41
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
42
import { Position, IResourceInput, IEditorInput } from 'vs/platform/editor/common/editor';
J
Johannes Rieken 已提交
43 44 45
import { IInstantiationService, IConstructorSignature2 } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction } from 'vs/platform/message/common/message';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
46
import { Keybinding, KeyMod, KeyCode } from 'vs/base/common/keyCodes';
J
Johannes Rieken 已提交
47
import { Selection } from 'vs/editor/common/core/selection';
S
Sandeep Somavarapu 已提交
48
import { getCodeEditor } from 'vs/editor/common/services/codeEditorService';
E
Erich Gamma 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

export interface IEditableData {
	action: IAction;
	validator: IInputValidator;
}

export interface IFileViewletState {
	actionProvider: IActionProvider;
	getEditableData(stat: IFileStat): IEditableData;
	setEditable(stat: IFileStat, editableData: IEditableData): void;
	clearEditable(stat: IFileStat): void;
}

export class BaseFileAction extends Action {
	private _element: FileStat;

	constructor(
		id: string,
		label: string,
		@IFileService private _fileService: IFileService,
		@IMessageService private _messageService: IMessageService,
70
		@ITextFileService private _textFileService: ITextFileService
E
Erich Gamma 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	) {
		super(id, label);

		this.enabled = false;
	}

	public get messageService() {
		return this._messageService;
	}

	public get fileService() {
		return this._fileService;
	}

	public get textFileService() {
		return this._textFileService;
	}

	public get element() {
		return this._element;
	}

	public set element(element: FileStat) {
		this._element = element;
	}

	_isEnabled(): boolean {
		return true;
	}

	_updateEnablement(): void {
B
Benjamin Pasero 已提交
102
		this.enabled = !!(this._fileService && this._isEnabled());
E
Erich Gamma 已提交
103 104 105 106 107 108 109 110 111 112
	}

	protected onError(error: any): void {
		this._messageService.show(Severity.Error, error);
	}

	protected onWarning(warning: any): void {
		this._messageService.show(Severity.Warning, warning);
	}

113
	protected onErrorWithRetry(error: any, retry: () => TPromise<any>, extraAction?: Action): void {
114
		const actions = [
115 116
			new Action(this.id, nls.localize('retry', "Retry"), null, true, () => retry()),
			CancelAction
E
Erich Gamma 已提交
117 118 119
		];

		if (extraAction) {
120
			actions.unshift(extraAction);
E
Erich Gamma 已提交
121 122
		}

123
		const errorWithRetry: IMessageWithAction = {
124
			actions,
125
			message: toErrorMessage(error, false)
E
Erich Gamma 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
		};

		this._messageService.show(Severity.Error, errorWithRetry);
	}
}

export class TriggerRenameFileAction extends BaseFileAction {

	public static ID = 'workbench.files.action.triggerRename';

	private tree: ITree;
	private renameAction: BaseRenameAction;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
147
		super(TriggerRenameFileAction.ID, nls.localize('rename', "Rename"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
148 149 150 151 152 153 154 155 156 157 158

		this.tree = tree;
		this.element = element;
		this.renameAction = instantiationService.createInstance(RenameFileAction, element);
		this._updateEnablement();
	}

	public validateFileName(parent: IFileStat, name: string): string {
		return this.renameAction.validateFileName(this.element.parent, name);
	}

159
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
160
		if (!context) {
161
			return TPromise.wrapError('No context provided to BaseEnableFileRenameAction.');
E
Erich Gamma 已提交
162 163
		}

164
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
165
		if (!viewletState) {
166
			return TPromise.wrapError('Invalid viewlet state provided to BaseEnableFileRenameAction.');
E
Erich Gamma 已提交
167 168
		}

169
		const stat = <IFileStat>context.stat;
E
Erich Gamma 已提交
170
		if (!stat) {
171
			return TPromise.wrapError('Invalid stat provided to BaseEnableFileRenameAction.');
E
Erich Gamma 已提交
172 173 174 175 176
		}

		viewletState.setEditable(stat, {
			action: this.renameAction,
			validator: (value) => {
177
				const message = this.validateFileName(this.element.parent, value);
E
Erich Gamma 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

				if (!message) {
					return null;
				}

				return {
					content: message,
					formatContent: true,
					type: MessageType.ERROR
				};
			}
		});

		this.tree.refresh(stat, false).then(() => {
			this.tree.setHighlight(stat);

194
			const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
E
Erich Gamma 已提交
195 196 197
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
198
					unbind.dispose();
E
Erich Gamma 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212
				}
			});
		}).done(null, errors.onUnexpectedError);
	}
}

export abstract class BaseRenameAction extends BaseFileAction {

	constructor(
		id: string,
		label: string,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
213
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
214
	) {
B
Benjamin Pasero 已提交
215
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
216 217 218 219

		this.element = element;
	}

220
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
221
		if (!context) {
222
			return TPromise.wrapError('No context provided to BaseRenameFileAction.');
E
Erich Gamma 已提交
223 224 225 226
		}

		let name = <string>context.value;
		if (!name) {
227
			return TPromise.wrapError('No new name provided to BaseRenameFileAction.');
E
Erich Gamma 已提交
228 229 230 231
		}

		// Automatically trim whitespaces and trailing dots to produce nice file names
		name = getWellFormedFileName(name);
232
		const existingName = getWellFormedFileName(this.element.name);
E
Erich Gamma 已提交
233

234
		// Return early if name is invalid or didn't change
E
Erich Gamma 已提交
235
		if (name === existingName || this.validateFileName(this.element.parent, name)) {
A
Alex Dima 已提交
236
			return TPromise.as(null);
E
Erich Gamma 已提交
237 238 239
		}

		// Call function and Emit Event through viewer
240
		const promise = this.runAction(name).then(null, (error: any) => {
E
Erich Gamma 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
			this.onError(error);
		});

		return promise;
	}

	public validateFileName(parent: IFileStat, name: string): string {
		let source = this.element.name;
		let target = name;

		if (!isLinux) { // allow rename of same file also when case differs (e.g. Game.js => game.js)
			source = source.toLowerCase();
			target = target.toLowerCase();
		}

		if (getWellFormedFileName(source) === getWellFormedFileName(target)) {
			return null;
		}

		return validateFileName(parent, name, false);
	}

263
	public abstract runAction(newName: string): TPromise<any>;
E
Erich Gamma 已提交
264 265
}

266
class RenameFileAction extends BaseRenameAction {
E
Erich Gamma 已提交
267 268 269 270 271 272 273

	public static ID = 'workbench.files.action.renameFile';

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
274
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
275
	) {
B
Benjamin Pasero 已提交
276
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, fileService, messageService, textFileService);
E
Erich Gamma 已提交
277 278 279 280

		this._updateEnablement();
	}

281
	public runAction(newName: string): TPromise<any> {
E
Erich Gamma 已提交
282

283 284 285 286 287 288 289 290 291 292 293 294 295
		// Handle dirty
		let revertPromise: TPromise<any> = TPromise.as(null);
		const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, this.element.resource.fsPath));
		if (dirty.length) {
			let message: string;
			if (this.element.isDirectory) {
				if (dirty.length === 1) {
					message = nls.localize('dirtyMessageFolderOne', "You are renaming a folder with unsaved changes in 1 file. Do you want to continue?");
				} else {
					message = nls.localize('dirtyMessageFolder', "You are renaming a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
				}
			} else {
				message = nls.localize('dirtyMessageFile', "You are renaming a file with unsaved changes. Do you want to continue?");
E
Erich Gamma 已提交
296 297
			}

298 299 300 301 302 303
			const res = this.messageService.confirm({
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton: nls.localize({ key: 'renameLabel', comment: ['&& denotes a mnemonic'] }, "&&Rename")
			});
E
Erich Gamma 已提交
304

305
			if (!res) {
A
Alex Dima 已提交
306
				return TPromise.as(null);
E
Erich Gamma 已提交
307 308
			}

309 310 311 312
			revertPromise = this.textFileService.revertAll(dirty);
		}

		return revertPromise.then(() => {
E
Erich Gamma 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
			return this.fileService.rename(this.element.resource, newName).then(null, (error: Error) => {
				this.onErrorWithRetry(error, () => this.runAction(newName));
			});
		});
	}
}

/* Base New File/Folder Action */
export class BaseNewAction extends BaseFileAction {
	private presetFolder: FileStat;
	private tree: ITree;
	private isFile: boolean;
	private renameAction: BaseRenameAction;

	constructor(
		id: string,
		label: string,
		tree: ITree,
		isFile: boolean,
		editableAction: BaseRenameAction,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
336
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
337
	) {
B
Benjamin Pasero 已提交
338
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
339 340 341 342 343 344 345 346 347 348

		if (element) {
			this.presetFolder = element.isDirectory ? element : element.parent;
		}

		this.tree = tree;
		this.isFile = isFile;
		this.renameAction = editableAction;
	}

349
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
350
		if (!context) {
351
			return TPromise.wrapError('No context provided to BaseNewAction.');
E
Erich Gamma 已提交
352 353
		}

354
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
355
		if (!viewletState) {
356
			return TPromise.wrapError('Invalid viewlet state provided to BaseNewAction.');
E
Erich Gamma 已提交
357 358 359 360
		}

		let folder: FileStat = this.presetFolder;
		if (!folder) {
361
			const focus = <FileStat>this.tree.getFocus();
E
Erich Gamma 已提交
362 363 364 365 366 367 368 369
			if (focus) {
				folder = focus.isDirectory ? focus : focus.parent;
			} else {
				folder = this.tree.getInput();
			}
		}

		if (!folder) {
370
			return TPromise.wrapError('Invalid parent folder to create.');
E
Erich Gamma 已提交
371 372 373 374
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
375
				const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);
E
Erich Gamma 已提交
376 377 378 379 380 381

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
382
						const message = this.renameAction.validateFileName(folder, value);
E
Erich Gamma 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

						if (!message) {
							return null;
						}

						return {
							content: message,
							formatContent: true,
							type: MessageType.ERROR
						};
					}
				});

				return this.tree.refresh(folder).then(() => {
					return this.tree.expand(folder).then(() => {
						return this.tree.reveal(stat, 0.5).then(() => {
							this.tree.setHighlight(stat);

401
							const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
E
Erich Gamma 已提交
402 403 404
								if (!e.highlight) {
									stat.destroy();
									this.tree.refresh(folder).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
405
									unbind.dispose();
E
Erich Gamma 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
								}
							});
						});
					});
				});
			});
		});
	}
}

/* New File */
export class NewFileAction extends BaseNewAction {

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
427
		super('workbench.action.files.newFile', nls.localize('newFile', "New File"), tree, true, instantiationService.createInstance(CreateFileAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

		this.class = 'explorer-action new-file';
		this._updateEnablement();
	}
}

/* New Folder */
export class NewFolderAction extends BaseNewAction {

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
445
		super('workbench.action.files.newFolder', nls.localize('newFolder', "New Folder"), tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458

		this.class = 'explorer-action new-folder';
		this._updateEnablement();
	}
}

export abstract class BaseGlobalNewAction extends Action {
	private toDispose: Action;

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService,
B
fix npe  
Benjamin Pasero 已提交
459 460
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
461 462 463 464
	) {
		super(id, label);
	}

465
	public run(): TPromise<any> {
466
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet) => {
467
			return TPromise.timeout(100).then(() => { // use a timeout to prevent the explorer from revealing the active file
E
Erich Gamma 已提交
468 469
				viewlet.focus();

470 471
				const explorer = <ExplorerViewlet>viewlet;
				const explorerView = explorer.getExplorerView();
E
Erich Gamma 已提交
472

B
fix npe  
Benjamin Pasero 已提交
473 474 475 476 477
				// Not having a folder opened
				if (!explorerView) {
					return this.messageService.show(Severity.Info, nls.localize('openFolderFirst', "Open a folder first to create files or folders within."));
				}

E
Erich Gamma 已提交
478 479 480 481
				if (!explorerView.isExpanded()) {
					explorerView.expand();
				}

482
				const action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);
E
Erich Gamma 已提交
483 484 485 486 487 488

				return explorer.getActionRunner().run(action);
			});
		});
	}

489
	protected abstract getAction(): IConstructorSignature2<ITree, IFileStat, Action>;
E
Erich Gamma 已提交
490 491 492 493 494 495 496 497 498 499 500 501

	public dispose(): void {
		super.dispose();

		if (this.toDispose) {
			this.toDispose.dispose();
			this.toDispose = null;
		}
	}
}

/* Create new file from anywhere: Open untitled */
502
export class GlobalNewUntitledFileAction extends Action {
E
Erich Gamma 已提交
503
	public static ID = 'workbench.action.files.newUntitledFile';
S
Sam Verschueren 已提交
504
	public static LABEL = nls.localize('newUntitledFile', "New Untitled File");
E
Erich Gamma 已提交
505 506 507 508 509 510 511 512 513 514

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService
	) {
		super(id, label);
	}

515
	public run(): TPromise<any> {
516
		const input = this.untitledEditorService.createOrGet();
E
Erich Gamma 已提交
517

518
		return this.editorService.openEditor(input, { pinned: true }); // untitled are always pinned
E
Erich Gamma 已提交
519 520 521
	}
}

522 523 524 525 526 527 528 529 530 531
/* Create new file from anywhere */
export class GlobalNewFileAction extends BaseGlobalNewAction {
	public static ID = 'workbench.action.files.newFile';
	public static LABEL = nls.localize('newFile', "New File");

	protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
		return NewFileAction;
	}
}

E
Erich Gamma 已提交
532 533 534 535 536
/* Create new folder from anywhere */
export class GlobalNewFolderAction extends BaseGlobalNewAction {
	public static ID = 'workbench.action.files.newFolder';
	public static LABEL = nls.localize('newFolder', "New Folder");

537
	protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
E
Erich Gamma 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
		return NewFolderAction;
	}
}

/* Create New File/Folder (only used internally by explorerViewer) */
export abstract class BaseCreateAction extends BaseRenameAction {

	public validateFileName(parent: IFileStat, name: string): string {
		if (this.element instanceof NewStatPlaceholder) {
			return validateFileName(parent, name, false);
		}

		return super.validateFileName(parent, name);
	}
}

/* Create New File (only used internally by explorerViewer) */
export class CreateFileAction extends BaseCreateAction {

	public static ID = 'workbench.files.action.createFileFromExplorer';
	public static LABEL = nls.localize('createNewFile', "New File");

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
564
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
565
	) {
B
Benjamin Pasero 已提交
566
		super(CreateFileAction.ID, CreateFileAction.LABEL, element, fileService, messageService, textFileService);
E
Erich Gamma 已提交
567 568 569 570

		this._updateEnablement();
	}

571
	public runAction(fileName: string): TPromise<any> {
572
		return this.fileService.createFile(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
E
Erich Gamma 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

/* Create New Folder (only used internally by explorerViewer) */
export class CreateFolderAction extends BaseCreateAction {

	public static ID = 'workbench.files.action.createFolderFromExplorer';
	public static LABEL = nls.localize('createNewFolder', "New Folder");

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
588
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
589
	) {
B
Benjamin Pasero 已提交
590
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
591 592 593 594

		this._updateEnablement();
	}

595
	public runAction(fileName: string): TPromise<any> {
E
Erich Gamma 已提交
596 597 598 599 600 601 602 603 604
		return this.fileService.createFolder(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

export class BaseDeleteFileAction extends BaseFileAction {
	private tree: ITree;
	private useTrash: boolean;
605
	private skipConfirm: boolean;
E
Erich Gamma 已提交
606 607 608 609 610 611 612 613 614

	constructor(
		id: string,
		label: string,
		tree: ITree,
		element: FileStat,
		useTrash: boolean,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
615
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
616
	) {
B
Benjamin Pasero 已提交
617
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
618 619 620 621 622 623 624 625

		this.tree = tree;
		this.element = element;
		this.useTrash = useTrash && !paths.isUNC(element.resource.fsPath); // on UNC shares there is no trash

		this._updateEnablement();
	}

626
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
627 628 629 630 631 632

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

633 634 635 636 637 638 639 640
		// Read context
		if (context && context.event) {
			const bypassTrash = (isMacintosh && context.event.altKey) || (!isMacintosh && context.event.shiftKey);
			if (bypassTrash) {
				this.useTrash = false;
			}
		}

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
		let primaryButton: string;
		if (this.useTrash) {
			primaryButton = isWindows ? nls.localize('deleteButtonLabelRecycleBin', "&&Move to Recycle Bin") : nls.localize({ key: 'deleteButtonLabelTrash', comment: ['&& denotes a mnemonic'] }, "&&Move to Trash");
		} else {
			primaryButton = nls.localize({ key: 'deleteButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete");
		}

		// Handle dirty
		let revertPromise: TPromise<any> = TPromise.as(null);
		const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, this.element.resource.fsPath));
		if (dirty.length) {
			let message: string;
			if (this.element.isDirectory) {
				if (dirty.length === 1) {
					message = nls.localize('dirtyMessageFolderOneDelete', "You are deleting a folder with unsaved changes in 1 file. Do you want to continue?");
				} else {
					message = nls.localize('dirtyMessageFolderDelete', "You are deleting a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
				}
659
			} else {
660
				message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
661
			}
E
Erich Gamma 已提交
662

663 664 665 666 667 668 669 670
			const res = this.messageService.confirm({
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
			});

			if (!res) {
A
Alex Dima 已提交
671
				return TPromise.as(null);
672
			}
673 674 675

			this.skipConfirm = true; // since we already asked for confirmation
			revertPromise = this.textFileService.revertAll(dirty);
E
Erich Gamma 已提交
676 677
		}

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
		// Check if file is dirty in editor and save it to avoid data loss
		return revertPromise.then(() => {

			// Ask for Confirm
			if (!this.skipConfirm) {
				let confirm: IConfirmation;
				if (this.useTrash) {
					confirm = {
						message: this.element.isDirectory ? nls.localize('confirmMoveTrashMessageFolder', "Are you sure you want to delete '{0}' and its contents?", this.element.name) : nls.localize('confirmMoveTrashMessageFile', "Are you sure you want to delete '{0}'?", this.element.name),
						detail: isWindows ? nls.localize('undoBin', "You can restore from the recycle bin.") : nls.localize('undoTrash', "You can restore from the trash."),
						primaryButton
					};
				} else {
					confirm = {
						message: this.element.isDirectory ? nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", this.element.name) : nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", this.element.name),
						detail: nls.localize('irreversible', "This action is irreversible!"),
						primaryButton
					};
				}
B
Benjamin Pasero 已提交
697

698 699 700
				if (!this.messageService.confirm(confirm)) {
					return TPromise.as(null);
				}
E
Erich Gamma 已提交
701 702
			}

703
			// Call function
704
			const servicePromise = this.fileService.del(this.element.resource, this.useTrash).then(() => {
705 706 707 708
				if (this.element.parent) {
					this.tree.setFocus(this.element.parent); // move focus to parent
				}
			}, (error: any) => {
E
Erich Gamma 已提交
709

710 711 712 713 714
				// Allow to retry
				let extraAction: Action;
				if (this.useTrash) {
					extraAction = new Action('permanentDelete', nls.localize('permDelete', "Delete Permanently"), null, true, () => { this.useTrash = false; this.skipConfirm = true; return this.run(); });
				}
E
Erich Gamma 已提交
715

716
				this.onErrorWithRetry(error, () => this.run(), extraAction);
B
Benjamin Pasero 已提交
717

718 719 720 721 722 723
				// Focus back to tree
				this.tree.DOMFocus();
			});

			return servicePromise;
		});
E
Erich Gamma 已提交
724 725 726 727 728 729 730 731 732 733 734 735
	}
}

/* Move File/Folder to trash */
export class MoveFileToTrashAction extends BaseDeleteFileAction {
	public static ID = 'workbench.files.action.moveFileToTrash';

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
736
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
737
	) {
B
Benjamin Pasero 已提交
738
		super(MoveFileToTrashAction.ID, nls.localize('delete', "Delete"), tree, element, true, fileService, messageService, textFileService);
E
Erich Gamma 已提交
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
	}
}

/* Import File */
export class ImportFileAction extends BaseFileAction {

	public static ID = 'workbench.files.action.importFile';
	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
754
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
755
	) {
B
Benjamin Pasero 已提交
756
		super(ImportFileAction.ID, nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

		this.tree = tree;
		this.element = element;

		if (clazz) {
			this.class = clazz;
		}

		this._updateEnablement();
	}

	public getViewer(): ITree {
		return this.tree;
	}

772
	public run(context?: any): TPromise<any> {
773 774
		const importPromise = TPromise.as(null).then(() => {
			const input = context.input;
E
Erich Gamma 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
			if (input.files && input.files.length > 0) {

				// Find parent for import
				let targetElement: FileStat;
				if (this.element) {
					targetElement = this.element;
				} else {
					targetElement = this.tree.getFocus() || this.tree.getInput();
				}

				if (!targetElement.isDirectory) {
					targetElement = targetElement.parent;
				}

				// Create real files array
790
				const filesArray: File[] = [];
E
Erich Gamma 已提交
791
				for (let i = 0; i < input.files.length; i++) {
792
					const file = input.files[i];
E
Erich Gamma 已提交
793 794 795 796 797 798 799
					filesArray.push(file);
				}

				// Resolve target to check for name collisions and ask user
				return this.fileService.resolveFile(targetElement.resource).then((targetStat: IFileStat) => {

					// Check for name collisions
800
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
801 802 803 804 805 806 807 808
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

					let overwrite = true;
					if (filesArray.some((file) => {
						return !!targetNames[isLinux ? file.name : file.name.toLowerCase()];
					})) {
809
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
810 811
							message: nls.localize('confirmOverwrite', "A file or folder with the same name already exists in the destination folder. Do you want to replace it?"),
							detail: nls.localize('irreversible', "This action is irreversible!"),
B
Benjamin Pasero 已提交
812
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace")
E
Erich Gamma 已提交
813 814 815 816 817 818 819 820 821
						};

						overwrite = this.messageService.confirm(confirm);
					}

					if (!overwrite) {
						return;
					}

822
					// Run import in sequence
823
					const importPromisesFactory: ITask<TPromise<void>>[] = [];
E
Erich Gamma 已提交
824 825
					filesArray.forEach((file) => {
						importPromisesFactory.push(() => {
B
Benjamin Pasero 已提交
826
							const sourceFile = URI.file(file.path);
827

828
							return this.fileService.importFile(sourceFile, targetElement.resource).then(null, (error: any) => {
E
Erich Gamma 已提交
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
								this.messageService.show(Severity.Error, error);
							});
						});
					});

					return sequence(importPromisesFactory);
				});
			}
		});

		return importPromise.then(() => {
			this.tree.clearHighlight();
		}, (error: any) => {
			this.onError(error);
			this.tree.clearHighlight();
		});
	}
}

// Copy File/Folder
let fileToCopy: FileStat;
export class CopyFileAction extends BaseFileAction {

	public static ID = 'workbench.files.action.copyFile';

	private tree: ITree;
	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
860
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
861
	) {
B
Benjamin Pasero 已提交
862
		super(CopyFileAction.ID, nls.localize('copyFile', "Copy"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
863 864 865 866 867 868

		this.tree = tree;
		this.element = element;
		this._updateEnablement();
	}

869
	public run(): TPromise<any> {
E
Erich Gamma 已提交
870 871 872 873 874 875 876 877 878 879 880

		// Remember as file/folder to copy
		fileToCopy = this.element;

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

		this.tree.DOMFocus();

A
Alex Dima 已提交
881
		return TPromise.as(null);
E
Erich Gamma 已提交
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
	}
}

// Paste File/Folder
export class PasteFileAction extends BaseFileAction {

	public static ID = 'workbench.files.action.pasteFile';

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
900
		super(PasteFileAction.ID, nls.localize('pasteFile', "Paste"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914

		this.tree = tree;
		this.element = element;
		this._updateEnablement();
	}

	_isEnabled(): boolean {

		// Need at least a file to copy
		if (!fileToCopy) {
			return false;
		}

		// Check if file was deleted or moved meanwhile
915 916
		const root: FileStat = this.tree.getInput();
		const exists = root.find(fileToCopy.resource);
E
Erich Gamma 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929
		if (!exists) {
			fileToCopy = null;
			return false;
		}

		// Check if target is ancestor of pasted folder
		if (this.element.resource.toString() !== fileToCopy.resource.toString() && paths.isEqualOrParent(this.element.resource.fsPath, fileToCopy.resource.fsPath)) {
			return false;
		}

		return true;
	}

930
	public run(): TPromise<any> {
E
Erich Gamma 已提交
931 932 933 934 935 936 937 938 939 940

		// Find target
		let target: FileStat;
		if (this.element.resource.toString() === fileToCopy.resource.toString()) {
			target = this.element.parent;
		} else {
			target = this.element.isDirectory ? this.element : this.element.parent;
		}

		// Reuse duplicate action
941
		const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
E
Erich Gamma 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

		return pasteAction.run().then(() => {
			this.tree.DOMFocus();
		});
	}
}

// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
	private tree: ITree;
	private target: IFileStat;

	constructor(
		tree: ITree,
		element: FileStat,
		target: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
960
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
961
	) {
B
Benjamin Pasero 已提交
962
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
963 964 965 966 967 968 969

		this.tree = tree;
		this.element = element;
		this.target = (target && target.isDirectory) ? target : element.parent;
		this._updateEnablement();
	}

970
	public run(): TPromise<any> {
E
Erich Gamma 已提交
971 972 973 974 975 976

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

977 978
		// Copy File
		const result = this.fileService.copyFile(this.element.resource, this.findTarget()).then(null, (error: any) => {
E
Erich Gamma 已提交
979 980 981 982 983 984 985 986 987 988 989
			this.onError(error);
		});

		return result;
	}

	public onError(error: any): void {
		this.messageService.show(Severity.Error, error);
	}

	private findTarget(): URI {
990
		const root: FileStat = this.tree.getInput();
E
Erich Gamma 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
		let name = this.element.name;

		let candidate = URI.file(paths.join(this.target.resource.fsPath, name));
		while (true) {
			if (!root.find(candidate)) {
				break;
			}

			name = this.toCopyName(name, this.element.isDirectory);
			candidate = URI.file(paths.join(this.target.resource.fsPath, name));
		}

		return candidate;
	}

	private toCopyName(name: string, isFolder: boolean): string {

		// file.1.txt=>file.2.txt
		if (!isFolder && name.match(/(\d+)(\..*)$/)) {
			return name.replace(/(\d+)(\..*)$/, (match, g1?, g2?) => { return (parseInt(g1) + 1) + g2; });
		}

		// file.txt=>file.1.txt
1014
		const lastIndexOfDot = name.lastIndexOf('.');
E
Erich Gamma 已提交
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
		if (!isFolder && lastIndexOfDot >= 0) {
			return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
		}

		// folder.1=>folder.2
		if (isFolder && name.match(/(\d+)$/)) {
			return name.replace(/(\d+)$/, (match: string, ...groups: any[]) => { return String(parseInt(groups[0]) + 1); });
		}

		// file/folder=>file.1/folder.1
		return strings.format('{0}.1', name);
	}
}

// Open to the side
export class OpenToSideAction extends Action {

	public static ID = 'workbench.files.action.openToSide';
	public static LABEL = nls.localize('openToSide', "Open to the Side");

	private tree: ITree;
	private resource: URI;
	private preserveFocus: boolean;

	constructor(
		tree: ITree,
		resource: URI,
		preserveFocus: boolean,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
	) {
		super(OpenToSideAction.ID, OpenToSideAction.LABEL);

		this.tree = tree;
		this.preserveFocus = preserveFocus;
		this.resource = resource;

		this.updateEnablement();
	}

	private updateEnablement(): void {
1055
		const activeEditor = this.editorService.getActiveEditor();
1056
		this.enabled = (!activeEditor || activeEditor.position !== Position.THREE);
E
Erich Gamma 已提交
1057 1058
	}

1059
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

		// Remove highlight
		this.tree.clearHighlight();

		// Set side input
		return this.editorService.openEditor({
			resource: this.resource,
			options: {
				preserveFocus: this.preserveFocus
			}
		}, true);
	}
}

let globalResourceToCompare: URI;
export class SelectResourceForCompareAction extends Action {
	private resource: URI;
	private tree: ITree;

1079
	constructor(resource: URI, tree: ITree) {
E
Erich Gamma 已提交
1080 1081 1082 1083 1084 1085 1086
		super('workbench.files.action.selectForCompare', nls.localize('compareSource', "Select for Compare"));

		this.tree = tree;
		this.resource = resource;
		this.enabled = true;
	}

1087
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097

		// Remember as source file to compare
		globalResourceToCompare = this.resource;

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
			this.tree.DOMFocus();
		}

A
Alex Dima 已提交
1098
		return TPromise.as(null);
E
Erich Gamma 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
	}
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

	public static ID = 'workbench.files.action.compareFileWith';
	public static LABEL = nls.localize('globalCompareFile', "Compare Active File With...");

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1114 1115
		@IHistoryService private historyService: IHistoryService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
1116
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
1117 1118 1119 1120
	) {
		super(id, label);
	}

1121
	public run(): TPromise<any> {
1122 1123
		const fileResource = toResource(this.editorService.getActiveEditorInput(), { filter: 'file' });
		if (fileResource) {
E
Erich Gamma 已提交
1124 1125

			// Keep as resource to compare
1126
			globalResourceToCompare = fileResource;
E
Erich Gamma 已提交
1127

1128 1129 1130 1131
			// Pick another entry from history
			interface IHistoryPickEntry extends IFilePickOpenEntry {
				input: IEditorInput | IResourceInput;
			}
E
Erich Gamma 已提交
1132

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
			const history = this.historyService.getHistory();
			const picks: IHistoryPickEntry[] = history.map(input => {
				let resource: URI;
				let label: string;
				let description: string;

				if (input instanceof EditorInput) {
					return void 0; // only files supported
				}

				const resourceInput = input as IResourceInput;
				resource = resourceInput.resource;
				label = paths.basename(resourceInput.resource.fsPath);
				description = labels.getPathLabel(paths.dirname(resource.fsPath), this.contextService);
E
Erich Gamma 已提交
1147

1148 1149 1150 1151 1152 1153 1154
				return <IHistoryPickEntry>{ input, resource, label, description };
			}).filter(p => !!p);

			return this.quickOpenService.pick(picks, { placeHolder: nls.localize('pickHistory', "Select an editor history entry to compare with"), autoFocus: { autoFocusFirstEntry: true }, matchOnDescription: true }).then(pick => {
				if (pick) {
					const compareAction = this.instantiationService.createInstance(CompareResourcesAction, pick.resource, null);
					if (compareAction._isEnabled()) {
E
Erich Gamma 已提交
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
						compareAction.run().done(() => compareAction.dispose());
					} else {
						this.messageService.show(Severity.Info, nls.localize('unableToFileToCompare', "The selected file can not be compared with '{0}'.", paths.basename(globalResourceToCompare.fsPath)));
					}
				}
			});
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1165
		return TPromise.as(true);
E
Erich Gamma 已提交
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
	}
}

// Compare with Resource
export class CompareResourcesAction extends Action {
	private tree: ITree;
	private resource: URI;

	constructor(
		resource: URI,
		tree: ITree,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
	) {
		super('workbench.files.action.compareFiles', CompareResourcesAction.computeLabel());

		this.tree = tree;
		this.resource = resource;
	}

	private static computeLabel(): string {
		if (globalResourceToCompare) {
			return nls.localize('compareWith', "Compare with '{0}'", paths.basename(globalResourceToCompare.fsPath));
		}

		return nls.localize('compareFiles', "Compare Files");
	}

	public getLabel(): string {
		return CompareResourcesAction.computeLabel();
	}

	_isEnabled(): boolean {

		// Need at least a resource to compare
		if (!globalResourceToCompare) {
			return false;
		}

		// Check if file was deleted or moved meanwhile (explorer only)
		if (this.tree) {
1206
			const root: FileStat = this.tree.getInput();
E
Erich Gamma 已提交
1207
			if (root instanceof FileStat) {
1208
				const exists = root.find(globalResourceToCompare);
E
Erich Gamma 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
				if (!exists) {
					globalResourceToCompare = null;
					return false;
				}
			}
		}

		// Check if target is identical to source
		if (this.resource.toString() === globalResourceToCompare.toString()) {
			return false;
		}

		return true;
	}

1224
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1225 1226 1227 1228 1229 1230

		// Remove highlight
		if (this.tree) {
			this.tree.clearHighlight();
		}

1231 1232
		return this.editorService.openEditor({
			leftResource: globalResourceToCompare,
1233
			rightResource: this.resource
1234
		});
E
Erich Gamma 已提交
1235 1236 1237 1238 1239 1240
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1241
	constructor(explorerView: ExplorerView, clazz: string) {
B
Benjamin Pasero 已提交
1242
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	}
}

export abstract class BaseActionWithErrorReporting extends Action {
	constructor(
		id: string,
		label: string,
		private messageService: IMessageService
	) {
		super(id, label);
	}

1255 1256
	public run(context?: any): TPromise<boolean> {
		return this.doRun(context).then(() => true, (error) => {
1257
			this.messageService.show(Severity.Error, toErrorMessage(error, false));
E
Erich Gamma 已提交
1258 1259 1260
		});
	}

1261
	protected abstract doRun(context?: any): TPromise<boolean>;
E
Erich Gamma 已提交
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
}

export abstract class BaseSaveFileAction extends BaseActionWithErrorReporting {
	private resource: URI;

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IMessageService messageService: IMessageService
	) {
		super(id, label, messageService);

		this.enabled = true;
	}

	public abstract isSaveAs(): boolean;

	public setResource(resource: URI): void {
		this.resource = resource;
	}

1286
	protected doRun(context: any): TPromise<boolean> {
E
Erich Gamma 已提交
1287 1288 1289 1290
		let source: URI;
		if (this.resource) {
			source = this.resource;
		} else {
1291
			source = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: ['file', 'untitled'] });
E
Erich Gamma 已提交
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		}

		if (source) {

			// Save As (or Save untitled with associated path)
			if (this.isSaveAs() || source.scheme === 'untitled') {
				let encodingOfSource: string;
				if (source.scheme === 'untitled') {
					encodingOfSource = this.untitledEditorService.get(source).getEncoding();
				} else if (source.scheme === 'file') {
1302
					const textModel = this.textFileService.models.get(source);
E
Erich Gamma 已提交
1303 1304 1305
					encodingOfSource = textModel && textModel.getEncoding(); // text model can be null e.g. if this is a binary file!
				}

1306
				let selectionOfSource: Selection;
1307
				const activeEditor = this.editorService.getActiveEditor();
S
Sandeep Somavarapu 已提交
1308 1309
				const editor = getCodeEditor(activeEditor);
				if (editor) {
1310
					const activeResource = toResource(activeEditor.input, { supportSideBySide: true, filter: ['file', 'untitled'] });
1311
					if (activeResource && activeResource.toString() === source.toString()) {
S
Sandeep Somavarapu 已提交
1312
						selectionOfSource = <Selection>editor.getSelection();
1313 1314 1315
					}
				}

E
Erich Gamma 已提交
1316
				// Special case: an untitled file with associated path gets saved directly unless "saveAs" is true
1317
				let savePromise: TPromise<URI>;
E
Erich Gamma 已提交
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
				if (!this.isSaveAs() && source.scheme === 'untitled' && this.untitledEditorService.hasAssociatedFilePath(source)) {
					savePromise = this.textFileService.save(source).then((result) => {
						if (result) {
							return URI.file(source.fsPath);
						}

						return null;
					});
				}

				// Otherwise, really "Save As..."
				else {
					savePromise = this.textFileService.saveAs(source);
				}

				return savePromise.then((target) => {
1334 1335
					if (!target || target.toString() === source.toString()) {
						return; // save canceled or same resource used
E
Erich Gamma 已提交
1336 1337
					}

1338 1339 1340 1341 1342 1343
					const replaceWith: IResourceInput = {
						resource: target,
						encoding: encodingOfSource,
						options: {
							pinned: true,
							selection: selectionOfSource
1344
						}
1345
					};
1346

1347 1348 1349 1350
					return this.editorService.replaceEditors([{
						toReplace: { resource: source },
						replaceWith: replaceWith
					}]).then(() => true);
E
Erich Gamma 已提交
1351 1352 1353 1354
				});
			}

			// Just save
J
Johannes Rieken 已提交
1355
			return this.textFileService.save(source, { force: true /* force a change to the file to trigger external watchers if any */ });
E
Erich Gamma 已提交
1356 1357
		}

A
Alex Dima 已提交
1358
		return TPromise.as(false);
E
Erich Gamma 已提交
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
	}
}

export class SaveFileAction extends BaseSaveFileAction {

	public static ID = 'workbench.action.files.save';
	public static LABEL = nls.localize('save', "Save");

	public isSaveAs(): boolean {
		return false;
	}
}

export class SaveFileAsAction extends BaseSaveFileAction {

	public static ID = 'workbench.action.files.saveAs';
1375
	public static LABEL = nls.localize('saveAs', "Save As...");
E
Erich Gamma 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388

	public isSaveAs(): boolean {
		return true;
	}
}

export abstract class BaseSaveAllAction extends BaseActionWithErrorReporting {
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
1389
		@IWorkbenchEditorService protected editorService: IWorkbenchEditorService,
1390
		@IEditorGroupService private editorGroupService: IEditorGroupService,
E
Erich Gamma 已提交
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IMessageService messageService: IMessageService
	) {
		super(id, label, messageService);

		this.toDispose = [];
		this.lastIsDirty = this.textFileService.isDirty();
		this.enabled = this.lastIsDirty;

		this.registerListeners();
	}

1404
	protected abstract getSaveAllArguments(context?: any): any;
E
Erich Gamma 已提交
1405 1406 1407 1408 1409
	protected abstract includeUntitled(): boolean;

	private registerListeners(): void {

		// listen to files being changed locally
1410 1411 1412 1413
		this.toDispose.push(this.textFileService.models.onModelsDirty(e => this.updateEnablement(true)));
		this.toDispose.push(this.textFileService.models.onModelsSaved(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelsReverted(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelsSaveError(e => this.updateEnablement(true)));
E
Erich Gamma 已提交
1414 1415

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1416
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
		}
	}

	private updateEnablement(isDirty: boolean): void {
		if (this.lastIsDirty !== isDirty) {
			this.enabled = this.textFileService.isDirty();
			this.lastIsDirty = this.enabled;
		}
	}

1427
	protected doRun(context: any): TPromise<boolean> {
1428
		const stacks = this.editorGroupService.getStacksModel();
E
Erich Gamma 已提交
1429

1430
		// Store some properties per untitled file to restore later after save is completed
1431
		const mapUntitledToProperties: { [resource: string]: { encoding: string; indexInGroups: number[]; activeInGroups: boolean[] } } = Object.create(null);
1432
		this.textFileService.getDirty()
1433
			.filter(r => r.scheme === 'untitled')			// All untitled resources
1434
			.map(r => this.untitledEditorService.get(r))	// Mapped to their inputs
B
Benjamin Pasero 已提交
1435 1436 1437 1438 1439 1440 1441
			.filter(input => !!input)								// If possible :)
			.forEach(input => {
				mapUntitledToProperties[input.getResource().toString()] = {
					encoding: input.getEncoding(),
					indexInGroups: stacks.groups.map(g => g.indexOf(input)),
					activeInGroups: stacks.groups.map(g => g.isActive(input))
				};
1442
			});
1443

E
Erich Gamma 已提交
1444
		// Save all
1445 1446 1447
		return this.textFileService.saveAll(this.getSaveAllArguments(context)).then(results => {

			// Reopen saved untitled editors
B
Benjamin Pasero 已提交
1448
			const untitledToReopen: { input: IResourceInput, position: Position }[] = [];
E
Erich Gamma 已提交
1449

1450
			results.results.forEach(result => {
B
Benjamin Pasero 已提交
1451
				if (!result.success || result.source.scheme !== 'untitled') {
1452
					return;
1453
				}
E
Erich Gamma 已提交
1454

B
Benjamin Pasero 已提交
1455 1456 1457 1458
				const untitledProps = mapUntitledToProperties[result.source.toString()];
				if (!untitledProps) {
					return;
				}
1459

B
Benjamin Pasero 已提交
1460 1461
				// For each position where the untitled file was opened
				untitledProps.indexInGroups.forEach((indexInGroup, index) => {
1462
					if (indexInGroup >= 0) {
B
Benjamin Pasero 已提交
1463
						untitledToReopen.push({
1464 1465
							input: {
								resource: result.target,
B
Benjamin Pasero 已提交
1466
								encoding: untitledProps.encoding,
1467 1468 1469
								options: {
									pinned: true,
									index: indexInGroup,
B
Benjamin Pasero 已提交
1470 1471
									preserveFocus: true,
									inactive: !untitledProps.activeInGroups[index]
1472 1473 1474 1475
								}
							},
							position: index
						});
E
Erich Gamma 已提交
1476
					}
1477 1478 1479
				});
			});

B
Benjamin Pasero 已提交
1480 1481 1482
			if (untitledToReopen.length) {
				return this.editorService.openEditors(untitledToReopen).then(() => true);
			}
E
Erich Gamma 已提交
1483 1484 1485 1486
		});
	}

	public dispose(): void {
J
Joao Moreno 已提交
1487
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

	public static ID = 'workbench.action.files.saveAll';
	public static LABEL = nls.localize('saveAll', "Save All");

	public get class(): string {
		return 'explorer-action save-all';
	}

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveAllInGroupAction extends BaseSaveAllAction {

	public static ID = 'workbench.files.action.saveAllInGroup';
	public static LABEL = nls.localize('saveAllInGroup', "Save All in Group");

	public get class(): string {
		return 'explorer-action save-all';
	}

I
isidor 已提交
1520 1521
	protected getSaveAllArguments(editorIdentifier: IEditorIdentifier): any {
		if (!editorIdentifier) {
1522 1523 1524
			return this.includeUntitled();
		}

I
isidor 已提交
1525
		const editorGroup = editorIdentifier.group;
B
Benjamin Pasero 已提交
1526
		const resourcesToSave: URI[] = [];
1527
		editorGroup.getEditors().forEach(editor => {
1528
			const resource = toResource(editor, { supportSideBySide: true, filter: ['file', 'untitled'] });
1529 1530
			if (resource) {
				resourcesToSave.push(resource);
1531 1532 1533 1534 1535 1536
			}
		});

		return resourcesToSave;
	}

E
Erich Gamma 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveFilesAction extends BaseSaveAllAction {

	public static ID = 'workbench.action.files.saveFiles';
	public static LABEL = nls.localize('saveFiles', "Save Dirty Files");

1547 1548 1549 1550
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

E
Erich Gamma 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
	protected includeUntitled(): boolean {
		return false;
	}
}

export class RevertFileAction extends Action {

	public static ID = 'workbench.action.files.revert';
	public static LABEL = nls.localize('revert', "Revert File");

	private resource: URI;

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService
	) {
		super(id, label);

		this.enabled = true;
	}

	public setResource(resource: URI): void {
		this.resource = resource;
	}

1578
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1579 1580 1581 1582
		let resource: URI;
		if (this.resource) {
			resource = this.resource;
		} else {
1583
			resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
E
Erich Gamma 已提交
1584 1585 1586 1587 1588 1589
		}

		if (resource && resource.scheme !== 'untitled') {
			return this.textFileService.revert(resource, true /* force */);
		}

A
Alex Dima 已提交
1590
		return TPromise.as(true);
E
Erich Gamma 已提交
1591 1592 1593
	}
}

1594
export class FocusOpenEditorsView extends Action {
1595

1596
	public static ID = 'workbench.files.action.focusOpenEditorsView';
I
isidor 已提交
1597
	public static LABEL = nls.localize({ key: 'focusOpenEditors', comment: ['Open is an adjective'] }, "Focus on Open Editors View");
1598 1599 1600 1601 1602 1603 1604 1605 1606

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

1607
	public run(): TPromise<any> {
1608
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1609 1610 1611 1612 1613
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
				openEditorsView.expand();
				openEditorsView.getViewer().DOMFocus();
			}
1614 1615 1616 1617
		});
	}
}

1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
export class FocusFilesExplorer extends Action {

	public static ID = 'workbench.files.action.focusFilesExplorer';
	public static LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1632
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1633 1634 1635 1636 1637 1638 1639 1640 1641
			const view = viewlet.getExplorerView();
			if (view) {
				view.expand();
				view.getViewer().DOMFocus();
			}
		});
	}
}

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
export class ShowActiveFileInExplorer extends Action {

	public static ID = 'workbench.files.action.showActiveFileInExplorer';
	public static LABEL = nls.localize('showInExplorer', "Show Active File in Explorer");

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IViewletService private viewletService: IViewletService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IMessageService private messageService: IMessageService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1659 1660
		const fileResource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
		if (fileResource) {
1661
			return this.viewletService.openViewlet(VIEWLET_ID, false).then((viewlet: ExplorerViewlet) => {
1662
				const isInsideWorkspace = this.contextService.isInsideWorkspace(fileResource);
1663 1664 1665 1666
				if (isInsideWorkspace) {
					const explorerView = viewlet.getExplorerView();
					if (explorerView) {
						explorerView.expand();
1667
						explorerView.select(fileResource, true);
1668 1669
					}
				} else {
I
isidor 已提交
1670
					const openEditorsView = viewlet.getOpenEditorsView();
I
isidor 已提交
1671 1672 1673
					if (openEditorsView) {
						openEditorsView.expand();
					}
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
				}
			});
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1684 1685
export class CollapseExplorerView extends Action {

B
Benjamin Pasero 已提交
1686
	public static ID = 'workbench.files.action.collapseExplorerFolders';
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
	public static LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			const explorerView = viewlet.getExplorerView();
			if (explorerView) {
				const viewer = explorerView.getViewer();
				if (viewer) {
					const action = new CollapseAction(viewer, true, null);
					action.run().done();
					action.dispose();
				}
			}
		});
	}
}

export class RefreshExplorerView extends Action {

B
Benjamin Pasero 已提交
1714
	public static ID = 'workbench.files.action.refreshFilesExplorer';
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
	public static LABEL = nls.localize('refreshExplorer', "Refresh Explorer");

	constructor(
		id: string,
		label: string,
		@IViewletService private viewletService: IViewletService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			const explorerView = viewlet.getExplorerView();
			if (explorerView) {
				explorerView.refresh();
			}
		});
	}
}

1735
export function keybindingForAction(id: string, keybindingService: IKeybindingService): Keybinding {
E
Erich Gamma 已提交
1736
	switch (id) {
1737
		case GlobalNewUntitledFileAction.ID:
E
Erich Gamma 已提交
1738 1739 1740 1741 1742 1743
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_N);
		case TriggerRenameFileAction.ID:
			return new Keybinding(isMacintosh ? KeyCode.Enter : KeyCode.F2);
		case SaveFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_S);
		case MoveFileToTrashAction.ID:
1744
			return new Keybinding(isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete);
E
Erich Gamma 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
		case CopyFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_C);
		case PasteFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_V);
		case OpenToSideAction.ID:
			if (isMacintosh) {
				return new Keybinding(KeyMod.WinCtrl | KeyCode.Enter);
			} else {
				return new Keybinding(KeyMod.CtrlCmd | KeyCode.Enter);
			}
	}

B
Benjamin Pasero 已提交
1757 1758 1759 1760 1761 1762 1763
	if (keybindingService) {
		const keys = keybindingService.lookupKeybindings(id);
		if (keys.length > 0) {
			return keys[0]; // only take the first one
		}
	}

E
Erich Gamma 已提交
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
	return null;
}

export function validateFileName(parent: IFileStat, name: string, allowOverwriting: boolean = false): string {

	// Produce a well formed file name
	name = getWellFormedFileName(name);

	// Name not provided
	if (!name || name.length === 0 || /^\s+$/.test(name)) {
		return nls.localize('emptyFileNameError', "A file or folder name must be provided.");
	}

	// Do not allow to overwrite existing file
	if (!allowOverwriting) {
		if (parent.children && parent.children.some((c) => {
			if (isLinux) {
				return c.name === name;
			}

			return c.name.toLowerCase() === name.toLowerCase();
		})) {
			return nls.localize('fileNameExistsError', "A file or folder **{0}** already exists at this location. Please choose a different name.", name);
		}
	}

1790 1791 1792
	// Invalid File name
	if (!paths.isValidBasename(name)) {
		return nls.localize('invalidFileNameError', "The name **{0}** is not valid as a file or folder name. Please choose a different name.", name);
E
Erich Gamma 已提交
1793 1794 1795 1796
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1797
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
		if (fullPathLength > 255) {
			return nls.localize('filePathTooLongError', "The name **{0}** results in a path that is too long. Please choose a shorter name.", name);
		}
	}

	return null;
}

export function getWellFormedFileName(filename: string): string {
	if (!filename) {
		return filename;
	}

	// Trim whitespaces
	filename = strings.trim(strings.trim(filename, ' '), '\t');

	// Remove trailing dots
	filename = strings.rtrim(filename, '.');

	return filename;
}

// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
1823
	diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
E
Erich Gamma 已提交
1824 1825
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
J
Johannes Rieken 已提交
1826
}