forked from adobe/brackets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProjectModel.js
More file actions
1387 lines (1235 loc) · 49.9 KB
/
ProjectModel.js
File metadata and controls
1387 lines (1235 loc) · 49.9 KB
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) 2014 - 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.
*
*/
/* unittests: ProjectModel */
/**
* Provides the data source for a project and manages the view model for the FileTreeView.
*/
define(function (require, exports, module) {
"use strict";
var InMemoryFile = require("document/InMemoryFile"),
EventDispatcher = require("utils/EventDispatcher"),
FileUtils = require("file/FileUtils"),
_ = require("thirdparty/lodash"),
FileSystem = require("filesystem/FileSystem"),
FileSystemError = require("filesystem/FileSystemError"),
FileTreeViewModel = require("project/FileTreeViewModel"),
Async = require("utils/Async"),
PerfUtils = require("utils/PerfUtils");
// Constants
var EVENT_CHANGE = "change",
EVENT_SHOULD_SELECT = "select",
EVENT_SHOULD_FOCUS = "focus",
ERROR_CREATION = "creationError",
ERROR_INVALID_FILENAME = "invalidFilename",
ERROR_NOT_IN_PROJECT = "notInProject";
/**
* @private
* File and folder names which are not displayed or searched
* TODO: We should add the rest of the file names that TAR excludes:
* http://www.gnu.org/software/tar/manual/html_section/exclude.html
* TODO: This should be user configurable
* https://github.com/adobe/brackets/issues/6781
* @type {RegExp}
*/
var _exclusionListRegEx = /\.pyc$|^\.git$|^\.gitmodules$|^\.svn$|^\.DS_Store$|^Icon\r|^Thumbs\.db$|^\.hg$|^CVS$|^\.hgtags$|^\.idea$|^\.c9revisions$|^\.SyncArchive$|^\.SyncID$|^\.SyncIgnore$|\~$/;
/**
* Glob definition of files and folders that should be excluded directly
* inside node domain watching with chokidar
*/
var defaultIgnoreGlobs = [
"**/(.pyc|.git|.gitmodules|.svn|.DS_Store|Thumbs.db|.hg|CVS|.hgtags|.idea|.c9revisions|.SyncArchive|.SyncID|.SyncIgnore)",
"**/bower_components",
"**/node_modules"
];
/**
* @private
* RegEx to validate a file path.
*/
var _invalidChars = /([?\*\|\<\>"]+|\/{2,}|\.{2,}|\.$)/i;
/**
* @private
* RegEx to validate if a filename is not allowed even if the system allows it.
* This is done to prevent cross-platform issues.
*/
var _illegalFilenamesRegEx = /((\b(com[0-9]+|lpt[0-9]+|nul|con|prn|aux)\b)|\.+$|\/+|\\+|\:)/i;
/**
* Returns true if this matches valid filename specifications.
* See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
*
* TODO: This likely belongs in FileUtils.
*
* @param {string} filename to check
* @return {boolean} true if the filename is valid
*/
function isValidFilename(filename) {
// Fix issue adobe#13099
// See https://github.com/adobe/brackets/issues/13099
return !(
filename.match(_invalidChars)|| filename.match(_illegalFilenamesRegEx)
);
}
/**
* Returns true if given path is valid.
*
* @param {string} path to check
* @return {boolean} true if the filename is valid
*/
function isValidPath(path) {
// Fix issue adobe#13099
// See https://github.com/adobe/brackets/issues/13099
return !(path.match(_invalidChars));
}
/**
* @private
* @see #shouldShow
*/
function _shouldShowName(name) {
return !_exclusionListRegEx.test(name);
}
/**
* Returns false for files and directories that are not commonly useful to display.
*
* @param {!FileSystemEntry} entry File or directory to filter
* @return {boolean} true if the file should be displayed
*/
function shouldShow(entry) {
return _shouldShowName(entry.name);
}
// Constants used by the ProjectModel
var FILE_RENAMING = 0,
FILE_CREATING = 1,
RENAME_CANCELLED = 2;
/**
* @private
*
* Determines if a path string is pointing to a directory (does it have a trailing slash?)
*
* @param {string} path Path to test.
*/
function _pathIsFile(path) {
return _.last(path) !== "/";
}
/**
* @private
*
* Gets the FileSystem object (either a File or Directory) based on the path provided.
*
* @param {string} path Path to retrieve
*/
function _getFSObject(path) {
if (!path) {
return path;
} else if (_pathIsFile(path)) {
return FileSystem.getFileForPath(path);
}
return FileSystem.getDirectoryForPath(path);
}
/**
* @private
*
* Given what is possible a FileSystem object, return its path (if a string path is passed in,
* it will be returned as-is).
*
* @param {FileSystemEntry} fsobj Object from which the path should be extracted
*/
function _getPathFromFSObject(fsobj) {
if (fsobj && fsobj.fullPath) {
return fsobj.fullPath;
}
return fsobj;
}
/**
* Creates a new file or folder at the given path. The returned promise is rejected if the filename
* is invalid, the new path already exists or some other filesystem error comes up.
*
* @param {string} path path to create
* @param {boolean} isFolder true if the new entry is a folder
* @return {$.Promise} resolved when the file or directory has been created.
*/
function doCreate(path, isFolder) {
var d = new $.Deferred();
var filename = FileUtils.getBaseName(path);
// Check if filename
if (!isValidFilename(filename)){
return d.reject(ERROR_INVALID_FILENAME).promise();
}
// Check if fullpath with filename is valid
// This check is used to circumvent directory jumps (Like ../..)
if (!isValidPath(path)) {
return d.reject(ERROR_INVALID_FILENAME).promise();
}
FileSystem.resolve(path, function (err) {
if (!err) {
// Item already exists, fail with error
d.reject(FileSystemError.ALREADY_EXISTS);
} else {
if (isFolder) {
var directory = FileSystem.getDirectoryForPath(path);
directory.create(function (err) {
if (err) {
d.reject(err);
} else {
d.resolve(directory);
}
});
} else {
// Create an empty file
var file = FileSystem.getFileForPath(path);
FileUtils.writeText(file, "").then(function () {
d.resolve(file);
}, d.reject);
}
}
});
return d.promise();
}
/**
* @constructor
*
* The ProjectModel provides methods for accessing information about the current open project.
* It also manages the view model to display a FileTreeView of the project.
*
* Events:
* - EVENT_CHANGE (`change`) - Fired when there's a change that should refresh the UI
* - EVENT_SHOULD_SELECT (`select`) - Fired when a selection has been made in the file tree and the file tree should be selected
* - EVENT_SHOULD_FOCUS (`focus`)
* - ERROR_CREATION (`creationError`) - Triggered when there's a problem creating a file
*/
function ProjectModel(initial) {
initial = initial || {};
if (initial.projectRoot) {
this.projectRoot = initial.projectRoot;
}
if (initial.focused !== undefined) {
this._focused = initial.focused;
}
this._viewModel = new FileTreeViewModel.FileTreeViewModel();
this._viewModel.on(FileTreeViewModel.EVENT_CHANGE, function () {
this.trigger(EVENT_CHANGE);
}.bind(this));
this._selections = {};
}
EventDispatcher.makeEventDispatcher(ProjectModel.prototype);
/**
* @type {Directory}
*
* The root Directory object for the project.
*/
ProjectModel.prototype.projectRoot = null;
/**
* @private
* @type {FileTreeViewModel}
*
* The view model for this project.
*/
ProjectModel.prototype._viewModel = null;
/**
* @private
* @type {string}
*
* Encoded URL
* @see {@link ProjectModel#getBaseUrl}, {@link ProjectModel#setBaseUrl}
*/
ProjectModel.prototype._projectBaseUrl = "";
/**
* @private
* @type {{selected: ?string, context: ?string, previousContext: ?string, rename: ?Object}}
*
* Keeps track of selected files, context, previous context and files
* that are being renamed or created.
*/
ProjectModel.prototype._selections = null;
/**
* @private
* @type {boolean}
*
* Flag to store whether the file tree has focus.
*/
ProjectModel.prototype._focused = true;
/**
* @private
* @type {string}
*
* Current file path being viewed.
*/
ProjectModel.prototype._currentPath = null;
/**
* @private
* @type {?$.Promise.<Array<File>>}
*
* A promise that is resolved with an array of all project files. Used by
* ProjectManager.getAllFiles().
*/
ProjectModel.prototype._allFilesCachePromise = null;
/**
* Sets whether the file tree is focused or not.
*
* @param {boolean} focused True if the file tree has the focus.
*/
ProjectModel.prototype.setFocused = function (focused) {
this._focused = focused;
if (!focused) {
this.setSelected(null);
}
};
/**
* Sets the width of the selection bar.
*
* @param {int} width New width
*/
ProjectModel.prototype.setSelectionWidth = function (width) {
this._viewModel.setSelectionWidth(width);
};
/**
* Tracks the scroller position.
*
* @param {int} scrollWidth Width of the tree container
* @param {int} scrollTop Top of scroll position
* @param {int} scrollLeft Left of scroll position
* @param {int} offsetTop Top of scroller element
*/
ProjectModel.prototype.setScrollerInfo = function (scrollWidth, scrollTop, scrollLeft, offsetTop) {
this._viewModel.setSelectionScrollerInfo(scrollWidth, scrollTop, scrollLeft, offsetTop);
};
/**
* Returns the encoded Base URL of the currently loaded project, or empty string if no project
* is open (during startup, or running outside of app shell).
* @return {String}
*/
ProjectModel.prototype.getBaseUrl = function getBaseUrl() {
return this._projectBaseUrl;
};
/**
* Sets the encoded Base URL of the currently loaded project.
* @param {String}
*/
ProjectModel.prototype.setBaseUrl = function setBaseUrl(projectBaseUrl) {
// Ensure trailing slash to be consistent with projectRoot.fullPath
// so they're interchangable (i.e. easy to convert back and forth)
if (projectBaseUrl.length > 0 && projectBaseUrl[projectBaseUrl.length - 1] !== "/") {
projectBaseUrl += "/";
}
this._projectBaseUrl = projectBaseUrl;
return projectBaseUrl;
};
/**
* Returns true if absPath lies within the project, false otherwise.
* Does not support paths containing ".."
*
* @param {string|FileSystemEntry} absPathOrEntry
* @return {boolean}
*/
ProjectModel.prototype.isWithinProject = function isWithinProject(absPathOrEntry) {
var absPath = absPathOrEntry.fullPath || absPathOrEntry;
return (this.projectRoot && absPath.indexOf(this.projectRoot.fullPath) === 0);
};
/**
* If absPath lies within the project, returns a project-relative path. Else returns absPath
* unmodified.
* Does not support paths containing ".."
*
* @param {!string} absPath
* @return {!string}
*/
ProjectModel.prototype.makeProjectRelativeIfPossible = function makeProjectRelativeIfPossible(absPath) {
if (absPath && this.isWithinProject(absPath)) {
return absPath.slice(this.projectRoot.fullPath.length);
}
return absPath;
};
/**
* Returns a valid directory within the project, either the path (or Directory object)
* provided or the project root.
*
* @param {string|Directory} path Directory path to verify against the project
* @return {string} A directory path within the project.
*/
ProjectModel.prototype.getDirectoryInProject = function (path) {
if (path && typeof path === "string") {
if (_.last(path) !== "/") {
path += "/";
}
} else if (path && path.isDirectory) {
path = path.fullPath;
} else {
path = null;
}
if (!path || (typeof path !== "string") || !this.isWithinProject(path)) {
path = this.projectRoot.fullPath;
}
return path;
};
/**
* @private
*
* Returns a promise that resolves with a cached copy of all project files.
* Used by ProjectManager.getAllFiles(). Ensures that at most one un-cached
* directory traversal is active at a time, which is useful at project load
* time when watchers (and hence filesystem-level caching) has not finished
* starting up. The cache is cleared on every filesystem change event, and
* also on project load and unload.
*
* @param {boolean} true to sort files by their paths
* @return {$.Promise.<Array.<File>>}
*/
ProjectModel.prototype._getAllFilesCache = function _getAllFilesCache(sort) {
if (!this._allFilesCachePromise) {
var deferred = new $.Deferred(),
allFiles = [],
allFilesVisitor = function (entry) {
if (shouldShow(entry)) {
if (entry.isFile) {
allFiles.push(entry);
}
return true;
}
return false;
};
this._allFilesCachePromise = deferred.promise();
var projectIndexTimer = PerfUtils.markStart("Creating project files cache: " +
this.projectRoot.fullPath),
options = {
sortList : sort
};
this.projectRoot.visit(allFilesVisitor, options, function (err) {
if (err) {
PerfUtils.finalizeMeasurement(projectIndexTimer);
deferred.reject(err);
} else {
PerfUtils.addMeasurement(projectIndexTimer);
deferred.resolve(allFiles);
}
}.bind(this));
}
return this._allFilesCachePromise;
};
/**
* Returns an Array of all files for this project, optionally including
* files additional files provided. Files are filtered out by shouldShow().
*
* @param {function (File, number):boolean=} filter Optional function to filter
* the file list (does not filter directory traversal). API matches Array.filter().
* @param {Array.<File>=} additionalFiles Additional files to include (for example, the WorkingSet)
* Only adds files that are *not* under the project root or untitled documents.
* @param {boolean} true to sort files by their paths
*
* @return {$.Promise} Promise that is resolved with an Array of File objects.
*/
ProjectModel.prototype.getAllFiles = function getAllFiles(filter, additionalFiles, sort) {
// The filter and includeWorkingSet params are both optional.
// Handle the case where filter is omitted but includeWorkingSet is
// specified.
if (additionalFiles === undefined && typeof (filter) !== "function") {
additionalFiles = filter;
filter = null;
}
var filteredFilesDeferred = new $.Deferred();
// First gather all files in project proper
// Note that with proper promises we may be able to fix this so that we're not doing this
// anti-pattern of creating a separate deferred rather than just chaining off of the promise
// from _getAllFilesCache
this._getAllFilesCache(sort).done(function (result) {
// Add working set entries, if requested
if (additionalFiles) {
additionalFiles.forEach(function (file) {
if (result.indexOf(file) === -1 && !(file instanceof InMemoryFile)) {
result.push(file);
}
});
}
// Filter list, if requested
if (filter) {
result = result.filter(filter);
}
// If a done handler attached to the returned filtered files promise
// throws an exception that isn't handled here then it will leave
// _allFilesCachePromise in an inconsistent state such that no
// additional done handlers will ever be called!
try {
filteredFilesDeferred.resolve(result);
} catch (e) {
console.error("Unhandled exception in getAllFiles handler: " + e, e.stack);
}
}).fail(function (err) {
try {
filteredFilesDeferred.reject(err);
} catch (e) {
console.error("Unhandled exception in getAllFiles handler: " + e, e.stack);
}
});
return filteredFilesDeferred.promise();
};
/**
* @private
*
* Resets the all files cache.
*/
ProjectModel.prototype._resetCache = function _resetCache() {
this._allFilesCachePromise = null;
};
/**
* Sets the project root (effectively resetting this ProjectModel).
*
* @param {Directory} projectRoot new project root
* @return {$.Promise} resolved when the project root has been updated
*/
ProjectModel.prototype.setProjectRoot = function (projectRoot) {
this.projectRoot = projectRoot;
this._resetCache();
this._viewModel._rootChanged();
var d = new $.Deferred(),
self = this;
projectRoot.getContents(function (err, contents) {
if (err) {
d.reject(err);
} else {
self._viewModel.setDirectoryContents("", contents);
d.resolve();
}
});
return d.promise();
};
/**
* @private
*
* Gets the contents of a directory at the given path.
*
* @param {string} path path to retrieve
* @return {$.Promise} Resolved with the directory contents.
*/
ProjectModel.prototype._getDirectoryContents = function (path) {
var d = new $.Deferred();
FileSystem.getDirectoryForPath(path).getContents(function (err, contents) {
if (err) {
d.reject(err);
} else {
d.resolve(contents);
}
});
return d.promise();
};
/**
* Opens or closes the given directory in the file tree.
*
* @param {string} path Path to open
* @param {boolean} open `true` to open the path
* @return {$.Promise} resolved when the path has been opened.
*/
ProjectModel.prototype.setDirectoryOpen = function (path, open) {
var projectRelative = this.makeProjectRelativeIfPossible(path),
needsLoading = !this._viewModel.isPathLoaded(projectRelative),
d = new $.Deferred(),
self = this;
function onSuccess(contents) {
// Update the view model
if (contents) {
self._viewModel.setDirectoryContents(projectRelative, contents);
}
if (open) {
self._viewModel.openPath(projectRelative);
if (self._focused) {
var currentPathInProject = self.makeProjectRelativeIfPossible(self._currentPath);
if (self._viewModel.isFilePathVisible(currentPathInProject)) {
self.setSelected(self._currentPath, true);
} else {
self.setSelected(null);
}
}
} else {
self._viewModel.setDirectoryOpen(projectRelative, false);
var selected = self._selections.selected;
if (selected) {
var relativeSelected = self.makeProjectRelativeIfPossible(selected);
if (!self._viewModel.isFilePathVisible(relativeSelected)) {
self.setSelected(null);
}
}
}
d.resolve();
}
// If the view model doesn't have the data it needs, we load it now, otherwise we can just
// manage the selection and resovle the promise.
if (open && needsLoading) {
var parentDirectory = FileUtils.getDirectoryPath(FileUtils.stripTrailingSlash(path));
this.setDirectoryOpen(parentDirectory, true).then(function () {
self._getDirectoryContents(path).then(onSuccess).fail(function (err) {
d.reject(err);
});
}, function (err) {
d.reject(err);
});
} else {
onSuccess();
}
return d.promise();
};
/**
* Shows the given path in the tree and selects it if it's a file. Any intermediate directories
* will be opened and a promise is returned to show when the entire operation is complete.
*
* @param {string|File|Directory} path full path to the file or directory
* @return {$.Promise} promise resolved when the path is shown
*/
ProjectModel.prototype.showInTree = function (path) {
var d = new $.Deferred();
path = _getPathFromFSObject(path);
if (!this.isWithinProject(path)) {
return d.resolve().promise();
}
var parentDirectory = FileUtils.getDirectoryPath(path),
self = this;
this.setDirectoryOpen(parentDirectory, true).then(function () {
if (_pathIsFile(path)) {
self.setSelected(path);
}
d.resolve();
}, function (err) {
d.reject(err);
});
return d.promise();
};
/**
* Selects the given path in the file tree and opens the file (unless doNotOpen is specified).
* Directories will not be selected.
*
* When the selection changes, any rename operation that is currently underway will be completed.
*
* @param {string} path full path to the file being selected
* @param {boolean} doNotOpen `true` if the file should not be opened.
*/
ProjectModel.prototype.setSelected = function (path, doNotOpen) {
path = _getPathFromFSObject(path);
// Directories are not selectable
if (!_pathIsFile(path)) {
return;
}
var oldProjectPath = this.makeProjectRelativeIfPossible(this._selections.selected),
pathInProject = this.makeProjectRelativeIfPossible(path);
if (path && !this._viewModel.isFilePathVisible(pathInProject)) {
path = null;
pathInProject = null;
}
this.performRename();
this._viewModel.moveMarker("selected", oldProjectPath, pathInProject);
if (this._selections.context) {
this._viewModel.moveMarker("context", this.makeProjectRelativeIfPossible(this._selections.context), null);
delete this._selections.context;
}
var previousSelection = this._selections.selected;
this._selections.selected = path;
if (path) {
if (!doNotOpen) {
this.trigger(EVENT_SHOULD_SELECT, {
path: path,
previousPath: previousSelection,
hadFocus: this._focused
});
}
this.trigger(EVENT_SHOULD_FOCUS);
}
};
/**
* Gets the currently selected file or directory.
*
* @return {FileSystemEntry} the filesystem object for the currently selected file
*/
ProjectModel.prototype.getSelected = function () {
return _getFSObject(this._selections.selected);
};
/**
* Keeps track of which file is currently being edited.
*
* @param {File|string} curFile Currently edited file.
*/
ProjectModel.prototype.setCurrentFile = function (curFile) {
this._currentPath = _getPathFromFSObject(curFile);
};
/**
* Adds the file at the given path to the Working Set and selects it there.
*
* @param {string} path full path of file to open in Working Set
*/
ProjectModel.prototype.selectInWorkingSet = function (path) {
this.performRename();
this.trigger(EVENT_SHOULD_SELECT, {
path: path,
add: true
});
};
/**
* Sets the context (for context menu operations) to the given path. This is independent from the
* open/selected file.
*
* @param {string} path full path of file or directory to which the context should be setBaseUrl
* @param {boolean} _doNotRename True if this context change should not cause a rename operation to finish. This is a special case that goes with context menu handling.
* @param {boolean} _saveContext True if the current context should be saved (see comment below)
*/
ProjectModel.prototype.setContext = function (path, _doNotRename, _saveContext) {
// This bit is not ideal: when the user right-clicks on an item in the file tree
// and there is already a context menu up, the FileTreeView sends a signal to set the
// context to the new element but the PopupManager follows that with a message that it's
// closing the context menu (because it closes the previous one and then opens the new
// one.) This timing means that we need to provide some special case handling here.
if (_saveContext) {
if (!path) {
this._selections.previousContext = this._selections.context;
} else {
this._selections.previousContext = path;
}
} else {
delete this._selections.previousContext;
}
path = _getPathFromFSObject(path);
if (!_doNotRename) {
this.performRename();
}
var currentContext = this._selections.context;
this._selections.context = path;
this._viewModel.moveMarker("context", this.makeProjectRelativeIfPossible(currentContext),
this.makeProjectRelativeIfPossible(path));
};
/**
* Restores the context to the last non-null context. This is specifically here to handle
* the sequence of messages that we get from the project context menu.
*/
ProjectModel.prototype.restoreContext = function () {
if (this._selections.previousContext) {
this.setContext(this._selections.previousContext);
}
};
/**
* Gets the currently selected context.
*
* @return {FileSystemEntry} filesystem object for the context file or directory
*/
ProjectModel.prototype.getContext = function () {
return _getFSObject(this._selections.context);
};
/**
* Starts a rename operation for the file or directory at the given path. If the path is
* not provided, the current context is used.
*
* If a rename operation is underway, it will be completed automatically.
*
* The Promise returned is resolved with an object with a `newPath` property with the renamed path. If the user cancels the operation, the promise is resolved with the value RENAME_CANCELLED.
*
* @param {string=} path optional path to start renaming
* @param {boolean=} isMoved optional flag which indicates whether the entry is being moved instead of renamed
* @return {$.Promise} resolved when the operation is complete.
*/
ProjectModel.prototype.startRename = function (path, isMoved) {
var d = new $.Deferred();
path = _getPathFromFSObject(path);
if (!path) {
path = this._selections.context;
if (!path) {
return d.resolve().promise();
}
}
if (this._selections.rename && this._selections.rename.path === path) {
return d.resolve().promise();
}
if (!this.isWithinProject(path)) {
return d.reject({
type: ERROR_NOT_IN_PROJECT,
isFolder: !_pathIsFile(path),
fullPath: path
}).promise();
}
var projectRelativePath = this.makeProjectRelativeIfPossible(path);
if (!this._viewModel.isFilePathVisible(projectRelativePath)) {
this.showInTree(path);
}
if (!isMoved) {
if (path !== this._selections.context) {
this.setContext(path);
} else {
this.performRename();
}
this._viewModel.moveMarker("rename", null,
projectRelativePath);
}
this._selections.rename = {
deferred: d,
type: FILE_RENAMING,
path: path,
newPath: path
};
return d.promise();
};
/**
* Sets the new value for the rename operation that is in progress (started previously with a call
* to `startRename`).
*
* @param {string} newPath new path for the file or directory being renamed
*/
ProjectModel.prototype.setRenameValue = function (newPath) {
if (!this._selections.rename) {
return;
}
this._selections.rename.newPath = newPath;
};
/**
* Cancels the rename operation that is in progress. This resolves the original promise with
* a RENAME_CANCELLED value.
*/
ProjectModel.prototype.cancelRename = function () {
var renameInfo = this._selections.rename;
if (!renameInfo) {
return;
}
// File creation is a special case.
if (renameInfo.type === FILE_CREATING) {
this._cancelCreating();
return;
}
this._viewModel.moveMarker("rename", this.makeProjectRelativeIfPossible(renameInfo.path), null);
renameInfo.deferred.resolve(RENAME_CANCELLED);
delete this._selections.rename;
this.setContext(null);
};
/**
* Rename a file/folder. This will update the project tree data structures
* and send notifications about the rename.
*
* @param {string} oldPath Old name of the item with the path
* @param {string} newPath New name of the item with the path
* @param {string} newName New name of the item
* @param {boolean} isFolder True if item is a folder; False if it is a file.
* @return {$.Promise} A promise object that will be resolved or rejected when
* the rename is finished.
*/
function _renameItem(oldPath, newPath, newName, isFolder) {
var result = new $.Deferred();
if (oldPath === newPath) {
result.resolve();
} else if (!isValidFilename(newName)) {
result.reject(ERROR_INVALID_FILENAME);
} else {
var entry = isFolder ? FileSystem.getDirectoryForPath(oldPath) : FileSystem.getFileForPath(oldPath);
entry.rename(newPath, function (err) {
if (err) {
result.reject(err);
} else {
result.resolve();
}
});
}
return result.promise();
}
/**
* @private
*
* Renames the item at the old path to the new name provided.
*
* @param {string} oldPath full path to the current location of file or directory (should include trailing slash for directory)
* @param {string} newPath full path to the new location of the file or directory
* @param {string} newName new name for the file or directory
*/
ProjectModel.prototype._renameItem = function (oldPath, newPath, newName) {
return _renameItem(oldPath, newPath, newName, !_pathIsFile(oldPath));
};
/**
* Completes the rename operation that is in progress.
*/
ProjectModel.prototype.performRename = function () {
var renameInfo = this._selections.rename;
if (!renameInfo) {
return;
}
var oldPath = renameInfo.path,
isFolder = renameInfo.isFolder || !_pathIsFile(oldPath),
oldProjectPath = this.makeProjectRelativeIfPossible(oldPath),
// To get the parent directory, we need to strip off the trailing slash on a directory name
parentDirectory = FileUtils.getDirectoryPath(isFolder ? FileUtils.stripTrailingSlash(oldPath) : oldPath),
oldName = FileUtils.getBaseName(oldPath),
newPath = renameInfo.newPath,
newName = FileUtils.getBaseName(newPath),
viewModel = this._viewModel,
self = this;
if (renameInfo.type !== FILE_CREATING && oldPath === newPath) {
this.cancelRename();
return;
}
if (isFolder && _.last(newPath) !== "/") {
newPath += "/";
}
delete this._selections.rename;
delete this._selections.context;
viewModel.moveMarker("rename", oldProjectPath, null);
viewModel.moveMarker("context", oldProjectPath, null);
viewModel.moveMarker("creating", oldProjectPath, null);
function finalizeRename() {
viewModel.renameItem(oldProjectPath, self.makeProjectRelativeIfPossible(newPath));
if (self._selections.selected && self._selections.selected.indexOf(oldPath) === 0) {
self._selections.selected = newPath + self._selections.selected.slice(oldPath.length);
self.setCurrentFile(newPath);
}
}
if (renameInfo.type === FILE_CREATING) {
this.createAtPath(newPath).done(function (entry) {
finalizeRename();