fileActions.ts 74.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/*---------------------------------------------------------------------------------------------
 *  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';
import {Promise, TPromise} from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import {isWindows, isLinux, isMacintosh} from 'vs/base/common/platform';
import {$} from 'vs/base/browser/builder';
import {sequence, ITask} from 'vs/base/common/async';
import {MIME_TEXT, isUnspecific, isBinaryMime, guessMimeTypes} from 'vs/base/common/mime';
import paths = require('vs/base/common/paths');
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
import strings = require('vs/base/common/strings');
import {Event, EventType as CommonEventType} from 'vs/base/common/events';
import {getPathLabel} from 'vs/base/common/labels';
import diagnostics = require('vs/base/common/diagnostics');
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/common/tree';
import {disposeAll, IDisposable} from 'vs/base/common/lifecycle';
import {EventType as WorkbenchEventType, EditorEvent} from 'vs/workbench/browser/events';
import Files = require('vs/workbench/parts/files/common/files');
import {IFileService, IFileStat, IImportResult} from 'vs/platform/files/common/files';
import {EditorInputAction} from 'vs/workbench/browser/parts/editor/baseEditor';
import {IFrameEditor} from 'vs/workbench/browser/parts/editor/iframeEditor';
import {DiffEditorInput} from 'vs/workbench/browser/parts/editor/diffEditorInput';
import workbenchEditorCommon = require('vs/workbench/common/editor');
33
import {IEditorSelection} from 'vs/editor/common/editorCommon';
E
Erich Gamma 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
import {FileEditorInput} from 'vs/workbench/parts/files/browser/editors/fileEditorInput';
import {FileStat, NewStatPlaceholder} from 'vs/workbench/parts/files/browser/views/explorerViewModel';
import {ExplorerView} from 'vs/workbench/parts/files/browser/views/explorerView';
import {ExplorerViewlet} from 'vs/workbench/parts/files/browser/explorerViewlet';
import {CACHE} from 'vs/workbench/parts/files/browser/editors/textFileEditorModel';
import {HTMLFrameEditorInput} from 'vs/workbench/parts/files/browser/editors/htmlFrameEditorInput';
import {DerivedFrameEditorInput} from 'vs/workbench/parts/files/browser/editors/derivedFrameEditorInput';
import {IActionProvider} from 'vs/base/parts/tree/browser/actionsRenderer';
import {WorkingFileEntry, WorkingFilesModel} from 'vs/workbench/parts/files/browser/workingFilesModel';
import {IUntitledEditorService} from 'vs/workbench/services/untitled/browser/untitledEditorService';
import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService';
import {IQuickOpenService} from 'vs/workbench/services/quickopen/browser/quickOpenService';
import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService';
import {IPartService} from 'vs/workbench/services/part/common/partService';
import {IStorageService} from 'vs/platform/storage/common/storage';
import {IResourceInput, Position} from 'vs/platform/editor/common/editor';
import {IEventService} from 'vs/platform/event/common/event';
51
import {ISelection} from 'vs/platform/selection/common/selection';
E
Erich Gamma 已提交
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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 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 289 290 291 292
import {IInstantiationService, IConstructorSignature2, INewConstructorSignature2, INewConstructorSignature1, INullService} from 'vs/platform/instantiation/common/instantiation';
import {IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction} from 'vs/platform/message/common/message';
import {IProgressService, IProgressRunner} from 'vs/platform/progress/common/progress';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {KeyMod, KeyCode, Keybinding} from 'vs/base/common/keyCodes';

import ITextFileService = Files.ITextFileService;

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;
	private listenerToUnbind: () => void;

	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;

		// update enablement when options change
		this.listenerToUnbind = this._eventService.addListener(WorkbenchEventType.WORKBENCH_OPTIONS_CHANGED, () => this._updateEnablement());
	}

	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 {
		this.enabled = !!(this._contextService && this._fileService && this._editorService && !this._contextService.getOptions().readOnly && this._isEnabled());
	}

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

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

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

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

		let errorWithRetry: IMessageWithAction = {
			actions: actions,
			message: errors.toErrorMessage(error, false)
		};

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

	protected handleDirty(): TPromise<boolean /* cancel */> {
		if (this.textFileService.isDirty(this._element.resource)) {
			let res = this.textFileService.confirmSave(this._element.resource);
			if (res === Files.ConfirmResult.SAVE) {
				return this.textFileService.save(this._element.resource).then(() => false);
			}

			if (res === Files.ConfirmResult.DONT_SAVE) {
				return this.textFileService.revert(this._element.resource).then(() => false);
			}

			return Promise.as(true);
		}

		return Promise.as(false);
	}

	public dispose(): void {
		this.listenerToUnbind();

		super.dispose();
	}
}

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

	public run(context?: any): Promise {
		if (!context) {
			return Promise.wrapError('No context provided to BaseEnableFileRenameAction.');
		}

		let viewletState = <IFileViewletState>context.viewletState;
		if (!viewletState) {
			return Promise.wrapError('Invalid viewlet state provided to BaseEnableFileRenameAction.');
		}

		let stat = <IFileStat>context.stat;
		if (!stat) {
			return Promise.wrapError('Invalid stat provided to BaseEnableFileRenameAction.');
		}

		viewletState.setEditable(stat, {
			action: this.renameAction,
			validator: (value) => {
				let message = this.validateFileName(this.element.parent, value);

				if (!message) {
					return null;
				}

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

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

			let unbind = this.tree.addListener(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
				if (!e.highlight) {
					viewletState.clearEditable(stat);
					this.tree.refresh(stat).done(null, errors.onUnexpectedError);
					unbind();
				}
			});
		}).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,
		@IProgressService private progressService: IProgressService,
		@IEventService eventService: IEventService
	) {
		super(id, label, contextService, editorService, fileService, messageService, textFileService, eventService);

		this.element = element;
	}

	public run(context?: any): Promise {
		if (!context) {
			return Promise.wrapError('No context provided to BaseRenameFileAction.');
		}

		let name = <string>context.value;
		if (!name) {
			return Promise.wrapError('No new name provided to BaseRenameFileAction.');
		}

		// Automatically trim whitespaces and trailing dots to produce nice file names
		name = getWellFormedFileName(name);
		let existingName = getWellFormedFileName(this.element.name);

293
		// Return early if name is invalid or didn't change
E
Erich Gamma 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 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 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 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 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 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 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 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 931 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 981 982 983 984 985 986 987 988 989 990 991 992 993 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 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 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 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 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 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 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 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
		if (name === existingName || this.validateFileName(this.element.parent, name)) {
			return Promise.as(null);
		}

		// Call function and Emit Event through viewer
		let promise = this.runAction(name).then((stat: IFileStat) => {
			if (stat) {
				this.onSuccess(stat);
			}
		}, (error: any) => {
			this.onError(error);
		});

		if (this.progressService) {
			this.progressService.showWhile(promise, 800);
		}

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

	public abstract runAction(newName: string): Promise;

	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
		}

		this.eventService.emit('files.internal:fileChanged', new Files.LocalFileChangeEvent(before, stat));
	}
}

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,
		@IProgressService progressService: IProgressService,
		@IEventService eventService: IEventService
	) {
		super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, contextService, editorService, fileService, messageService, textFileService, progressService, eventService);

		this._updateEnablement();
	}

	public runAction(newName: string): Promise {

		// Check if file is dirty in editor and save it to avoid data loss
		return this.handleDirty().then((cancel: boolean) => {
			if (cancel) {
				return Promise.as(null);
			}

			// If the file is still dirty, do not touch it because a save is pending to disk and we can not abort it
			if (this.textFileService.isDirty(this.element.resource)) {
				this.onWarning(nls.localize('warningFileDirty', "File '{0}' is currently being saved, please try again later.", getPathLabel(this.element.resource)));

				return Promise.as(null);
			}

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

	public run(context?: any): Promise {
		if (!context) {
			return Promise.wrapError('No context provided to BaseNewAction.');
		}

		let viewletState = <IFileViewletState>context.viewletState;
		if (!viewletState) {
			return Promise.wrapError('Invalid viewlet state provided to BaseNewAction.');
		}

		let folder: FileStat = this.presetFolder;
		if (!folder) {
			let focus = <FileStat>this.tree.getFocus();
			if (focus) {
				folder = focus.isDirectory ? focus : focus.parent;
			} else {
				folder = this.tree.getInput();
			}
		}

		if (!folder) {
			return Promise.wrapError('Invalid parent folder to create.');
		}

		return this.tree.reveal(folder, 0.5).then(() => {
			return this.tree.expand(folder).then(() => {
				let stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);

				this.renameAction.element = stat;

				viewletState.setEditable(stat, {
					action: this.renameAction,
					validator: (value) => {
						let message = this.renameAction.validateFileName(folder, value);

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

							let unbind: () => void = this.tree.addListener(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
								if (!e.highlight) {
									stat.destroy();
									this.tree.refresh(folder).done(null, errors.onUnexpectedError);
									unbind();
								}
							});
						});
					});
				});
			});
		});
	}
}

/* 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,
		@IInstantiationService private instantiationService: IInstantiationService
	) {
		super(id, label);
	}

	public run(): Promise {
		return this.viewletService.openViewlet(Files.VIEWLET_ID, true).then((viewlet) => {
			return Promise.timeout(100).then(() => { // use a timeout to prevent the explorer from revealing the active file
				viewlet.focus();

				let explorer = <ExplorerViewlet>viewlet;
				let explorerView = explorer.getExplorerView();

				if (!explorerView.isExpanded()) {
					explorerView.expand();
				}

				let action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);

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

	protected abstract getAction(): INewConstructorSignature2<ITree, IFileStat, Action>;

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

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

/* Create new file from anywhere: Open untitled */
export class GlobalNewFileAction extends Action {
	public static ID = 'workbench.action.files.newUntitledFile';
	public static LABEL = nls.localize('newFile', "New File");

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

	public run(): Promise {
		let input = this.untitledEditorService.createOrGet();

		// Make sure this untitled buffer shows up in working files set
		this.textFileService.getWorkingFilesModel().addEntry(input.getResource());

		return this.editorService.openEditor(input);
	}
}

/* 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");

	protected getAction(): INewConstructorSignature2<ITree, IFileStat, Action> {
		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,
		@IProgressService progressService: IProgressService,
		@IEventService eventService: IEventService
	) {
		super(CreateFileAction.ID, CreateFileAction.LABEL, element, contextService, editorService, fileService, messageService, textFileService, progressService, eventService);

		this._updateEnablement();
	}

	public runAction(fileName: string): Promise {
		return this.fileService.createFile(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then((stat) => {
			this.textFileService.getWorkingFilesModel().addEntry(stat.resource); // add to working files

			return stat;
		}, (error) => {
			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,
		@IProgressService progressService: IProgressService,
		@IEventService eventService: IEventService
	) {
		super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, contextService, editorService, fileService, messageService, textFileService, progressService, eventService);

		this._updateEnablement();
	}

	public runAction(fileName: string): Promise {
		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;

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

	public run(): Promise {

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

		// Ask for Confirm
		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: isWindows ? nls.localize('deleteButtonLabelRecycleBin', "Move to Recycle Bin") : nls.localize('deleteButtonLabelTrash', "Move to Trash")
			};
		} 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: nls.localize('deleteButtonLabel', "Delete")
			};
		}

		if (!this.messageService.confirm(confirm)) {
			return Promise.as(null);
		}

		// Check if file is dirty in editor and save it to avoid data loss
		return this.handleDirty().then((cancel: boolean) => {
			if (cancel) {
				return Promise.as(null);
			}

			// If the file is still dirty, do not touch it because a save is pending to disk and we can not abort it
			if (this.textFileService.isDirty(this.element.resource)) {
				this.onWarning(nls.localize('warningFileDirty', "File '{0}' is currently being saved, please try again later.", getPathLabel(this.element.resource)));

				return Promise.as(null);
			}

			// 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 Files.LocalFileChangeEvent(this.element.clone(), null));

			// Call function
			let 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; return this.run(); });
				}

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

				// Since the delete failed, best we can do is to refresh the explorer from the root to show the current state of files.
				let event = new Files.LocalFileChangeEvent(new FileStat(this.contextService.getWorkspace().resource, true, true), new FileStat(this.contextService.getWorkspace().resource, true, true));
				this.eventService.emit('files.internal:fileChanged', event);

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

			return servicePromise;
		});
	}
}

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

/* Delete File/Folder */
export class DeleteFileAction extends BaseDeleteFileAction {
	public static ID = 'workbench.files.action.deleteFile';

	constructor(
		tree: ITree,
		element: FileStat,
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IWorkbenchEditorService editorService: IWorkbenchEditorService,
		@IFileService fileService: IFileService,
		@IMessageService messageService: IMessageService,
		@ITextFileService textFileService: ITextFileService,
		@IEventService eventService: IEventService
	) {
		super(DeleteFileAction.ID, nls.localize('delete', "Delete"), tree, element, false, 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,
		@IEventService eventService: IEventService,
		@IProgressService private progressService: IProgressService
	) {
		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;
	}

	public run(context?: any): Promise {
		let multiFileProgressTracker: IProgressRunner;
		let importPromise = Promise.as(null).then(() => {
			let input = context.input;
			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
				let filesArray: File[] = [];
				for (let i = 0; i < input.files.length; i++) {
					let file = input.files[i];
					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
					let targetNames: { [name: string]: IFileStat } = {};
					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()];
					})) {
						let confirm: IConfirmation = {
							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!"),
							primaryButton: nls.localize('replaceButtonLabel', "Replace")
						};

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

					if (!overwrite) {
						return;
					}

					// Progress per file imported
					if (filesArray.length > 1 && this.progressService) {
						multiFileProgressTracker = this.progressService.show(filesArray.length);
					}

					// Run import in sequence to not consume too many connections
					let importPromisesFactory: ITask<Promise>[] = [];
					filesArray.forEach((file) => {
						importPromisesFactory.push(() => {
							return this.fileService.importFile(URI.file((<any>file).path), targetElement.resource).then((result: IImportResult) => {

								// Progress
								if (multiFileProgressTracker) {
									multiFileProgressTracker.worked(1);
								}

								if (result.stat) {

									// Emit Deleted Event if file gets replaced
									let oldFile = targetNames[isLinux ? file.name : file.name.toLowerCase()];
									if (oldFile) {
										this.eventService.emit('files.internal:fileChanged', new Files.LocalFileChangeEvent(oldFile, null));
									}

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

		if (this.progressService && !multiFileProgressTracker) {
			this.progressService.showWhile(importPromise, 800);
		}

		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. */
export class FileImportedEvent extends Files.LocalFileChangeEvent {
	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;
	}
}

// Preview HTML File
export class PreviewHTMLAction extends Action {
	private element: IFileStat;

	constructor(
		element: IFileStat,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITextFileService private textFileService: ITextFileService
	) {
		super('workbench.files.action.previewHTMLFromExplorer', nls.localize('openPreview', "Open Preview"));

		this.element = element;
		this.enabled = true;
	}

	public run(): Promise {
		let htmlInput = this.instantiationService.createInstance(HTMLFrameEditorInput, this.element.resource);

		let savePromise = Promise.as(null);
		if (this.textFileService.isDirty(this.element.resource)) {
			savePromise = this.textFileService.save(this.element.resource);
		}

		return savePromise.then(() => {
			return this.editorService.openEditor(htmlInput);
		});
	}
}

export class PreviewHTMLEditorInputAction extends EditorInputAction {

	constructor(
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@ITextFileService private textFileService: ITextFileService
	) {
		super('workbench.files.action.previewHTMLFromEditor', nls.localize('openPreview', "Open Preview"));

		this.class = 'file-editor-action action-open-preview';
	}

	public run(event?: any): Promise {
		let input = <Files.FileEditorInput>this.input;

		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));
		let htmlInput = this.instantiationService.createInstance(HTMLFrameEditorInput, input.getResource());

		let savePromise = Promise.as(null);
		if (this.textFileService.isDirty(input.getResource())) {
			savePromise = this.textFileService.save(input.getResource());
		}

		return savePromise.then(() => {
			return this.editorService.openEditor(htmlInput, null, sideBySide);
		});
	}
}

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

	public run(): Promise {

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

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

		this.tree.DOMFocus();

		return Promise.as(null);
	}
}

// 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
		let root: FileStat = this.tree.getInput();
		let exists = root.find(fileToCopy.resource);
		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;
	}

	public run(): Promise {

		// 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
		let pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);

		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,
		@IEventService eventService: IEventService,
		@IProgressService private progressService: IProgressService
	) {
		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();
	}

	public run(): Promise {

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

		// Copy File and emit event
		let result = this.fileService.copyFile(this.element.resource, this.findTarget()).then((stat: IFileStat) => {
			this.eventService.emit('files.internal:fileChanged', new Files.LocalFileChangeEvent(null, stat));
		}, (error: any) => {
			this.onError(error);
		});

		if (this.progressService) {
			this.progressService.showWhile(result, 800);
		}

		return result;
	}

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

	private findTarget(): URI {
		let root: FileStat = this.tree.getInput();
		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
		let lastIndexOfDot = name.lastIndexOf('.');
		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 {
		let activeEditor = this.editorService.getActiveEditor();
		this.enabled = (!activeEditor || activeEditor.position !== Position.RIGHT);
	}

	public run(): Promise {

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

	constructor(resource: URI, tree: ITree, @INullService ns) {
		super('workbench.files.action.selectForCompare', nls.localize('compareSource', "Select for Compare"));

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

	public run(): Promise {

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

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

		return Promise.as(null);
	}
}

// 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,
		@IMessageService private messageService: IMessageService,
		@IEventService private eventService: IEventService
	) {
		super(id, label);
	}

	public run(): Promise {
		let fileInput = workbenchEditorCommon.asFileEditorInput(this.editorService.getActiveEditorInput());
		if (fileInput) {

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

			// Listen for next editor to open
			let unbind = this.eventService.addListener(WorkbenchEventType.EDITOR_INPUT_OPENING, (e: EditorEvent) => {
				unbind(); // listen once

				let otherFileInput = workbenchEditorCommon.asFileEditorInput(e.editorInput);
				if (otherFileInput) {
					let compareAction = this.instantiationService.createInstance(CompareResourcesAction, otherFileInput.getResource(), null);
					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(() => {
				unbind(); // make sure to unbind if quick open is closing
			});

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

		return Promise.as(true);
	}
}

// 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) {
			let root: FileStat = this.tree.getInput();
			if (root instanceof FileStat) {
				let exists = root.find(globalResourceToCompare);
				if (!exists) {
					globalResourceToCompare = null;
					return false;
				}
			}
		}

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

		let mimeA = guessMimeTypes(this.resource.fsPath).join(', ');
		let mimeB = guessMimeTypes(globalResourceToCompare.fsPath).join(', ');

		// Check if target has same mime
		if (mimeA === mimeB) {
			return true;
		}

		// Ensure the mode is equal if this is text (limitation of current diff infrastructure)
		let isBinaryA = isBinaryMime(mimeA);
		let isBinaryB = isBinaryMime(mimeB);

		// Ensure we are not comparing binary with text
		if (isBinaryA !== isBinaryB) {
			return false;
		}

		return true;
	}

	public run(): Promise {

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

		let leftInput = this.instantiationService.createInstance(FileEditorInput, globalResourceToCompare, void 0, void 0);
		let rightInput = this.instantiationService.createInstance(FileEditorInput, this.resource, void 0, void 0);

		let leftName = getPathLabel(globalResourceToCompare.fsPath, this.contextService);
		let rightName = getPathLabel(this.resource.fsPath, this.contextService);

		return this.editorService.openEditor(new DiffEditorInput(nls.localize('compareLabels', "{0} ↔ {1}", leftName, rightName), null, leftInput, rightInput));
	}
}

// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {

	constructor(explorerView: ExplorerView, clazz: string, @INullService ns) {
		super('workbench.files.action.refreshExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => {
			if (explorerView.getViewer().getHighlight()) {
				return Promise.as(null); // Global action disabled if user is in edit mode from another action
			}

			return explorerView.refresh(true, true, true);
		});
	}
}

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

	public run(): TPromise<boolean> {
		return this.doRun().then(() => true, (error) => {
			this.messageService.show(Severity.Error, errors.toErrorMessage(error, false));
		});
	}

	protected abstract doRun(): TPromise<boolean>;
}

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,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IMessageService messageService: IMessageService
	) {
		super(id, label, messageService);

		this.enabled = true;
	}

	public abstract isSaveAs(): boolean;

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

	protected doRun(): TPromise<boolean> {
		let source: URI;
		if (this.resource) {
			source = this.resource;
		} else {
			source = workbenchEditorCommon.getUntitledOrFileResource(this.editorService.getActiveEditorInput(), true);
		}

		if (source) {

			// Save As (or Save untitled with associated path)
			if (this.isSaveAs() || source.scheme === 'untitled') {
				let positionsOfSource = findSaveAsPositions(this.editorService, source);

				let mimeOfSource: string;
				if (source.scheme === 'untitled') {
					let selectedMime = this.untitledEditorService.get(source).getMime();
					if (!isUnspecific(selectedMime)) {
						mimeOfSource = [selectedMime, MIME_TEXT].join(', ');
					}
				}

				let encodingOfSource: string;
				if (source.scheme === 'untitled') {
					encodingOfSource = this.untitledEditorService.get(source).getEncoding();
				} else if (source.scheme === 'file') {
					let textModel = CACHE.get(source);
					encodingOfSource = textModel && textModel.getEncoding(); // text model can be null e.g. if this is a binary file!
				}

1532 1533 1534 1535 1536 1537 1538 1539
				let selectionOfSource: IEditorSelection;
				if (positionsOfSource.length) {
					const activeEditor = this.editorService.getActiveEditor();
					if (activeEditor && positionsOfSource.indexOf(activeEditor.position) >= 0) {
						selectionOfSource = <IEditorSelection>activeEditor.getSelection();
					}
				}

E
Erich Gamma 已提交
1540
				// Special case: an untitled file with associated path gets saved directly unless "saveAs" is true
1541
				let savePromise: TPromise<URI>;
E
Erich Gamma 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
				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) => {
					if (!target) {
						return;
					}

					// Reopen editors for the resource based on the positions
					let reopenPromise = Promise.as(null);
					if (target.toString() !== source.toString() && positionsOfSource.length) {
						let targetInput = this.instantiationService.createInstance(FileEditorInput, target, mimeOfSource, encodingOfSource);

1567 1568 1569 1570 1571 1572 1573
						let options: workbenchEditorCommon.TextEditorOptions;
						if (selectionOfSource) {
							options = new workbenchEditorCommon.TextEditorOptions();
							options.selection(selectionOfSource.startLineNumber, selectionOfSource.startColumn, selectionOfSource.endLineNumber, selectionOfSource.endColumn);
						}

						reopenPromise = this.editorService.openEditor(targetInput, options, positionsOfSource[0]).then(() => {
E
Erich Gamma 已提交
1574
							if (positionsOfSource.length > 1) {
1575
								return this.editorService.openEditor(targetInput, options, positionsOfSource[1]).then(() => {
E
Erich Gamma 已提交
1576
									if (positionsOfSource.length > 2) {
1577
										return this.editorService.openEditor(targetInput, options, positionsOfSource[2]);
E
Erich Gamma 已提交
1578 1579 1580 1581 1582 1583
									}
								});
							}
						});
					}

1584
					return reopenPromise;
E
Erich Gamma 已提交
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
				});
			}

			// Just save
			return this.textFileService.save(source);
		}

		return Promise.as(false);
	}
}

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';
	public static LABEL = 'Save As...';

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

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

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

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

		this.registerListeners();
	}

	protected abstract includeUntitled(): boolean;

	private registerListeners(): void {

		// listen to files being changed locally
		this.toDispose.push(this.eventService.addListener2(Files.EventType.FILE_DIRTY, (e: Files.LocalFileChangeEvent) => this.updateEnablement(true)));
		this.toDispose.push(this.eventService.addListener2(Files.EventType.FILE_SAVED, (e: Files.LocalFileChangeEvent) => this.updateEnablement(false)));
		this.toDispose.push(this.eventService.addListener2(Files.EventType.FILE_REVERTED, (e: Files.LocalFileChangeEvent) => this.updateEnablement(false)));
		this.toDispose.push(this.eventService.addListener2(Files.EventType.FILE_SAVE_ERROR, (e: Files.LocalFileChangeEvent) => this.updateEnablement(true)));

		if (this.includeUntitled()) {
			this.toDispose.push(this.eventService.addListener2(WorkbenchEventType.UNTITLED_FILE_DIRTY, () => this.updateEnablement(true)));
			this.toDispose.push(this.eventService.addListener2(WorkbenchEventType.UNTITLED_FILE_DELETED, () => this.updateEnablement(false)));
		}
	}

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

	protected doRun(): TPromise<boolean> {

1664
		// Store mimes per untitled file to restore later
1665
		const mapUntitledToProperties: { [resource: string]: { mime: string; encoding: string; } } = Object.create(null);
1666 1667 1668 1669 1670 1671
		this.textFileService.getDirty()
			.filter(r => r.scheme === 'untitled')			// All untitled resources^
			.map(r => this.untitledEditorService.get(r))	// Mapped to their inputs
			.filter(i => !!i)								// If possible :)
			.forEach(i => mapUntitledToProperties[i.getResource().toString()] = { mime: i.getMime(), encoding: i.getEncoding() });

E
Erich Gamma 已提交
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
		// Save all
		return this.textFileService.saveAll(this.includeUntitled()).then((result) => {

			// all saved - now try to reopen saved untitled ones
			if (this.includeUntitled()) {
				let untitledResults = result.results.filter((res) => res.source.scheme === 'untitled');
				let reopenPromises: { (): Promise }[] = [];

				// Create a promise function for each editor open call to reopen
				untitledResults.forEach((res) => {
					if (res.success) {
						let positions = findSaveAsPositions(this.editorService, res.source);

						let mimeOfSource: string;
1686
						let selectedMime = mapUntitledToProperties[res.source.toString()] && mapUntitledToProperties[res.source.toString()].mime;
E
Erich Gamma 已提交
1687 1688 1689 1690
						if (!isUnspecific(selectedMime)) {
							mimeOfSource = [selectedMime, MIME_TEXT].join(', ');
						}

1691
						let encodingOfSource: string = mapUntitledToProperties[res.source.toString()] && mapUntitledToProperties[res.source.toString()].encoding;
E
Erich Gamma 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

						let targetInput = this.instantiationService.createInstance(FileEditorInput, res.target, mimeOfSource, encodingOfSource);

						let options = new workbenchEditorCommon.EditorOptions();
						options.preserveFocus = true;

						positions.forEach((position) => {
							reopenPromises.push(() => {
								return this.editorService.openEditor(targetInput, options, position);
							});
						});
					}
				});

				// Build a promise that completes when reopen is done
				let reopenPromise = Promise.as(null);
				if (reopenPromises.length) {
					reopenPromise = reopenPromises[0]().then(() => {
						if (reopenPromises.length > 1) {
							return reopenPromises[1]().then(() => {
								if (reopenPromises.length > 2) {
									return reopenPromises[2]();
								}
							});
						}
					});
				}

1720
				return reopenPromise;
E
Erich Gamma 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 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 1895 1896 1897 1898 1899 1900 1901 1902 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 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
			}
		});
	}

	public dispose(): void {
		this.toDispose = disposeAll(this.toDispose);

		super.dispose();
	}
}

function findSaveAsPositions(editorService: IWorkbenchEditorService, outerResource: URI): Position[] {
	let activeInput = editorService.getActiveEditorInput();

	return editorService.getVisibleEditors().filter((editor) => {
		if (outerResource.scheme === 'file' && activeInput !== editor.input) {
			return false; // skip non active if this is about a file; for untitled respect them all
		}

		let innerResource = workbenchEditorCommon.getUntitledOrFileResource(editor.input);

		return innerResource && innerResource.toString() === outerResource.toString();
	}).map((editor) => editor.position);
}

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

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

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

	public run(): Promise {
		let resource: URI;
		if (this.resource) {
			resource = this.resource;
		} else {
			let activeFileInput = workbenchEditorCommon.asFileEditorInput(this.editorService.getActiveEditorInput(), true);
			if (activeFileInput) {
				resource = activeFileInput.getResource();
			}
		}

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

		return Promise.as(true);
	}
}

export class ViewDerivedSourceEditorInputAction extends EditorInputAction {

	constructor(
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
	) {
		super('workbench.files.action.openDerivedResourceFromEditor', nls.localize('viewSource', "View Source"), 'derived-frame-editor-action view-source');
	}

	public run(event?: any): Promise {
		let derivedFrameEditorInput = <DerivedFrameEditorInput>this.input;
		let sideBySide = !!(event && (event.ctrlKey || event.metaKey));

		return this.editorService.openEditor({
			resource: derivedFrameEditorInput.getResource()
		}, sideBySide);
	}
}

export class RefreshDerivedFrameEditorInputAction extends EditorInputAction {

	constructor( @IWorkbenchEditorService private editorService: IWorkbenchEditorService) {
		super('workbench.files.action.refreshDerivedFrameEditor', nls.localize('reload', "Reload"), 'derived-frame-editor-action refresh');
	}

	public run(event?: any): Promise {
		let editor = this.editorService.getActiveEditor();
		if (editor instanceof IFrameEditor) {
			(<IFrameEditor>editor).reload(true);
		}

		return Promise.as(null);
	}
}

export class OpenResourcesAction extends Action {
	private filesToOpen: IResourceInput[];

	constructor(
		filesToOpen: IResourceInput[],
		@IPartService private partService: IPartService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IViewletService private viewletService: IViewletService,
		@ITextFileService private textFileService: ITextFileService,
		@IWorkspaceContextService private contextService: IWorkspaceContextService
	) {
		super('workbench.files.action.openResourcesAction');

		this.filesToOpen = filesToOpen;
	}

	public run(): Promise {
		return this.partService.joinCreation().then(() => {
			let viewletPromise = Promise.as(null);
			if (!this.partService.isSideBarHidden()) {
				viewletPromise = this.viewletService.openViewlet(Files.VIEWLET_ID, false);
			}

			return viewletPromise.then(() => {

				// Out of workspace files get added right away to working files model
				this.filesToOpen.forEach((fileToOpen) => {
					let resource = fileToOpen.resource;
					let workspace = this.contextService.getWorkspace();

					if (!workspace || !paths.isEqualOrParent(resource.fsPath, workspace.resource.fsPath)) {
						this.textFileService.getWorkingFilesModel().addEntry(resource);
					}
				});

				// For one file, just put it into the current active editor
				if (this.filesToOpen.length === 1) {
					return this.editorService.openEditor(this.filesToOpen[0]);
				}

				// Otherwise replace all
				return this.editorService.setEditors(this.filesToOpen);
			});
		});
	}
}

export class CloseWorkingFileAction extends Action {

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

	private model: WorkingFilesModel;
	private element: WorkingFileEntry;

	constructor(
		model: WorkingFilesModel,
		element: WorkingFileEntry,
		@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
		@IMessageService private messageService: IMessageService,
		@IQuickOpenService private quickOpenService: IQuickOpenService
	) {
		super(CloseWorkingFileAction.ID, element ? nls.localize('closeLabel', "Close File") : nls.localize('closeAllLabel', "Close All Files"), element ? (element.dirty ? 'action-close-dirty-file' : 'action-close-file') : 'action-close-all-files');

		this.model = model;
		this.element = element;

		if (this.model) {
			this.enabled = (this.model.count() > 0);
			this.model.onModelChange.add(this.onModelChange, this);
		}
	}

	private onModelChange(event: Files.IWorkingFileModelChangeEvent): void {
		this.enabled = (this.model.count() > 0);
	}

	public run(): Promise {
		let workingFilesCount = this.model.getEntries().length;

		// Handle dirty
		let saveOrRevertPromise: TPromise<Files.ITextFileOperationResult> = Promise.as(null);
		if (this.textFileService.isDirty(this.element ? this.element.resource : void 0 /* all */)) {
			let confirmResult = this.textFileService.confirmSave(this.element ? this.element.resource : void 0 /* all */);

			switch (confirmResult) {
				case Files.ConfirmResult.SAVE:
					if (this.element) {
						saveOrRevertPromise = this.textFileService.saveAll([this.element.resource]);
					} else {
						saveOrRevertPromise = this.textFileService.saveAll(true /* include untitled */);
					}

					break;
				case Files.ConfirmResult.DONT_SAVE:
					if (this.element) {
						saveOrRevertPromise = this.textFileService.revertAll([this.element.resource]);
					} else {
						saveOrRevertPromise = this.textFileService.revertAll();
					}

					break;
				case Files.ConfirmResult.CANCEL:
					return Promise.as(null);
			}
		}

		return saveOrRevertPromise.then((result?: Files.ITextFileOperationResult) => {

			// Collect resources to dispose
			let resourcesToDispose: URI[] = [];
			if (this.element) {
				resourcesToDispose.push(this.element.resource);
			} else {
				resourcesToDispose = this.model.getEntries().map((e) => e.resource);
			}

			// Remove those that failed from the save/revert if we had it
			if (result) {
				let failed = result.results.filter((r) => !r.success).map((r) => r.source.toString());
				resourcesToDispose = resourcesToDispose.filter((r) => failed.indexOf(r.toString()) < 0);
			}

			// remove from model
			if (resourcesToDispose.length === workingFilesCount) {
				this.model.clear();
			} else {
				resourcesToDispose.forEach((r) => this.model.removeEntry(r));
			}

			// dispose
			resourcesToDispose.forEach((r) => this.disposeResource(r));
		}, (error) => {
			this.messageService.show(Severity.Error, error);
		});
	}

	private disposeResource(resource: URI): void {

		// file inputs
		fileEditorInputsForResource(resource, this.editorService, this.quickOpenService).forEach((input) => {
			if (!input.isDisposed()) {
				input.dispose(true);
			}
		});

		// untitled inputs
		let input = this.untitledEditorService.get(resource);
		if (input) {
			input.dispose();
		}
	}

	public dispose(): void {
		if (this.model) {
			this.model.onModelChange.remove(this.onModelChange, this);
		}

		super.dispose();
	}
};

function fileEditorInputsForResource(resource: URI, editorService: IWorkbenchEditorService, quickopenService: IQuickOpenService): FileEditorInput[] {

	// Get cached ones
	let inputs: FileEditorInput[] = FileEditorInput.getAll(resource);

	// Add those from history as well
	let history = quickopenService.getEditorHistory();
	for (let i = 0; i < history.length; i++) {
		let element = history[i];
		if (element instanceof FileEditorInput && (<FileEditorInput>element).getResource().toString() === resource.toString()) {
			inputs.push(<FileEditorInput>element);
		}
	}

	// Add those from visible editors too
	let editors = editorService.getVisibleEditors();
	editors.forEach((editor) => {
		let input = editor.input;
		if (input instanceof FileEditorInput && (<FileEditorInput>input).getResource().toString() === resource.toString()) {
			inputs.push(<FileEditorInput>input);
		}
	});

	return inputs;
}

export class CloseFileAction extends Action {

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

	constructor(
		id: string,
		label: string,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
		@IMessageService private messageService: IMessageService,
		@IQuickOpenService private quickOpenService: IQuickOpenService
	) {
		super(id, label);
	}

	public run(): Promise {
		let input = this.editorService.getActiveEditorInput();
		let resource = workbenchEditorCommon.getUntitledOrFileResource(input, true);

		// Only works if we have a file or untitled input
		if (resource) {
			let model = this.textFileService.getWorkingFilesModel();
			let entry = model.findEntry(resource);

			// Use action to close a working file that will take care of everthing
			if (entry) {
				let closeAction = this.instantiationService.createInstance(CloseWorkingFileAction, model, entry);
				closeAction.run().done(() => closeAction.dispose(), errors.onUnexpectedError);
			}

			// Otherwise just dispose
			else {
2070 2071
				if (input instanceof DiffEditorInput) {
					input = (<DiffEditorInput>input).getModifiedInput();
E
Erich Gamma 已提交
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
				}

				// File Input
				if (input instanceof FileEditorInput) {
					fileEditorInputsForResource(input.getResource(), this.editorService, this.quickOpenService).forEach((input) => {
						if (!input.isDisposed()) {
							input.dispose(true);
						}
					});
				}

				// Untitled Input
				else {
					input.dispose();
				}
			}
		}

		// Otherwise tell the user
		else {
			this.messageService.show(Severity.Info, nls.localize('noFileOpen', "There is currently no file opened to close."));
		}

		return Promise.as(true);
	}
}

export class CloseAllFilesAction extends Action {

	public static ID = 'workbench.files.action.closeAllFiles';
	public static LABEL = nls.localize('closeAllFiles', "Close All Files");

	constructor(
		id: string,
		label: string,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@ITextFileService private textFileService: ITextFileService,
		@IMessageService private messageService: IMessageService,
		@IQuickOpenService private quickOpenService: IQuickOpenService
	) {
		super(id, label);
	}

	public run(): Promise {
		let activeFileInputs = this.editorService.getVisibleEditors().map(e => workbenchEditorCommon.asFileEditorInput(e.input, true)).filter(i => i instanceof FileEditorInput);

		// Close all Working Files
		let closeAction = this.instantiationService.createInstance(CloseWorkingFileAction, this.textFileService.getWorkingFilesModel(), null);
		return closeAction.run().then(() => {
			closeAction.dispose();

			// Dispose remaining non dirty ones
			activeFileInputs.forEach((f: FileEditorInput) => {
				if (!this.textFileService.isDirty(f.getResource())) {
					fileEditorInputsForResource(f.getResource(), this.editorService, this.quickOpenService).forEach(i => {
						if (!i.isDisposed()) {
							i.dispose(true);
						}
					});
				}
			});
		});
	}
}

export class OpenNextWorkingFile extends Action {

	public static ID = 'workbench.files.action.openNextWorkingFile';
	public static LABEL = nls.localize('openNextWorkingFile', "Open Next Working File");

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

	public run(): Promise {
		let model = this.textFileService.getWorkingFilesModel();

		// Return: No working files
		if (model.count() === 0) {
			this.messageService.show(Severity.Info, nls.localize('noWorkingFiles', "Currently there are no working files."));
		}

		// If entry found, open next one
		else {
			let resource = workbenchEditorCommon.getUntitledOrFileResource(this.editorService.getActiveEditorInput(), true);
			return this.editorService.openEditor({ resource: model.next(resource).resource });
		}

		return Promise.as(true);
	}
}

export class OpenPreviousWorkingFile extends Action {

	public static ID = 'workbench.files.action.openPreviousWorkingFile';
	public static LABEL = nls.localize('openPreviousWorkingFile', "Open Previous Working File");

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

	public run(): Promise {
		let model = this.textFileService.getWorkingFilesModel();

		// Return: No working files
		if (model.count() === 0) {
			this.messageService.show(Severity.Info, nls.localize('noWorkingFiles', "Currently there are no working files."));
		}

		// If entry found, open previous one
		else {
			let resource = workbenchEditorCommon.getUntitledOrFileResource(this.editorService.getActiveEditorInput(), true);
			return this.editorService.openEditor({ resource: model.previous(resource).resource });
		}

		return Promise.as(true);
	}
}

export class AddToWorkingFiles extends Action {

	public static ID = 'workbench.files.action.addToWorkingFiles';
	public static LABEL = nls.localize('addToWorkingFiles', "Add Active File to Working Files");

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

	public run(): Promise {
		let fileInput = workbenchEditorCommon.asFileEditorInput(this.editorService.getActiveEditorInput(), true);
		if (fileInput) {
			this.textFileService.getWorkingFilesModel().addEntry(fileInput.getResource());
		} else {
			this.messageService.show(Severity.Info, nls.localize('openFileToAdd', "Open a file first to add it to working files"));
		}

		return Promise.as(true);
	}
}

2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
export class FocusWorkingFiles extends Action {

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

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

	public run(): Promise {
		return this.viewletService.openViewlet(Files.VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
			viewlet.getWorkingFilesView().expand();
			viewlet.getWorkingFilesView().focus();
		});
	}
}

E
Erich Gamma 已提交
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
export function keybindingForAction(id: string): Keybinding {
	switch (id) {
		case GlobalNewFileAction.ID:
			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 DeleteFileAction.ID:
		case MoveFileToTrashAction.ID:
			return new Keybinding(KeyCode.Delete);
		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;
}

// See also http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
let INVALID_FILE_CHARS = isWindows ? ['/', '\\', ':', '*', '?', '\'', '<', '>', '|'] : ['/', '\\'];

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

	// Invalid File Char
	for (let i = 0; i < INVALID_FILE_CHARS.length; i++) {
		if (name.indexOf(INVALID_FILE_CHARS[i]) >= 0) {
			return nls.localize('invalidFileNameError', "The name **{0}** contains characters that are not valid as a file or folder name. Please choose a different name.", name);
		}
	}

	// Max length restriction (on Windows)
	if (isWindows) {
		let fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
		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) {
	diag = diagnostics.register('FileActionsDiagnostics', function(...args: any[]) {
		console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
	});
}