fileActions.ts 65.2 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, IActionProvider } from 'vs/base/parts/tree/browser/tree';
J
Johannes Rieken 已提交
24
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
25
import { VIEWLET_ID, FileOnDiskContentProvider } from 'vs/workbench/parts/files/common/files';
26
import labels = require('vs/base/common/labels');
27
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
28
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
B
Benjamin Pasero 已提交
29
import { toResource, IEditorIdentifier } from 'vs/workbench/common/editor';
30
import { FileStat, Model, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerModel';
31 32
import { ExplorerView } from 'vs/workbench/parts/files/electron-browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/electron-browser/explorerViewlet';
J
Johannes Rieken 已提交
33 34 35 36
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 已提交
37
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
B
Benjamin Pasero 已提交
38
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
B
Benjamin Pasero 已提交
39
import { Position, IResourceInput, IUntitledResourceInput } from 'vs/platform/editor/common/editor';
40
import { IInstantiationService, IConstructorSignature2, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
41
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction, IConfirmationResult } from 'vs/platform/message/common/message';
J
Johannes Rieken 已提交
42
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
43
import { getCodeEditor } from 'vs/editor/browser/services/codeEditorService';
M
Max Furman 已提交
44
import { IEditorViewState, IModel } from 'vs/editor/common/editorCommon';
45
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
46
import { IWindowsService } from 'vs/platform/windows/common/windows';
47
import { withFocusedFilesExplorer, revealInOSCommand, revealInExplorerCommand, copyPathCommand } from 'vs/workbench/parts/files/electron-browser/fileCommands';
48
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
M
Max Furman 已提交
49
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
50
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
51
import { once } from 'vs/base/common/event';
M
Max Furman 已提交
52 53 54 55
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';

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

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

68
export class BaseErrorReportingAction extends Action {
E
Erich Gamma 已提交
69 70 71 72

	constructor(
		id: string,
		label: string,
73
		private _messageService: IMessageService
E
Erich Gamma 已提交
74 75 76 77 78 79 80 81
	) {
		super(id, label);
	}

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

82
	protected onError(error: any): void {
83 84
		if (error.message === 'string') {
			error = error.message;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
		}

		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 {
	private _element: FileStat;

	constructor(
		id: string,
		label: string,
		@IFileService private _fileService: IFileService,
		@IMessageService _messageService: IMessageService,
		@ITextFileService private _textFileService: ITextFileService
	) {
		super(id, label, _messageService);

		this.enabled = false;
	}

E
Erich Gamma 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	public get fileService() {
		return this._fileService;
	}

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

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

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

	_isEnabled(): boolean {
		return true;
	}

	_updateEnablement(): void {
B
Benjamin Pasero 已提交
145
		this.enabled = !!(this._fileService && this._isEnabled());
E
Erich Gamma 已提交
146 147 148 149 150
	}
}

export class TriggerRenameFileAction extends BaseFileAction {

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

	private tree: ITree;
	private renameAction: BaseRenameAction;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
164
		super(TriggerRenameFileAction.ID, nls.localize('rename', "Rename"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
165 166 167 168 169 170 171 172 173 174 175

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

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

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

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

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

				if (!message) {
					return null;
				}

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

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

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

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

export abstract class BaseRenameAction extends BaseFileAction {

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

		this.element = element;
	}

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

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

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

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

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

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

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

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

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

		this._updateEnablement();
	}

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

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

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

318
			dirtyRenamed.push(renamed);
319

320
			const model = this.textFileService.models.get(d);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

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

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

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

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

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

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

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

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

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

				this.renameAction.element = stat;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

537
	public run(): TPromise<any> {
538
		return this.editorService.openEditor({ options: { pinned: true } } as IUntitledResourceInput); // untitled are always pinned
E
Erich Gamma 已提交
539 540 541
	}
}

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

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

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

557
	protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
E
Erich Gamma 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
		return NewFolderAction;
	}
}

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

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

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

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

M
Matt Bierner 已提交
577 578
	public static readonly ID = 'workbench.files.action.createFileFromExplorer';
	public static readonly LABEL = nls.localize('createNewFile', "New File");
E
Erich Gamma 已提交
579 580 581 582

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
583
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
584
		@IMessageService messageService: IMessageService,
585
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
586
	) {
B
Benjamin Pasero 已提交
587
		super(CreateFileAction.ID, CreateFileAction.LABEL, element, fileService, messageService, textFileService);
E
Erich Gamma 已提交
588 589 590 591

		this._updateEnablement();
	}

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

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

M
Matt Bierner 已提交
605 606
	public static readonly ID = 'workbench.files.action.createFolderFromExplorer';
	public static readonly LABEL = nls.localize('createNewFolder', "New Folder");
E
Erich Gamma 已提交
607 608 609 610 611

	constructor(
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
612
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
613
	) {
B
Benjamin Pasero 已提交
614
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
615 616 617 618

		this._updateEnablement();
	}

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

export class BaseDeleteFileAction extends BaseFileAction {
628

629
	private static readonly CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';
630

E
Erich Gamma 已提交
631 632
	private tree: ITree;
	private useTrash: boolean;
633
	private skipConfirm: boolean;
E
Erich Gamma 已提交
634 635 636 637 638 639 640 641 642

	constructor(
		id: string,
		label: string,
		tree: ITree,
		element: FileStat,
		useTrash: boolean,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
643
		@ITextFileService textFileService: ITextFileService,
644
		@IConfigurationService private configurationService: IConfigurationService
E
Erich Gamma 已提交
645
	) {
B
Benjamin Pasero 已提交
646
		super(id, label, fileService, messageService, textFileService);
E
Erich Gamma 已提交
647 648 649 650 651 652 653 654

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

		this._updateEnablement();
	}

655
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
656 657 658 659 660 661

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

662
		// Read context
663 664 665 666 667 668 669 670
		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;
671 672 673
			}
		}

674 675 676 677 678 679 680 681 682
		let primaryButton: string;
		if (this.useTrash) {
			primaryButton = isWindows ? nls.localize('deleteButtonLabelRecycleBin', "&&Move to Recycle Bin") : nls.localize({ key: 'deleteButtonLabelTrash', comment: ['&& denotes a mnemonic'] }, "&&Move to Trash");
		} else {
			primaryButton = nls.localize({ key: 'deleteButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete");
		}

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

696
			const res = this.messageService.confirmSync({
697 698 699 700 701 702 703
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
			});

			if (!res) {
A
Alex Dima 已提交
704
				return TPromise.as(null);
705
			}
706 707 708

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

711 712
		// Check if file is dirty in editor and save it to avoid data loss
		return revertPromise.then(() => {
713
			let confirmPromise: TPromise<IConfirmationResult>;
714

715
			// Check if we need to ask for confirmation at all
S
Sandeep Somavarapu 已提交
716
			if (this.skipConfirm || (this.useTrash && this.configurationService.getValue<boolean>(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY) === false)) {
717 718
				confirmPromise = TPromise.as({ confirmed: true } as IConfirmationResult);
			}
B
Benjamin Pasero 已提交
719

720 721 722 723 724 725 726 727 728 729 730
			// Confirm for moving to trash
			else if (this.useTrash) {
				confirmPromise = this.messageService.confirm({
					message: this.element.isDirectory ? nls.localize('confirmMoveTrashMessageFolder', "Are you sure you want to delete '{0}' and its contents?", this.element.name) : nls.localize('confirmMoveTrashMessageFile', "Are you sure you want to delete '{0}'?", this.element.name),
					detail: isWindows ? nls.localize('undoBin', "You can restore from the recycle bin.") : nls.localize('undoTrash', "You can restore from the trash."),
					primaryButton,
					checkbox: {
						label: nls.localize('doNotAskAgain', "Do not ask me again")
					},
					type: 'question'
				});
E
Erich Gamma 已提交
731 732
			}

733 734 735 736 737 738 739 740 741 742 743
			// Confirm for deleting permanently
			else {
				confirmPromise = this.messageService.confirm({
					message: this.element.isDirectory ? nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", this.element.name) : nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", this.element.name),
					detail: nls.localize('irreversible', "This action is irreversible!"),
					primaryButton,
					type: 'warning'
				});
			}

			return confirmPromise.then(confirmation => {
E
Erich Gamma 已提交
744

745 746
				// Check for confirmation checkbox
				let updateConfirmSettingsPromise: TPromise<void> = TPromise.as(void 0);
747
				if (confirmation.confirmed && confirmation.checkboxChecked === true) {
748
					updateConfirmSettingsPromise = this.configurationService.updateValue(BaseDeleteFileAction.CONFIRM_DELETE_SETTING_KEY, false, ConfigurationTarget.USER);
749
				}
E
Erich Gamma 已提交
750

751
				return updateConfirmSettingsPromise.then(() => {
B
Benjamin Pasero 已提交
752

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
					// 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);
772

773 774 775 776 777 778 779
						// Focus back to tree
						this.tree.DOMFocus();
					});

					return servicePromise;
				});
			});
780
		});
E
Erich Gamma 已提交
781 782 783 784 785
	}
}

/* Move File/Folder to trash */
export class MoveFileToTrashAction extends BaseDeleteFileAction {
M
Matt Bierner 已提交
786
	public static readonly ID = 'moveFileToTrash';
E
Erich Gamma 已提交
787 788 789 790 791 792

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
793
		@ITextFileService textFileService: ITextFileService,
794
		@IConfigurationService configurationService: IConfigurationService
E
Erich Gamma 已提交
795
	) {
796
		super(MoveFileToTrashAction.ID, nls.localize('delete', "Delete"), tree, element, true, fileService, messageService, textFileService, configurationService);
E
Erich Gamma 已提交
797 798 799 800 801 802
	}
}

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

M
Matt Bierner 已提交
803
	public static readonly ID = 'workbench.files.action.importFile';
E
Erich Gamma 已提交
804 805 806 807 808 809 810
	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IFileService fileService: IFileService,
811
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
812
		@IMessageService messageService: IMessageService,
813
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
814
	) {
B
Benjamin Pasero 已提交
815
		super(ImportFileAction.ID, nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
816 817 818 819 820 821 822 823 824 825 826

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

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

		this._updateEnablement();
	}

827
	public run(resources: URI[]): TPromise<any> {
828
		const importPromise = TPromise.as(null).then(() => {
829
			if (resources && resources.length > 0) {
E
Erich Gamma 已提交
830 831 832 833 834 835

				// Find parent for import
				let targetElement: FileStat;
				if (this.element) {
					targetElement = this.element;
				} else {
I
isidor 已提交
836 837
					const input: FileStat | Model = this.tree.getInput();
					targetElement = this.tree.getFocus() || (input instanceof Model ? input.roots[0] : input);
E
Erich Gamma 已提交
838 839 840 841 842 843 844 845 846 847
				}

				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
848
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
849 850 851 852 853
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

					let overwrite = true;
854 855
					if (resources.some(resource => {
						return !!targetNames[isLinux ? paths.basename(resource.fsPath) : paths.basename(resource.fsPath).toLowerCase()];
E
Erich Gamma 已提交
856
					})) {
857
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
858 859
							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 已提交
860 861
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
							type: 'warning'
E
Erich Gamma 已提交
862 863
						};

864
						overwrite = this.messageService.confirmSync(confirm);
E
Erich Gamma 已提交
865 866 867
					}

					if (!overwrite) {
868
						return void 0;
E
Erich Gamma 已提交
869 870
					}

871
					// Run import in sequence
872
					const importPromisesFactory: ITask<TPromise<void>>[] = [];
873
					resources.forEach(resource => {
E
Erich Gamma 已提交
874
						importPromisesFactory.push(() => {
875 876
							const sourceFile = resource;
							const targetFile = targetElement.resource.with({ path: paths.join(targetElement.resource.path, paths.basename(sourceFile.path)) });
877 878 879 880

							// 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.
881
							let revertPromise = TPromise.wrap(null);
882 883 884 885 886
							if (this.textFileService.isDirty(targetFile)) {
								revertPromise = this.textFileService.revertAll([targetFile], { soft: true });
							}

							return revertPromise.then(() => {
887 888 889
								return this.fileService.importFile(sourceFile, targetElement.resource).then(res => {

									// if we only import one file, just open it directly
890
									if (resources.length === 1) {
891 892
										this.editorService.openEditor({ resource: res.stat.resource, options: { pinned: true } }).done(null, errors.onUnexpectedError);
									}
893
								}, error => this.onError(error));
E
Erich Gamma 已提交
894 895 896 897 898 899 900
							});
						});
					});

					return sequence(importPromisesFactory);
				});
			}
901 902

			return void 0;
E
Erich Gamma 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
		});

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

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

M
Matt Bierner 已提交
918
	public static readonly ID = 'filesExplorer.copy';
E
Erich Gamma 已提交
919 920 921 922 923 924 925

	private tree: ITree;
	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
926
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
927
	) {
B
Benjamin Pasero 已提交
928
		super(CopyFileAction.ID, nls.localize('copyFile', "Copy"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
929 930 931 932 933 934

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

935
	public run(): TPromise<any> {
E
Erich Gamma 已提交
936 937 938 939 940 941 942 943 944 945 946

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

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

		this.tree.DOMFocus();

A
Alex Dima 已提交
947
		return TPromise.as(null);
E
Erich Gamma 已提交
948 949 950 951 952 953
	}
}

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

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

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
B
Benjamin Pasero 已提交
966
		super(PasteFileAction.ID, nls.localize('pasteFile', "Paste"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
967 968

		this.tree = tree;
I
isidor 已提交
969 970 971 972 973
		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 已提交
974 975 976 977 978 979 980 981 982 983 984
		this._updateEnablement();
	}

	_isEnabled(): boolean {

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

		// Check if file was deleted or moved meanwhile
I
isidor 已提交
985
		const exists = fileToCopy.root.find(fileToCopy.resource);
E
Erich Gamma 已提交
986 987 988 989 990 991
		if (!exists) {
			fileToCopy = null;
			return false;
		}

		// Check if target is ancestor of pasted folder
I
isidor 已提交
992
		if (this.element.resource.toString() !== fileToCopy.resource.toString() && resources.isEqualOrParent(this.element.resource, fileToCopy.resource, !isLinux /* ignorecase */)) {
E
Erich Gamma 已提交
993 994 995 996 997 998
			return false;
		}

		return true;
	}

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

		// Find target
		let target: FileStat;
1003
		if (this.element.resource.toString() === fileToCopy.resource.toString()) {
E
Erich Gamma 已提交
1004 1005 1006 1007 1008 1009
			target = this.element.parent;
		} else {
			target = this.element.isDirectory ? this.element : this.element.parent;
		}

		// Reuse duplicate action
1010
		const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
E
Erich Gamma 已提交
1011 1012 1013 1014 1015 1016 1017

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

1018 1019 1020
export const pasteIntoFocusedFilesExplorerViewItem = (accessor: ServicesAccessor) => {
	const instantiationService = accessor.get(IInstantiationService);

1021
	withFocusedFilesExplorer(accessor).then(res => {
1022 1023
		if (res) {
			const pasteAction = instantiationService.createInstance(PasteFileAction, res.tree, res.tree.getFocus());
1024 1025 1026 1027 1028 1029 1030
			if (pasteAction._isEnabled()) {
				pasteAction.run().done(null, errors.onUnexpectedError);
			}
		}
	});
};

E
Erich Gamma 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
	private tree: ITree;
	private target: IFileStat;

	constructor(
		tree: ITree,
		element: FileStat,
		target: FileStat,
		@IFileService fileService: IFileService,
1041
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
1042
		@IMessageService messageService: IMessageService,
1043
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
1044
	) {
B
Benjamin Pasero 已提交
1045
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
1046 1047 1048 1049 1050 1051 1052

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

1053
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1054 1055 1056 1057 1058 1059

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

1060
		// Copy File
1061 1062 1063 1064
		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 } });
			}
1065 1066

			return void 0;
1067
		}, error => this.onError(error));
E
Erich Gamma 已提交
1068 1069 1070 1071 1072 1073 1074

		return result;
	}

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

I
isidor 已提交
1075
		let candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1076
		while (true) {
I
isidor 已提交
1077
			if (!this.element.root.find(candidate)) {
E
Erich Gamma 已提交
1078 1079 1080 1081
				break;
			}

			name = this.toCopyName(name, this.element.isDirectory);
I
isidor 已提交
1082
			candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1083 1084 1085 1086 1087 1088 1089 1090
		}

		return candidate;
	}

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

		// file.1.txt=>file.2.txt
1091 1092
		if (!isFolder && name.match(/(.*\.)(\d+)(\..*)$/)) {
			return name.replace(/(.*\.)(\d+)(\..*)$/, (match, g1?, g2?, g3?) => { return g1 + (parseInt(g2) + 1) + g3; });
E
Erich Gamma 已提交
1093 1094 1095
		}

		// file.txt=>file.1.txt
1096
		const lastIndexOfDot = name.lastIndexOf('.');
E
Erich Gamma 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
		if (!isFolder && lastIndexOfDot >= 0) {
			return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
		}

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

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

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

M
Matt Bierner 已提交
1114 1115
	public static readonly ID = 'explorer.openToSide';
	public static readonly LABEL = nls.localize('openToSide', "Open to the Side");
E
Erich Gamma 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

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

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

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

		this.updateEnablement();
	}

	private updateEnablement(): void {
1137
		const activeEditor = this.editorService.getActiveEditor();
1138
		this.enabled = (!activeEditor || activeEditor.position !== Position.THREE);
E
Erich Gamma 已提交
1139 1140
	}

1141
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

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

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

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

1161
	constructor(resource: URI, tree: ITree) {
E
Erich Gamma 已提交
1162 1163 1164 1165 1166 1167 1168
		super('workbench.files.action.selectForCompare', nls.localize('compareSource', "Select for Compare"));

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

1169
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

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

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

A
Alex Dima 已提交
1180
		return TPromise.as(null);
E
Erich Gamma 已提交
1181 1182 1183 1184 1185 1186
	}
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

M
Matt Bierner 已提交
1187 1188
	public static readonly ID = 'workbench.files.action.compareFileWith';
	public static readonly LABEL = nls.localize('globalCompareFile', "Compare Active File With...");
E
Erich Gamma 已提交
1189 1190 1191 1192 1193 1194

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1195
		@IMessageService private messageService: IMessageService,
B
Benjamin Pasero 已提交
1196
		@IEditorGroupService private editorGroupService: IEditorGroupService
E
Erich Gamma 已提交
1197 1198 1199 1200
	) {
		super(id, label);
	}

1201
	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1202 1203
		const activeInput = this.editorService.getActiveEditorInput();
		const activeResource = activeInput ? activeInput.getResource() : void 0;
1204
		if (activeResource) {
E
Erich Gamma 已提交
1205

B
Benjamin Pasero 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
			// 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
						});
					});
1216
				}
B
Benjamin Pasero 已提交
1217
			});
1218

B
Benjamin Pasero 已提交
1219 1220 1221
			// 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 已提交
1222 1223 1224 1225 1226
			});
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1227
		return TPromise.as(true);
E
Erich Gamma 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
	}
}

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

	constructor(
		resource: URI,
		tree: ITree,
1239 1240 1241
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IEnvironmentService environmentService: IEnvironmentService
E
Erich Gamma 已提交
1242
	) {
1243
		super('workbench.files.action.compareFiles', CompareResourcesAction.computeLabel(resource, contextService, environmentService));
E
Erich Gamma 已提交
1244 1245 1246 1247 1248

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

1249
	private static computeLabel(resource: URI, contextService: IWorkspaceContextService, environmentService: IEnvironmentService): string {
E
Erich Gamma 已提交
1250
		if (globalResourceToCompare) {
1251 1252 1253 1254 1255 1256
			let leftResourceName = paths.basename(globalResourceToCompare.fsPath);
			let rightResourceName = paths.basename(resource.fsPath);

			// If the file names are identical, add more context by looking at the parent folder
			if (leftResourceName === rightResourceName) {
				const folderPaths = labels.shorten([
B
Benjamin Pasero 已提交
1257 1258
					labels.getPathLabel(resources.dirname(globalResourceToCompare), contextService, environmentService),
					labels.getPathLabel(resources.dirname(resource), contextService, environmentService)
1259 1260 1261 1262 1263 1264 1265
				]);

				leftResourceName = paths.join(folderPaths[0], leftResourceName);
				rightResourceName = paths.join(folderPaths[1], rightResourceName);
			}

			return nls.localize('compareWith', "Compare '{0}' with '{1}'", leftResourceName, rightResourceName);
E
Erich Gamma 已提交
1266 1267 1268 1269 1270
		}

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

B
Benjamin Pasero 已提交
1271
	public _isEnabled(): boolean {
E
Erich Gamma 已提交
1272 1273 1274 1275 1276 1277 1278 1279

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

		// Check if file was deleted or moved meanwhile (explorer only)
		if (this.tree) {
1280 1281 1282 1283 1284 1285 1286 1287
			const input = this.tree.getInput();
			if (input instanceof FileStat || input instanceof Model) {
				const exists = input instanceof Model ? input.findClosest(globalResourceToCompare) : input.find(globalResourceToCompare);
				if (!exists) {
					globalResourceToCompare = null;

					return false;
				}
E
Erich Gamma 已提交
1288 1289 1290 1291
			}
		}

		// Check if target is identical to source
1292
		if (this.resource.toString() === globalResourceToCompare.toString()) {
E
Erich Gamma 已提交
1293 1294 1295 1296 1297 1298
			return false;
		}

		return true;
	}

1299
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1300 1301 1302 1303 1304 1305

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

1306 1307
		return this.editorService.openEditor({
			leftResource: globalResourceToCompare,
1308
			rightResource: this.resource
1309
		});
E
Erich Gamma 已提交
1310 1311 1312 1313 1314 1315
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1316
	constructor(explorerView: ExplorerView, clazz: string) {
B
Benjamin Pasero 已提交
1317
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1318 1319 1320
	}
}

1321
export abstract class BaseSaveFileAction extends BaseErrorReportingAction {
E
Erich Gamma 已提交
1322 1323 1324
	constructor(
		id: string,
		label: string,
1325
		messageService: IMessageService
E
Erich Gamma 已提交
1326
	) {
1327
		super(id, label, messageService);
E
Erich Gamma 已提交
1328 1329
	}

1330
	public run(context?: any): TPromise<boolean> {
R
Ron Buckton 已提交
1331 1332 1333 1334
		return this.doRun(context).then(() => true, error => {
			this.onError(error);
			return null;
		});
E
Erich Gamma 已提交
1335 1336
	}

1337
	protected abstract doRun(context?: any): TPromise<boolean>;
E
Erich Gamma 已提交
1338 1339
}

1340
export abstract class BaseSaveOneFileAction extends BaseSaveFileAction {
E
Erich Gamma 已提交
1341 1342 1343 1344 1345 1346 1347
	private resource: URI;

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
1348
		@IEditorGroupService private editorGroupService: IEditorGroupService,
E
Erich Gamma 已提交
1349
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
1350 1351
		@IMessageService messageService: IMessageService,
		@IFileService private fileService: IFileService
E
Erich Gamma 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	) {
		super(id, label, messageService);

		this.enabled = true;
	}

	public abstract isSaveAs(): boolean;

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

1364
	protected doRun(context: any): TPromise<boolean> {
E
Erich Gamma 已提交
1365 1366 1367 1368
		let source: URI;
		if (this.resource) {
			source = this.resource;
		} else {
J
Johannes Rieken 已提交
1369
			source = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true });
E
Erich Gamma 已提交
1370 1371
		}

I
isidor 已提交
1372
		if (source && (this.fileService.canHandleResource(source) || source.scheme === 'untitled')) {
E
Erich Gamma 已提交
1373 1374 1375 1376 1377

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

B
Benjamin Pasero 已提交
1384
				let viewStateOfSource: IEditorViewState;
1385
				const activeEditor = this.editorService.getActiveEditor();
S
Sandeep Somavarapu 已提交
1386 1387
				const editor = getCodeEditor(activeEditor);
				if (editor) {
1388
					const activeResource = toResource(activeEditor.input, { supportSideBySide: true });
I
isidor 已提交
1389
					if (activeResource && (this.fileService.canHandleResource(activeResource) || source.scheme === 'untitled') && activeResource.toString() === source.toString()) {
B
Benjamin Pasero 已提交
1390
						viewStateOfSource = editor.saveViewState();
1391 1392 1393
					}
				}

E
Erich Gamma 已提交
1394
				// Special case: an untitled file with associated path gets saved directly unless "saveAs" is true
1395
				let savePromise: TPromise<URI>;
E
Erich Gamma 已提交
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
				if (!this.isSaveAs() && source.scheme === 'untitled' && this.untitledEditorService.hasAssociatedFilePath(source)) {
					savePromise = this.textFileService.save(source).then((result) => {
						if (result) {
							return URI.file(source.fsPath);
						}

						return null;
					});
				}

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

				return savePromise.then((target) => {
1412
					if (!target || target.toString() === source.toString()) {
1413
						return void 0; // save canceled or same resource used
E
Erich Gamma 已提交
1414 1415
					}

1416 1417 1418 1419 1420
					const replaceWith: IResourceInput = {
						resource: target,
						encoding: encodingOfSource,
						options: {
							pinned: true,
B
Benjamin Pasero 已提交
1421
							viewState: viewStateOfSource
1422
						}
1423
					};
1424

1425 1426
					return this.editorService.replaceEditors([{
						toReplace: { resource: source },
B
Benjamin Pasero 已提交
1427
						replaceWith
1428
					}]).then(() => true);
E
Erich Gamma 已提交
1429 1430
				});
			}
1431 1432 1433 1434 1435 1436 1437 1438

			// Pin the active editor if we are saving it
			if (!this.resource) {
				const editor = this.editorService.getActiveEditor();
				if (editor) {
					this.editorGroupService.pinEditor(editor.position, editor.input);
				}
			}
E
Erich Gamma 已提交
1439 1440

			// Just save
1441
			return this.textFileService.save(source, { force: true /* force a change to the file to trigger external watchers if any */ });
E
Erich Gamma 已提交
1442 1443
		}

A
Alex Dima 已提交
1444
		return TPromise.as(false);
E
Erich Gamma 已提交
1445 1446 1447
	}
}

1448
export class SaveFileAction extends BaseSaveOneFileAction {
E
Erich Gamma 已提交
1449

M
Matt Bierner 已提交
1450 1451
	public static readonly ID = 'workbench.action.files.save';
	public static readonly LABEL = nls.localize('save', "Save");
E
Erich Gamma 已提交
1452 1453 1454 1455 1456 1457

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

1458
export class SaveFileAsAction extends BaseSaveOneFileAction {
E
Erich Gamma 已提交
1459

M
Matt Bierner 已提交
1460 1461
	public static readonly ID = 'workbench.action.files.saveAs';
	public static readonly LABEL = nls.localize('saveAs', "Save As...");
E
Erich Gamma 已提交
1462 1463 1464 1465 1466 1467

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

1468
export abstract class BaseSaveAllAction extends BaseSaveFileAction {
E
Erich Gamma 已提交
1469 1470 1471 1472 1473 1474
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
1475
		@IWorkbenchEditorService protected editorService: IWorkbenchEditorService,
1476
		@IEditorGroupService private editorGroupService: IEditorGroupService,
E
Erich Gamma 已提交
1477 1478
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
1479 1480
		@IMessageService messageService: IMessageService,
		@IFileService protected fileService: IFileService
E
Erich Gamma 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
	) {
		super(id, label, messageService);

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

		this.registerListeners();
	}

1491
	protected abstract getSaveAllArguments(context?: any): any;
E
Erich Gamma 已提交
1492 1493 1494 1495 1496
	protected abstract includeUntitled(): boolean;

	private registerListeners(): void {

		// listen to files being changed locally
1497 1498 1499 1500
		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 已提交
1501 1502

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1503
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
		}
	}

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

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

1517
		// Store some properties per untitled file to restore later after save is completed
1518
		const mapUntitledToProperties: { [resource: string]: { encoding: string; indexInGroups: number[]; activeInGroups: boolean[] } } = Object.create(null);
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
		this.untitledEditorService.getDirty().forEach(resource => {
			const activeInGroups: boolean[] = [];
			const indexInGroups: number[] = [];
			const encoding = this.untitledEditorService.getEncoding(resource);

			// For each group
			stacks.groups.forEach((group, groupIndex) => {

				// Find out if editor is active in group
				const activeEditor = group.activeEditor;
				const activeResource = toResource(activeEditor, { supportSideBySide: true });
				activeInGroups[groupIndex] = (activeResource && activeResource.toString() === resource.toString());

				// Find index of editor in group
				indexInGroups[groupIndex] = -1;
				group.getEditors().forEach((editor, editorIndex) => {
					const editorResource = toResource(editor, { supportSideBySide: true });
					if (editorResource && editorResource.toString() === resource.toString()) {
						indexInGroups[groupIndex] = editorIndex;
						return;
					}
				});
1541
			});
1542

1543 1544 1545
			mapUntitledToProperties[resource.toString()] = { encoding, indexInGroups, activeInGroups };
		});

E
Erich Gamma 已提交
1546
		// Save all
1547 1548 1549
		return this.textFileService.saveAll(this.getSaveAllArguments(context)).then(results => {

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

1552
			results.results.forEach(result => {
B
Benjamin Pasero 已提交
1553
				if (!result.success || result.source.scheme !== 'untitled') {
1554
					return;
1555
				}
E
Erich Gamma 已提交
1556

B
Benjamin Pasero 已提交
1557 1558 1559 1560
				const untitledProps = mapUntitledToProperties[result.source.toString()];
				if (!untitledProps) {
					return;
				}
1561

B
Benjamin Pasero 已提交
1562 1563
				// For each position where the untitled file was opened
				untitledProps.indexInGroups.forEach((indexInGroup, index) => {
1564
					if (indexInGroup >= 0) {
B
Benjamin Pasero 已提交
1565
						untitledToReopen.push({
1566 1567
							input: {
								resource: result.target,
B
Benjamin Pasero 已提交
1568
								encoding: untitledProps.encoding,
1569 1570 1571
								options: {
									pinned: true,
									index: indexInGroup,
B
Benjamin Pasero 已提交
1572 1573
									preserveFocus: true,
									inactive: !untitledProps.activeInGroups[index]
1574 1575 1576 1577
								}
							},
							position: index
						});
E
Erich Gamma 已提交
1578
					}
1579 1580 1581
				});
			});

B
Benjamin Pasero 已提交
1582 1583 1584
			if (untitledToReopen.length) {
				return this.editorService.openEditors(untitledToReopen).then(() => true);
			}
1585 1586

			return void 0;
E
Erich Gamma 已提交
1587 1588 1589 1590
		});
	}

	public dispose(): void {
J
Joao Moreno 已提交
1591
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1592 1593 1594 1595 1596 1597 1598

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1599 1600
	public static readonly ID = 'workbench.action.files.saveAll';
	public static readonly LABEL = nls.localize('saveAll', "Save All");
E
Erich Gamma 已提交
1601 1602 1603 1604 1605

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

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

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

export class SaveAllInGroupAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1617 1618
	public static readonly ID = 'workbench.files.action.saveAllInGroup';
	public static readonly LABEL = nls.localize('saveAllInGroup', "Save All in Group");
1619 1620 1621 1622 1623

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

I
isidor 已提交
1624 1625
	protected getSaveAllArguments(editorIdentifier: IEditorIdentifier): any {
		if (!editorIdentifier) {
1626 1627 1628
			return this.includeUntitled();
		}

I
isidor 已提交
1629
		const editorGroup = editorIdentifier.group;
B
Benjamin Pasero 已提交
1630
		const resourcesToSave: URI[] = [];
1631
		editorGroup.getEditors().forEach(editor => {
1632
			const resource = toResource(editor, { supportSideBySide: true });
1633
			if (resource && (resource.scheme === 'untitled' || this.fileService.canHandleResource(resource))) {
1634
				resourcesToSave.push(resource);
1635 1636 1637 1638 1639 1640
			}
		});

		return resourcesToSave;
	}

E
Erich Gamma 已提交
1641 1642 1643 1644 1645 1646 1647
	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveFilesAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1648 1649
	public static readonly ID = 'workbench.action.files.saveFiles';
	public static readonly LABEL = nls.localize('saveFiles', "Save All Files");
E
Erich Gamma 已提交
1650

1651 1652 1653 1654
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

E
Erich Gamma 已提交
1655 1656 1657 1658 1659 1660 1661
	protected includeUntitled(): boolean {
		return false;
	}
}

export class RevertFileAction extends Action {

M
Matt Bierner 已提交
1662 1663
	public static readonly ID = 'workbench.action.files.revert';
	public static readonly LABEL = nls.localize('revert', "Revert File");
E
Erich Gamma 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681

	private resource: URI;

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

		this.enabled = true;
	}

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

1682
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1683 1684 1685 1686
		let resource: URI;
		if (this.resource) {
			resource = this.resource;
		} else {
1687
			resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
E
Erich Gamma 已提交
1688 1689 1690
		}

		if (resource && resource.scheme !== 'untitled') {
1691
			return this.textFileService.revert(resource, { force: true });
E
Erich Gamma 已提交
1692 1693
		}

A
Alex Dima 已提交
1694
		return TPromise.as(true);
E
Erich Gamma 已提交
1695 1696 1697
	}
}

1698
export class FocusOpenEditorsView extends Action {
1699

M
Matt Bierner 已提交
1700 1701
	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");
1702 1703 1704 1705 1706 1707 1708 1709 1710

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

1711
	public run(): TPromise<any> {
1712
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1713 1714
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
1715
				openEditorsView.setExpanded(true);
I
isidor 已提交
1716 1717
				openEditorsView.getViewer().DOMFocus();
			}
1718 1719 1720 1721
		});
	}
}

1722 1723
export class FocusFilesExplorer extends Action {

M
Matt Bierner 已提交
1724 1725
	public static readonly ID = 'workbench.files.action.focusFilesExplorer';
	public static readonly LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735

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

	public run(): TPromise<any> {
1736
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1737 1738
			const view = viewlet.getExplorerView();
			if (view) {
1739
				view.setExpanded(true);
1740 1741 1742 1743 1744 1745
				view.getViewer().DOMFocus();
			}
		});
	}
}

1746 1747
export class ShowActiveFileInExplorer extends Action {

M
Matt Bierner 已提交
1748 1749
	public static readonly ID = 'workbench.files.action.showActiveFileInExplorer';
	public static readonly LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");
1750 1751 1752 1753 1754

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1755
		@IInstantiationService private instantiationService: IInstantiationService,
1756 1757 1758 1759 1760 1761
		@IMessageService private messageService: IMessageService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1762 1763 1764
		const resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true });
		if (resource) {
			this.instantiationService.invokeFunction.apply(this.instantiationService, [revealInExplorerCommand, resource]);
1765 1766 1767 1768 1769 1770 1771 1772
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1773 1774
export class CollapseExplorerView extends Action {

M
Matt Bierner 已提交
1775 1776
	public static readonly ID = 'workbench.files.action.collapseExplorerFolders';
	public static readonly LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

	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 已提交
1803 1804
	public static readonly ID = 'workbench.files.action.refreshFilesExplorer';
	public static readonly LABEL = nls.localize('refreshExplorer', "Refresh Explorer");
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823

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

1824 1825
export class ShowOpenedFileInNewWindow extends Action {

M
Matt Bierner 已提交
1826 1827
	public static readonly ID = 'workbench.action.files.showOpenedFileInNewWindow';
	public static readonly LABEL = nls.localize('openFileInNewWindow', "Open Active File in New Window");
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

	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) {
1842
			this.windowsService.openWindow([fileResource.fsPath], { forceNewWindow: true, forceOpenWorkspaceAsFile: true });
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShowInNewWindow', "Open a file first to open in new window"));
		}

		return TPromise.as(true);
	}
}

export class RevealInOSAction extends Action {

M
Matt Bierner 已提交
1853
	public static readonly LABEL = isWindows ? nls.localize('revealInWindows', "Reveal in Explorer") : isMacintosh ? nls.localize('revealInMac', "Reveal in Finder") : nls.localize('openContainer', "Open Containing Folder");
1854 1855 1856 1857 1858

	constructor(
		private resource: URI,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
1859
		super('revealFileInOS', RevealInOSAction.LABEL);
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872

		this.order = 45;
	}

	public run(): TPromise<any> {
		this.instantiationService.invokeFunction.apply(this.instantiationService, [revealInOSCommand, this.resource]);

		return TPromise.as(true);
	}
}

export class GlobalRevealInOSAction extends Action {

M
Matt Bierner 已提交
1873 1874
	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"));
1875 1876 1877 1878

	constructor(
		id: string,
		label: string,
B
Benjamin Pasero 已提交
1879
		@IInstantiationService private instantiationService: IInstantiationService
1880 1881 1882 1883 1884
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1885
		this.instantiationService.invokeFunction.apply(this.instantiationService, [revealInOSCommand]);
1886 1887 1888 1889 1890

		return TPromise.as(true);
	}
}

1891 1892
export class CopyPathAction extends Action {

M
Matt Bierner 已提交
1893
	public static readonly LABEL = nls.localize('copyPath', "Copy Path");
1894 1895 1896 1897 1898

	constructor(
		private resource: URI,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
1899
		super('copyFilePath', CopyPathAction.LABEL);
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912

		this.order = 140;
	}

	public run(): TPromise<any> {
		this.instantiationService.invokeFunction.apply(this.instantiationService, [copyPathCommand, this.resource]);

		return TPromise.as(true);
	}
}

export class GlobalCopyPathAction extends Action {

M
Matt Bierner 已提交
1913 1914
	public static readonly ID = 'workbench.action.files.copyPathOfActiveFile';
	public static readonly LABEL = nls.localize('copyPathOfActive', "Copy Path of Active File");
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

	constructor(
		id: string,
		label: string,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1925
		this.instantiationService.invokeFunction.apply(this.instantiationService, [copyPathCommand]);
1926 1927 1928 1929 1930

		return TPromise.as(true);
	}
}

E
Erich Gamma 已提交
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
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);
		}
	}

1954 1955
	// Invalid File name
	if (!paths.isValidBasename(name)) {
1956
		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 已提交
1957 1958 1959 1960
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1961
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1962
		if (fullPathLength > 255) {
1963
			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 已提交
1964 1965 1966 1967 1968 1969
		}
	}

	return null;
}

1970 1971 1972 1973 1974 1975 1976 1977
function trimLongName(name: string): string {
	if (name && name.length > 255) {
		return `${name.substr(0, 255)}...`;
	}

	return name;
}

E
Erich Gamma 已提交
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
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;
}

1992
export class CompareWithSavedAction extends Action {
B
Benjamin Pasero 已提交
1993

M
Matt Bierner 已提交
1994 1995
	public static readonly ID = 'workbench.files.action.compareWithSaved';
	public static readonly LABEL = nls.localize('compareWithSaved', "Compare Active File with Saved");
B
Benjamin Pasero 已提交
1996

1997
	private static readonly SCHEME = 'showModifications';
1998 1999

	private resource: URI;
2000
	private toDispose: IDisposable[];
2001 2002 2003 2004 2005

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
2006
		@IInstantiationService instantiationService: IInstantiationService,
2007 2008 2009 2010 2011
		@ITextModelService textModelService: ITextModelService
	) {
		super(id, label);

		this.enabled = true;
2012 2013 2014 2015 2016 2017 2018
		this.toDispose = [];

		const provider = instantiationService.createInstance(FileOnDiskContentProvider);
		this.toDispose.push(provider);

		const registrationDisposal = textModelService.registerTextModelContentProvider(CompareWithSavedAction.SCHEME, provider);
		this.toDispose.push(registrationDisposal);
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
	}

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

	public run(): TPromise<any> {
		let resource: URI;
		if (this.resource) {
			resource = this.resource;
		} else {
			resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
		}

2033
		if (resource && resource.scheme === 'file') {
2034 2035
			const name = paths.basename(resource.fsPath);
			const editorLabel = nls.localize('modifiedLabel', "{0} (on disk) ↔ {1}", name, name);
B
Benjamin Pasero 已提交
2036 2037

			return this.editorService.openEditor({ leftResource: URI.from({ scheme: CompareWithSavedAction.SCHEME, path: resource.fsPath }), rightResource: resource, label: editorLabel });
2038 2039 2040 2041 2042
		}

		return TPromise.as(true);
	}

2043 2044 2045
	public dispose(): void {
		super.dispose();

2046
		this.toDispose = dispose(this.toDispose);
2047
	}
2048 2049
}

M
Max Furman 已提交
2050 2051
export class CompareWithClipboardAction extends Action {

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

2055
	private static readonly SCHEME = 'clipboardCompare';
M
Max Furman 已提交
2056

B
Benjamin Pasero 已提交
2057
	private registrationDisposal: IDisposable;
M
Max Furman 已提交
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071

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

		if (resource) {
B
Benjamin Pasero 已提交
2076 2077 2078 2079
			if (!this.registrationDisposal) {
				this.registrationDisposal = this.textModelService.registerTextModelContentProvider(CompareWithClipboardAction.SCHEME, provider);
			}

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

B
Benjamin Pasero 已提交
2083 2084 2085 2086 2087
			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 已提交
2088 2089 2090 2091 2092 2093 2094 2095
		}

		return TPromise.as(true);
	}

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

B
Benjamin Pasero 已提交
2096
		this.registrationDisposal = dispose(this.registrationDisposal);
M
Max Furman 已提交
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
	}
}

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 已提交
2109

M
Max Furman 已提交
2110 2111 2112 2113
		return TPromise.as(model);
	}
}

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