fileActions.ts 55.8 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import 'vs/css!./media/fileactions';
J
Johannes Rieken 已提交
9
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
10
import nls = require('vs/nls');
J
Johannes Rieken 已提交
11
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
12
import { sequence, ITask, always } from 'vs/base/common/async';
E
Erich Gamma 已提交
13
import paths = require('vs/base/common/paths');
I
isidor 已提交
14
import resources = require('vs/base/common/resources');
E
Erich Gamma 已提交
15 16
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
J
Johannes Rieken 已提交
17
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
18
import strings = require('vs/base/common/strings');
19
import severity from 'vs/base/common/severity';
E
Erich Gamma 已提交
20
import diagnostics = require('vs/base/common/diagnostics');
J
Johannes Rieken 已提交
21 22
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
23
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
J
Johannes Rieken 已提交
24
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
25
import { VIEWLET_ID, FileOnDiskContentProvider } from 'vs/workbench/parts/files/common/files';
26
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
27
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
I
isidor 已提交
28
import { toResource } from 'vs/workbench/common/editor';
29
import { FileStat, Model, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerModel';
30 31
import { ExplorerView } from 'vs/workbench/parts/files/electron-browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/electron-browser/explorerViewlet';
J
Johannes Rieken 已提交
32 33 34 35
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
B
Benjamin Pasero 已提交
36
import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen';
B
Benjamin Pasero 已提交
37
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
38
import { IUntitledResourceInput } from 'vs/platform/editor/common/editor';
39
import { IInstantiationService, IConstructorSignature2, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
40
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction, IConfirmationResult } from 'vs/platform/message/common/message';
41
import { IModel } from 'vs/editor/common/editorCommon';
42
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
43
import { IWindowsService } from 'vs/platform/windows/common/windows';
I
isidor 已提交
44
import { withFocusedFilesExplorer, REVERT_FILE_COMMAND_ID, COMPARE_WITH_SAVED_COMMAND_ID, REVEAL_IN_OS_COMMAND_ID, COPY_PATH_COMMAND_ID, REVEAL_IN_EXPLORER_COMMAND_ID, SAVE_FILE_AS_COMMAND_ID, SAVE_FILE_COMMAND_ID, SAVE_FILE_LABEL, SAVE_FILE_AS_LABEL, SAVE_ALL_COMMAND_ID, SAVE_ALL_LABEL, SAVE_ALL_IN_GROUP_COMMAND_ID, SAVE_FILES_COMMAND_ID, SAVE_FILES_LABEL, COMPARE_WITH_SAVED_SCHEMA, IExplorerContext } from 'vs/workbench/parts/files/electron-browser/fileCommands';
M
Max Furman 已提交
45
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
46
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
47
import { once } from 'vs/base/common/event';
M
Max Furman 已提交
48 49 50
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IModelService } from 'vs/editor/common/services/modelService';
I
isidor 已提交
51 52
import { ICommandService, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { IListService } from 'vs/platform/list/browser/listService';
M
Max Furman 已提交
53

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

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

I
isidor 已提交
65 66 67 68 69 70
export const NEW_FILE_COMMAND_ID = 'workbench.command.files.newFile';
export const NEW_FILE_LABEL = nls.localize('newFile', "New File");

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

71
export class BaseErrorReportingAction extends Action {
E
Erich Gamma 已提交
72 73 74 75

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

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

85
	protected onError(error: any): void {
86 87
		if (error.message === 'string') {
			error = error.message;
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 124 125 126
		}

		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 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	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 已提交
148
		this.enabled = !!(this._fileService && this._isEnabled());
E
Erich Gamma 已提交
149 150 151 152 153
	}
}

export class TriggerRenameFileAction extends BaseFileAction {

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

	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 已提交
167
		super(TriggerRenameFileAction.ID, nls.localize('rename', "Rename"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
168 169 170 171 172 173 174 175 176 177 178

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

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

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

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

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

				if (!message) {
					return null;
				}

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

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

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

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

export abstract class BaseRenameAction extends BaseFileAction {

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

		this.element = element;
	}

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

		let name = <string>context.value;
		if (!name) {
249
			return TPromise.wrapError(new Error('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(null, (error: any) => {
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
			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);
	}

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

288
class RenameFileAction extends BaseRenameAction {
E
Erich Gamma 已提交
289

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

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

		this._updateEnablement();
	}

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

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

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

321
			dirtyRenamed.push(renamed);
322

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

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

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

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

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

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

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

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

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

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

				this.renameAction.element = stat;

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

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

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

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

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

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

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

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IInstantiationService instantiationService: IInstantiationService
	) {
I
isidor 已提交
471
		super('explorer.newFolder', NEW_FOLDER_LABEL, tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, messageService, textFileService);
E
Erich Gamma 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		this._updateEnablement();
	}

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

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

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

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

		this._updateEnablement();
	}

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

export class BaseDeleteFileAction extends BaseFileAction {
631

632
	private static readonly CONFIRM_DELETE_SETTING_KEY = 'explorer.confirmDelete';
633

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

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

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

		this._updateEnablement();
	}

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

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

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

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

		// Handle dirty
685
		let confirmDirtyPromise: TPromise<boolean> = TPromise.as(true);
I
isidor 已提交
686
		const dirty = this.textFileService.getDirty().filter(d => resources.isEqualOrParent(d, this.element.resource, !isLinux /* ignorecase */));
687 688 689 690 691 692 693 694
		if (dirty.length) {
			let message: string;
			if (this.element.isDirectory) {
				if (dirty.length === 1) {
					message = nls.localize('dirtyMessageFolderOneDelete', "You are deleting a folder with unsaved changes in 1 file. Do you want to continue?");
				} else {
					message = nls.localize('dirtyMessageFolderDelete', "You are deleting a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
				}
695
			} else {
696
				message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
697
			}
E
Erich Gamma 已提交
698

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

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

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

			let confirmDeletePromise: TPromise<IConfirmationResult>;
721

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

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

740 741
			// Confirm for deleting permanently
			else {
742
				confirmDeletePromise = this.messageService.confirmWithCheckbox({
743 744 745 746 747 748 749
					message: this.element.isDirectory ? nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", this.element.name) : nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", this.element.name),
					detail: nls.localize('irreversible', "This action is irreversible!"),
					primaryButton,
					type: 'warning'
				});
			}

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

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

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

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

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

						// Allow to retry
						let extraAction: Action;
						if (this.useTrash) {
							extraAction = new Action('permanentDelete', nls.localize('permDelete', "Delete Permanently"), null, true, () => { this.useTrash = false; this.skipConfirm = true; return this.run(); });
						}

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

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

					return servicePromise;
				});
			});
787
		});
E
Erich Gamma 已提交
788 789 790 791 792
	}
}

/* Move File/Folder to trash */
export class MoveFileToTrashAction extends BaseDeleteFileAction {
M
Matt Bierner 已提交
793
	public static readonly ID = 'moveFileToTrash';
E
Erich Gamma 已提交
794 795 796 797 798 799

	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
800
		@ITextFileService textFileService: ITextFileService,
801
		@IConfigurationService configurationService: IConfigurationService
E
Erich Gamma 已提交
802
	) {
803
		super(MoveFileToTrashAction.ID, nls.localize('delete', "Delete"), tree, element, true, fileService, messageService, textFileService, configurationService);
E
Erich Gamma 已提交
804 805 806 807 808 809
	}
}

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

M
Matt Bierner 已提交
810
	public static readonly ID = 'workbench.files.action.importFile';
E
Erich Gamma 已提交
811 812 813 814 815 816 817
	private tree: ITree;

	constructor(
		tree: ITree,
		element: FileStat,
		clazz: string,
		@IFileService fileService: IFileService,
818
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
819
		@IMessageService messageService: IMessageService,
820
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
821
	) {
B
Benjamin Pasero 已提交
822
		super(ImportFileAction.ID, nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
823 824 825 826 827 828 829 830 831 832 833

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

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

		this._updateEnablement();
	}

834
	public run(resources: URI[]): TPromise<any> {
835
		const importPromise = TPromise.as(null).then(() => {
836
			if (resources && resources.length > 0) {
E
Erich Gamma 已提交
837 838 839 840 841 842

				// Find parent for import
				let targetElement: FileStat;
				if (this.element) {
					targetElement = this.element;
				} else {
I
isidor 已提交
843 844
					const input: FileStat | Model = this.tree.getInput();
					targetElement = this.tree.getFocus() || (input instanceof Model ? input.roots[0] : input);
E
Erich Gamma 已提交
845 846 847 848 849 850 851 852 853 854
				}

				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
855
					const targetNames: { [name: string]: IFileStat } = {};
E
Erich Gamma 已提交
856 857 858 859
					targetStat.children.forEach((child) => {
						targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
					});

860
					let overwritePromise = TPromise.as(true);
861 862
					if (resources.some(resource => {
						return !!targetNames[isLinux ? paths.basename(resource.fsPath) : paths.basename(resource.fsPath).toLowerCase()];
E
Erich Gamma 已提交
863
					})) {
864
						const confirm: IConfirmation = {
E
Erich Gamma 已提交
865 866
							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 已提交
867 868
							primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace"),
							type: 'warning'
E
Erich Gamma 已提交
869 870
						};

871
						overwritePromise = this.messageService.confirm(confirm);
E
Erich Gamma 已提交
872 873
					}

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
					return overwritePromise.then(overwrite => {
						if (!overwrite) {
							return void 0;
						}

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

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

894 895 896 897 898 899 900 901 902
								return revertPromise.then(() => {
									return this.fileService.importFile(sourceFile, targetElement.resource).then(res => {

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

906 907
						return sequence(importPromisesFactory);
					});
E
Erich Gamma 已提交
908 909
				});
			}
910 911

			return void 0;
E
Erich Gamma 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
		});

		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 已提交
927
	public static readonly ID = 'filesExplorer.copy';
E
Erich Gamma 已提交
928 929 930 931 932 933 934

	private tree: ITree;
	constructor(
		tree: ITree,
		element: FileStat,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
935
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
936
	) {
B
Benjamin Pasero 已提交
937
		super(CopyFileAction.ID, nls.localize('copyFile', "Copy"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
938 939 940 941 942 943

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

944
	public run(): TPromise<any> {
E
Erich Gamma 已提交
945 946 947 948 949 950 951 952 953 954 955

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

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

		this.tree.DOMFocus();

A
Alex Dima 已提交
956
		return TPromise.as(null);
E
Erich Gamma 已提交
957 958 959 960 961 962
	}
}

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

M
Matt Bierner 已提交
963
	public static readonly ID = 'filesExplorer.paste';
E
Erich Gamma 已提交
964 965 966 967 968 969 970 971 972 973 974

	private tree: ITree;

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

		this.tree = tree;
I
isidor 已提交
978 979 980 981 982
		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 已提交
983 984 985 986 987 988 989 990 991 992 993
		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 已提交
994
		const exists = fileToCopy.root.find(fileToCopy.resource);
E
Erich Gamma 已提交
995 996 997 998 999 1000
		if (!exists) {
			fileToCopy = null;
			return false;
		}

		// Check if target is ancestor of pasted folder
I
isidor 已提交
1001
		if (this.element.resource.toString() !== fileToCopy.resource.toString() && resources.isEqualOrParent(this.element.resource, fileToCopy.resource, !isLinux /* ignorecase */)) {
E
Erich Gamma 已提交
1002 1003 1004 1005 1006 1007
			return false;
		}

		return true;
	}

1008
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1009 1010 1011

		// Find target
		let target: FileStat;
1012
		if (this.element.resource.toString() === fileToCopy.resource.toString()) {
E
Erich Gamma 已提交
1013 1014 1015 1016 1017 1018
			target = this.element.parent;
		} else {
			target = this.element.isDirectory ? this.element : this.element.parent;
		}

		// Reuse duplicate action
1019
		const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
E
Erich Gamma 已提交
1020 1021 1022 1023 1024 1025 1026

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

1027 1028 1029
export const pasteIntoFocusedFilesExplorerViewItem = (accessor: ServicesAccessor) => {
	const instantiationService = accessor.get(IInstantiationService);

1030
	withFocusedFilesExplorer(accessor).then(res => {
1031 1032
		if (res) {
			const pasteAction = instantiationService.createInstance(PasteFileAction, res.tree, res.tree.getFocus());
1033 1034 1035 1036 1037 1038 1039
			if (pasteAction._isEnabled()) {
				pasteAction.run().done(null, errors.onUnexpectedError);
			}
		}
	});
};

E
Erich Gamma 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
	private tree: ITree;
	private target: IFileStat;

	constructor(
		tree: ITree,
		element: FileStat,
		target: FileStat,
		@IFileService fileService: IFileService,
1050
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
E
Erich Gamma 已提交
1051
		@IMessageService messageService: IMessageService,
1052
		@ITextFileService textFileService: ITextFileService
E
Erich Gamma 已提交
1053
	) {
B
Benjamin Pasero 已提交
1054
		super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
E
Erich Gamma 已提交
1055 1056 1057 1058 1059 1060 1061

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

1062
	public run(): TPromise<any> {
E
Erich Gamma 已提交
1063 1064 1065 1066 1067 1068

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

1069
		// Copy File
1070 1071 1072 1073
		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 } });
			}
1074 1075

			return void 0;
1076
		}, error => this.onError(error));
E
Erich Gamma 已提交
1077 1078 1079 1080 1081 1082 1083

		return result;
	}

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

I
isidor 已提交
1084
		let candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1085
		while (true) {
I
isidor 已提交
1086
			if (!this.element.root.find(candidate)) {
E
Erich Gamma 已提交
1087 1088 1089 1090
				break;
			}

			name = this.toCopyName(name, this.element.isDirectory);
I
isidor 已提交
1091
			candidate = this.target.resource.with({ path: paths.join(this.target.resource.path, name) });
E
Erich Gamma 已提交
1092 1093 1094 1095 1096 1097 1098 1099
		}

		return candidate;
	}

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

		// file.1.txt=>file.2.txt
1100 1101
		if (!isFolder && name.match(/(.*\.)(\d+)(\..*)$/)) {
			return name.replace(/(.*\.)(\d+)(\..*)$/, (match, g1?, g2?, g3?) => { return g1 + (parseInt(g2) + 1) + g3; });
E
Erich Gamma 已提交
1102 1103 1104
		}

		// file.txt=>file.1.txt
1105
		const lastIndexOfDot = name.lastIndexOf('.');
E
Erich Gamma 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
		if (!isFolder && lastIndexOfDot >= 0) {
			return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
		}

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

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

// Global Compare with
export class GlobalCompareResourcesAction extends Action {

M
Matt Bierner 已提交
1123 1124
	public static readonly ID = 'workbench.files.action.compareFileWith';
	public static readonly LABEL = nls.localize('globalCompareFile', "Compare Active File With...");
E
Erich Gamma 已提交
1125 1126 1127 1128 1129 1130

	constructor(
		id: string,
		label: string,
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
1131
		@IMessageService private messageService: IMessageService,
B
Benjamin Pasero 已提交
1132
		@IEditorGroupService private editorGroupService: IEditorGroupService
E
Erich Gamma 已提交
1133 1134 1135 1136
	) {
		super(id, label);
	}

1137
	public run(): TPromise<any> {
B
Benjamin Pasero 已提交
1138 1139
		const activeInput = this.editorService.getActiveEditorInput();
		const activeResource = activeInput ? activeInput.getResource() : void 0;
1140
		if (activeResource) {
E
Erich Gamma 已提交
1141

B
Benjamin Pasero 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
			// 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
						});
					});
1152
				}
B
Benjamin Pasero 已提交
1153
			});
1154

B
Benjamin Pasero 已提交
1155 1156 1157
			// 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 已提交
1158 1159 1160 1161 1162
			});
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
		}

A
Alex Dima 已提交
1163
		return TPromise.as(true);
E
Erich Gamma 已提交
1164 1165 1166 1167 1168 1169
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

1170
	constructor(explorerView: ExplorerView, clazz: string) {
B
Benjamin Pasero 已提交
1171
		super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
E
Erich Gamma 已提交
1172 1173 1174
	}
}

1175 1176 1177 1178 1179 1180 1181
export class SaveFileAction extends BaseErrorReportingAction {

	public static readonly ID = 'workbench.action.files.save';
	public static readonly LABEL = SAVE_FILE_LABEL;

	private resource: URI;

E
Erich Gamma 已提交
1182 1183 1184
	constructor(
		id: string,
		label: string,
1185 1186
		@ICommandService private commandService: ICommandService,
		@IMessageService messageService: IMessageService
E
Erich Gamma 已提交
1187
	) {
1188
		super(id, label, messageService);
E
Erich Gamma 已提交
1189 1190
	}

1191 1192 1193 1194
	public setResource(resource: URI): void {
		this.resource = resource;
	}

1195
	public run(context?: any): TPromise<boolean> {
1196
		return this.commandService.executeCommand(SAVE_FILE_COMMAND_ID, { resource: this.resource }).then(() => true, error => {
R
Ron Buckton 已提交
1197 1198 1199
			this.onError(error);
			return null;
		});
E
Erich Gamma 已提交
1200 1201 1202
	}
}

1203 1204 1205 1206 1207
export class SaveFileAsAction extends BaseErrorReportingAction {

	public static readonly ID = 'workbench.action.files.saveAs';
	public static readonly LABEL = SAVE_FILE_AS_LABEL;

E
Erich Gamma 已提交
1208 1209 1210 1211 1212
	private resource: URI;

	constructor(
		id: string,
		label: string,
1213 1214
		@ICommandService private commandService: ICommandService,
		@IMessageService messageService: IMessageService
E
Erich Gamma 已提交
1215 1216 1217 1218 1219 1220 1221 1222
	) {
		super(id, label, messageService);
	}

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

1223 1224 1225 1226 1227
	public run(context?: any): TPromise<boolean> {
		return this.commandService.executeCommand(SAVE_FILE_AS_COMMAND_ID, { resource: this.resource }).then(() => true, error => {
			this.onError(error);
			return null;
		});
E
Erich Gamma 已提交
1228 1229 1230
	}
}

1231
export abstract class BaseSaveAllAction extends BaseErrorReportingAction {
E
Erich Gamma 已提交
1232 1233 1234 1235 1236 1237 1238 1239
	private toDispose: IDisposable[];
	private lastIsDirty: boolean;

	constructor(
		id: string,
		label: string,
		@ITextFileService private textFileService: ITextFileService,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
I
isidor 已提交
1240
		@ICommandService protected commandService: ICommandService,
1241
		@IMessageService messageService: IMessageService,
E
Erich Gamma 已提交
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	) {
		super(id, label, messageService);

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

		this.registerListeners();
	}

	protected abstract includeUntitled(): boolean;
I
isidor 已提交
1253
	protected abstract doRun(context: any): TPromise<any>;
E
Erich Gamma 已提交
1254 1255 1256 1257

	private registerListeners(): void {

		// listen to files being changed locally
1258 1259 1260 1261
		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 已提交
1262 1263

		if (this.includeUntitled()) {
B
Benjamin Pasero 已提交
1264
			this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
E
Erich Gamma 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
		}
	}

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

1275 1276 1277 1278 1279 1280 1281
	public run(context?: any): TPromise<boolean> {
		return this.doRun(context).then(() => true, error => {
			this.onError(error);
			return null;
		});
	}

E
Erich Gamma 已提交
1282
	public dispose(): void {
J
Joao Moreno 已提交
1283
		this.toDispose = dispose(this.toDispose);
E
Erich Gamma 已提交
1284 1285 1286 1287 1288 1289 1290

		super.dispose();
	}
}

export class SaveAllAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1291
	public static readonly ID = 'workbench.action.files.saveAll';
I
isidor 已提交
1292
	public static readonly LABEL = SAVE_ALL_LABEL;
E
Erich Gamma 已提交
1293 1294 1295 1296 1297

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

I
isidor 已提交
1298 1299
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_COMMAND_ID);
1300 1301 1302 1303 1304 1305 1306 1307 1308
	}

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

export class SaveAllInGroupAction extends BaseSaveAllAction {

M
Matt Bierner 已提交
1309
	public static readonly ID = 'workbench.files.action.saveAllInGroup';
1310
	public static readonly LABEL = nls.localize('saveAllInGroup', "Save All in Group");
1311 1312 1313 1314 1315

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

I
isidor 已提交
1316 1317
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_ALL_IN_GROUP_COMMAND_ID);
1318 1319
	}

E
Erich Gamma 已提交
1320 1321 1322 1323 1324 1325 1326
	protected includeUntitled(): boolean {
		return true;
	}
}

export class SaveFilesAction extends BaseSaveAllAction {

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

I
isidor 已提交
1330 1331
	protected doRun(context: any): TPromise<any> {
		return this.commandService.executeCommand(SAVE_FILES_COMMAND_ID, false);
1332 1333
	}

E
Erich Gamma 已提交
1334 1335 1336 1337 1338 1339 1340
	protected includeUntitled(): boolean {
		return false;
	}
}

export class RevertFileAction extends Action {

M
Matt Bierner 已提交
1341 1342
	public static readonly ID = 'workbench.action.files.revert';
	public static readonly LABEL = nls.localize('revert', "Revert File");
E
Erich Gamma 已提交
1343 1344 1345 1346 1347 1348

	private resource: URI;

	constructor(
		id: string,
		label: string,
1349
		@ICommandService private commandService: ICommandService
E
Erich Gamma 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
	) {
		super(id, label);

		this.enabled = true;
	}

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

1360
	public run(): TPromise<any> {
I
isidor 已提交
1361
		return this.commandService.executeCommand(REVERT_FILE_COMMAND_ID, { resource: this.resource });
E
Erich Gamma 已提交
1362 1363 1364
	}
}

1365
export class FocusOpenEditorsView extends Action {
1366

M
Matt Bierner 已提交
1367 1368
	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");
1369 1370 1371 1372 1373 1374 1375 1376 1377

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

1378
	public run(): TPromise<any> {
1379
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
I
isidor 已提交
1380 1381
			const openEditorsView = viewlet.getOpenEditorsView();
			if (openEditorsView) {
1382
				openEditorsView.setExpanded(true);
I
isidor 已提交
1383
				openEditorsView.getList().domFocus();
I
isidor 已提交
1384
			}
1385 1386 1387 1388
		});
	}
}

1389 1390
export class FocusFilesExplorer extends Action {

M
Matt Bierner 已提交
1391 1392
	public static readonly ID = 'workbench.files.action.focusFilesExplorer';
	public static readonly LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

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

	public run(): TPromise<any> {
1403
		return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
1404 1405
			const view = viewlet.getExplorerView();
			if (view) {
1406
				view.setExpanded(true);
1407 1408 1409 1410 1411 1412
				view.getViewer().DOMFocus();
			}
		});
	}
}

1413 1414
export class ShowActiveFileInExplorer extends Action {

M
Matt Bierner 已提交
1415 1416
	public static readonly ID = 'workbench.files.action.showActiveFileInExplorer';
	public static readonly LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");
1417 1418 1419 1420 1421

	constructor(
		id: string,
		label: string,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
I
isidor 已提交
1422 1423
		@IMessageService private messageService: IMessageService,
		@ICommandService private commandService: ICommandService
1424 1425 1426 1427 1428
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
1429 1430
		const resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true });
		if (resource) {
I
isidor 已提交
1431
			this.commandService.executeCommand(REVEAL_IN_EXPLORER_COMMAND_ID, { resource });
1432 1433 1434 1435 1436 1437 1438 1439
		} else {
			this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
		}

		return TPromise.as(true);
	}
}

1440 1441
export class CollapseExplorerView extends Action {

M
Matt Bierner 已提交
1442 1443
	public static readonly ID = 'workbench.files.action.collapseExplorerFolders';
	public static readonly LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

	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 已提交
1470 1471
	public static readonly ID = 'workbench.files.action.refreshFilesExplorer';
	public static readonly LABEL = nls.localize('refreshExplorer', "Refresh Explorer");
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490

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

1491 1492
export class ShowOpenedFileInNewWindow extends Action {

M
Matt Bierner 已提交
1493 1494
	public static readonly ID = 'workbench.action.files.showOpenedFileInNewWindow';
	public static readonly LABEL = nls.localize('openFileInNewWindow', "Open Active File in New Window");
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508

	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) {
1509
			this.windowsService.openWindow([fileResource.fsPath], { forceNewWindow: true, forceOpenWorkspaceAsFile: true });
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
		} 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 已提交
1520
	public static readonly LABEL = isWindows ? nls.localize('revealInWindows', "Reveal in Explorer") : isMacintosh ? nls.localize('revealInMac', "Reveal in Finder") : nls.localize('openContainer', "Open Containing Folder");
1521 1522 1523

	constructor(
		private resource: URI,
I
isidor 已提交
1524
		@ICommandService private commandService: ICommandService
1525
	) {
1526
		super('revealFileInOS', RevealInOSAction.LABEL);
1527 1528 1529 1530 1531

		this.order = 45;
	}

	public run(): TPromise<any> {
I
isidor 已提交
1532
		return this.commandService.executeCommand(REVEAL_IN_OS_COMMAND_ID, { resource: this.resource });
1533 1534 1535 1536 1537
	}
}

export class GlobalRevealInOSAction extends Action {

M
Matt Bierner 已提交
1538 1539
	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"));
1540 1541 1542 1543

	constructor(
		id: string,
		label: string,
I
isidor 已提交
1544
		@ICommandService private commandService: ICommandService
1545 1546 1547 1548 1549
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
I
isidor 已提交
1550
		return this.commandService.executeCommand(REVEAL_IN_OS_COMMAND_ID);
1551 1552 1553
	}
}

1554 1555
export class CopyPathAction extends Action {

M
Matt Bierner 已提交
1556
	public static readonly LABEL = nls.localize('copyPath', "Copy Path");
1557 1558 1559

	constructor(
		private resource: URI,
I
isidor 已提交
1560
		@ICommandService private commandService: ICommandService
1561
	) {
1562
		super('copyFilePath', CopyPathAction.LABEL);
1563 1564 1565 1566 1567

		this.order = 140;
	}

	public run(): TPromise<any> {
I
isidor 已提交
1568
		return this.commandService.executeCommand(COPY_PATH_COMMAND_ID, { resource: this.resource });
1569 1570 1571 1572 1573
	}
}

export class GlobalCopyPathAction extends Action {

M
Matt Bierner 已提交
1574 1575
	public static readonly ID = 'workbench.action.files.copyPathOfActiveFile';
	public static readonly LABEL = nls.localize('copyPathOfActive', "Copy Path of Active File");
1576 1577 1578 1579

	constructor(
		id: string,
		label: string,
I
isidor 已提交
1580
		@ICommandService private commandService: ICommandService
1581 1582 1583 1584 1585
	) {
		super(id, label);
	}

	public run(): TPromise<any> {
I
isidor 已提交
1586
		return this.commandService.executeCommand(COPY_PATH_COMMAND_ID);
1587 1588 1589
	}
}

E
Erich Gamma 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
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);
		}
	}

1613 1614
	// Invalid File name
	if (!paths.isValidBasename(name)) {
1615
		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 已提交
1616 1617 1618 1619
	}

	// Max length restriction (on Windows)
	if (isWindows) {
1620
		const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
E
Erich Gamma 已提交
1621
		if (fullPathLength > 255) {
1622
			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 已提交
1623 1624 1625 1626 1627 1628
		}
	}

	return null;
}

1629 1630 1631 1632 1633 1634 1635 1636
function trimLongName(name: string): string {
	if (name && name.length > 255) {
		return `${name.substr(0, 255)}...`;
	}

	return name;
}

E
Erich Gamma 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
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;
}

1651
export class CompareWithSavedAction extends Action {
B
Benjamin Pasero 已提交
1652

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

1656
	private resource: URI;
1657
	private toDispose: IDisposable[];
1658 1659 1660 1661

	constructor(
		id: string,
		label: string,
I
isidor 已提交
1662
		@ICommandService private commandService: ICommandService,
1663
		@IInstantiationService instantiationService: IInstantiationService,
1664 1665 1666 1667 1668
		@ITextModelService textModelService: ITextModelService
	) {
		super(id, label);

		this.enabled = true;
1669 1670 1671 1672 1673
		this.toDispose = [];

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

I
isidor 已提交
1674
		const registrationDisposal = textModelService.registerTextModelContentProvider(COMPARE_WITH_SAVED_SCHEMA, provider);
1675
		this.toDispose.push(registrationDisposal);
1676 1677 1678 1679 1680 1681 1682
	}

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

	public run(): TPromise<any> {
I
isidor 已提交
1683
		return this.commandService.executeCommand(COMPARE_WITH_SAVED_COMMAND_ID, { resource: this.resource });
1684 1685
	}

1686 1687 1688
	public dispose(): void {
		super.dispose();

1689
		this.toDispose = dispose(this.toDispose);
1690
	}
1691 1692
}

M
Max Furman 已提交
1693 1694
export class CompareWithClipboardAction extends Action {

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

1698
	private static readonly SCHEME = 'clipboardCompare';
M
Max Furman 已提交
1699

B
Benjamin Pasero 已提交
1700
	private registrationDisposal: IDisposable;
M
Max Furman 已提交
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714

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

		if (resource) {
B
Benjamin Pasero 已提交
1719 1720 1721 1722
			if (!this.registrationDisposal) {
				this.registrationDisposal = this.textModelService.registerTextModelContentProvider(CompareWithClipboardAction.SCHEME, provider);
			}

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

B
Benjamin Pasero 已提交
1726 1727 1728 1729 1730
			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 已提交
1731 1732 1733 1734 1735 1736 1737 1738
		}

		return TPromise.as(true);
	}

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

B
Benjamin Pasero 已提交
1739
		this.registrationDisposal = dispose(this.registrationDisposal);
M
Max Furman 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
	}
}

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

M
Max Furman 已提交
1753 1754 1755 1756
		return TPromise.as(model);
	}
}

E
Erich Gamma 已提交
1757 1758 1759
// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
1760
	diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
E
Erich Gamma 已提交
1761 1762
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
J
Johannes Rieken 已提交
1763
}
I
isidor 已提交
1764

I
isidor 已提交
1765 1766
// TODO@isidor these commands are calling into actions due to the complex inheritance action structure.
// It should be the other way around, that actions call into commands.
I
isidor 已提交
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
CommandsRegistry.registerCommand({
	id: NEW_FILE_COMMAND_ID,
	handler: (accessor, resource: URI, explorerContext: IExplorerContext) => {
		const instantationService = accessor.get(IInstantiationService);
		const listService = accessor.get(IListService);
		const newFileAction = instantationService.createInstance(NewFileAction, listService.lastFocusedList, explorerContext.stat);

		return newFileAction.run(explorerContext);
	}
});
I
isidor 已提交
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787

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

		return newFolderAction.run(explorerContext);
	}
});