fileActions.ts 53.4 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');
I
isidor 已提交
11
import { isWindows, isLinux } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
12
import { sequence, ITask, always } from 'vs/base/common/async';
E
Erich Gamma 已提交
13
import paths = require('vs/base/common/paths');
I
isidor 已提交
14
import resources = require('vs/base/common/resources');
E
Erich Gamma 已提交
15 16
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
17
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
18
import strings = require('vs/base/common/strings');
19
import severity from 'vs/base/common/severity';
E
Erich Gamma 已提交
20
import diagnostics = require('vs/base/common/diagnostics');
J
Johannes Rieken 已提交
21 22
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
23
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
J
Johannes Rieken 已提交
24
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
25
import { VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
26
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
27
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
I
isidor 已提交
28
import { toResource } from 'vs/workbench/common/editor';
29
import { FileStat, Model, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerModel';
30 31
import { ExplorerView } from 'vs/workbench/parts/files/electron-browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/electron-browser/explorerViewlet';
J
Johannes Rieken 已提交
32 33 34 35
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';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
B
Benjamin Pasero 已提交
36
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
B
Benjamin Pasero 已提交
37
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
38
import { IUntitledResourceInput } from 'vs/platform/editor/common/editor';
39
import { IInstantiationService, IConstructorSignature2, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
I
isidor 已提交
40
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction, IConfirmationResult, getConfirmMessage } from 'vs/platform/message/common/message';
A
Alex Dima 已提交
41
import { ITextModel } from 'vs/editor/common/model';
42
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
43
import { IWindowsService } from 'vs/platform/windows/common/windows';
I
isidor 已提交
44
import { COPY_PATH_COMMAND_ID, REVEAL_IN_EXPLORER_COMMAND_ID, SAVE_ALL_COMMAND_ID, SAVE_ALL_LABEL, SAVE_ALL_IN_GROUP_COMMAND_ID } from 'vs/workbench/parts/files/electron-browser/fileCommands';
M
Max Furman 已提交
45
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
46
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
47
import { once } from 'vs/base/common/event';
M
Max Furman 已提交
48 49 50
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
I
isidor 已提交
51
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
I
isidor 已提交
52
import { IListService, ListWidget } from 'vs/platform/list/browser/listService';
53 54
import { RawContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { distinctParents, basenameOrAuthority } from 'vs/base/common/resources';
M
Max Furman 已提交
55

E
Erich Gamma 已提交
56 57 58 59 60 61 62 63 64 65 66
export interface IEditableData {
	action: IAction;
	validator: IInputValidator;
}

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

I
isidor 已提交
67
export const NEW_FILE_COMMAND_ID = 'explorer.newFile';
I
isidor 已提交
68 69
export const NEW_FILE_LABEL = nls.localize('newFile', "New File");

I
isidor 已提交
70
export const NEW_FOLDER_COMMAND_ID = 'explorer.newFolder';
I
isidor 已提交
71 72
export const NEW_FOLDER_LABEL = nls.localize('newFolder', "New Folder");

I
isidor 已提交
73 74
export const TRIGGER_RENAME_LABEL = nls.localize('rename', "Rename");

I
isidor 已提交
75 76
export const MOVE_FILE_TO_TRASH_LABEL = nls.localize('delete', "Delete");

I
isidor 已提交
77 78 79 80 81 82
export const COPY_FILE_LABEL = nls.localize('copyFile', "Copy");

export const PASTE_FILE_LABEL = nls.localize('pasteFile', "Paste");

export const FileCopiedContext = new RawContextKey<boolean>('fileCopied', false);

83
export class BaseErrorReportingAction extends Action {
E
Erich Gamma 已提交
84 85 86 87

	constructor(
		id: string,
		label: string,
88
		private _messageService: IMessageService
E
Erich Gamma 已提交
89 90 91 92 93 94 95 96
	) {
		super(id, label);
	}

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

97
	protected onError(error: any): void {
98 99
		if (error.message === 'string') {
			error = error.message;
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
		}

		this._messageService.show(Severity.Error, toErrorMessage(error, false));
	}

	protected onErrorWithRetry(error: any, retry: () => TPromise<any>, extraAction?: Action): void {
		const actions = [
			new Action(this.id, nls.localize('retry', "Retry"), null, true, () => retry()),
			CancelAction
		];

		if (extraAction) {
			actions.unshift(extraAction);
		}

		const errorWithRetry: IMessageWithAction = {
			actions,
			message: toErrorMessage(error, false)
		};

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

export class BaseFileAction extends BaseErrorReportingAction {
I
isidor 已提交
125
	public element: FileStat;
126 127 128 129

	constructor(
		id: string,
		label: string,
I
isidor 已提交
130
		@IFileService protected fileService: IFileService,
131
		@IMessageService _messageService: IMessageService,
I
isidor 已提交
132
		@ITextFileService protected textFileService: ITextFileService
133 134 135 136 137 138
	) {
		super(id, label, _messageService);

		this.enabled = false;
	}

E
Erich Gamma 已提交
139 140 141 142 143
	_isEnabled(): boolean {
		return true;
	}

	_updateEnablement(): void {
I
isidor 已提交
144
		this.enabled = !!(this.fileService && this._isEnabled());
E
Erich Gamma 已提交
145 146 147
	}
}

I
isidor 已提交
148
class TriggerRenameFileAction extends BaseFileAction {
E
Erich Gamma 已提交
149

M
Matt Bierner 已提交
150
	public static readonly ID = 'renameFile';
E
Erich Gamma 已提交
151 152 153 154 155 156 157 158 159 160 161 162

	private tree: ITree;
	private renameAction: BaseRenameAction;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
I
isidor 已提交
163
		super(TriggerRenameFileAction.ID, TRIGGER_RENAME_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
164 165 166 167 168 169 170 171 172 173 174

		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);
	}

175
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
176
		if (!context) {
177
			return TPromise.wrapError(new Error('No context provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
178 179
		}

180
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
181
		if (!viewletState) {
182
			return TPromise.wrapError(new Error('Invalid viewlet state provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
183 184
		}

185
		const stat = <IFileStat>context.stat;
E
Erich Gamma 已提交
186
		if (!stat) {
187
			return TPromise.wrapError(new Error('Invalid stat provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
188 189 190 191 192
		}

		viewletState.setEditable(stat, {
			action: this.renameAction,
			validator: (value) => {
193
				const message = this.validateFileName(this.element.parent, value);
E
Erich Gamma 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

				if (!message) {
					return null;
				}

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

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

210
			const unbind = this.tree.onDidChangeHighlight((e: IHighlightEvent) => {
E
Erich Gamma 已提交
211 212 213
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
214
					unbind.dispose();
E
Erich Gamma 已提交
215 216 217
				}
			});
		}).done(null, errors.onUnexpectedError);
M
Matt Bierner 已提交
218

219
		return void 0;
E
Erich Gamma 已提交
220 221 222 223 224 225 226 227 228 229 230
	}
}

export abstract class BaseRenameAction extends BaseFileAction {

	constructor(
		id: string,
		label: string,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
231
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
232
	) {
B
Benjamin Pasero 已提交
233
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
234 235 236 237

		this.element = element;
	}

238
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
239
		if (!context) {
240
			return TPromise.wrapError(new Error('No context provided to BaseRenameFileAction.'));
E
Erich Gamma 已提交
241 242 243 244
		}

		let name = <string>context.value;
		if (!name) {
245
			return TPromise.wrapError(new Error('No new name provided to BaseRenameFileAction.'));
E
Erich Gamma 已提交
246 247 248 249
		}

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

252
		// Return early if name is invalid or didn't change
E
Erich Gamma 已提交
253
		if (name === existingName || this.validateFileName(this.element.parent, name)) {
A
Alex Dima 已提交
254
			return TPromise.as(null);
E
Erich Gamma 已提交
255 256 257
		}

		// Call function and Emit Event through viewer
258
		const promise = this.runAction(name).then(null, (error: any) => {
E
Erich Gamma 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
			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);
	}

281
	public abstract runAction(newName: string): TPromise<any>;
E
Erich Gamma 已提交
282 283
}

284
class RenameFileAction extends BaseRenameAction {
E
Erich Gamma 已提交
285

M
Matt Bierner 已提交
286
	public static readonly ID = 'workbench.files.action.renameFile';
E
Erich Gamma 已提交
287 288 289 290 291

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
292 293
		@ITextFileService textFileService: ITextFileService,
		@IBackupFileService private backupFileService: IBackupFileService
E
Erich Gamma 已提交
294
	) {
B
Benjamin Pasero 已提交
295
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, fileService, messageService, textFileService);
E
Erich Gamma 已提交
296 297 298 299

		this._updateEnablement();
	}

300
	public runAction(newName: string): TPromise<any> {
I
isidor 已提交
301
		const dirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, this.element.resource, !isLinux /* ignorecase */));
302 303
		const dirtyRenamed: URI[] = [];
		return TPromise.join(dirty.map(d => {
304 305 306
			let renamed: URI;

			// If the dirty file itself got moved, just reparent it to the target folder
B
Benjamin Pasero 已提交
307
			const targetPath = paths.join(this.element.parent.resource.path, newName);
I
isidor 已提交
308
			if (this.element.resource.toString() === d.toString()) {
B
Benjamin Pasero 已提交
309
				renamed = this.element.parent.resource.with({ path: targetPath });
E
Erich Gamma 已提交
310 311
			}

312 313
			// Otherwise, a parent of the dirty resource got moved, so we have to reparent more complicated. Example:
			else {
B
Benjamin Pasero 已提交
314
				renamed = this.element.parent.resource.with({ path: paths.join(targetPath, d.path.substr(this.element.resource.path.length + 1)) });
E
Erich Gamma 已提交
315 316
			}

317
			dirtyRenamed.push(renamed);
318

319
			const model = this.textFileService.models.get(d);
320

321
			return this.backupFileService.backupResource(renamed, model.createSnapshot(), model.getVersionId());
322 323 324 325 326 327 328 329 330 331 332 333 334 335
		}))

			// 2. soft revert all dirty since we have backed up their contents
			.then(() => this.textFileService.revertAll(dirty, { soft: true /* do not attempt to load content from disk */ }))

			// 3.) run the rename operation
			.then(() => this.fileService.rename(this.element.resource, newName).then(null, (error: Error) => {
				return TPromise.join(dirtyRenamed.map(d => this.backupFileService.discardResourceBackup(d))).then(() => {
					this.onErrorWithRetry(error, () => this.runAction(newName));
				});
			}))

			// 4.) resolve those that were dirty to load their previous dirty contents from disk
			.then(() => {
336
				return TPromise.join(dirtyRenamed.map(t => this.textFileService.models.loadOrCreate(t)));
E
Erich Gamma 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
			});
	}
}

/* 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,
357
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
358
	) {
B
Benjamin Pasero 已提交
359
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
360 361 362 363 364 365 366 367 368 369

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

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

370
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
371
		if (!context) {
372
			return TPromise.wrapError(new Error('No context provided to BaseNewAction.'));
E
Erich Gamma 已提交
373 374
		}

375
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
376
		if (!viewletState) {
377
			return TPromise.wrapError(new Error('Invalid viewlet state provided to BaseNewAction.'));
E
Erich Gamma 已提交
378 379
		}

I
isidor 已提交
380
		let folder = this.presetFolder;
E
Erich Gamma 已提交
381
		if (!folder) {
382
			const focus = <FileStat>this.tree.getFocus();
E
Erich Gamma 已提交
383 384 385
			if (focus) {
				folder = focus.isDirectory ? focus : focus.parent;
			} else {
I
isidor 已提交
386
				const input: FileStat | Model = this.tree.getInput();
387
				folder = input instanceof Model ? input.roots[0] : input;
E
Erich Gamma 已提交
388 389 390 391
			}
		}

		if (!folder) {
392
			return TPromise.wrapError(new Error('Invalid parent folder to create.'));
E
Erich Gamma 已提交
393 394 395 396
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
397
				const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);
E
Erich Gamma 已提交
398 399 400 401 402 403

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
404
						const message = this.renameAction.validateFileName(folder, value);
E
Erich Gamma 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

						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);

423
							const unbind = this.tree.onDidChangeHighlight((e: IHighlightEvent) => {
E
Erich Gamma 已提交
424 425 426
								if (!e.highlight) {
									stat.destroy();
									this.tree.refresh(folder).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
427
									unbind.dispose();
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
								}
							});
						});
					});
				});
			});
		});
	}
}

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

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
I
isidor 已提交
449
		super('explorer.newFile', NEW_FILE_LABEL, tree, true, instantiationService.createInstance(CreateFileAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

		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
	) {
I
isidor 已提交
467
		super('explorer.newFolder', NEW_FOLDER_LABEL, tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480

		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 已提交
481 482
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
483 484 485 486
	) {
		super(id, label);
	}

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

492 493
				const explorer = <ExplorerViewlet>viewlet;
				const explorerView = explorer.getExplorerView();
E
Erich Gamma 已提交
494

B
fix npe  
Benjamin Pasero 已提交
495 496 497 498 499
				// 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 已提交
500
				if (!explorerView.isExpanded()) {
501
					explorerView.setExpanded(true);
E
Erich Gamma 已提交
502 503
				}

504
				const action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);
E
Erich Gamma 已提交
505 506 507 508 509 510

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

511
	protected abstract getAction(): IConstructorSignature2<ITree, IFileStat, Action>;
E
Erich Gamma 已提交
512 513 514 515 516 517 518 519 520 521 522 523

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

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

/* Create new file from anywhere: Open untitled */
524
export class GlobalNewUntitledFileAction extends Action {
M
Matt Bierner 已提交
525 526
	public static readonly ID = 'workbench.action.files.newUntitledFile';
	public static readonly LABEL = nls.localize('newUntitledFile', "New Untitled File");
E
Erich Gamma 已提交
527 528 529 530

	constructor(
		id: string,
		label: string,
531
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
E
Erich Gamma 已提交
532 533 534 535
	) {
		super(id, label);
	}

536
	public run(): TPromise<any> {
537
		return this.editorService.openEditor({ options: { pinned: true } } as IUntitledResourceInput); // untitled are always pinned
E
Erich Gamma 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
	}
}

/* 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) */
554
class CreateFileAction extends BaseCreateAction {
E
Erich Gamma 已提交
555

M
Matt Bierner 已提交
556 557
	public static readonly ID = 'workbench.files.action.createFileFromExplorer';
	public static readonly LABEL = nls.localize('createNewFile', "New File");
E
Erich Gamma 已提交
558 559 560 561

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
562
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
563
		@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 573
		const resource = this.element.parent.resource;
		return this.fileService.createFile(resource.with({ path: paths.join(resource.path, fileName) })).then(stat => {
574 575
			return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
		}, (error) => {
E
Erich Gamma 已提交
576 577 578 579 580 581
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

/* Create New Folder (only used internally by explorerViewer) */
582
class CreateFolderAction extends BaseCreateAction {
E
Erich Gamma 已提交
583

M
Matt Bierner 已提交
584 585
	public static readonly ID = 'workbench.files.action.createFolderFromExplorer';
	public static readonly LABEL = nls.localize('createNewFolder', "New Folder");
E
Erich Gamma 已提交
586 587 588 589 590

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

		this._updateEnablement();
	}

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

I
isidor 已提交
606
class BaseDeleteFileAction extends BaseFileAction {
607

608
	private static readonly CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';
609

610
	private skipConfirm: boolean;
E
Erich Gamma 已提交
611 612

	constructor(
613
		private tree: ITree,
614
		private elements: FileStat[],
615
		private useTrash: boolean,
E
Erich Gamma 已提交
616 617
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
618
		@ITextFileService textFileService: ITextFileService,
619
		@IConfigurationService private configurationService: IConfigurationService
E
Erich Gamma 已提交
620
	) {
I
isidor 已提交
621
		super('moveFileToTrash', MOVE_FILE_TO_TRASH_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
622 623

		this.tree = tree;
624
		this.useTrash = useTrash && elements.every(e => !paths.isUNC(e.resource.fsPath)); // on UNC shares there is no trash
E
Erich Gamma 已提交
625 626 627 628

		this._updateEnablement();
	}

629
	public run(): TPromise<any> {
E
Erich Gamma 已提交
630 631 632 633 634 635

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

636 637 638 639 640 641 642
		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");
		}

643 644
		const distinctElements = distinctParents(this.elements, e => e.resource);

645
		// Handle dirty
646
		let confirmDirtyPromise: TPromise<boolean> = TPromise.as(true);
647
		const dirty = this.textFileService.getDirty().filter(d => distinctElements.some(e => resources.isEqualOrParent(d, e.resource, !isLinux /* ignorecase */)));
648 649
		if (dirty.length) {
			let message: string;
650
			if (distinctElements.length > 1) {
651
				message = nls.localize('dirtyMessageFilesDelete', "You are deleting files with unsaved changes. Do you want to continue?");
652
			} else if (distinctElements[0].isDirectory) {
653 654 655 656 657
				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);
				}
658
			} else {
659
				message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
660
			}
E
Erich Gamma 已提交
661

662
			confirmDirtyPromise = this.messageService.confirm({
663 664 665 666
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
667 668 669 670
			}).then(confirmed => {
				if (!confirmed) {
					return false;
				}
671

672 673 674
				this.skipConfirm = true; // since we already asked for confirmation
				return this.textFileService.revertAll(dirty).then(() => true);
			});
E
Erich Gamma 已提交
675 676
		}

677
		// Check if file is dirty in editor and save it to avoid data loss
678 679 680 681 682 683
		return confirmDirtyPromise.then(confirmed => {
			if (!confirmed) {
				return null;
			}

			let confirmDeletePromise: TPromise<IConfirmationResult>;
684

685
			// Check if we need to ask for confirmation at all
S
Sandeep Somavarapu 已提交
686
			if (this.skipConfirm || (this.useTrash && this.configurationService.getValue<boolean>(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY) === false)) {
687
				confirmDeletePromise = TPromise.as({ confirmed: true } as IConfirmationResult);
688
			}
B
Benjamin Pasero 已提交
689

690 691
			// Confirm for moving to trash
			else if (this.useTrash) {
692 693 694
				const message = distinctElements.length > 1 ? getConfirmMessage(nls.localize('confirmMoveTrashMessageMultiple', "Are you sure you want to delete the following {0} files?", distinctElements.length), distinctElements.map(e => e.resource))
					: distinctElements[0].isDirectory ? nls.localize('confirmMoveTrashMessageFolder', "Are you sure you want to delete '{0}' and its contents?", distinctElements[0].name)
						: nls.localize('confirmMoveTrashMessageFile', "Are you sure you want to delete '{0}'?", distinctElements[0].name);
695
				confirmDeletePromise = this.messageService.confirmWithCheckbox({
696
					message,
697 698 699 700 701 702 703
					detail: isWindows ? nls.localize('undoBin', "You can restore from the recycle bin.") : nls.localize('undoTrash', "You can restore from the trash."),
					primaryButton,
					checkbox: {
						label: nls.localize('doNotAskAgain', "Do not ask me again")
					},
					type: 'question'
				});
E
Erich Gamma 已提交
704 705
			}

706 707
			// Confirm for deleting permanently
			else {
708 709 710
				const message = distinctElements.length > 1 ? getConfirmMessage(nls.localize('confirmDeleteMessageMultiple', "Are you sure you want to permanently delete the following {0} files?", distinctElements.length), distinctElements.map(e => e.resource))
					: distinctElements[0].isDirectory ? nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", distinctElements[0].name)
						: nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", distinctElements[0].name);
711
				confirmDeletePromise = this.messageService.confirmWithCheckbox({
712
					message,
713 714 715 716 717 718
					detail: nls.localize('irreversible', "This action is irreversible!"),
					primaryButton,
					type: 'warning'
				});
			}

719
			return confirmDeletePromise.then(confirmation => {
E
Erich Gamma 已提交
720

721 722
				// Check for confirmation checkbox
				let updateConfirmSettingsPromise: TPromise<void> = TPromise.as(void 0);
723
				if (confirmation.confirmed && confirmation.checkboxChecked === true) {
724
					updateConfirmSettingsPromise = this.configurationService.updateValue(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY, false, ConfigurationTarget.USER);
725
				}
E
Erich Gamma 已提交
726

727
				return updateConfirmSettingsPromise.then(() => {
B
Benjamin Pasero 已提交
728

729 730 731 732 733 734
					// Check for confirmation
					if (!confirmation.confirmed) {
						return TPromise.as(null);
					}

					// Call function
735 736 737
					const servicePromise = TPromise.join(distinctElements.map(e => this.fileService.del(e.resource, this.useTrash))).then(() => {
						if (distinctElements[0].parent) {
							this.tree.setFocus(distinctElements[0].parent); // move focus to parent
738 739
						}
					}, (error: any) => {
740 741 742 743 744

						// 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(); });
745 746
						}

747 748
						this.onErrorWithRetry(error, () => this.run(), extraAction);

749 750 751 752 753 754 755
						// Focus back to tree
						this.tree.DOMFocus();
					});

					return servicePromise;
				});
			});
756
		});
E
Erich Gamma 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769
	}
}

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

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IFileService fileService: IFileService,
770
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
771
		@IMessageService messageService: IMessageService,
772
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
773
	) {
I
isidor 已提交
774
		super('workbench.files.action.importFile', nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
775 776 777 778 779 780 781 782 783 784 785

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

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

		this._updateEnablement();
	}

786
	public run(resources: URI[]): TPromise<any> {
787
		const importPromise = TPromise.as(null).then(() => {
788
			if (resources && resources.length > 0) {
E
Erich Gamma 已提交
789 790 791 792 793 794

				// Find parent for import
				let targetElement: FileStat;
				if (this.element) {
					targetElement = this.element;
				} else {
I
isidor 已提交
795 796
					const input: FileStat | Model = this.tree.getInput();
					targetElement = this.tree.getFocus() || (input instanceof Model ? input.roots[0] : input);
E
Erich Gamma 已提交
797 798 799 800 801 802 803 804 805 806
				}

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

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

					// Check for name collisions
807
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
808 809 810 811
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

812
					let overwritePromise = TPromise.as(true);
813 814
					if (resources.some(resource => {
						return !!targetNames[isLinux ? paths.basename(resource.fsPath) : paths.basename(resource.fsPath).toLowerCase()];
E
Erich Gamma 已提交
815
					})) {
816
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
817 818
							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 已提交
819 820
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
							type: 'warning'
E
Erich Gamma 已提交
821 822
						};

823
						overwritePromise = this.messageService.confirm(confirm);
E
Erich Gamma 已提交
824 825
					}

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
					return overwritePromise.then(overwrite => {
						if (!overwrite) {
							return void 0;
						}

						// Run import in sequence
						const importPromisesFactory: ITask<TPromise<void>>[] = [];
						resources.forEach(resource => {
							importPromisesFactory.push(() => {
								const sourceFile = resource;
								const targetFile = targetElement.resource.with({ path: paths.join(targetElement.resource.path, paths.basename(sourceFile.path)) });

								// if the target exists and is dirty, make sure to revert it. otherwise the dirty contents
								// of the target file would replace the contents of the imported file. since we already
								// confirmed the overwrite before, this is OK.
								let revertPromise = TPromise.wrap(null);
								if (this.textFileService.isDirty(targetFile)) {
									revertPromise = this.textFileService.revertAll([targetFile], { soft: true });
								}
E
Erich Gamma 已提交
845

846 847 848 849 850 851 852 853 854
								return revertPromise.then(() => {
									return this.fileService.importFile(sourceFile, targetElement.resource).then(res => {

										// if we only import one file, just open it directly
										if (resources.length === 1) {
											this.editorService.openEditor({ resource: res.stat.resource, options: { pinned: true } }).done(null, errors.onUnexpectedError);
										}
									}, error => this.onError(error));
								});
E
Erich Gamma 已提交
855 856 857
							});
						});

858 859
						return sequence(importPromisesFactory);
					});
E
Erich Gamma 已提交
860 861
				});
			}
862 863

			return void 0;
E
Erich Gamma 已提交
864 865 866 867 868 869 870 871 872 873 874 875
		});

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

// Copy File/Folder
I
isidor 已提交
876
class CopyFileAction extends BaseFileAction {
E
Erich Gamma 已提交
877 878 879 880

	private tree: ITree;
	constructor(
		tree: ITree,
I
isidor 已提交
881
		private elements: FileStat[],
E
Erich Gamma 已提交
882 883
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
I
isidor 已提交
884
		@ITextFileService textFileService: ITextFileService,
885 886
		@IContextKeyService contextKeyService: IContextKeyService,
		@IClipboardService private clipboardService: IClipboardService
E
Erich Gamma 已提交
887
	) {
I
isidor 已提交
888
		super('filesExplorer.copy', COPY_FILE_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
889 890 891 892 893

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

894
	public run(): TPromise<any> {
E
Erich Gamma 已提交
895

896 897
		// Write to clipboard as file/folder to copy
		this.clipboardService.writeFiles(this.elements.map(e => e.resource));
E
Erich Gamma 已提交
898 899 900 901 902 903 904 905

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

		this.tree.DOMFocus();

A
Alex Dima 已提交
906
		return TPromise.as(null);
E
Erich Gamma 已提交
907 908 909 910
	}
}

// Paste File/Folder
I
isidor 已提交
911
class PasteFileAction extends BaseFileAction {
E
Erich Gamma 已提交
912

M
Matt Bierner 已提交
913
	public static readonly ID = 'filesExplorer.paste';
E
Erich Gamma 已提交
914 915 916 917 918 919 920 921 922

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
923
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
E
Erich Gamma 已提交
924
	) {
I
isidor 已提交
925
		super(PasteFileAction.ID, PASTE_FILE_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
926 927

		this.tree = tree;
I
isidor 已提交
928 929 930 931 932
		this.element = element;
		if (!this.element) {
			const input: FileStat | Model = this.tree.getInput();
			this.element = input instanceof Model ? input.roots[0] : input;
		}
E
Erich Gamma 已提交
933 934 935
		this._updateEnablement();
	}

936
	public run(fileToPaste: URI): TPromise<any> {
E
Erich Gamma 已提交
937 938

		// Check if target is ancestor of pasted folder
939 940
		if (this.element.resource.toString() !== fileToPaste.toString() && resources.isEqualOrParent(this.element.resource, fileToPaste, !isLinux /* ignorecase */)) {
			throw new Error(nls.localize('fileIsAncestor', "File to paste is an ancestor of the destination folder"));
E
Erich Gamma 已提交
941 942
		}

943
		return this.fileService.resolveFile(fileToPaste).then(fileToPasteStat => {
E
Erich Gamma 已提交
944

945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
			// Remove highlight
			if (this.tree) {
				this.tree.clearHighlight();
			}

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

			const targetFile = findValidPasteFileTarget(target, { resource: fileToPaste, isDirectory: fileToPasteStat.isDirectory });

			// Copy File
			return this.fileService.copyFile(fileToPaste, targetFile).then(stat => {
				if (!stat.isDirectory) {
					return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
				}
E
Erich Gamma 已提交
965

966 967 968 969 970 971
				return void 0;
			}, error => this.onError(error)).then(() => {
				this.tree.DOMFocus();
			});
		}, error => {
			this.onError(new Error(nls.localize('fileDeleted', "File to paste was deleted or moved meanwhile")));
E
Erich Gamma 已提交
972 973 974 975 976 977 978
		});
	}
}

// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
	private tree: ITree;
979
	private target: FileStat;
E
Erich Gamma 已提交
980 981 982

	constructor(
		tree: ITree,
983
		fileToDuplicate: FileStat,
E
Erich Gamma 已提交
984 985
		target: FileStat,
		@IFileService fileService: IFileService,
986
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
987
		@IMessageService messageService: IMessageService,
988
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
989
	) {
B
Benjamin Pasero 已提交
990
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
991 992

		this.tree = tree;
993 994
		this.element = fileToDuplicate;
		this.target = (target && target.isDirectory) ? target : fileToDuplicate.parent;
E
Erich Gamma 已提交
995 996 997
		this._updateEnablement();
	}

998
	public run(): TPromise<any> {
E
Erich Gamma 已提交
999 1000 1001 1002 1003 1004

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

1005
		// Copy File
1006
		const result = this.fileService.copyFile(this.element.resource, findValidPasteFileTarget(this.target, { resource: this.element.resource, isDirectory: this.element.isDirectory })).then(stat => {
1007 1008 1009
			if (!stat.isDirectory) {
				return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
			}
1010 1011

			return void 0;
1012
		}, error => this.onError(error));
E
Erich Gamma 已提交
1013 1014 1015

		return result;
	}
1016
}
E
Erich Gamma 已提交
1017

1018 1019
function findValidPasteFileTarget(targetFolder: FileStat, fileToPaste: { resource: URI, isDirectory?: boolean }): URI {
	let name = basenameOrAuthority(fileToPaste.resource);
E
Erich Gamma 已提交
1020

1021 1022 1023 1024
	let candidate = targetFolder.resource.with({ path: paths.join(targetFolder.resource.path, name) });
	while (true) {
		if (!targetFolder.root.find(candidate)) {
			break;
E
Erich Gamma 已提交
1025 1026
		}

1027 1028
		name = incrementFileName(name, fileToPaste.isDirectory);
		candidate = targetFolder.resource.with({ path: paths.join(targetFolder.resource.path, name) });
E
Erich Gamma 已提交
1029 1030
	}

1031 1032
	return candidate;
}
E
Erich Gamma 已提交
1033

1034
function incrementFileName(name: string, isFolder: boolean): string {
E
Erich Gamma 已提交
1035

1036 1037 1038 1039
	// file.1.txt=>file.2.txt
	if (!isFolder && name.match(/(.*\.)(\d+)(\..*)$/)) {
		return name.replace(/(.*\.)(\d+)(\..*)$/, (match, g1?, g2?, g3?) => { return g1 + (parseInt(g2) + 1) + g3; });
	}
E
Erich Gamma 已提交
1040

1041 1042 1043 1044 1045
	// file.txt=>file.1.txt
	const lastIndexOfDot = name.lastIndexOf('.');
	if (!isFolder && lastIndexOfDot >= 0) {
		return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
	}
E
Erich Gamma 已提交
1046

1047 1048 1049
	// folder.1=>folder.2
	if (isFolder && name.match(/(\d+)$/)) {
		return name.replace(/(\d+)$/, (match: string, ...groups: any[]) => { return String(parseInt(groups[0]) + 1); });
E
Erich Gamma 已提交
1050
	}
1051 1052 1053

	// file/folder=>file.1/folder.1
	return strings.format('{0}.1', name);
E
Erich Gamma 已提交
1054 1055 1056 1057 1058
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

M
Matt Bierner 已提交
1059 1060
	public static readonly ID = 'workbench.files.action.compareFileWith';
	public static readonly LABEL = nls.localize('globalCompareFile', "Compare Active File With...");
E
Erich Gamma 已提交
1061 1062 1063 1064 1065 1066

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1067
		@IMessageService private messageService: IMessageService,
B
Benjamin Pasero 已提交
1068
		@IEditorGroupService private editorGroupService: IEditorGroupService
E
Erich Gamma 已提交
1069 1070 1071 1072
	) {
		super(id, label);
	}

1073
	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1074 1075
		const activeInput = this.editorService.getActiveEditorInput();
		const activeResource = activeInput ? activeInput.getResource() : void 0;
1076
		if (activeResource) {
E
Erich Gamma 已提交
1077

B
Benjamin Pasero 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
			// Compare with next editor that opens
			const unbind = once(this.editorGroupService.onEditorOpening)(e => {
				const resource = e.input.getResource();
				if (resource) {
					e.prevent(() => {
						return this.editorService.openEditor({
							leftResource: activeResource,
							rightResource: resource
						});
					});
1088
				}
B
Benjamin Pasero 已提交
1089
			});
1090

B
Benjamin Pasero 已提交
1091 1092 1093
			// Bring up quick open
			this.quickOpenService.show('', { autoFocus: { autoFocusSecondEntry: true } }).then(() => {
				unbind.dispose(); // make sure to unbind if quick open is closing
E
Erich Gamma 已提交
1094 1095 1096 1097 1098
			});
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1099
		return TPromise.as(true);
E
Erich Gamma 已提交
1100 1101 1102 1103 1104 1105
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1106
	constructor(explorerView: ExplorerView, clazz: string) {
B
Benjamin Pasero 已提交
1107
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1108 1109 1110
	}
}

1111
export abstract class BaseSaveAllAction extends BaseErrorReportingAction {
E
Erich Gamma 已提交
1112 1113 1114 1115 1116 1117 1118 1119
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
I
isidor 已提交
1120
		@ICommandService protected commandService: ICommandService,
1121
		@IMessageService messageService: IMessageService,
E
Erich Gamma 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
	) {
		super(id, label, messageService);

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

		this.registerListeners();
	}

	protected abstract includeUntitled(): boolean;
I
isidor 已提交
1133
	protected abstract doRun(context: any): TPromise<any>;
E
Erich Gamma 已提交
1134 1135 1136 1137

	private registerListeners(): void {

		// listen to files being changed locally
1138 1139 1140 1141
		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 已提交
1142 1143

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1144
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
		}
	}

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

1155 1156 1157 1158 1159 1160 1161
	public run(context?: any): TPromise<boolean> {
		return this.doRun(context).then(() => true, error => {
			this.onError(error);
			return null;
		});
	}

E
Erich Gamma 已提交
1162
	public dispose(): void {
J
Joao Moreno 已提交
1163
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1164 1165 1166 1167 1168 1169 1170

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1171
	public static readonly ID = 'workbench.action.files.saveAll';
I
isidor 已提交
1172
	public static readonly LABEL = SAVE_ALL_LABEL;
E
Erich Gamma 已提交
1173 1174 1175 1176 1177

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

I
isidor 已提交
1178 1179
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_COMMAND_ID);
1180 1181 1182 1183 1184 1185 1186 1187 1188
	}

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

export class SaveAllInGroupAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1189
	public static readonly ID = 'workbench.files.action.saveAllInGroup';
1190
	public static readonly LABEL = nls.localize('saveAllInGroup', "Save All in Group");
1191 1192 1193 1194 1195

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

I
isidor 已提交
1196 1197
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_IN_GROUP_COMMAND_ID);
1198 1199
	}

E
Erich Gamma 已提交
1200 1201 1202 1203 1204
	protected includeUntitled(): boolean {
		return true;
	}
}

1205
export class FocusOpenEditorsView extends Action {
1206

M
Matt Bierner 已提交
1207 1208
	public static readonly ID = 'workbench.files.action.focusOpenEditorsView';
	public static readonly LABEL = nls.localize({ key: 'focusOpenEditors', comment: ['Open is an adjective'] }, "Focus on Open Editors View");
1209 1210 1211 1212 1213 1214 1215 1216 1217

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

1218
	public run(): TPromise<any> {
1219
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1220 1221
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
1222
				openEditorsView.setExpanded(true);
I
isidor 已提交
1223
				openEditorsView.getList().domFocus();
I
isidor 已提交
1224
			}
1225 1226 1227 1228
		});
	}
}

1229 1230
export class FocusFilesExplorer extends Action {

M
Matt Bierner 已提交
1231 1232
	public static readonly ID = 'workbench.files.action.focusFilesExplorer';
	public static readonly LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

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

	public run(): TPromise<any> {
1243
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1244 1245
			const view = viewlet.getExplorerView();
			if (view) {
1246
				view.setExpanded(true);
1247 1248 1249 1250 1251 1252
				view.getViewer().DOMFocus();
			}
		});
	}
}

1253 1254
export class ShowActiveFileInExplorer extends Action {

M
Matt Bierner 已提交
1255 1256
	public static readonly ID = 'workbench.files.action.showActiveFileInExplorer';
	public static readonly LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");
1257 1258 1259 1260 1261

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
I
isidor 已提交
1262 1263
		@IMessageService private messageService: IMessageService,
		@ICommandService private commandService: ICommandService
1264 1265 1266 1267 1268
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1269 1270
		const resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true });
		if (resource) {
I
isidor 已提交
1271
			this.commandService.executeCommand(REVEAL_IN_EXPLORER_COMMAND_ID, resource);
1272 1273 1274 1275 1276 1277 1278 1279
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1280 1281
export class CollapseExplorerView extends Action {

M
Matt Bierner 已提交
1282 1283
	public static readonly ID = 'workbench.files.action.collapseExplorerFolders';
	public static readonly LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

	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 {

M
Matt Bierner 已提交
1310 1311
	public static readonly ID = 'workbench.files.action.refreshFilesExplorer';
	public static readonly LABEL = nls.localize('refreshExplorer', "Refresh Explorer");
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

	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();
			}
		});
	}
}

1331 1332
export class ShowOpenedFileInNewWindow extends Action {

M
Matt Bierner 已提交
1333 1334
	public static readonly ID = 'workbench.action.files.showOpenedFileInNewWindow';
	public static readonly LABEL = nls.localize('openFileInNewWindow', "Open Active File in New Window");
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

	constructor(
		id: string,
		label: string,
		@IWindowsService private windowsService: IWindowsService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IMessageService private messageService: IMessageService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
		const fileResource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
		if (fileResource) {
1349
			this.windowsService.openWindow([fileResource.fsPath], { forceNewWindow: true, forceOpenWorkspaceAsFile: true });
1350 1351 1352 1353 1354 1355 1356 1357
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShowInNewWindow', "Open a file first to open in new window"));
		}

		return TPromise.as(true);
	}
}

1358 1359
export class CopyPathAction extends Action {

M
Matt Bierner 已提交
1360
	public static readonly LABEL = nls.localize('copyPath', "Copy Path");
1361 1362 1363

	constructor(
		private resource: URI,
I
isidor 已提交
1364
		@ICommandService private commandService: ICommandService
1365
	) {
1366
		super('copyFilePath', CopyPathAction.LABEL);
1367 1368 1369 1370 1371

		this.order = 140;
	}

	public run(): TPromise<any> {
1372
		return this.commandService.executeCommand(COPY_PATH_COMMAND_ID, this.resource);
1373 1374 1375
	}
}

E
Erich Gamma 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
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);
		}
	}

1399 1400
	// Invalid File name
	if (!paths.isValidBasename(name)) {
1401
		return nls.localize('invalidFileNameError', "The name **{0}** is not valid as a file or folder name. Please choose a different name.", trimLongName(name));
E
Erich Gamma 已提交
1402 1403 1404 1405
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1406
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1407
		if (fullPathLength > 255) {
1408
			return nls.localize('filePathTooLongError', "The name **{0}** results in a path that is too long. Please choose a shorter name.", trimLongName(name));
E
Erich Gamma 已提交
1409 1410 1411 1412 1413 1414
		}
	}

	return null;
}

1415 1416 1417 1418 1419 1420 1421 1422
function trimLongName(name: string): string {
	if (name && name.length > 255) {
		return `${name.substr(0, 255)}...`;
	}

	return name;
}

E
Erich Gamma 已提交
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
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;
}

M
Max Furman 已提交
1437 1438
export class CompareWithClipboardAction extends Action {

M
Matt Bierner 已提交
1439 1440
	public static readonly ID = 'workbench.files.action.compareWithClipboard';
	public static readonly LABEL = nls.localize('compareWithClipboard', "Compare Active File with Clipboard");
M
Max Furman 已提交
1441

1442
	private static readonly SCHEME = 'clipboardCompare';
M
Max Furman 已提交
1443

B
Benjamin Pasero 已提交
1444
	private registrationDisposal: IDisposable;
M
Max Furman 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITextModelService private textModelService: ITextModelService,
	) {
		super(id, label);

		this.enabled = true;
	}

	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1459
		const resource: URI = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
M
Max Furman 已提交
1460 1461 1462
		const provider = this.instantiationService.createInstance(ClipboardContentProvider);

		if (resource) {
B
Benjamin Pasero 已提交
1463 1464 1465 1466
			if (!this.registrationDisposal) {
				this.registrationDisposal = this.textModelService.registerTextModelContentProvider(CompareWithClipboardAction.SCHEME, provider);
			}

M
Max Furman 已提交
1467 1468 1469
			const name = paths.basename(resource.fsPath);
			const editorLabel = nls.localize('clipboardComparisonLabel', "Clipboard ↔ {0}", name);

B
Benjamin Pasero 已提交
1470 1471 1472 1473 1474
			const cleanUp = () => {
				this.registrationDisposal = dispose(this.registrationDisposal);
			};

			return always(this.editorService.openEditor({ leftResource: URI.from({ scheme: CompareWithClipboardAction.SCHEME, path: resource.fsPath }), rightResource: resource, label: editorLabel }), cleanUp);
M
Max Furman 已提交
1475 1476 1477 1478 1479 1480 1481 1482
		}

		return TPromise.as(true);
	}

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

B
Benjamin Pasero 已提交
1483
		this.registrationDisposal = dispose(this.registrationDisposal);
M
Max Furman 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
	}
}

class ClipboardContentProvider implements ITextModelContentProvider {
	constructor(
		@IClipboardService private clipboardService: IClipboardService,
		@IModeService private modeService: IModeService,
		@IModelService private modelService: IModelService
	) { }

A
Alex Dima 已提交
1494
	provideTextContent(resource: URI): TPromise<ITextModel> {
M
Max Furman 已提交
1495
		const model = this.modelService.createModel(this.clipboardService.readText(), this.modeService.getOrCreateMode('text/plain'), resource);
B
Benjamin Pasero 已提交
1496

M
Max Furman 已提交
1497 1498 1499 1500
		return TPromise.as(model);
	}
}

E
Erich Gamma 已提交
1501 1502 1503
// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
1504
	diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
E
Erich Gamma 已提交
1505 1506
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
J
Johannes Rieken 已提交
1507
}
I
isidor 已提交
1508

I
isidor 已提交
1509 1510 1511
interface IExplorerContext {
	viewletState: IFileViewletState;
	stat: FileStat;
1512
	selection: FileStat[];
I
isidor 已提交
1513 1514
}

1515
function getContext(listWidget: ListWidget, viewletService: IViewletService): IExplorerContext {
I
isidor 已提交
1516
	// These commands can only be triggered when explorer viewlet is visible so get it using the active viewlet
1517 1518 1519 1520 1521 1522
	const tree = <ITree>listWidget;
	const stat = tree.getFocus();
	const selection = tree.getSelection();

	// Only respect the selection if user clicked inside it (focus belongs to it)
	return { stat, selection: selection && selection.indexOf(stat) >= 0 ? selection : [], viewletState: (<ExplorerViewlet>viewletService.getActiveViewlet()).getViewletState() };
I
isidor 已提交
1523 1524
}

I
isidor 已提交
1525 1526
// TODO@isidor these commands are calling into actions due to the complex inheritance action structure.
// It should be the other way around, that actions call into commands.
I
isidor 已提交
1527 1528
CommandsRegistry.registerCommand({
	id: NEW_FILE_COMMAND_ID,
I
isidor 已提交
1529
	handler: (accessor) => {
I
isidor 已提交
1530 1531
		const instantationService = accessor.get(IInstantiationService);
		const listService = accessor.get(IListService);
I
isidor 已提交
1532
		const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1533 1534 1535 1536 1537
		const newFileAction = instantationService.createInstance(NewFileAction, listService.lastFocusedList, explorerContext.stat);

		return newFileAction.run(explorerContext);
	}
});
I
isidor 已提交
1538 1539 1540

CommandsRegistry.registerCommand({
	id: NEW_FOLDER_COMMAND_ID,
I
isidor 已提交
1541
	handler: (accessor) => {
I
isidor 已提交
1542 1543
		const instantationService = accessor.get(IInstantiationService);
		const listService = accessor.get(IListService);
I
isidor 已提交
1544
		const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1545 1546 1547 1548 1549
		const newFolderAction = instantationService.createInstance(NewFolderAction, listService.lastFocusedList, explorerContext.stat);

		return newFolderAction.run(explorerContext);
	}
});
I
isidor 已提交
1550

I
isidor 已提交
1551
export const renameHandler = (accessor: ServicesAccessor) => {
I
isidor 已提交
1552 1553
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
I
isidor 已提交
1554
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1555

I
isidor 已提交
1556 1557 1558
	const renameAction = instantationService.createInstance(TriggerRenameFileAction, listService.lastFocusedList, explorerContext.stat);
	return renameAction.run(explorerContext);
};
I
isidor 已提交
1559

1560
export const moveFileToTrashHandler = (accessor: ServicesAccessor) => {
I
isidor 已提交
1561 1562
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
I
isidor 已提交
1563
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
1564
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];
I
isidor 已提交
1565

1566
	const moveFileToTrashAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, stats, true);
1567
	return moveFileToTrashAction.run();
I
isidor 已提交
1568
};
I
isidor 已提交
1569

1570
export const deleteFileHandler = (accessor: ServicesAccessor) => {
I
isidor 已提交
1571 1572
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
I
isidor 已提交
1573
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
1574
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];
I
isidor 已提交
1575

1576
	const deleteFileAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, stats, false);
1577
	return deleteFileAction.run();
I
isidor 已提交
1578
};
I
isidor 已提交
1579

1580
export const copyFileHandler = (accessor: ServicesAccessor) => {
I
isidor 已提交
1581 1582
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
I
isidor 已提交
1583
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1584
	const stats = explorerContext.selection.length > 1 ? explorerContext.selection : [explorerContext.stat];
I
isidor 已提交
1585

I
isidor 已提交
1586
	const copyFileAction = instantationService.createInstance(CopyFileAction, listService.lastFocusedList, stats);
I
isidor 已提交
1587 1588 1589
	return copyFileAction.run();
};

1590
export const pasteFileHandler = (accessor: ServicesAccessor) => {
I
isidor 已提交
1591 1592
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
1593
	const clipboardService = accessor.get(IClipboardService);
I
isidor 已提交
1594
	const explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1595

1596
	return TPromise.join(distinctParents(clipboardService.readFiles(), r => r).map(toCopy => {
I
isidor 已提交
1597 1598 1599
		const pasteFileAction = instantationService.createInstance(PasteFileAction, listService.lastFocusedList, explorerContext.stat);
		return pasteFileAction.run(toCopy);
	}));
I
isidor 已提交
1600
};