fileActions.ts 59.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 12
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
import { sequence, ITask } from 'vs/base/common/async';
E
Erich Gamma 已提交
13 14 15
import paths = require('vs/base/common/paths');
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
16
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
17
import strings = require('vs/base/common/strings');
J
Johannes Rieken 已提交
18
import { Event, EventType as CommonEventType } from 'vs/base/common/events';
19
import severity from 'vs/base/common/severity';
E
Erich Gamma 已提交
20
import diagnostics = require('vs/base/common/diagnostics');
J
Johannes Rieken 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import { BaseTextEditor } from 'vs/workbench/browser/parts/editor/textEditor';
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import { LocalFileChangeEvent, ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService, IFileStat, IImportResult } from 'vs/platform/files/common/files';
import { DiffEditorInput, toDiffLabel } from 'vs/workbench/common/editor/diffEditorInput';
import { asFileEditorInput, getUntitledOrFileResource, IEditorIdentifier } from 'vs/workbench/common/editor';
import { FileEditorInput } from 'vs/workbench/parts/files/common/editors/fileEditorInput';
import { FileStat, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerViewModel';
import { ExplorerView } from 'vs/workbench/parts/files/browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/browser/explorerViewlet';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService';
import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService';
import { Position, IResourceInput } from 'vs/platform/editor/common/editor';
import { IEventService } from 'vs/platform/event/common/event';
import { IInstantiationService, IConstructorSignature2 } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction } from 'vs/platform/message/common/message';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { Keybinding } from 'vs/base/common/keybinding';
import { Selection } from 'vs/editor/common/core/selection';
E
Erich Gamma 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

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

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

export class BaseFileAction extends Action {
	private _element: FileStat;

	constructor(
		id: string,
		label: string,
		@IWorkspaceContextService private _contextService: IWorkspaceContextService,
		@IWorkbenchEditorService private _editorService: IWorkbenchEditorService,
		@IFileService private _fileService: IFileService,
		@IMessageService private _messageService: IMessageService,
		@ITextFileService private _textFileService: ITextFileService,
		@IEventService private _eventService: IEventService
	) {
		super(id, label);

		this.enabled = false;
	}

	public get contextService() {
		return this._contextService;
	}

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

	public get editorService() {
		return this._editorService;
	}

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

	public get eventService() {
		return this._eventService;
	}

	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 {
118
		this.enabled = !!(this._contextService && this._fileService && this._editorService && this._isEnabled());
E
Erich Gamma 已提交
119 120 121 122 123 124 125 126 127 128
	}

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

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

129
	protected onErrorWithRetry(error: any, retry: () => TPromise<any>, extraAction?: Action): void {
130
		const actions = [
131 132
			new Action(this.id, nls.localize('retry', "Retry"), null, true, () => retry()),
			CancelAction
E
Erich Gamma 已提交
133 134 135
		];

		if (extraAction) {
136
			actions.unshift(extraAction);
E
Erich Gamma 已提交
137 138
		}

139
		const errorWithRetry: IMessageWithAction = {
140
			actions,
141
			message: toErrorMessage(error, false)
E
Erich Gamma 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
		};

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

export class TriggerRenameFileAction extends BaseFileAction {

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

	private tree: ITree;
	private renameAction: BaseRenameAction;

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super(TriggerRenameFileAction.ID, nls.localize('rename', "Rename"), contextService, editorService, fileService, messageService, textFileService, eventService);

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

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

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

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

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

				if (!message) {
					return null;
				}

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

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

213
			const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
E
Erich Gamma 已提交
214 215 216
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
217
					unbind.dispose();
E
Erich Gamma 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
				}
			});
		}).done(null, errors.onUnexpectedError);
	}
}

export abstract class BaseRenameAction extends BaseFileAction {

	constructor(
		id: string,
		label: string,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(id, label, contextService, editorService, fileService, messageService, textFileService, eventService);

		this.element = element;
	}

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

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

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

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

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

289
	public abstract runAction(newName: string): TPromise<any>;
E
Erich Gamma 已提交
290 291 292 293 294 295 296

	public onSuccess(stat: IFileStat): void {
		let before: IFileStat = null;
		if (!(this.element instanceof NewStatPlaceholder)) {
			before = this.element.clone(); // Clone element to not expose viewers element to listeners
		}

297
		this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(before, stat));
E
Erich Gamma 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
	}
}

export class RenameFileAction extends BaseRenameAction {

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

	constructor(
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
B
Benjamin Pasero 已提交
314
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, contextService, editorService, fileService, messageService, textFileService, eventService);
E
Erich Gamma 已提交
315 316 317 318

		this._updateEnablement();
	}

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

321 322 323 324 325 326 327 328 329 330 331 332 333
		// Handle dirty
		let revertPromise: TPromise<any> = TPromise.as(null);
		const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, this.element.resource.fsPath));
		if (dirty.length) {
			let message: string;
			if (this.element.isDirectory) {
				if (dirty.length === 1) {
					message = nls.localize('dirtyMessageFolderOne', "You are renaming a folder with unsaved changes in 1 file. Do you want to continue?");
				} else {
					message = nls.localize('dirtyMessageFolder', "You are renaming a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
				}
			} else {
				message = nls.localize('dirtyMessageFile', "You are renaming a file with unsaved changes. Do you want to continue?");
E
Erich Gamma 已提交
334 335
			}

336 337 338 339 340 341
			const res = this.messageService.confirm({
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton: nls.localize({ key: 'renameLabel', comment: ['&& denotes a mnemonic'] }, "&&Rename")
			});
E
Erich Gamma 已提交
342

343
			if (!res) {
A
Alex Dima 已提交
344
				return TPromise.as(null);
E
Erich Gamma 已提交
345 346
			}

347 348 349 350
			revertPromise = this.textFileService.revertAll(dirty);
		}

		return revertPromise.then(() => {
E
Erich Gamma 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
			return this.fileService.rename(this.element.resource, newName).then(null, (error: Error) => {
				this.onErrorWithRetry(error, () => this.runAction(newName));
			});
		});
	}
}

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

	constructor(
		id: string,
		label: string,
		tree: ITree,
		isFile: boolean,
		editableAction: BaseRenameAction,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(id, label, contextService, editorService, fileService, messageService, textFileService, eventService);

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

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

390
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
391
		if (!context) {
392
			return TPromise.wrapError('No context provided to BaseNewAction.');
E
Erich Gamma 已提交
393 394
		}

395
		const viewletState = <IFileViewletState>context.viewletState;
E
Erich Gamma 已提交
396
		if (!viewletState) {
397
			return TPromise.wrapError('Invalid viewlet state provided to BaseNewAction.');
E
Erich Gamma 已提交
398 399 400 401
		}

		let folder: FileStat = this.presetFolder;
		if (!folder) {
402
			const focus = <FileStat>this.tree.getFocus();
E
Erich Gamma 已提交
403 404 405 406 407 408 409 410
			if (focus) {
				folder = focus.isDirectory ? focus : focus.parent;
			} else {
				folder = this.tree.getInput();
			}
		}

		if (!folder) {
411
			return TPromise.wrapError('Invalid parent folder to create.');
E
Erich Gamma 已提交
412 413 414 415
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
416
				const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);
E
Erich Gamma 已提交
417 418 419 420 421 422

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
423
						const message = this.renameAction.validateFileName(folder, value);
E
Erich Gamma 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

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

442
							const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
E
Erich Gamma 已提交
443 444 445
								if (!e.highlight) {
									stat.destroy();
									this.tree.refresh(folder).done(null, errors.onUnexpectedError);
A
Alex Dima 已提交
446
									unbind.dispose();
E
Erich Gamma 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
								}
							});
						});
					});
				});
			});
		});
	}
}

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

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super('workbench.action.files.newFile', nls.localize('newFile', "New File"), tree, true, instantiationService.createInstance(CreateFileAction, element), null, contextService, editorService, fileService, messageService, textFileService, eventService);

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

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

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
		super('workbench.action.files.newFolder', nls.localize('newFolder', "New Folder"), tree, false, instantiationService.createInstance(CreateFolderAction, element), null, contextService, editorService, fileService, messageService, textFileService, eventService);

		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 已提交
506 507
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
508 509 510 511
	) {
		super(id, label);
	}

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

517 518
				const explorer = <ExplorerViewlet>viewlet;
				const explorerView = explorer.getExplorerView();
E
Erich Gamma 已提交
519

B
fix npe  
Benjamin Pasero 已提交
520 521 522 523 524
				// 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 已提交
525 526 527 528
				if (!explorerView.isExpanded()) {
					explorerView.expand();
				}

529
				const action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);
E
Erich Gamma 已提交
530 531 532 533 534 535

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

536
	protected abstract getAction(): IConstructorSignature2<ITree, IFileStat, Action>;
E
Erich Gamma 已提交
537 538 539 540 541 542 543 544 545 546 547 548

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

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

/* Create new file from anywhere: Open untitled */
549
export class GlobalNewUntitledFileAction extends Action {
E
Erich Gamma 已提交
550
	public static ID = 'workbench.action.files.newUntitledFile';
S
Sam Verschueren 已提交
551
	public static LABEL = nls.localize('newUntitledFile', "New Untitled File");
E
Erich Gamma 已提交
552 553 554 555 556 557 558 559 560 561

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

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

565
		return this.editorService.openEditor(input, { pinned: true }); // untitled are always pinned
E
Erich Gamma 已提交
566 567 568
	}
}

569 570 571 572 573 574 575 576 577 578
/* Create new file from anywhere */
export class GlobalNewFileAction extends BaseGlobalNewAction {
	public static ID = 'workbench.action.files.newFile';
	public static LABEL = nls.localize('newFile', "New File");

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

E
Erich Gamma 已提交
579 580 581 582 583
/* Create new folder from anywhere */
export class GlobalNewFolderAction extends BaseGlobalNewAction {
	public static ID = 'workbench.action.files.newFolder';
	public static LABEL = nls.localize('newFolder', "New Folder");

584
	protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
E
Erich Gamma 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
		return NewFolderAction;
	}
}

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

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

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

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

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

	constructor(
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
B
Benjamin Pasero 已提交
616
		super(CreateFileAction.ID, CreateFileAction.LABEL, element, contextService, editorService, fileService, messageService, textFileService, eventService);
E
Erich Gamma 已提交
617 618 619 620

		this._updateEnablement();
	}

621
	public runAction(fileName: string): TPromise<any> {
622
		return this.fileService.createFile(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
E
Erich Gamma 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

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

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

	constructor(
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
B
Benjamin Pasero 已提交
643
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, contextService, editorService, fileService, messageService, textFileService, eventService);
E
Erich Gamma 已提交
644 645 646 647

		this._updateEnablement();
	}

648
	public runAction(fileName: string): TPromise<any> {
E
Erich Gamma 已提交
649 650 651 652 653 654 655 656 657
		return this.fileService.createFolder(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
			this.onErrorWithRetry(error, () => this.runAction(fileName));
		});
	}
}

export class BaseDeleteFileAction extends BaseFileAction {
	private tree: ITree;
	private useTrash: boolean;
658
	private skipConfirm: boolean;
E
Erich Gamma 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

	constructor(
		id: string,
		label: string,
		tree: ITree,
		element: FileStat,
		useTrash: boolean,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(id, label, contextService, editorService, fileService, messageService, textFileService, eventService);

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

		this._updateEnablement();
	}

682
	public run(context?: any): TPromise<any> {
E
Erich Gamma 已提交
683 684 685 686 687 688

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

689 690 691 692 693 694 695 696
		// Read context
		if (context && context.event) {
			const bypassTrash = (isMacintosh && context.event.altKey) || (!isMacintosh && context.event.shiftKey);
			if (bypassTrash) {
				this.useTrash = false;
			}
		}

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
		let primaryButton: string;
		if (this.useTrash) {
			primaryButton = isWindows ? nls.localize('deleteButtonLabelRecycleBin', "&&Move to Recycle Bin") : nls.localize({ key: 'deleteButtonLabelTrash', comment: ['&& denotes a mnemonic'] }, "&&Move to Trash");
		} else {
			primaryButton = nls.localize({ key: 'deleteButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete");
		}

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

719 720 721 722 723 724 725 726
			const res = this.messageService.confirm({
				message,
				type: 'warning',
				detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
				primaryButton
			});

			if (!res) {
A
Alex Dima 已提交
727
				return TPromise.as(null);
728
			}
729 730 731

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

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
		// Check if file is dirty in editor and save it to avoid data loss
		return revertPromise.then(() => {

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

754 755 756
				if (!this.messageService.confirm(confirm)) {
					return TPromise.as(null);
				}
E
Erich Gamma 已提交
757 758
			}

759 760 761
			// Since a delete operation can take a while we want to emit the event proactively to avoid issues
			// with stale entries in the explorer tree.
			this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(this.element.clone(), null));
E
Erich Gamma 已提交
762

763
			// Call function
764
			const servicePromise = this.fileService.del(this.element.resource, this.useTrash).then(() => {
765 766 767 768
				if (this.element.parent) {
					this.tree.setFocus(this.element.parent); // move focus to parent
				}
			}, (error: any) => {
E
Erich Gamma 已提交
769

770 771 772 773 774
				// Allow to retry
				let extraAction: Action;
				if (this.useTrash) {
					extraAction = new Action('permanentDelete', nls.localize('permDelete', "Delete Permanently"), null, true, () => { this.useTrash = false; this.skipConfirm = true; return this.run(); });
				}
E
Erich Gamma 已提交
775

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

778
				// Since the delete failed, best we can do is to refresh the explorer from the root to show the current state of files.
779
				const event = new LocalFileChangeEvent(new FileStat(this.contextService.getWorkspace().resource, true, true), new FileStat(this.contextService.getWorkspace().resource, true, true));
780 781 782 783 784 785 786 787
				this.eventService.emit('files.internal:fileChanged', event);

				// Focus back to tree
				this.tree.DOMFocus();
			});

			return servicePromise;
		});
E
Erich Gamma 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
	}
}

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

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(MoveFileToTrashAction.ID, nls.localize('delete', "Delete"), tree, element, true, contextService, editorService, fileService, messageService, textFileService, eventService);
	}
}

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

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

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
B
Benjamin Pasero 已提交
824
		@IEventService eventService: IEventService
E
Erich Gamma 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
	) {
		super(ImportFileAction.ID, nls.localize('importFiles', "Import Files"), contextService, editorService, fileService, messageService, textFileService, eventService);

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

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

		this._updateEnablement();
	}

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

842
	public run(context?: any): TPromise<any> {
843 844
		const importPromise = TPromise.as(null).then(() => {
			const input = context.input;
E
Erich Gamma 已提交
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
			if (input.files && input.files.length > 0) {

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

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

				// Create real files array
860
				const filesArray: File[] = [];
E
Erich Gamma 已提交
861
				for (let i = 0; i < input.files.length; i++) {
862
					const file = input.files[i];
E
Erich Gamma 已提交
863 864 865 866 867 868 869
					filesArray.push(file);
				}

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

					// Check for name collisions
870
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
871 872 873 874 875 876 877 878
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

					let overwrite = true;
					if (filesArray.some((file) => {
						return !!targetNames[isLinux ? file.name : file.name.toLowerCase()];
					})) {
879
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
880 881
							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 已提交
882
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace")
E
Erich Gamma 已提交
883 884 885 886 887 888 889 890 891
						};

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

					if (!overwrite) {
						return;
					}

892
					// Run import in sequence
893
					const importPromisesFactory: ITask<TPromise<void>>[] = [];
E
Erich Gamma 已提交
894 895
					filesArray.forEach((file) => {
						importPromisesFactory.push(() => {
896
							const sourceFile = URI.file((<any>file).path);
897 898

							return this.fileService.importFile(sourceFile, targetElement.resource).then((result: IImportResult) => {
E
Erich Gamma 已提交
899 900
								if (result.stat) {

901
									// Emit Deleted Event if file gets replaced unless it is the same file
902
									const oldFile = targetNames[isLinux ? file.name : file.name.toLowerCase()];
903
									if (oldFile && oldFile.resource.fsPath !== result.stat.resource.fsPath) {
904
										this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(oldFile, null));
E
Erich Gamma 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
									}

									// Emit Import Event
									this.eventService.emit('files.internal:fileChanged', new FileImportedEvent(result.stat, result.isNew, context.event));
								}
							}, (error: any) => {
								this.messageService.show(Severity.Error, error);
							});
						});
					});

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

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

/** File import event is emitted when a file is import into the workbench. */
931
export class FileImportedEvent extends LocalFileChangeEvent {
E
Erich Gamma 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
	private isNew: boolean;

	constructor(stat?: IFileStat, isNew?: boolean, originalEvent?: Event) {
		super(null, stat, originalEvent);

		this.isNew = isNew;
	}

	public gotAdded(): boolean {
		return this.isNew;
	}

	public gotMoved(): boolean {
		return false;
	}

	public gotUpdated(): boolean {
		return !this.isNew;
	}

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

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

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

	private tree: ITree;
	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(CopyFileAction.ID, nls.localize('copyFile', "Copy"), contextService, editorService, fileService, messageService, textFileService, eventService);

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

981
	public run(): TPromise<any> {
E
Erich Gamma 已提交
982 983 984 985 986 987 988 989 990 991 992

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

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

		this.tree.DOMFocus();

A
Alex Dima 已提交
993
		return TPromise.as(null);
E
Erich Gamma 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
	}
}

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

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

	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
		super(PasteFileAction.ID, nls.localize('pasteFile', "Paste"), contextService, editorService, fileService, messageService, textFileService, eventService);

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

	_isEnabled(): boolean {

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

		// Check if file was deleted or moved meanwhile
1030 1031
		const root: FileStat = this.tree.getInput();
		const exists = root.find(fileToCopy.resource);
E
Erich Gamma 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
		if (!exists) {
			fileToCopy = null;
			return false;
		}

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

		return true;
	}

1045
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

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

		// Reuse duplicate action
1056
		const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
E
Erich Gamma 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

		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,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
B
Benjamin Pasero 已提交
1078
		@IEventService eventService: IEventService
E
Erich Gamma 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087
	) {
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), contextService, editorService, fileService, messageService, textFileService, eventService);

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

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

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

		// Copy File and emit event
1096
		const result = this.fileService.copyFile(this.element.resource, this.findTarget()).then((stat: IFileStat) => {
1097
			this.eventService.emit('files.internal:fileChanged', new LocalFileChangeEvent(null, stat));
E
Erich Gamma 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
		}, (error: any) => {
			this.onError(error);
		});

		return result;
	}

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

	private findTarget(): URI {
1110
		const root: FileStat = this.tree.getInput();
E
Erich Gamma 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
		let name = this.element.name;

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

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

		return candidate;
	}

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

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

		// file.txt=>file.1.txt
1134
		const lastIndexOfDot = name.lastIndexOf('.');
E
Erich Gamma 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
		if (!isFolder && lastIndexOfDot >= 0) {
			return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
		}

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

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

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

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

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

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

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

		this.updateEnablement();
	}

	private updateEnablement(): void {
1175
		const activeEditor = this.editorService.getActiveEditor();
E
Erich Gamma 已提交
1176 1177 1178
		this.enabled = (!activeEditor || activeEditor.position !== Position.RIGHT);
	}

1179
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

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

1199
	constructor(resource: URI, tree: ITree) {
E
Erich Gamma 已提交
1200 1201 1202 1203 1204 1205 1206
		super('workbench.files.action.selectForCompare', nls.localize('compareSource', "Select for Compare"));

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

1207
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

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

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

A
Alex Dima 已提交
1218
		return TPromise.as(null);
E
Erich Gamma 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
	}
}

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

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

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1234
		@IEditorGroupService private editorGroupService: IEditorGroupService,
1235
		@IMessageService private messageService: IMessageService
E
Erich Gamma 已提交
1236 1237 1238 1239
	) {
		super(id, label);
	}

1240
	public run(): TPromise<any> {
1241
		const fileInput = asFileEditorInput(this.editorService.getActiveEditorInput());
E
Erich Gamma 已提交
1242 1243 1244 1245 1246 1247
		if (fileInput) {

			// Keep as resource to compare
			globalResourceToCompare = fileInput.getResource();

			// Listen for next editor to open
1248
			const unbind = this.editorGroupService.onEditorOpening(e => {
A
Alex Dima 已提交
1249
				unbind.dispose(); // listen once
E
Erich Gamma 已提交
1250

1251
				const otherFileInput = asFileEditorInput(e.editorInput);
E
Erich Gamma 已提交
1252
				if (otherFileInput) {
1253
					const compareAction = this.instantiationService.createInstance(CompareResourcesAction, otherFileInput.getResource(), null);
E
Erich Gamma 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
					if (compareAction._isEnabled()) {
						e.prevent();

						compareAction.run().done(() => compareAction.dispose());
					} else {
						this.messageService.show(Severity.Info, nls.localize('unableToFileToCompare', "The selected file can not be compared with '{0}'.", paths.basename(globalResourceToCompare.fsPath)));
					}
				}
			});

			// Bring up quick open
			this.quickOpenService.show().then(() => {
A
Alex Dima 已提交
1266
				unbind.dispose(); // make sure to unbind if quick open is closing
E
Erich Gamma 已提交
1267 1268 1269 1270 1271 1272
			});

		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1273
		return TPromise.as(true);
E
Erich Gamma 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	}
}

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

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

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

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

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

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

	_isEnabled(): boolean {

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

		// Check if file was deleted or moved meanwhile (explorer only)
		if (this.tree) {
1316
			const root: FileStat = this.tree.getInput();
E
Erich Gamma 已提交
1317
			if (root instanceof FileStat) {
1318
				const exists = root.find(globalResourceToCompare);
E
Erich Gamma 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
				if (!exists) {
					globalResourceToCompare = null;
					return false;
				}
			}
		}

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

		return true;
	}

1334
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1335 1336 1337 1338 1339 1340

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

1341 1342
		const leftInput = this.instantiationService.createInstance(FileEditorInput, globalResourceToCompare, void 0);
		const rightInput = this.instantiationService.createInstance(FileEditorInput, this.resource, void 0);
E
Erich Gamma 已提交
1343

1344
		return this.editorService.openEditor(new DiffEditorInput(toDiffLabel(globalResourceToCompare, this.resource, this.contextService), null, leftInput, rightInput));
E
Erich Gamma 已提交
1345 1346 1347 1348 1349 1350
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1351
	constructor(explorerView: ExplorerView, clazz: string) {
1352
		super('workbench.files.action.refreshExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
	}
}

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

1365 1366
	public run(context?: any): TPromise<boolean> {
		return this.doRun(context).then(() => true, (error) => {
1367
			this.messageService.show(Severity.Error, toErrorMessage(error, false));
E
Erich Gamma 已提交
1368 1369 1370
		});
	}

1371
	protected abstract doRun(context?: any): TPromise<boolean>;
E
Erich Gamma 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
}

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

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

		this.enabled = true;
	}

	public abstract isSaveAs(): boolean;

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

1396
	protected doRun(context: any): TPromise<boolean> {
E
Erich Gamma 已提交
1397 1398 1399 1400
		let source: URI;
		if (this.resource) {
			source = this.resource;
		} else {
B
Benjamin Pasero 已提交
1401
			source = getUntitledOrFileResource(this.editorService.getActiveEditorInput(), true);
E
Erich Gamma 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
		}

		if (source) {

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

1416
				let selectionOfSource: Selection;
1417 1418
				const activeEditor = this.editorService.getActiveEditor();
				if (activeEditor instanceof BaseTextEditor) {
1419 1420
					const activeResource = getUntitledOrFileResource(activeEditor.input, true);
					if (activeResource && activeResource.toString() === source.toString()) {
1421
						selectionOfSource = <Selection>activeEditor.getSelection();
1422 1423 1424
					}
				}

E
Erich Gamma 已提交
1425
				// Special case: an untitled file with associated path gets saved directly unless "saveAs" is true
1426
				let savePromise: TPromise<URI>;
E
Erich Gamma 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
				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) => {
1443 1444
					if (!target || target.toString() === source.toString()) {
						return; // save canceled or same resource used
E
Erich Gamma 已提交
1445 1446
					}

1447 1448 1449 1450 1451 1452
					const replaceWith: IResourceInput = {
						resource: target,
						encoding: encodingOfSource,
						options: {
							pinned: true,
							selection: selectionOfSource
1453
						}
1454
					};
1455

1456 1457 1458 1459
					return this.editorService.replaceEditors([{
						toReplace: { resource: source },
						replaceWith: replaceWith
					}]).then(() => true);
E
Erich Gamma 已提交
1460 1461 1462 1463
				});
			}

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

A
Alex Dima 已提交
1467
		return TPromise.as(false);
E
Erich Gamma 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
	}
}

export class SaveFileAction extends BaseSaveFileAction {

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

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

export class SaveFileAsAction extends BaseSaveFileAction {

	public static ID = 'workbench.action.files.saveAs';
1484
	public static LABEL = nls.localize('saveAs', "Save As...");
E
Erich Gamma 已提交
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

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

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

	constructor(
		id: string,
		label: string,
1498
		@IWorkbenchEditorService protected editorService: IWorkbenchEditorService,
1499
		@IEditorGroupService private editorGroupService: IEditorGroupService,
E
Erich Gamma 已提交
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IMessageService messageService: IMessageService
	) {
		super(id, label, messageService);

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

		this.registerListeners();
	}

1513
	protected abstract getSaveAllArguments(context?: any): any;
E
Erich Gamma 已提交
1514 1515 1516 1517 1518
	protected abstract includeUntitled(): boolean;

	private registerListeners(): void {

		// listen to files being changed locally
1519 1520 1521 1522
		this.toDispose.push(this.textFileService.models.onModelDirty(e => this.updateEnablement(true)));
		this.toDispose.push(this.textFileService.models.onModelSaved(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelReverted(e => this.updateEnablement(false)));
		this.toDispose.push(this.textFileService.models.onModelSaveError(e => this.updateEnablement(true)));
E
Erich Gamma 已提交
1523 1524

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1525
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
		}
	}

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

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

1539
		// Store some properties per untitled file to restore later after save is completed
1540
		const mapUntitledToProperties: { [resource: string]: { encoding: string; indexInGroups: number[]; activeInGroups: boolean[] } } = Object.create(null);
1541
		this.textFileService.getDirty()
1542
			.filter(r => r.scheme === 'untitled')			// All untitled resources
1543
			.map(r => this.untitledEditorService.get(r))	// Mapped to their inputs
B
Benjamin Pasero 已提交
1544 1545 1546 1547 1548 1549 1550
			.filter(input => !!input)								// If possible :)
			.forEach(input => {
				mapUntitledToProperties[input.getResource().toString()] = {
					encoding: input.getEncoding(),
					indexInGroups: stacks.groups.map(g => g.indexOf(input)),
					activeInGroups: stacks.groups.map(g => g.isActive(input))
				};
1551
			});
1552

E
Erich Gamma 已提交
1553
		// Save all
1554 1555 1556
		return this.textFileService.saveAll(this.getSaveAllArguments(context)).then(results => {

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

1559
			results.results.forEach(result => {
B
Benjamin Pasero 已提交
1560
				if (!result.success || result.source.scheme !== 'untitled') {
1561
					return;
1562
				}
E
Erich Gamma 已提交
1563

B
Benjamin Pasero 已提交
1564 1565 1566 1567
				const untitledProps = mapUntitledToProperties[result.source.toString()];
				if (!untitledProps) {
					return;
				}
1568

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

B
Benjamin Pasero 已提交
1589 1590 1591
			if (untitledToReopen.length) {
				return this.editorService.openEditors(untitledToReopen).then(() => true);
			}
E
Erich Gamma 已提交
1592 1593 1594 1595
		});
	}

	public dispose(): void {
J
Joao Moreno 已提交
1596
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

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

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

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

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

export class SaveAllInGroupAction extends BaseSaveAllAction {

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

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

I
isidor 已提交
1629 1630
	protected getSaveAllArguments(editorIdentifier: IEditorIdentifier): any {
		if (!editorIdentifier) {
1631 1632 1633
			return this.includeUntitled();
		}

I
isidor 已提交
1634
		const editorGroup = editorIdentifier.group;
1635 1636
		const resourcesToSave = [];
		editorGroup.getEditors().forEach(editor => {
1637 1638 1639
			const resource = getUntitledOrFileResource(editor, true);
			if (resource) {
				resourcesToSave.push(resource);
1640 1641 1642 1643 1644 1645
			}
		});

		return resourcesToSave;
	}

E
Erich Gamma 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveFilesAction extends BaseSaveAllAction {

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

1656 1657 1658 1659
	protected getSaveAllArguments(): boolean {
		return this.includeUntitled();
	}

E
Erich Gamma 已提交
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	protected includeUntitled(): boolean {
		return false;
	}
}

export class RevertFileAction extends Action {

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

	private resource: URI;

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

		this.enabled = true;
	}

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

1687
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1688 1689 1690 1691
		let resource: URI;
		if (this.resource) {
			resource = this.resource;
		} else {
1692
			const activeFileInput = asFileEditorInput(this.editorService.getActiveEditorInput(), true);
E
Erich Gamma 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701
			if (activeFileInput) {
				resource = activeFileInput.getResource();
			}
		}

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

A
Alex Dima 已提交
1702
		return TPromise.as(true);
E
Erich Gamma 已提交
1703 1704 1705
	}
}

1706
export class FocusOpenEditorsView extends Action {
1707

1708
	public static ID = 'workbench.files.action.focusOpenEditorsView';
I
isidor 已提交
1709
	public static LABEL = nls.localize({ key: 'focusOpenEditors', comment: ['Open is an adjective'] }, "Focus on Open Editors View");
1710 1711 1712 1713 1714 1715 1716 1717 1718

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

1719
	public run(): TPromise<any> {
1720
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1721 1722 1723 1724 1725
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
				openEditorsView.expand();
				openEditorsView.getViewer().DOMFocus();
			}
1726 1727 1728 1729
		});
	}
}

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
export class FocusFilesExplorer extends Action {

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

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

	public run(): TPromise<any> {
1744
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1745 1746 1747 1748 1749 1750 1751 1752 1753
			const view = viewlet.getExplorerView();
			if (view) {
				view.expand();
				view.getViewer().DOMFocus();
			}
		});
	}
}

1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
export class ShowActiveFileInExplorer extends Action {

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

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

	public run(): TPromise<any> {
1771
		const fileInput = asFileEditorInput(this.editorService.getActiveEditorInput(), true);
1772
		if (fileInput) {
1773
			return this.viewletService.openViewlet(VIEWLET_ID, false).then((viewlet: ExplorerViewlet) => {
1774 1775 1776 1777 1778 1779 1780 1781
				const isInsideWorkspace = this.contextService.isInsideWorkspace(fileInput.getResource());
				if (isInsideWorkspace) {
					const explorerView = viewlet.getExplorerView();
					if (explorerView) {
						explorerView.expand();
						explorerView.select(fileInput.getResource(), true);
					}
				} else {
I
isidor 已提交
1782
					const openEditorsView = viewlet.getOpenEditorsView();
I
isidor 已提交
1783 1784 1785
					if (openEditorsView) {
						openEditorsView.expand();
					}
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
				}
			});
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1796 1797
export class CollapseExplorerView extends Action {

B
Benjamin Pasero 已提交
1798
	public static ID = 'workbench.files.action.collapseFilesExplorerFolders';
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
	public static LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");

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

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

export class RefreshExplorerView extends Action {

B
Benjamin Pasero 已提交
1826
	public static ID = 'workbench.files.action.refreshFilesExplorer';
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
	public static LABEL = nls.localize('refreshExplorer', "Refresh Explorer");

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

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

E
Erich Gamma 已提交
1847 1848
export function keybindingForAction(id: string): Keybinding {
	switch (id) {
1849
		case GlobalNewUntitledFileAction.ID:
E
Erich Gamma 已提交
1850 1851 1852 1853 1854 1855
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_N);
		case TriggerRenameFileAction.ID:
			return new Keybinding(isMacintosh ? KeyCode.Enter : KeyCode.F2);
		case SaveFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_S);
		case MoveFileToTrashAction.ID:
1856
			return new Keybinding(isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete);
E
Erich Gamma 已提交
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
		case CopyFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_C);
		case PasteFileAction.ID:
			return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_V);
		case OpenToSideAction.ID:
			if (isMacintosh) {
				return new Keybinding(KeyMod.WinCtrl | KeyCode.Enter);
			} else {
				return new Keybinding(KeyMod.CtrlCmd | KeyCode.Enter);
			}
	}

	return null;
}

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

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

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

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

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

1895 1896 1897
	// Invalid File name
	if (!paths.isValidBasename(name)) {
		return nls.localize('invalidFileNameError', "The name **{0}** is not valid as a file or folder name. Please choose a different name.", name);
E
Erich Gamma 已提交
1898 1899 1900 1901
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1902
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
		if (fullPathLength > 255) {
			return nls.localize('filePathTooLongError', "The name **{0}** results in a path that is too long. Please choose a shorter name.", name);
		}
	}

	return null;
}

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

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

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

	return filename;
}

// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
1928
	diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
E
Erich Gamma 已提交
1929 1930 1931
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
}