This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
DocumentCommandHandlers.js
1878 lines (1677 loc) · 78.6 KB
/
DocumentCommandHandlers.js
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
293
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
/*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint regexp: true */
define(function (require, exports, module) {
"use strict";
// Load dependent modules
var AppInit = require("utils/AppInit"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
DeprecationWarning = require("utils/DeprecationWarning"),
EventDispatcher = require("utils/EventDispatcher"),
ProjectManager = require("project/ProjectManager"),
DocumentManager = require("document/DocumentManager"),
MainViewManager = require("view/MainViewManager"),
EditorManager = require("editor/EditorManager"),
FileSystem = require("filesystem/FileSystem"),
FileSystemError = require("filesystem/FileSystemError"),
FileUtils = require("file/FileUtils"),
FileViewController = require("project/FileViewController"),
InMemoryFile = require("document/InMemoryFile"),
StringUtils = require("utils/StringUtils"),
Async = require("utils/Async"),
HealthLogger = require("utils/HealthLogger"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
Strings = require("strings"),
PopUpManager = require("widgets/PopUpManager"),
PreferencesManager = require("preferences/PreferencesManager"),
PerfUtils = require("utils/PerfUtils"),
KeyEvent = require("utils/KeyEvent"),
Inspector = require("LiveDevelopment/Inspector/Inspector"),
Menus = require("command/Menus"),
UrlParams = require("utils/UrlParams").UrlParams,
StatusBar = require("widgets/StatusBar"),
WorkspaceManager = require("view/WorkspaceManager"),
LanguageManager = require("language/LanguageManager"),
_ = require("thirdparty/lodash");
/**
* Handlers for commands related to document handling (opening, saving, etc.)
*/
/**
* Container for label shown above editor; must be an inline element
* @type {jQueryObject}
*/
var _$title = null;
/**
* Container for dirty dot; must be an inline element
* @type {jQueryObject}
*/
var _$dirtydot = null;
/**
* Container for _$title; need not be an inline element
* @type {jQueryObject}
*/
var _$titleWrapper = null;
/**
* Label shown above editor for current document: filename and potentially some of its path
* @type {string}
*/
var _currentTitlePath = null;
/**
* Determine the dash character for each platform. Use emdash on Mac
* and a standard dash on all other platforms.
* @type {string}
*/
var _osDash = brackets.platform === "mac" ? "\u2014" : "-";
/**
* String template for window title when no file is open.
* @type {string}
*/
var WINDOW_TITLE_STRING_NO_DOC = "{0} " + _osDash + " {1}";
/**
* String template for window title when a file is open.
* @type {string}
*/
var WINDOW_TITLE_STRING_DOC = "{0} ({1}) " + _osDash + " {2}";
/**
* Container for _$titleWrapper; if changing title changes this element's height, must kick editor to resize
* @type {jQueryObject}
*/
var _$titleContainerToolbar = null;
/**
* Last known height of _$titleContainerToolbar
* @type {number}
*/
var _lastToolbarHeight = null;
/**
* index to use for next, new Untitled document
* @type {number}
*/
var _nextUntitledIndexToUse = 1;
/**
* prevents reentrancy of browserReload()
* @type {boolean}
*/
var _isReloading = false;
/** Unique token used to indicate user-driven cancellation of Save As (as opposed to file IO error) */
var USER_CANCELED = { userCanceled: true };
PreferencesManager.definePreference("defaultExtension", "string", "", {
excludeFromHints: true
});
EventDispatcher.makeEventDispatcher(exports);
/**
* Event triggered when File Save is cancelled, when prompted to save dirty files
*/
var APP_QUIT_CANCELLED = "appQuitCancelled";
/**
* JSLint workaround for circular dependency
* @type {function}
*/
var handleFileSaveAs;
/**
* Updates the title bar with new file title or dirty indicator
* @private
*/
function _updateTitle() {
var currentDoc = DocumentManager.getCurrentDocument(),
windowTitle = brackets.config.app_title,
currentlyViewedFile = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE),
currentlyViewedPath = currentlyViewedFile && currentlyViewedFile.fullPath,
readOnlyString = (currentlyViewedFile && currentlyViewedFile.readOnly) ? "[Read Only] - " : "";
if (!brackets.nativeMenus) {
if (currentlyViewedPath) {
_$title.text(_currentTitlePath);
_$title.attr("title", currentlyViewedPath);
if (currentDoc) {
// dirty dot is always in DOM so layout doesn't change, and visibility is toggled
_$dirtydot.css("visibility", (currentDoc.isDirty) ? "visible" : "hidden");
} else {
// hide dirty dot if there is no document
_$dirtydot.css("visibility", "hidden");
}
} else {
_$title.text("");
_$title.attr("title", "");
_$dirtydot.css("visibility", "hidden");
}
// Set _$titleWrapper to a fixed width just large enough to accommodate _$title. This seems equivalent to what
// the browser would do automatically, but the CSS trick we use for layout requires _$titleWrapper to have a
// fixed width set on it (see the "#titlebar" CSS rule for details).
_$titleWrapper.css("width", "");
var newWidth = _$title.width();
_$titleWrapper.css("width", newWidth);
// Changing the width of the title may cause the toolbar layout to change height, which needs to resize the
// editor beneath it (toolbar changing height due to window resize is already caught by EditorManager).
var newToolbarHeight = _$titleContainerToolbar.height();
if (_lastToolbarHeight !== newToolbarHeight) {
_lastToolbarHeight = newToolbarHeight;
WorkspaceManager.recomputeLayout();
}
}
var projectRoot = ProjectManager.getProjectRoot();
if (projectRoot) {
var projectName = projectRoot.name;
// Construct shell/browser window title, e.g. "• index.html (myProject) — Brackets"
if (currentlyViewedPath) {
windowTitle = StringUtils.format(WINDOW_TITLE_STRING_DOC, readOnlyString + _currentTitlePath, projectName, brackets.config.app_title);
// Display dirty dot when there are unsaved changes
if (currentDoc && currentDoc.isDirty) {
windowTitle = "• " + windowTitle;
}
} else {
// A document is not open
windowTitle = StringUtils.format(WINDOW_TITLE_STRING_NO_DOC, projectName, brackets.config.app_title);
}
}
window.document.title = windowTitle;
}
/**
* Returns a short title for a given document.
*
* @param {Document} doc - the document to compute the short title for
* @return {string} - a short title for doc.
*/
function _shortTitleForDocument(doc) {
var fullPath = doc.file.fullPath;
// If the document is untitled then return the filename, ("Untitled-n.ext");
// otherwise show the project-relative path if the file is inside the
// current project or the full absolute path if it's not in the project.
if (doc.isUntitled()) {
return fullPath.substring(fullPath.lastIndexOf("/") + 1);
} else {
return ProjectManager.makeProjectRelativeIfPossible(fullPath);
}
}
/**
* Handles currentFileChange and filenameChanged events and updates the titlebar
*/
function handleCurrentFileChange() {
var newFile = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE);
if (newFile) {
var newDocument = DocumentManager.getOpenDocumentForPath(newFile.fullPath);
if (newDocument) {
_currentTitlePath = _shortTitleForDocument(newDocument);
} else {
_currentTitlePath = ProjectManager.makeProjectRelativeIfPossible(newFile.fullPath);
}
} else {
_currentTitlePath = null;
}
// Update title text & "dirty dot" display
_updateTitle();
}
/**
* Handles dirtyFlagChange event and updates the title bar if necessary
*/
function handleDirtyChange(event, changedDoc) {
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc && changedDoc.file.fullPath === currentDoc.file.fullPath) {
_updateTitle();
}
}
/**
* Shows an error dialog indicating that the given file could not be opened due to the given error
* @param {!FileSystemError} name
* @return {!Dialog}
*/
function showFileOpenError(name, path) {
return Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_OPENING_FILE_TITLE,
StringUtils.format(
Strings.ERROR_OPENING_FILE,
StringUtils.breakableUrl(path),
FileUtils.getFileErrorString(name)
)
);
}
/**
* @private
* Creates a document and displays an editor for the specified file path.
* @param {!string} fullPath
* @param {boolean=} silent If true, don't show error message
* @param {string=} paneId, the id oi the pane in which to open the file. Can be undefined, a valid pane id or ACTIVE_PANE.
* @param {{*}=} options, command options
* @return {$.Promise} a jQuery promise that will either
* - be resolved with a file for the specified file path or
* - be rejected with FileSystemError if the file can not be read.
* If paneId is undefined, the ACTIVE_PANE constant
*/
function _doOpen(fullPath, silent, paneId, options) {
var result = new $.Deferred();
// workaround for https://github.com/adobe/brackets/issues/6001
// TODO should be removed once bug is closed.
// if we are already displaying a file do nothing but resolve immediately.
// this fixes timing issues in test cases.
if (MainViewManager.getCurrentlyViewedPath(paneId || MainViewManager.ACTIVE_PANE) === fullPath) {
result.resolve(MainViewManager.getCurrentlyViewedFile(paneId || MainViewManager.ACTIVE_PANE));
return result.promise();
}
function _cleanup(fileError, fullFilePath) {
if (fullFilePath) {
// For performance, we do lazy checking of file existence, so it may be in workingset
MainViewManager._removeView(paneId, FileSystem.getFileForPath(fullFilePath));
MainViewManager.focusActivePane();
}
result.reject(fileError);
}
function _showErrorAndCleanUp(fileError, fullFilePath) {
if (silent) {
_cleanup(fileError, fullFilePath);
} else {
showFileOpenError(fileError, fullFilePath).done(function () {
_cleanup(fileError, fullFilePath);
});
}
}
if (!fullPath) {
throw new Error("_doOpen() called without fullPath");
} else {
var perfTimerName = PerfUtils.markStart("Open File:\t" + fullPath);
result.always(function () {
PerfUtils.addMeasurement(perfTimerName);
});
var file = FileSystem.getFileForPath(fullPath);
if (options && options.encoding) {
file._encoding = options.encoding;
} else {
var projectRoot = ProjectManager.getProjectRoot(),
context = {
location : {
scope: "user",
layer: "project",
layerID: projectRoot.fullPath
}
};
var encoding = PreferencesManager.getViewState("encoding", context);
if (encoding && encoding[fullPath]) {
file._encoding = encoding[fullPath];
}
}
MainViewManager._open(paneId, file, options)
.done(function () {
result.resolve(file);
})
.fail(function (fileError) {
_showErrorAndCleanUp(fileError, fullPath);
result.reject();
});
}
return result.promise();
}
/**
* @private
* Used to track the default directory for the file open dialog
*/
var _defaultOpenDialogFullPath = null;
/**
* @private
* Opens a file and displays its view (editor, image view, etc...) for the specified path.
* If no path is specified, a file prompt is provided for input.
* @param {?string} fullPath - The path of the file to open; if it's null we'll prompt for it
* @param {boolean=} silent - If true, don't show error message
* @param {string=} paneId - the pane in which to open the file. Can be undefined, a valid pane id or ACTIVE_PANE
* @param {{*}=} options - options to pass to MainViewManager._open
* @return {$.Promise} a jQuery promise resolved with a Document object or
* rejected with an err
*/
function _doOpenWithOptionalPath(fullPath, silent, paneId, options) {
var result;
paneId = paneId || MainViewManager.ACTIVE_PANE;
if (!fullPath) {
// Create placeholder deferred
result = new $.Deferred();
//first time through, default to the current project path
if (!_defaultOpenDialogFullPath) {
_defaultOpenDialogFullPath = ProjectManager.getProjectRoot().fullPath;
}
// Prompt the user with a dialog
FileSystem.showOpenDialog(true, false, Strings.OPEN_FILE, _defaultOpenDialogFullPath, null, function (err, paths) {
if (!err) {
if (paths.length > 0) {
// Add all files to the workingset without verifying that
// they still exist on disk (for faster opening)
var filesToOpen = [];
paths.forEach(function (path) {
filesToOpen.push(FileSystem.getFileForPath(path));
});
MainViewManager.addListToWorkingSet(paneId, filesToOpen);
_doOpen(paths[paths.length - 1], silent, paneId, options)
.done(function (file) {
_defaultOpenDialogFullPath =
FileUtils.getDirectoryPath(
MainViewManager.getCurrentlyViewedPath(paneId)
);
})
// Send the resulting document that was opened
.then(result.resolve, result.reject);
} else {
// Reject if the user canceled the dialog
result.reject();
}
}
});
} else {
result = _doOpen(fullPath, silent, paneId, options);
}
return result.promise();
}
/**
* @private
* Splits a decorated file path into its parts.
* @param {?string} path - a string of the form "fullpath[:lineNumber[:columnNumber]]"
* @return {{path: string, line: ?number, column: ?number}}
*/
function _parseDecoratedPath(path) {
var result = {path: path, line: null, column: null};
if (path) {
// If the path has a trailing :lineNumber and :columnNumber, strip
// these off and assign to result.line and result.column.
var matchResult = /(.+?):([0-9]+)(:([0-9]+))?$/.exec(path);
if (matchResult) {
result.path = matchResult[1];
if (matchResult[2]) {
result.line = parseInt(matchResult[2], 10);
}
if (matchResult[4]) {
result.column = parseInt(matchResult[4], 10);
}
}
}
return result;
}
/**
* @typedef {{fullPath:?string=, silent:boolean=, paneId:string=}} FileCommandData
* fullPath: is in the form "path[:lineNumber[:columnNumber]]"
* lineNumber and columnNumber are 1-origin: lines and columns are 1-based
*/
/**
* @typedef {{fullPath:?string=, index:number=, silent:boolean=, forceRedraw:boolean=, paneId:string=}} PaneCommandData
* fullPath: is in the form "path[:lineNumber[:columnNumber]]"
* lineNumber and columnNumber are 1-origin: lines and columns are 1-based
*/
/**
* Opens the given file and makes it the current file. Does NOT add it to the workingset.
* @param {FileCommandData=} commandData - record with the following properties:
* fullPath: File to open;
* silent: optional flag to suppress error messages;
* paneId: optional PaneId (defaults to active pane)
* @return {$.Promise} a jQuery promise that will be resolved with a file object
*/
function handleFileOpen(commandData) {
var fileInfo = _parseDecoratedPath(commandData ? commandData.fullPath : null),
silent = (commandData && commandData.silent) || false,
paneId = (commandData && commandData.paneId) || MainViewManager.ACTIVE_PANE,
result = new $.Deferred();
_doOpenWithOptionalPath(fileInfo.path, silent, paneId, commandData && commandData.options)
.done(function (file) {
HealthLogger.fileOpened(file._path, false, file._encoding);
if (!commandData || !commandData.options || !commandData.options.noPaneActivate) {
MainViewManager.setActivePaneId(paneId);
}
// If a line and column number were given, position the editor accordingly.
if (fileInfo.line !== null) {
if (fileInfo.column === null || (fileInfo.column <= 0)) {
fileInfo.column = 1;
}
// setCursorPos expects line/column numbers as 0-origin, so we subtract 1
EditorManager.getCurrentFullEditor().setCursorPos(fileInfo.line - 1,
fileInfo.column - 1,
true);
}
result.resolve(file);
})
.fail(function (err) {
result.reject(err);
});
return result;
// Testing notes: here are some recommended manual tests for handleFileOpen, on Macintosh.
// Do all tests with brackets already running, and also with brackets not already running.
//
// drag a file onto brackets icon in desktop (this uses undecorated paths)
// drag a file onto brackets icon in taskbar (this uses undecorated paths)
// open a file from brackets sidebar (this uses undecorated paths)
// from command line: ...../Brackets.app/Contents path - where 'path' is undecorated
// from command line: ...../Brackets.app path - where 'path' has the form "path:line"
// from command line: ...../Brackets.app path - where 'path' has the form "path:line:column"
// from command line: open -a ...../Brackets.app path - where 'path' is undecorated
// do "View Source" from Adobe Scout version 1.2 or newer (this will use decorated paths of the form "path:line:column")
}
/**
* Opens the given file, makes it the current file, does NOT add it to the workingset
* @param {FileCommandData} commandData
* fullPath: File to open;
* silent: optional flag to suppress error messages;
* paneId: optional PaneId (defaults to active pane)
* @return {$.Promise} a jQuery promise that will be resolved with @type {Document}
*/
function handleDocumentOpen(commandData) {
var result = new $.Deferred();
handleFileOpen(commandData)
.done(function (file) {
// if we succeeded with an open file
// then we need to resolve that to a document.
// getOpenDocumentForPath will return null if there isn't a
// supporting document for that file (e.g. an image)
var doc = DocumentManager.getOpenDocumentForPath(file.fullPath);
result.resolve(doc);
})
.fail(function (err) {
result.reject(err);
});
return result.promise();
}
/**
* Opens the given file, makes it the current file, AND adds it to the workingset
* @param {!PaneCommandData} commandData - record with the following properties:
* fullPath: File to open;
* index: optional index to position in workingset (defaults to last);
* silent: optional flag to suppress error messages;
* forceRedraw: flag to force the working set view redraw;
* paneId: optional PaneId (defaults to active pane)
* @return {$.Promise} a jQuery promise that will be resolved with a @type {File}
*/
function handleFileAddToWorkingSetAndOpen(commandData) {
return handleFileOpen(commandData).done(function (file) {
var paneId = (commandData && commandData.paneId) || MainViewManager.ACTIVE_PANE;
MainViewManager.addToWorkingSet(paneId, file, commandData.index, commandData.forceRedraw);
HealthLogger.fileOpened(file.fullPath, true);
});
}
/**
* @deprecated
* Opens the given file, makes it the current document, AND adds it to the workingset
* @param {!PaneCommandData} commandData - record with the following properties:
* fullPath: File to open;
* index: optional index to position in workingset (defaults to last);
* silent: optional flag to suppress error messages;
* forceRedraw: flag to force the working set view redraw;
* paneId: optional PaneId (defaults to active pane)
* @return {$.Promise} a jQuery promise that will be resolved with @type {File}
*/
function handleFileAddToWorkingSet(commandData) {
// This is a legacy deprecated command that
// will use the new command and resolve with a document
// as the legacy command would only support.
DeprecationWarning.deprecationWarning("Commands.FILE_ADD_TO_WORKING_SET has been deprecated. Use Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN instead.");
var result = new $.Deferred();
handleFileAddToWorkingSetAndOpen(commandData)
.done(function (file) {
// if we succeeded with an open file
// then we need to resolve that to a document.
// getOpenDocumentForPath will return null if there isn't a
// supporting document for that file (e.g. an image)
var doc = DocumentManager.getOpenDocumentForPath(file.fullPath);
result.resolve(doc);
})
.fail(function (err) {
result.reject(err);
});
return result.promise();
}
/**
* @private
* Ensures the suggested file name doesn't already exit.
* @param {Directory} dir The directory to use
* @param {string} baseFileName The base to start with, "-n" will get appended to make unique
* @param {boolean} isFolder True if the suggestion is for a folder name
* @return {$.Promise} a jQuery promise that will be resolved with a unique name starting with
* the given base name
*/
function _getUntitledFileSuggestion(dir, baseFileName, isFolder) {
var suggestedName = baseFileName + "-" + _nextUntitledIndexToUse++,
deferred = $.Deferred();
if (_nextUntitledIndexToUse > 9999) {
//we've tried this enough
deferred.reject();
} else {
var path = dir.fullPath + suggestedName,
entry = isFolder ? FileSystem.getDirectoryForPath(path)
: FileSystem.getFileForPath(path);
entry.exists(function (err, exists) {
if (err || exists) {
_getUntitledFileSuggestion(dir, baseFileName, isFolder)
.then(deferred.resolve, deferred.reject);
} else {
deferred.resolve(suggestedName);
}
});
}
return deferred.promise();
}
/**
* Prevents re-entrancy into handleFileNewInProject()
*
* handleFileNewInProject() first prompts the user to name a file and then asynchronously writes the file when the
* filename field loses focus. This boolean prevent additional calls to handleFileNewInProject() when an existing
* file creation call is outstanding
*/
var fileNewInProgress = false;
/**
* Bottleneck function for creating new files and folders in the project tree.
* @private
* @param {boolean} isFolder - true if creating a new folder, false if creating a new file
*/
function _handleNewItemInProject(isFolder) {
if (fileNewInProgress) {
ProjectManager.forceFinishRename();
return;
}
fileNewInProgress = true;
// Determine the directory to put the new file
// If a file is currently selected in the tree, put it next to it.
// If a directory is currently selected in the tree, put it in it.
// If an Untitled document is selected or nothing is selected in the tree, put it at the root of the project.
var baseDirEntry,
selected = ProjectManager.getFileTreeContext();
if ((!selected) || (selected instanceof InMemoryFile)) {
selected = ProjectManager.getProjectRoot();
}
if (selected.isFile) {
baseDirEntry = FileSystem.getDirectoryForPath(selected.parentPath);
}
baseDirEntry = baseDirEntry || selected;
// Create the new node. The createNewItem function does all the heavy work
// of validating file name, creating the new file and selecting.
function createWithSuggestedName(suggestedName) {
return ProjectManager.createNewItem(baseDirEntry, suggestedName, false, isFolder)
.always(function () { fileNewInProgress = false; });
}
return _getUntitledFileSuggestion(baseDirEntry, Strings.UNTITLED, isFolder)
.then(createWithSuggestedName, createWithSuggestedName.bind(undefined, Strings.UNTITLED));
}
/**
* Create a new untitled document in the workingset, and make it the current document.
* Promise is resolved (synchronously) with the newly-created Document.
*/
function handleFileNew() {
//var defaultExtension = PreferencesManager.get("defaultExtension");
//if (defaultExtension) {
// defaultExtension = "." + defaultExtension;
//}
var defaultExtension = ""; // disable preference setting for now
var doc = DocumentManager.createUntitledDocument(_nextUntitledIndexToUse++, defaultExtension);
MainViewManager._edit(MainViewManager.ACTIVE_PANE, doc);
HealthLogger.sendAnalyticsData(
HealthLogger.commonStrings.USAGE +
HealthLogger.commonStrings.FILE_OPEN +
HealthLogger.commonStrings.FILE_NEW,
HealthLogger.commonStrings.USAGE,
HealthLogger.commonStrings.FILE_OPEN,
HealthLogger.commonStrings.FILE_NEW
);
return new $.Deferred().resolve(doc).promise();
}
/**
* Create a new file in the project tree.
*/
function handleFileNewInProject() {
_handleNewItemInProject(false);
}
/**
* Create a new folder in the project tree.
*/
function handleNewFolderInProject() {
_handleNewItemInProject(true);
}
/**
* @private
* Shows an Error modal dialog
* @param {string} name
* @param {string} path
* @return {Dialog}
*/
function _showSaveFileError(name, path) {
return Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_SAVING_FILE_TITLE,
StringUtils.format(
Strings.ERROR_SAVING_FILE,
StringUtils.breakableUrl(path),
FileUtils.getFileErrorString(name)
)
);
}
/**
* Saves a document to its existing path. Does NOT support untitled documents.
* @param {!Document} docToSave
* @param {boolean=} force Ignore CONTENTS_MODIFIED errors from the FileSystem
* @return {$.Promise} a promise that is resolved with the File of docToSave (to mirror
* the API of _doSaveAs()). Rejected in case of IO error (after error dialog dismissed).
*/
function doSave(docToSave, force) {
var result = new $.Deferred(),
file = docToSave.file;
function handleError(error) {
_showSaveFileError(error, file.fullPath)
.done(function () {
result.reject(error);
});
}
function handleContentsModified() {
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.EXT_MODIFIED_TITLE,
StringUtils.format(
Strings.EXT_MODIFIED_WARNING,
StringUtils.breakableUrl(docToSave.file.fullPath)
),
[
{
className : Dialogs.DIALOG_BTN_CLASS_LEFT,
id : Dialogs.DIALOG_BTN_SAVE_AS,
text : Strings.SAVE_AS
},
{
className : Dialogs.DIALOG_BTN_CLASS_NORMAL,
id : Dialogs.DIALOG_BTN_CANCEL,
text : Strings.CANCEL
},
{
className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
id : Dialogs.DIALOG_BTN_OK,
text : Strings.SAVE_AND_OVERWRITE
}
]
)
.done(function (id) {
if (id === Dialogs.DIALOG_BTN_CANCEL) {
result.reject();
} else if (id === Dialogs.DIALOG_BTN_OK) {
// Re-do the save, ignoring any CONTENTS_MODIFIED errors
doSave(docToSave, true).then(result.resolve, result.reject);
} else if (id === Dialogs.DIALOG_BTN_SAVE_AS) {
// Let the user choose a different path at which to write the file
handleFileSaveAs({doc: docToSave}).then(result.resolve, result.reject);
}
});
}
function trySave() {
// We don't want normalized line endings, so it's important to pass true to getText()
FileUtils.writeText(file, docToSave.getText(true), force)
.done(function () {
docToSave.notifySaved();
result.resolve(file);
HealthLogger.fileSaved(docToSave);
})
.fail(function (err) {
if (err === FileSystemError.CONTENTS_MODIFIED) {
handleContentsModified();
} else {
handleError(err);
}
});
}
if (docToSave.isDirty) {
if (docToSave.keepChangesTime) {
// The user has decided to keep conflicting changes in the editor. Check to make sure
// the file hasn't changed since they last decided to do that.
docToSave.file.stat(function (err, stat) {
// If the file has been deleted on disk, the stat will return an error, but that's fine since
// that means there's no file to overwrite anyway, so the save will succeed without us having
// to set force = true.
if (!err && docToSave.keepChangesTime === stat.mtime.getTime()) {
// OK, it's safe to overwrite the file even though we never reloaded the latest version,
// since the user already said s/he wanted to ignore the disk version.
force = true;
}
trySave();
});
} else {
trySave();
}
} else {
result.resolve(file);
}
result.always(function () {
MainViewManager.focusActivePane();
});
return result.promise();
}
/**
* Reverts the Document to the current contents of its file on disk. Discards any unsaved changes
* in the Document.
* @private
* @param {Document} doc
* @param {boolean=} suppressError If true, then a failure to read the file will be ignored and the
* resulting promise will be resolved rather than rejected.
* @return {$.Promise} a Promise that's resolved when done, or (if suppressError is false)
* rejected with a FileSystemError if the file cannot be read (after showing an error
* dialog to the user).
*/
function _doRevert(doc, suppressError) {
var result = new $.Deferred();
FileUtils.readAsText(doc.file)
.done(function (text, readTimestamp) {
doc.refreshText(text, readTimestamp);
result.resolve();
})
.fail(function (error) {
if (suppressError) {
result.resolve();
} else {
showFileOpenError(error, doc.file.fullPath)
.done(function () {
result.reject(error);
});
}
});
return result.promise();
}
/**
* Dispatches the app quit cancelled event
*/
function dispatchAppQuitCancelledEvent() {
exports.trigger(exports.APP_QUIT_CANCELLED);
}
/**
* Opens the native OS save as dialog and saves document.
* The original document is reverted in case it was dirty.
* Text selection and cursor position from the original document
* are preserved in the new document.
* When saving to the original document the document is saved as if save was called.
* @param {Document} doc
* @param {?{cursorPos:!Object, selection:!Object, scrollPos:!Object}} settings - properties of
* the original document's editor that need to be carried over to the new document
* i.e. scrollPos, cursorPos and text selection
* @return {$.Promise} a promise that is resolved with the saved document's File. Rejected in
* case of IO error (after error dialog dismissed), or if the Save dialog was canceled.
*/
function _doSaveAs(doc, settings) {
var origPath,
saveAsDefaultPath,
defaultName,
result = new $.Deferred();
function _doSaveAfterSaveDialog(path) {
var newFile;
// Reconstruct old doc's editor's view state, & finally resolve overall promise
function _configureEditorAndResolve() {
var editor = EditorManager.getActiveEditor();
if (editor) {
if (settings) {
editor.setSelections(settings.selections);
editor.setScrollPos(settings.scrollPos.x, settings.scrollPos.y);
}
}
result.resolve(newFile);
}
// Replace old document with new one in open editor & workingset
function openNewFile() {
var fileOpenPromise;
if (FileViewController.getFileSelectionFocus() === FileViewController.PROJECT_MANAGER) {
// If selection is in the tree, leave workingset unchanged - even if orig file is in the list
fileOpenPromise = FileViewController
.openAndSelectDocument(path, FileViewController.PROJECT_MANAGER);
} else {
// If selection is in workingset, replace orig item in place with the new file
var info = MainViewManager.findInAllWorkingSets(doc.file.fullPath).shift();
// Remove old file from workingset; no redraw yet since there's a pause before the new file is opened
MainViewManager._removeView(info.paneId, doc.file, true);
// Add new file to workingset, and ensure we now redraw (even if index hasn't changed)
fileOpenPromise = handleFileAddToWorkingSetAndOpen({fullPath: path, paneId: info.paneId, index: info.index, forceRedraw: true});
}
// always configure editor after file is opened
fileOpenPromise.always(function () {
_configureEditorAndResolve();
});
}
// Same name as before - just do a regular Save
if (path === origPath) {
doSave(doc).then(result.resolve, result.reject);
return;
}
doc.isSaving = true; // mark that we're saving the document
// First, write document's current text to new file
if (doc.file._encoding && doc.file._encoding !== "UTF-8") {
var projectRoot = ProjectManager.getProjectRoot(),
context = {
location : {
scope: "user",
layer: "project",
layerID: projectRoot.fullPath
}
};
var encoding = PreferencesManager.getViewState("encoding", context);
encoding[path] = doc.file._encoding;
PreferencesManager.setViewState("encoding", encoding, context);
}
newFile = FileSystem.getFileForPath(path);
newFile._encoding = doc.file._encoding;
// Save as warns you when you're about to overwrite a file, so we
// explicitly allow "blind" writes to the filesystem in this case,
// ignoring warnings about the contents being modified outside of
// the editor.
FileUtils.writeText(newFile, doc.getText(true), true)
.done(function () {
// If there were unsaved changes before Save As, they don't stay with the old
// file anymore - so must revert the old doc to match disk content.
// Only do this if the doc was dirty: _doRevert on a file that is not dirty and
// not in the workingset has the side effect of adding it to the workingset.
if (doc.isDirty && !(doc.isUntitled())) {
// if the file is dirty it must be in the workingset
// _doRevert is side effect free in this case
_doRevert(doc).always(openNewFile);
} else {
openNewFile();
}
HealthLogger.fileSaved(doc);
})
.fail(function (error) {
_showSaveFileError(error, path)
.done(function () {
result.reject(error);
});
})
.always(function () {
// mark that we're done saving the document
doc.isSaving = false;
});
}
if (doc) {
origPath = doc.file.fullPath;
// If the document is an untitled document, we should default to project root.
if (doc.isUntitled()) {
// (Issue #4489) if we're saving an untitled document, go ahead and switch to this document
// in the editor, so that if we're, for example, saving several files (ie. Save All),
// then the user can visually tell which document we're currently prompting them to save.