fileActions.ts 53.7 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
import { isWindows, isLinux, isMacintosh } 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';
40
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction, IConfirmationResult } from 'vs/platform/message/common/message';
41
import { IModel } from 'vs/editor/common/editorCommon';
42
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
43
import { IWindowsService } from 'vs/platform/windows/common/windows';
44
import { REVEAL_IN_OS_COMMAND_ID, COPY_PATH_COMMAND_ID, REVEAL_IN_EXPLORER_COMMAND_ID, SAVE_ALL_COMMAND_ID, SAVE_ALL_LABEL, SAVE_FILES_COMMAND_ID, SAVE_FILES_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';
I
isidor 已提交
53
import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
I
isidor 已提交
54
import { IEvent } from 'vs/platform/contextview/browser/contextView';
M
Max Furman 已提交
55

E
Erich Gamma 已提交
56 57 58 59 60
export interface IEditableData {
	action: IAction;
	validator: IInputValidator;
}

I
isidor 已提交
61 62 63 64 65 66
export interface IExplorerContext {
	viewletState: IFileViewletState;
	event?: IEvent;
	stat: FileStat;
}

E
Erich Gamma 已提交
67 68 69 70 71 72
export interface IFileViewletState {
	getEditableData(stat: IFileStat): IEditableData;
	setEditable(stat: IFileStat, editableData: IEditableData): void;
	clearEditable(stat: IFileStat): void;
}

I
isidor 已提交
73 74 75 76 77 78
export const NEW_FILE_COMMAND_ID = 'workbench.command.files.newFile';
export const NEW_FILE_LABEL = nls.localize('newFile', "New File");

export const NEW_FOLDER_COMMAND_ID = 'workbench.command.files.newFolder';
export const NEW_FOLDER_LABEL = nls.localize('newFolder', "New Folder");

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

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

I
isidor 已提交
83 84 85 86 87 88
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);

89
export class BaseErrorReportingAction extends Action {
E
Erich Gamma 已提交
90 91 92 93

	constructor(
		id: string,
		label: string,
94
		private _messageService: IMessageService
E
Erich Gamma 已提交
95 96 97 98 99 100 101 102
	) {
		super(id, label);
	}

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

103
	protected onError(error: any): void {
104 105
		if (error.message === 'string') {
			error = error.message;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
		}

		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 已提交
131
	public element: FileStat;
132 133 134 135

	constructor(
		id: string,
		label: string,
I
isidor 已提交
136
		@IFileService protected fileService: IFileService,
137
		@IMessageService _messageService: IMessageService,
I
isidor 已提交
138
		@ITextFileService protected textFileService: ITextFileService
139 140 141 142 143 144
	) {
		super(id, label, _messageService);

		this.enabled = false;
	}

E
Erich Gamma 已提交
145 146 147 148 149
	_isEnabled(): boolean {
		return true;
	}

	_updateEnablement(): void {
I
isidor 已提交
150
		this.enabled = !!(this.fileService && this._isEnabled());
E
Erich Gamma 已提交
151 152 153
	}
}

I
isidor 已提交
154
class TriggerRenameFileAction extends BaseFileAction {
E
Erich Gamma 已提交
155

M
Matt Bierner 已提交
156
	public static readonly ID = 'renameFile';
E
Erich Gamma 已提交
157 158 159 160 161 162 163 164 165 166 167 168

	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 已提交
169
		super(TriggerRenameFileAction.ID, TRIGGER_RENAME_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
170 171 172 173 174 175 176 177 178 179 180

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

181
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
182
		if (!context) {
183
			return TPromise.wrapError(new Error('No context provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
184 185
		}

186
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
187
		if (!viewletState) {
188
			return TPromise.wrapError(new Error('Invalid viewlet state provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
189 190
		}

191
		const stat = <IFileStat>context.stat;
E
Erich Gamma 已提交
192
		if (!stat) {
193
			return TPromise.wrapError(new Error('Invalid stat provided to BaseEnableFileRenameAction.'));
E
Erich Gamma 已提交
194 195 196 197 198
		}

		viewletState.setEditable(stat, {
			action: this.renameAction,
			validator: (value) => {
199
				const message = this.validateFileName(this.element.parent, value);
E
Erich Gamma 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

				if (!message) {
					return null;
				}

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

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

216
			const unbind = this.tree.onDidChangeHighlight((e: IHighlightEvent) => {
E
Erich Gamma 已提交
217 218 219
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
220
					unbind.dispose();
E
Erich Gamma 已提交
221 222 223
				}
			});
		}).done(null, errors.onUnexpectedError);
M
Matt Bierner 已提交
224

225
		return void 0;
E
Erich Gamma 已提交
226 227 228 229 230 231 232 233 234 235 236
	}
}

export abstract class BaseRenameAction extends BaseFileAction {

	constructor(
		id: string,
		label: string,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
237
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
238
	) {
B
Benjamin Pasero 已提交
239
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
240 241 242 243

		this.element = element;
	}

244
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
245
		if (!context) {
246
			return TPromise.wrapError(new Error('No context provided to BaseRenameFileAction.'));
E
Erich Gamma 已提交
247 248 249 250
		}

		let name = <string>context.value;
		if (!name) {
251
			return TPromise.wrapError(new Error('No new name provided to BaseRenameFileAction.'));
E
Erich Gamma 已提交
252 253 254 255
		}

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

258
		// Return early if name is invalid or didn't change
E
Erich Gamma 已提交
259
		if (name === existingName || this.validateFileName(this.element.parent, name)) {
A
Alex Dima 已提交
260
			return TPromise.as(null);
E
Erich Gamma 已提交
261 262 263
		}

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

287
	public abstract runAction(newName: string): TPromise<any>;
E
Erich Gamma 已提交
288 289
}

290
class RenameFileAction extends BaseRenameAction {
E
Erich Gamma 已提交
291

M
Matt Bierner 已提交
292
	public static readonly ID = 'workbench.files.action.renameFile';
E
Erich Gamma 已提交
293 294 295 296 297

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
298 299
		@ITextFileService textFileService: ITextFileService,
		@IBackupFileService private backupFileService: IBackupFileService
E
Erich Gamma 已提交
300
	) {
B
Benjamin Pasero 已提交
301
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, fileService, messageService, textFileService);
E
Erich Gamma 已提交
302 303 304 305

		this._updateEnablement();
	}

306
	public runAction(newName: string): TPromise<any> {
I
isidor 已提交
307
		const dirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, this.element.resource, !isLinux /* ignorecase */));
308 309
		const dirtyRenamed: URI[] = [];
		return TPromise.join(dirty.map(d => {
310 311 312
			let renamed: URI;

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

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

323
			dirtyRenamed.push(renamed);
324

325
			const model = this.textFileService.models.get(d);
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341

			return this.backupFileService.backupResource(renamed, model.getValue(), model.getVersionId());
		}))

			// 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(() => {
342
				return TPromise.join(dirtyRenamed.map(t => this.textFileService.models.loadOrCreate(t)));
E
Erich Gamma 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
			});
	}
}

/* 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,
363
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
364
	) {
B
Benjamin Pasero 已提交
365
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
366 367 368 369 370 371 372 373 374 375

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

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

376
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
377
		if (!context) {
378
			return TPromise.wrapError(new Error('No context provided to BaseNewAction.'));
E
Erich Gamma 已提交
379 380
		}

381
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
382
		if (!viewletState) {
383
			return TPromise.wrapError(new Error('Invalid viewlet state provided to BaseNewAction.'));
E
Erich Gamma 已提交
384 385
		}

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

		if (!folder) {
398
			return TPromise.wrapError(new Error('Invalid parent folder to create.'));
E
Erich Gamma 已提交
399 400 401 402
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
403
				const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);
E
Erich Gamma 已提交
404 405 406 407 408 409

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
410
						const message = this.renameAction.validateFileName(folder, value);
E
Erich Gamma 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

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

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

/* 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 已提交
455
		super('explorer.newFile', NEW_FILE_LABEL, tree, true, instantiationService.createInstance(CreateFileAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

		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 已提交
473
		super('explorer.newFolder', NEW_FOLDER_LABEL, tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
474 475 476 477 478 479 480 481 482 483 484 485 486

		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 已提交
487 488
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
489 490 491 492
	) {
		super(id, label);
	}

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

498 499
				const explorer = <ExplorerViewlet>viewlet;
				const explorerView = explorer.getExplorerView();
E
Erich Gamma 已提交
500

B
fix npe  
Benjamin Pasero 已提交
501 502 503 504 505
				// 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 已提交
506
				if (!explorerView.isExpanded()) {
507
					explorerView.setExpanded(true);
E
Erich Gamma 已提交
508 509
				}

510
				const action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);
E
Erich Gamma 已提交
511 512 513 514 515 516

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

517
	protected abstract getAction(): IConstructorSignature2<ITree, IFileStat, Action>;
E
Erich Gamma 已提交
518 519 520 521 522 523 524 525 526 527 528 529

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

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

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

	constructor(
		id: string,
		label: string,
537
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService
E
Erich Gamma 已提交
538 539 540 541
	) {
		super(id, label);
	}

542
	public run(): TPromise<any> {
543
		return this.editorService.openEditor({ options: { pinned: true } } as IUntitledResourceInput); // untitled are always pinned
E
Erich Gamma 已提交
544 545 546
	}
}

547 548
/* Create new file from anywhere */
export class GlobalNewFileAction extends BaseGlobalNewAction {
M
Matt Bierner 已提交
549 550
	public static readonly ID = 'explorer.newFile';
	public static readonly LABEL = nls.localize('newFile', "New File");
551 552 553 554 555 556

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

E
Erich Gamma 已提交
557 558
/* Create new folder from anywhere */
export class GlobalNewFolderAction extends BaseGlobalNewAction {
M
Matt Bierner 已提交
559 560
	public static readonly ID = 'explorer.newFolder';
	public static readonly LABEL = nls.localize('newFolder', "New Folder");
E
Erich Gamma 已提交
561

562
	protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
E
Erich Gamma 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
		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) */
580
class CreateFileAction extends BaseCreateAction {
E
Erich Gamma 已提交
581

M
Matt Bierner 已提交
582 583
	public static readonly ID = 'workbench.files.action.createFileFromExplorer';
	public static readonly LABEL = nls.localize('createNewFile', "New File");
E
Erich Gamma 已提交
584 585 586 587

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

		this._updateEnablement();
	}

597
	public runAction(fileName: string): TPromise<any> {
598 599
		const resource = this.element.parent.resource;
		return this.fileService.createFile(resource.with({ path: paths.join(resource.path, fileName) })).then(stat => {
600 601
			return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
		}, (error) => {
E
Erich Gamma 已提交
602 603 604 605 606 607
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

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

M
Matt Bierner 已提交
610 611
	public static readonly ID = 'workbench.files.action.createFolderFromExplorer';
	public static readonly LABEL = nls.localize('createNewFolder', "New Folder");
E
Erich Gamma 已提交
612 613 614 615 616

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
617
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
618
	) {
B
Benjamin Pasero 已提交
619
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
620 621 622 623

		this._updateEnablement();
	}

624
	public runAction(fileName: string): TPromise<any> {
625 626
		const resource = this.element.parent.resource;
		return this.fileService.createFolder(resource.with({ path: paths.join(resource.path, fileName) })).then(null, (error) => {
E
Erich Gamma 已提交
627 628 629 630 631
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

I
isidor 已提交
632
class BaseDeleteFileAction extends BaseFileAction {
633

634
	private static readonly CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';
635

E
Erich Gamma 已提交
636 637
	private tree: ITree;
	private useTrash: boolean;
638
	private skipConfirm: boolean;
E
Erich Gamma 已提交
639 640 641 642 643 644 645

	constructor(
		tree: ITree,
		element: FileStat,
		useTrash: boolean,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
646
		@ITextFileService textFileService: ITextFileService,
647
		@IConfigurationService private configurationService: IConfigurationService
E
Erich Gamma 已提交
648
	) {
I
isidor 已提交
649
		super('moveFileToTrash', MOVE_FILE_TO_TRASH_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
650 651 652 653 654 655 656 657

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

		this._updateEnablement();
	}

658
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
659 660 661 662 663 664

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

665
		// Read context
666 667 668 669 670 671 672 673
		if (context) {
			if (context.event) {
				const bypassTrash = (isMacintosh && context.event.altKey) || (!isMacintosh && context.event.shiftKey);
				if (bypassTrash) {
					this.useTrash = false;
				}
			} else if (typeof context.useTrash === 'boolean') {
				this.useTrash = context.useTrash;
674 675 676
			}
		}

677 678 679 680 681 682 683 684
		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
685
		let confirmDirtyPromise: TPromise<boolean> = TPromise.as(true);
I
isidor 已提交
686
		const dirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, this.element.resource, !isLinux /* ignorecase */));
687 688 689 690 691 692 693 694
		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);
				}
695
			} else {
696
				message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
697
			}
E
Erich Gamma 已提交
698

699
			confirmDirtyPromise = this.messageService.confirm({
700 701 702 703
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
704 705 706 707
			}).then(confirmed => {
				if (!confirmed) {
					return false;
				}
708

709 710 711
				this.skipConfirm = true; // since we already asked for confirmation
				return this.textFileService.revertAll(dirty).then(() => true);
			});
E
Erich Gamma 已提交
712 713
		}

714
		// Check if file is dirty in editor and save it to avoid data loss
715 716 717 718 719 720
		return confirmDirtyPromise.then(confirmed => {
			if (!confirmed) {
				return null;
			}

			let confirmDeletePromise: TPromise<IConfirmationResult>;
721

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

727 728
			// Confirm for moving to trash
			else if (this.useTrash) {
729
				confirmDeletePromise = this.messageService.confirmWithCheckbox({
730 731 732 733 734 735 736 737
					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,
					checkbox: {
						label: nls.localize('doNotAskAgain', "Do not ask me again")
					},
					type: 'question'
				});
E
Erich Gamma 已提交
738 739
			}

740 741
			// Confirm for deleting permanently
			else {
742
				confirmDeletePromise = this.messageService.confirmWithCheckbox({
743 744 745 746 747 748 749
					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,
					type: 'warning'
				});
			}

750
			return confirmDeletePromise.then(confirmation => {
E
Erich Gamma 已提交
751

752 753
				// Check for confirmation checkbox
				let updateConfirmSettingsPromise: TPromise<void> = TPromise.as(void 0);
754
				if (confirmation.confirmed && confirmation.checkboxChecked === true) {
755
					updateConfirmSettingsPromise = this.configurationService.updateValue(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY, false, ConfigurationTarget.USER);
756
				}
E
Erich Gamma 已提交
757

758
				return updateConfirmSettingsPromise.then(() => {
B
Benjamin Pasero 已提交
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
					// Check for confirmation
					if (!confirmation.confirmed) {
						return TPromise.as(null);
					}

					// Call function
					const servicePromise = this.fileService.del(this.element.resource, this.useTrash).then(() => {
						if (this.element.parent) {
							this.tree.setFocus(this.element.parent); // move focus to parent
						}
					}, (error: any) => {

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

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

780 781 782 783 784 785 786
						// Focus back to tree
						this.tree.DOMFocus();
					});

					return servicePromise;
				});
			});
787
		});
E
Erich Gamma 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800
	}
}

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

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IFileService fileService: IFileService,
801
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
802
		@IMessageService messageService: IMessageService,
803
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
804
	) {
I
isidor 已提交
805
		super('workbench.files.action.importFile', nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
806 807 808 809 810 811 812 813 814 815 816

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

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

		this._updateEnablement();
	}

817
	public run(resources: URI[]): TPromise<any> {
818
		const importPromise = TPromise.as(null).then(() => {
819
			if (resources && resources.length > 0) {
E
Erich Gamma 已提交
820 821 822 823 824 825

				// Find parent for import
				let targetElement: FileStat;
				if (this.element) {
					targetElement = this.element;
				} else {
I
isidor 已提交
826 827
					const input: FileStat | Model = this.tree.getInput();
					targetElement = this.tree.getFocus() || (input instanceof Model ? input.roots[0] : input);
E
Erich Gamma 已提交
828 829 830 831 832 833 834 835 836 837
				}

				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
838
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
839 840 841 842
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

843
					let overwritePromise = TPromise.as(true);
844 845
					if (resources.some(resource => {
						return !!targetNames[isLinux ? paths.basename(resource.fsPath) : paths.basename(resource.fsPath).toLowerCase()];
E
Erich Gamma 已提交
846
					})) {
847
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
848 849
							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 已提交
850 851
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
							type: 'warning'
E
Erich Gamma 已提交
852 853
						};

854
						overwritePromise = this.messageService.confirm(confirm);
E
Erich Gamma 已提交
855 856
					}

857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
					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 已提交
876

877 878 879 880 881 882 883 884 885
								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 已提交
886 887 888
							});
						});

889 890
						return sequence(importPromisesFactory);
					});
E
Erich Gamma 已提交
891 892
				});
			}
893 894

			return void 0;
E
Erich Gamma 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907
		});

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

// Copy File/Folder
let fileToCopy: FileStat;
I
isidor 已提交
908
let fileCopiedContextKey: IContextKey<boolean>;
E
Erich Gamma 已提交
909

I
isidor 已提交
910
class CopyFileAction extends BaseFileAction {
E
Erich Gamma 已提交
911 912 913 914 915 916 917

	private tree: ITree;
	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
I
isidor 已提交
918 919
		@ITextFileService textFileService: ITextFileService,
		@IContextKeyService contextKeyService: IContextKeyService
E
Erich Gamma 已提交
920
	) {
I
isidor 已提交
921
		super('filesExplorer.copy', COPY_FILE_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
922 923 924

		this.tree = tree;
		this.element = element;
I
isidor 已提交
925 926 927
		if (!fileCopiedContextKey) {
			fileCopiedContextKey = FileCopiedContext.bindTo(contextKeyService);
		}
E
Erich Gamma 已提交
928 929 930
		this._updateEnablement();
	}

931
	public run(): TPromise<any> {
E
Erich Gamma 已提交
932 933 934

		// Remember as file/folder to copy
		fileToCopy = this.element;
I
isidor 已提交
935
		fileCopiedContextKey.set(!!this.element);
E
Erich Gamma 已提交
936 937 938 939 940 941 942 943

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

		this.tree.DOMFocus();

A
Alex Dima 已提交
944
		return TPromise.as(null);
E
Erich Gamma 已提交
945 946 947 948
	}
}

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

M
Matt Bierner 已提交
951
	public static readonly ID = 'filesExplorer.paste';
E
Erich Gamma 已提交
952 953 954 955 956 957 958 959 960 961 962

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
I
isidor 已提交
963
		super(PasteFileAction.ID, PASTE_FILE_LABEL, fileService, messageService, textFileService);
E
Erich Gamma 已提交
964 965

		this.tree = tree;
I
isidor 已提交
966 967 968 969 970
		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 已提交
971 972 973
		this._updateEnablement();
	}

I
isidor 已提交
974
	public run(): TPromise<any> {
E
Erich Gamma 已提交
975

I
isidor 已提交
976
		const exists = fileToCopy.root.find(fileToCopy.resource);
E
Erich Gamma 已提交
977 978
		if (!exists) {
			fileToCopy = null;
I
isidor 已提交
979 980
			fileCopiedContextKey.set(false);
			throw new Error(nls.localize('fileDeleted', "File was deleted or moved meanwhile"));
E
Erich Gamma 已提交
981 982 983
		}

		// Check if target is ancestor of pasted folder
I
isidor 已提交
984
		if (this.element.resource.toString() !== fileToCopy.resource.toString() && resources.isEqualOrParent(this.element.resource, fileToCopy.resource, !isLinux /* ignorecase */)) {
I
isidor 已提交
985
			throw new Error(nls.localize('fileIsAncestor', "File to copy is an ancestor of the desitnation folder"));
E
Erich Gamma 已提交
986 987 988 989
		}

		// Find target
		let target: FileStat;
990
		if (this.element.resource.toString() === fileToCopy.resource.toString()) {
E
Erich Gamma 已提交
991 992 993 994 995 996
			target = this.element.parent;
		} else {
			target = this.element.isDirectory ? this.element : this.element.parent;
		}

		// Reuse duplicate action
997
		const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
E
Erich Gamma 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

		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,
1015
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
1016
		@IMessageService messageService: IMessageService,
1017
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
1018
	) {
B
Benjamin Pasero 已提交
1019
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
1020 1021 1022 1023 1024 1025 1026

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

1027
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1028 1029 1030 1031 1032 1033

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

1034
		// Copy File
1035 1036 1037 1038
		const result = this.fileService.copyFile(this.element.resource, this.findTarget()).then(stat => {
			if (!stat.isDirectory) {
				return this.editorService.openEditor({ resource: stat.resource, options: { pinned: true } });
			}
1039 1040

			return void 0;
1041
		}, error => this.onError(error));
E
Erich Gamma 已提交
1042 1043 1044 1045 1046 1047 1048

		return result;
	}

	private findTarget(): URI {
		let name = this.element.name;

I
isidor 已提交
1049
		let candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1050
		while (true) {
I
isidor 已提交
1051
			if (!this.element.root.find(candidate)) {
E
Erich Gamma 已提交
1052 1053 1054 1055
				break;
			}

			name = this.toCopyName(name, this.element.isDirectory);
I
isidor 已提交
1056
			candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1057 1058 1059 1060 1061 1062 1063 1064
		}

		return candidate;
	}

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

		// file.1.txt=>file.2.txt
1065 1066
		if (!isFolder && name.match(/(.*\.)(\d+)(\..*)$/)) {
			return name.replace(/(.*\.)(\d+)(\..*)$/, (match, g1?, g2?, g3?) => { return g1 + (parseInt(g2) + 1) + g3; });
E
Erich Gamma 已提交
1067 1068 1069
		}

		// file.txt=>file.1.txt
1070
		const lastIndexOfDot = name.lastIndexOf('.');
E
Erich Gamma 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
		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);
	}
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

M
Matt Bierner 已提交
1088 1089
	public static readonly ID = 'workbench.files.action.compareFileWith';
	public static readonly LABEL = nls.localize('globalCompareFile', "Compare Active File With...");
E
Erich Gamma 已提交
1090 1091 1092 1093 1094 1095

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1096
		@IMessageService private messageService: IMessageService,
B
Benjamin Pasero 已提交
1097
		@IEditorGroupService private editorGroupService: IEditorGroupService
E
Erich Gamma 已提交
1098 1099 1100 1101
	) {
		super(id, label);
	}

1102
	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1103 1104
		const activeInput = this.editorService.getActiveEditorInput();
		const activeResource = activeInput ? activeInput.getResource() : void 0;
1105
		if (activeResource) {
E
Erich Gamma 已提交
1106

B
Benjamin Pasero 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
			// 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
						});
					});
1117
				}
B
Benjamin Pasero 已提交
1118
			});
1119

B
Benjamin Pasero 已提交
1120 1121 1122
			// 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 已提交
1123 1124 1125 1126 1127
			});
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1128
		return TPromise.as(true);
E
Erich Gamma 已提交
1129 1130 1131 1132 1133 1134
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1135
	constructor(explorerView: ExplorerView, clazz: string) {
B
Benjamin Pasero 已提交
1136
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1137 1138 1139
	}
}

1140
export abstract class BaseSaveAllAction extends BaseErrorReportingAction {
E
Erich Gamma 已提交
1141 1142 1143 1144 1145 1146 1147 1148
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
I
isidor 已提交
1149
		@ICommandService protected commandService: ICommandService,
1150
		@IMessageService messageService: IMessageService,
E
Erich Gamma 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	) {
		super(id, label, messageService);

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

		this.registerListeners();
	}

	protected abstract includeUntitled(): boolean;
I
isidor 已提交
1162
	protected abstract doRun(context: any): TPromise<any>;
E
Erich Gamma 已提交
1163 1164 1165 1166

	private registerListeners(): void {

		// listen to files being changed locally
1167 1168 1169 1170
		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 已提交
1171 1172

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1173
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
		}
	}

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

1184 1185 1186 1187 1188 1189 1190
	public run(context?: any): TPromise<boolean> {
		return this.doRun(context).then(() => true, error => {
			this.onError(error);
			return null;
		});
	}

E
Erich Gamma 已提交
1191
	public dispose(): void {
J
Joao Moreno 已提交
1192
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1193 1194 1195 1196 1197 1198 1199

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1200
	public static readonly ID = 'workbench.action.files.saveAll';
I
isidor 已提交
1201
	public static readonly LABEL = SAVE_ALL_LABEL;
E
Erich Gamma 已提交
1202 1203 1204 1205 1206

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

I
isidor 已提交
1207 1208
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_COMMAND_ID);
1209 1210 1211 1212 1213 1214 1215 1216 1217
	}

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

export class SaveAllInGroupAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1218
	public static readonly ID = 'workbench.files.action.saveAllInGroup';
1219
	public static readonly LABEL = nls.localize('saveAllInGroup', "Save All in Group");
1220 1221 1222 1223 1224

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

I
isidor 已提交
1225 1226
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_IN_GROUP_COMMAND_ID);
1227 1228
	}

E
Erich Gamma 已提交
1229 1230 1231 1232 1233 1234 1235
	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveFilesAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1236
	public static readonly ID = 'workbench.action.files.saveFiles';
I
isidor 已提交
1237
	public static readonly LABEL = SAVE_FILES_LABEL;
E
Erich Gamma 已提交
1238

I
isidor 已提交
1239 1240
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_FILES_COMMAND_ID, false);
1241 1242
	}

E
Erich Gamma 已提交
1243 1244 1245 1246 1247
	protected includeUntitled(): boolean {
		return false;
	}
}

1248
export class FocusOpenEditorsView extends Action {
1249

M
Matt Bierner 已提交
1250 1251
	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");
1252 1253 1254 1255 1256 1257 1258 1259 1260

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

1261
	public run(): TPromise<any> {
1262
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1263 1264
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
1265
				openEditorsView.setExpanded(true);
I
isidor 已提交
1266
				openEditorsView.getList().domFocus();
I
isidor 已提交
1267
			}
1268 1269 1270 1271
		});
	}
}

1272 1273
export class FocusFilesExplorer extends Action {

M
Matt Bierner 已提交
1274 1275
	public static readonly ID = 'workbench.files.action.focusFilesExplorer';
	public static readonly LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

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

	public run(): TPromise<any> {
1286
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1287 1288
			const view = viewlet.getExplorerView();
			if (view) {
1289
				view.setExpanded(true);
1290 1291 1292 1293 1294 1295
				view.getViewer().DOMFocus();
			}
		});
	}
}

1296 1297
export class ShowActiveFileInExplorer extends Action {

M
Matt Bierner 已提交
1298 1299
	public static readonly ID = 'workbench.files.action.showActiveFileInExplorer';
	public static readonly LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");
1300 1301 1302 1303 1304

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
I
isidor 已提交
1305 1306
		@IMessageService private messageService: IMessageService,
		@ICommandService private commandService: ICommandService
1307 1308 1309 1310 1311
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1312 1313
		const resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true });
		if (resource) {
I
isidor 已提交
1314
			this.commandService.executeCommand(REVEAL_IN_EXPLORER_COMMAND_ID, { resource });
1315 1316 1317 1318 1319 1320 1321 1322
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1323 1324
export class CollapseExplorerView extends Action {

M
Matt Bierner 已提交
1325 1326
	public static readonly ID = 'workbench.files.action.collapseExplorerFolders';
	public static readonly LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

	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 已提交
1353 1354
	public static readonly ID = 'workbench.files.action.refreshFilesExplorer';
	public static readonly LABEL = nls.localize('refreshExplorer', "Refresh Explorer");
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

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

1374 1375
export class ShowOpenedFileInNewWindow extends Action {

M
Matt Bierner 已提交
1376 1377
	public static readonly ID = 'workbench.action.files.showOpenedFileInNewWindow';
	public static readonly LABEL = nls.localize('openFileInNewWindow', "Open Active File in New Window");
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

	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) {
1392
			this.windowsService.openWindow([fileResource.fsPath], { forceNewWindow: true, forceOpenWorkspaceAsFile: true });
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShowInNewWindow', "Open a file first to open in new window"));
		}

		return TPromise.as(true);
	}
}

export class GlobalRevealInOSAction extends Action {

M
Matt Bierner 已提交
1403 1404
	public static readonly ID = 'workbench.action.files.revealActiveFileInWindows';
	public static readonly LABEL = isWindows ? nls.localize('revealActiveFileInWindows', "Reveal Active File in Windows Explorer") : (isMacintosh ? nls.localize('revealActiveFileInMac', "Reveal Active File in Finder") : nls.localize('openActiveFileContainer', "Open Containing Folder of Active File"));
1405 1406 1407 1408

	constructor(
		id: string,
		label: string,
I
isidor 已提交
1409
		@ICommandService private commandService: ICommandService
1410 1411 1412 1413 1414
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
I
isidor 已提交
1415
		return this.commandService.executeCommand(REVEAL_IN_OS_COMMAND_ID);
1416 1417 1418
	}
}

1419 1420
export class CopyPathAction extends Action {

M
Matt Bierner 已提交
1421
	public static readonly LABEL = nls.localize('copyPath', "Copy Path");
1422 1423 1424

	constructor(
		private resource: URI,
I
isidor 已提交
1425
		@ICommandService private commandService: ICommandService
1426
	) {
1427
		super('copyFilePath', CopyPathAction.LABEL);
1428 1429 1430 1431 1432

		this.order = 140;
	}

	public run(): TPromise<any> {
1433
		return this.commandService.executeCommand(COPY_PATH_COMMAND_ID, this.resource);
1434 1435 1436
	}
}

E
Erich Gamma 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
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);
		}
	}

1460 1461
	// Invalid File name
	if (!paths.isValidBasename(name)) {
1462
		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 已提交
1463 1464 1465 1466
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1467
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1468
		if (fullPathLength > 255) {
1469
			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 已提交
1470 1471 1472 1473 1474 1475
		}
	}

	return null;
}

1476 1477 1478 1479 1480 1481 1482 1483
function trimLongName(name: string): string {
	if (name && name.length > 255) {
		return `${name.substr(0, 255)}...`;
	}

	return name;
}

E
Erich Gamma 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
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 已提交
1498 1499
export class CompareWithClipboardAction extends Action {

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

1503
	private static readonly SCHEME = 'clipboardCompare';
M
Max Furman 已提交
1504

B
Benjamin Pasero 已提交
1505
	private registrationDisposal: IDisposable;
M
Max Furman 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

	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 已提交
1520
		const resource: URI = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
M
Max Furman 已提交
1521 1522 1523
		const provider = this.instantiationService.createInstance(ClipboardContentProvider);

		if (resource) {
B
Benjamin Pasero 已提交
1524 1525 1526 1527
			if (!this.registrationDisposal) {
				this.registrationDisposal = this.textModelService.registerTextModelContentProvider(CompareWithClipboardAction.SCHEME, provider);
			}

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

B
Benjamin Pasero 已提交
1531 1532 1533 1534 1535
			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 已提交
1536 1537 1538 1539 1540 1541 1542 1543
		}

		return TPromise.as(true);
	}

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

B
Benjamin Pasero 已提交
1544
		this.registrationDisposal = dispose(this.registrationDisposal);
M
Max Furman 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
	}
}

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

	provideTextContent(resource: URI): TPromise<IModel> {
		const model = this.modelService.createModel(this.clipboardService.readText(), this.modeService.getOrCreateMode('text/plain'), resource);
B
Benjamin Pasero 已提交
1557

M
Max Furman 已提交
1558 1559 1560 1561
		return TPromise.as(model);
	}
}

E
Erich Gamma 已提交
1562 1563 1564
// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
1565
	diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
E
Erich Gamma 已提交
1566 1567
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
J
Johannes Rieken 已提交
1568
}
I
isidor 已提交
1569

I
isidor 已提交
1570 1571
// 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 已提交
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
CommandsRegistry.registerCommand({
	id: NEW_FILE_COMMAND_ID,
	handler: (accessor, resource: URI, explorerContext: IExplorerContext) => {
		const instantationService = accessor.get(IInstantiationService);
		const listService = accessor.get(IListService);
		const newFileAction = instantationService.createInstance(NewFileAction, listService.lastFocusedList, explorerContext.stat);

		return newFileAction.run(explorerContext);
	}
});
I
isidor 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

CommandsRegistry.registerCommand({
	id: NEW_FOLDER_COMMAND_ID,
	handler: (accessor, resource: URI, explorerContext: IExplorerContext) => {
		const instantationService = accessor.get(IInstantiationService);
		const listService = accessor.get(IListService);
		const newFolderAction = instantationService.createInstance(NewFolderAction, listService.lastFocusedList, explorerContext.stat);

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

I
isidor 已提交
1594 1595 1596
function getContext(tree: ListWidget, viewletService: IViewletService): IExplorerContext {
	return { stat: tree.getFocus(), viewletState: (<ExplorerViewlet>viewletService.getActiveViewlet()).getViewletState() };
}
I
isidor 已提交
1597

I
isidor 已提交
1598 1599 1600 1601 1602
export const renameHandler = (accessor: ServicesAccessor, resource: URI, explorerContext: IExplorerContext) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	if (!explorerContext) {
		explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1603
	}
I
isidor 已提交
1604

I
isidor 已提交
1605 1606 1607
	const renameAction = instantationService.createInstance(TriggerRenameFileAction, listService.lastFocusedList, explorerContext.stat);
	return renameAction.run(explorerContext);
};
I
isidor 已提交
1608

I
isidor 已提交
1609 1610 1611 1612 1613
export const moveFileToTrashHandler = (accessor, resource: URI, explorerContext: IExplorerContext) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	if (!explorerContext) {
		explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1614
	}
I
isidor 已提交
1615

I
isidor 已提交
1616 1617 1618
	const moveFileToTrashAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, explorerContext.stat, true);
	return moveFileToTrashAction.run(explorerContext);
};
I
isidor 已提交
1619

I
isidor 已提交
1620 1621 1622 1623 1624
export const deleteFileHandler = (accessor, resource: URI, explorerContext: IExplorerContext) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	if (!explorerContext) {
		explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1625 1626
	}

I
isidor 已提交
1627 1628 1629
	const deleteFileAction = instantationService.createInstance(BaseDeleteFileAction, listService.lastFocusedList, explorerContext.stat, false);
	return deleteFileAction.run(explorerContext);
};
I
isidor 已提交
1630

I
isidor 已提交
1631 1632 1633 1634 1635
export const copyFileHandler = (accessor, resource: URI, explorerContext: IExplorerContext) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	if (!explorerContext) {
		explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
I
isidor 已提交
1636
	}
I
isidor 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651

	const copyFileAction = instantationService.createInstance(CopyFileAction, listService.lastFocusedList, explorerContext.stat);
	return copyFileAction.run();
};

export const pasteFileHandler = (accessor, resource: URI, explorerContext: IExplorerContext) => {
	const instantationService = accessor.get(IInstantiationService);
	const listService = accessor.get(IListService);
	if (!explorerContext) {
		explorerContext = getContext(listService.lastFocusedList, accessor.get(IViewletService));
	}

	const pasteFileAction = instantationService.createInstance(PasteFileAction, listService.lastFocusedList, explorerContext.stat);
	return pasteFileAction.run();
};