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
/
ProjectManager.js
2162 lines (1888 loc) · 86.6 KB
/
ProjectManager.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 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 vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, FileError, window */
/**
* ProjectManager is the model for the set of currently open project. It is responsible for
* creating and updating the project tree when projects are opened and when changes occur to
* the file tree.
*
* This module dispatches these events:
* - beforeProjectClose -- before _projectRoot changes
* - beforeAppClose -- before Brackets quits entirely
* - projectOpen -- after _projectRoot changes and the tree is re-rendered
* - projectRefresh -- when project tree is re-rendered for a reason other than
* a project being opened (e.g. from the Refresh command)
*
* These are jQuery events, so to listen for them you do something like this:
* $(ProjectManager).on("eventname", handler);
*/
define(function (require, exports, module) {
"use strict";
require("utils/Global");
// Load dependent non-module scripts
require("thirdparty/jstree_pre1.0_fix_1/jquery.jstree");
var _ = require("thirdparty/lodash");
// Load dependent modules
var AppInit = require("utils/AppInit"),
PreferencesDialogs = require("preferences/PreferencesDialogs"),
PreferencesManager = require("preferences/PreferencesManager"),
DocumentManager = require("document/DocumentManager"),
InMemoryFile = require("document/InMemoryFile"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
LanguageManager = require("language/LanguageManager"),
Menus = require("command/Menus"),
StringUtils = require("utils/StringUtils"),
Strings = require("strings"),
FileSystem = require("filesystem/FileSystem"),
FileViewController = require("project/FileViewController"),
PerfUtils = require("utils/PerfUtils"),
ViewUtils = require("utils/ViewUtils"),
FileUtils = require("file/FileUtils"),
FileSystemError = require("filesystem/FileSystemError"),
Urls = require("i18n!nls/urls"),
KeyEvent = require("utils/KeyEvent"),
Async = require("utils/Async"),
FileSyncManager = require("project/FileSyncManager"),
EditorManager = require("editor/EditorManager");
/**
* @private
* Forward declaration for the _fileSystemChange and _fileSystemRename functions to make JSLint happy.
*/
var _fileSystemChange,
_fileSystemRename;
/**
* @private
* File tree sorting for mac-specific sorting behavior
*/
var _isMac = brackets.platform === "mac",
_sortPrefixDir = _isMac ? "" : "0",
_sortPrefixFile = _isMac ? "" : "1";
/**
* @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
* @type {RegExp}
*/
var _exclusionListRegEx = /\.pyc$|^\.git$|^\.gitignore$|^\.gitmodules$|^\.svn$|^\.DS_Store$|^Thumbs\.db$|^\.hg$|^CVS$|^\.cvsignore$|^\.gitattributes$|^\.hgtags$|^\.c9revisions|^\.SyncArchive|^\.SyncID|^\.SyncIgnore|^\.hgignore$|\~$/;
/**
* @private
* File names which are not showed in quick open dialog
* @type {RegExp}
*/
var _binaryExclusionListRegEx = /\.svgz$|\.jsz$|\.zip$|\.gz$|\.htmz$|\.htmlz$|\.rar$|\.tar$|\.exe$|\.bin$/;
/**
* @private
* Filename to use for project settings files.
* @type {string}
*/
var SETTINGS_FILENAME = "." + PreferencesManager.SETTINGS_FILENAME;
/**
* @private
* Reference to the tree control container div. Initialized by
* htmlReady handler
* @type {jQueryObject}
*/
var $projectTreeContainer;
/**
* @private
* Reference to the tree control
* @type {jQueryObject}
*/
var _projectTree = null;
/**
* @private
* Reference to previous selected jstree leaf node when ProjectManager had
* selection focus from FileViewController.
* @type {DOMElement}
*/
var _lastSelected = null;
/**
* @private
* Internal flag to suppress firing of selectionChanged event.
* @type {boolean}
*/
var _suppressSelectionChange = false;
/**
* @private
* Reference to the tree control UL element
* @type {DOMElement}
*/
var $projectTreeList;
/**
* @private
* @see getProjectRoot()
*/
var _projectRoot = null;
/**
* @private
* Encoded URL
* @ see getBaseUrl(), setBaseUrl()
*/
var _projectBaseUrl = "";
/**
* @private
* @type {PreferenceStorage}
*/
var _prefs = null;
/**
* @private
* Used to initialize jstree state
*/
var _projectInitialLoad = null;
/**
* @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 = /^(\.+|com[1-9]|lpt[1-9]|nul|con|prn|aux)$/i;
var suppressToggleOpen = false;
/**
* @private
* @type {?jQuery.Promise.<Array<File>>}
* A promise that is resolved with an array of all project files. Used by
* ProjectManager.getAllFiles().
*/
var _allFilesCachePromise = null;
/**
* @private
*/
function _hasFileSelectionFocus() {
return FileViewController.getFileSelectionFocus() === FileViewController.PROJECT_MANAGER;
}
/**
* @private
*/
function _redraw(selectionChanged, reveal) {
reveal = (reveal === undefined) ? true : reveal;
// redraw selection
if ($projectTreeList) {
if (selectionChanged && !_suppressSelectionChange) {
$projectTreeList.triggerHandler("selectionChanged", reveal);
}
// reposition the selection triangle
$projectTreeContainer.triggerHandler("selectionRedraw");
// in-lieu of resize events, manually trigger contentChanged for every
// FileViewController focus change. This event triggers scroll shadows
// on the jstree to update. documentSelectionFocusChange fires when
// a new file is added and removed (causing a new selection) from the working set
_projectTree.triggerHandler("contentChanged");
}
}
/**
* Returns the File or Directory corresponding to the item selected in the file tree, or null
* if no item is selected in the tree (though the working set may still have a selection; use
* getSelectedItem() to get the selection regardless of whether it's in the tree or working set).
* @return {?(File|Directory)}
*/
function _getTreeSelectedItem() {
var selected = _projectTree.jstree("get_selected");
if (selected) {
return selected.data("entry");
}
return null;
}
/**
* Returns the File or Directory corresponding to the item selected in the sidebar panel, whether in
* the file tree OR in the working set; or null if no item is selected anywhere in the sidebar.
* May NOT be identical to the current Document - a folder may be selected in the sidebar, or the sidebar may not
* have the current document visible in the tree & working set.
* @return {?(File|Directory)}
*/
function getSelectedItem() {
// Prefer file tree selection, else use working set selection
var selectedEntry = _getTreeSelectedItem();
if (!selectedEntry) {
var doc = DocumentManager.getCurrentDocument();
selectedEntry = (doc && doc.file);
}
return selectedEntry;
}
function _fileViewFocusChange() {
_redraw(true);
}
function _documentSelectionFocusChange() {
var curFile = EditorManager.getCurrentlyViewedPath();
if (curFile && _hasFileSelectionFocus()) {
var nodeFound = $("#project-files-container li").is(function (index) {
var $treeNode = $(this),
entry = $treeNode.data("entry");
if (entry && entry.fullPath === curFile) {
if (!_projectTree.jstree("is_selected", $treeNode)) {
if ($treeNode.parents(".jstree-closed").length) {
//don't auto-expand tree to show file - but remember it if parent is manually expanded later
_projectTree.jstree("deselect_all");
_lastSelected = $treeNode;
} else {
//we don't want to trigger another selection change event, so manually deselect
//and select without sending out notifications
_projectTree.jstree("deselect_all");
_projectTree.jstree("select_node", $treeNode, false); // sets _lastSelected
}
}
return true;
}
return false;
});
// file is outside project subtree, or in a folder that's never been expanded yet
if (!nodeFound) {
_projectTree.jstree("deselect_all");
_lastSelected = null;
}
} else if (_projectTree !== null) {
_projectTree.jstree("deselect_all");
_lastSelected = null;
}
_redraw(true);
}
/**
* Returns the root folder of the currently loaded project, or null if no project is open (during
* startup, or running outside of app shell).
* @return {Directory}
*/
function getProjectRoot() {
return _projectRoot;
}
/**
* @private
*/
function _getBaseUrlKey() {
return "projectBaseUrl_" + _projectRoot;
}
/**
* 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}
*/
function getBaseUrl() {
return _projectBaseUrl;
}
/**
* Sets the encoded Base URL of the currently loaded project.
* @param {String}
*/
function setBaseUrl(projectBaseUrl) {
_projectBaseUrl = 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 += "/";
}
_prefs.setValue(_getBaseUrlKey(), _projectBaseUrl);
}
/**
* Returns true if absPath lies within the project, false otherwise.
* Does not support paths containing ".."
* @param {string|FileSystemEntry} absPathOrEntry
* @return {boolean}
*/
function isWithinProject(absPathOrEntry) {
var absPath = absPathOrEntry.fullPath || absPathOrEntry;
return (_projectRoot && absPath.indexOf(_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}
*/
function makeProjectRelativeIfPossible(absPath) {
if (isWithinProject(absPath)) {
return absPath.slice(_projectRoot.fullPath.length);
}
return absPath;
}
/**
* @private
* Get prefs tree state lookup key for given project path.
*/
function _getTreeStateKey(path) {
// generate unique tree state key for this project path
var key = "projectTreeState_" + path;
// normalize to always have slash at end
if (key[key.length - 1] !== "/") {
key += "/";
}
return key;
}
/**
* @private
* Save ProjectManager project path and tree state.
*/
function _savePreferences() {
// save the current project
_prefs.setValue("projectPath", _projectRoot.fullPath);
// save jstree state
var openNodes = [],
projectPathLength = _projectRoot.fullPath.length,
entry,
fullPath,
shortPath,
depth;
// Query open nodes by class selector
$(".jstree-open:visible").each(function (index) {
entry = $(this).data("entry");
if (entry.fullPath) {
fullPath = entry.fullPath;
// Truncate project path prefix (including its last slash) AND remove trailing slash suffix
// So "/foo/bar/projroot/abc/xyz/" -> "abc/xyz"
shortPath = fullPath.slice(projectPathLength, -1);
// Determine depth of the node by counting path separators.
// Children at the root have depth of zero
depth = shortPath.split("/").length - 1;
// Map tree depth to list of open nodes
if (openNodes[depth] === undefined) {
openNodes[depth] = [];
}
openNodes[depth].push(fullPath);
}
});
// Store the open nodes by their full path and persist to storage
_prefs.setValue(_getTreeStateKey(_projectRoot.fullPath), openNodes);
}
/**
* @private
*/
function _forceSelection(current, target) {
// select_node will force the target to be revealed. Instead,
// keep the scroller position stable.
var savedScrollTop = $projectTreeContainer.get(0).scrollTop;
// suppress selectionChanged event from firing by jstree select_node
_suppressSelectionChange = true;
if (current) {
_projectTree.jstree("deselect_node", current);
}
_projectTree.jstree("select_node", target, false);
_suppressSelectionChange = false;
$projectTreeContainer.get(0).scrollTop = savedScrollTop;
_redraw(true, false);
}
/**
* Returns false when the event occured without any input present in the li closest to the DOM object
*
* @param {event} event to check
* @return boolean true if an input field is present
*/
function _isInRename(element) {
return ($(element).closest("li").find("input").length > 0);
}
/**
* @private
* Reopens a set of nodes in the tree by ID.
* @param {Array.<Array.<string>>} nodesByDepth An array of arrays of node ids to reopen. The ids within
* each sub-array are reopened in parallel, and the sub-arrays are reopened in order, so they should
* be sorted by depth within the tree.
* @param {$.Deferred} resultDeferred A Deferred that will be resolved when all nodes have been fully
* reopened.
*/
function _reopenNodes(nodesByDepth, resultDeferred) {
if (nodesByDepth.length === 0) {
// All paths are opened and fully rendered.
resultDeferred.resolve();
} else {
var toOpenPaths = nodesByDepth.shift(),
toOpenIds = [],
node = null;
// use path to lookup ID
toOpenPaths.forEach(function (value, index) {
node = _projectInitialLoad.fullPathToIdMap[value];
if (node) {
toOpenIds.push(node);
}
});
Async.doInParallel(
toOpenIds,
function (id) {
var result = new $.Deferred();
_projectTree.jstree("open_node", "#" + id, function () {
result.resolve();
}, true);
return result.promise();
},
false
).always(function () {
_reopenNodes(nodesByDepth, resultDeferred);
});
}
}
/**
* A memoized comparator of DOM nodes for use with jsTree
* @private
* @param {Node} First DOM node
* @param {Node} Second DOM node
* @return {number} Comparator value
*/
var _projectTreeSortComparator = _.memoize(function (a, b) {
var a1 = $(a).data("compareString"),
b1 = $(b).data("compareString");
return FileUtils.compareFilenames(a1, b1, false);
}, function (a, b) {
return $(a).data("compareString") + ":" + $(b).data("compareString");
});
/**
* @private
* Given an input to jsTree's json_data.data setting, display the data in the file tree UI
* (replacing any existing file tree that was previously displayed). This input could be
* raw JSON data, or it could be a dataprovider function. See jsTree docs for details:
* http://www.jstree.com/documentation/json_data
*/
function _renderTree(treeDataProvider) {
var result = new $.Deferred();
// For #1542, make sure the tree is scrolled to the top before refreshing.
// If we try to do this later (e.g. after the tree has been refreshed), it
// doesn't seem to work properly.
$projectTreeContainer.scrollTop(0);
// Instantiate tree widget
// (jsTree is smart enough to replace the old tree if there's already one there)
$projectTreeContainer.hide()
.addClass("no-focus");
_projectTree = $projectTreeContainer
.jstree({
plugins : ["ui", "themes", "json_data", "crrm", "sort"],
ui : { select_limit: 1, select_multiple_modifier: "", select_range_modifier: "" },
json_data : { data: treeDataProvider, correct_state: false },
core : { html_titles: true, animation: 0, strings : { loading : Strings.PROJECT_LOADING, new_node : "New node" } },
themes : { theme: "brackets", url: "styles/jsTreeTheme.css", dots: false, icons: false },
//(note: our actual jsTree theme CSS lives in brackets.less; we specify an empty .css
// file because jsTree insists on loading one itself)
sort : _projectTreeSortComparator
}).bind(
"before.jstree",
function (event, data) {
if (data.func === "toggle_node") {
// jstree will automaticaly select parent node when the parent is closed
// and any descendant is selected. Prevent the select_node handler from
// immediately toggling open again in this case.
suppressToggleOpen = _projectTree.jstree("is_open", data.args[0]);
}
}
).bind(
"select_node.jstree",
function (event, data) {
var entry = data.rslt.obj.data("entry");
if (entry) {
if (entry.isFile) {
var openResult = FileViewController.openAndSelectDocument(entry.fullPath, FileViewController.PROJECT_MANAGER);
openResult.done(function () {
// update when tree display state changes
_redraw(true);
_lastSelected = data.rslt.obj;
}).fail(function () {
if (_lastSelected) {
// revert this new selection and restore previous selection
_forceSelection(data.rslt.obj, _lastSelected);
} else {
_projectTree.jstree("deselect_all");
_lastSelected = null;
}
});
} else {
FileViewController.setFileViewFocus(FileViewController.PROJECT_MANAGER);
// show selection marker on folders
_redraw(true);
// toggle folder open/closed
// suppress if this selection was triggered by clicking the disclousre triangle
if (!suppressToggleOpen) {
_projectTree.jstree("toggle_node", data.rslt.obj);
}
}
}
suppressToggleOpen = false;
}
).bind(
"reopen.jstree",
function (event, data) {
if (_projectInitialLoad.previous) {
// Start reopening nodes that were previously open, starting
// with the first recorded depth level. As each level completes,
// it will trigger the next level to finish.
_reopenNodes(_projectInitialLoad.previous, result);
_projectInitialLoad.previous = null;
}
}
).bind(
"scroll.jstree",
function (e) {
// close all dropdowns on scroll
Menus.closeAll();
}
).bind(
"loaded.jstree open_node.jstree close_node.jstree",
function (event, data) {
if (event.type === "open_node") {
// select the current document if it becomes visible when this folder is opened
var curDoc = DocumentManager.getCurrentDocument();
if (_hasFileSelectionFocus() && curDoc && data) {
var entry = data.rslt.obj.data("entry");
if (entry && curDoc.file.fullPath.indexOf(entry.fullPath) === 0) {
_forceSelection(data.rslt.obj, _lastSelected);
} else {
_redraw(true, false);
}
}
} else if (event.type === "close_node") {
// always update selection marker position when collapsing a node
_redraw(true, false);
} else {
_redraw(false);
}
_savePreferences();
}
).bind(
"mousedown.jstree",
function (event) {
// select tree node on right-click
if (event.which === 3 || (event.ctrlKey && event.which === 1 && brackets.platform === "mac")) {
var treenode = $(event.target).closest("li");
if (treenode) {
var saveSuppressToggleOpen = suppressToggleOpen;
// don't toggle open folders (just select)
suppressToggleOpen = true;
_projectTree.jstree("deselect_all");
_projectTree.jstree("select_node", treenode, false);
suppressToggleOpen = saveSuppressToggleOpen;
}
}
}
);
// jstree has a default event handler for dblclick that attempts to clear the
// global window selection (presumably because it doesn't want text within the tree
// to be selected). This ends up messing up CodeMirror, and we don't need this anyway
// since we've turned off user selection of UI text globally. So we just unbind it,
// and add our own double-click handler here.
// Filed this bug against jstree at https://github.com/vakata/jstree/issues/163
_projectTree.bind("init.jstree", function () {
// install scroller shadows
ViewUtils.addScrollerShadow(_projectTree.get(0));
_projectTree
.unbind("dblclick.jstree")
.bind("dblclick.jstree", function (event) {
var entry = $(event.target).closest("li").data("entry");
if (entry && entry.isFile && !_isInRename(event.target)) {
FileViewController.addToWorkingSetAndSelect(entry.fullPath);
}
});
// fire selection changed events for sidebar-selection
$projectTreeList = $projectTreeContainer.find("ul");
ViewUtils.sidebarList($projectTreeContainer, "jstree-clicked", "jstree-leaf");
$projectTreeContainer.show();
});
return Async.withTimeout(result.promise(), 1000);
}
/**
* @private
* See shouldShow
*/
function _shouldShowName(name) {
return !name.match(_exclusionListRegEx);
}
/**
* 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);
}
/**
* Returns true if fileName's extension doesn't belong to binary (e.g. archived)
* @param {string} fileName
* @return {boolean}
*/
function isBinaryFile(fileName) {
return fileName.match(_binaryExclusionListRegEx);
}
/**
* @private
* Generate a string suitable for sorting
* @param {string} name
* @param {boolean} isFolder
* @return {string}
*/
function _toCompareString(name, isFolder) {
return ((isFolder) ? _sortPrefixDir : _sortPrefixFile) + name;
}
/**
* @private
* Insert a path in the fullPath-to-DOM ID cache
* @param {!(FileSystemEntry|string)} entry Entry or full path to add to cache
*/
function _insertTreeNodeCache(entry, id) {
var fullPath = entry.fullPath || entry;
_projectInitialLoad.fullPathToIdMap[fullPath] = id;
}
/**
* @private
* Delete a path from the fullPath-to-DOM ID cache
* @param {!(FileSystemEntry|string)} entry Entry or full path to remove from cache
*/
function _deleteTreeNodeCache(entry) {
var fullPath = entry.fullPath || entry;
delete _projectInitialLoad.fullPathToIdMap[fullPath];
}
/**
* @private
* Create JSON object for a jstree node. Insert mapping from full path to
* jstree node ID.
*
* For more info on jsTree's JSON format see: http://www.jstree.com/documentation/json_data
* @param {!FileSystemEntry} entry
* @return {data: string, attr: {id: string}, metadata: {entry: FileSystemEntry}, children: Array.<Object>, state: string}
*/
function _entryToJSON(entry) {
if (!shouldShow(entry)) {
return null;
}
var jsonEntry = {
data : entry.name,
attr : { id: "node" + _projectInitialLoad.id++ },
metadata: {
entry : entry,
compareString : _toCompareString(entry.name, entry.isDirectory)
}
};
if (entry.isDirectory) {
jsonEntry.children = [];
jsonEntry.state = "closed";
} else {
jsonEntry.data = ViewUtils.getFileEntryDisplay(entry);
}
// Map path to ID to initialize loaded and opened states
_insertTreeNodeCache(entry, jsonEntry.attr.id);
return jsonEntry;
}
/**
* @private
* Given an array of file system entries, returns a JSON array representing them in the format
* required by jsTree. Saves the corresponding Entry object as metadata (which jsTree will store in
* the DOM via $.data()).
*
* Does NOT recursively traverse the file system: folders are marked as expandable but are given no
* children initially.
*
* @param {Array.<FileSystemEntry>} entries Array of FileSystemEntry entry objects.
* @return {Array} jsTree node data: array of JSON objects
*/
function _convertEntriesToJSON(entries) {
var jsonEntryList = [],
entry,
entryI,
jsonEntry;
for (entryI = 0; entryI < entries.length; entryI++) {
jsonEntryList.push(_entryToJSON(entries[entryI]));
}
return jsonEntryList;
}
/**
* @private
* Called by jsTree when the user has expanded a node that has never been expanded before. We call
* jsTree back asynchronously with the node's immediate children data once the subfolder is done
* being fetched.
*
* @param {jQueryObject} $treeNode jQ object for the DOM node being expanded
* @param {function(Array)} jsTreeCallback jsTree callback to provide children to
*/
function _treeDataProvider($treeNode, jsTreeCallback) {
var dirEntry, isProjectRoot = false, deferred = new $.Deferred();
function processEntries(entries) {
var subtreeJSON = _convertEntriesToJSON(entries),
wasNodeOpen = false,
emptyDirectory = (subtreeJSON.length === 0);
if (emptyDirectory) {
if (!isProjectRoot) {
wasNodeOpen = $treeNode.hasClass("jstree-open");
} else {
// project root is a special case, add a placeholder
subtreeJSON.push({});
}
}
jsTreeCallback(subtreeJSON);
if (!isProjectRoot && emptyDirectory) {
// If the directory is empty, force it to appear as an open or closed node.
// This is a workaround for issue #149 where jstree would show this node as a leaf.
var classToAdd = (wasNodeOpen) ? "jstree-closed" : "jstree-open";
$treeNode.removeClass("jstree-leaf jstree-closed jstree-open")
.addClass(classToAdd);
// This is a workaround for a part of issue #2085, where the file creation process
// depends on the open_node.jstree event being triggered, which doesn't happen on
// empty folders
if (!wasNodeOpen) {
$treeNode.trigger("open_node.jstree");
}
}
deferred.resolve();
}
if ($treeNode === -1) {
// Special case: root of tree
dirEntry = _projectRoot;
isProjectRoot = true;
} else {
// All other nodes: the Directory is saved as jQ data in the tree (by _convertEntriesToJSON())
dirEntry = $treeNode.data("entry");
}
// Fetch dirEntry's contents
dirEntry.getContents(function (err, contents, stats, statsErrs) {
if (err) {
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_LOADING_PROJECT,
StringUtils.format(
Strings.READ_DIRECTORY_ENTRIES_ERROR,
StringUtils.breakableUrl(dirEntry.fullPath),
err
)
);
// Reject the render promise so we can move on.
deferred.reject();
} else {
if (statsErrs) {
// some but not all entries failed to load, so render what we can
console.warn("Error reading a subset of folder " + dirEntry);
}
processEntries(contents);
}
});
}
/**
* Forces createNewItem() to complete by removing focus from the rename field which causes
* the new file to be written to disk
*/
function forceFinishRename() {
$(".jstree-rename-input").blur();
}
/**
* Although Brackets is generally standardized on folder paths with a trailing "/", some APIs here
* receive project paths without "/" due to legacy preference storage formats, etc.
* @param {!string} fullPath Path that may or may not end in "/"
* @return {!string} Path that ends in "/"
*/
function _ensureTrailingSlash(fullPath) {
if (fullPath[fullPath.length - 1] !== "/") {
return fullPath + "/";
}
return fullPath;
}
/** Returns the full path to the welcome project, which we open on first launch.
* @private
* @return {!string} fullPath reference
*/
function _getWelcomeProjectPath() {
var initialPath = FileUtils.getNativeBracketsDirectoryPath(),
sampleUrl = Urls.GETTING_STARTED;
if (sampleUrl) {
// Back up one more folder. The samples folder is assumed to be at the same level as
// the src folder, and the sampleUrl is relative to the samples folder.
initialPath = initialPath.substr(0, initialPath.lastIndexOf("/")) + "/samples/" + sampleUrl;
}
return _ensureTrailingSlash(initialPath); // paths above weren't canonical
}
/**
* Returns true if the given path is the same as one of the welcome projects we've previously opened,
* or the one for the current build.
*/
function isWelcomeProjectPath(path) {
if (path === _getWelcomeProjectPath()) {
return true;
}
var pathNoSlash = FileUtils.stripTrailingSlash(path); // "welcomeProjects" pref has standardized on no trailing "/"
var welcomeProjects = _prefs.getValue("welcomeProjects") || [];
return welcomeProjects.indexOf(pathNoSlash) !== -1;
}
/**
* Adds the path to the list of welcome projects we've ever seen, if not on the list already.
*/
function addWelcomeProjectPath(path) {
var pathNoSlash = FileUtils.stripTrailingSlash(path); // "welcomeProjects" pref has standardized on no trailing "/"
var welcomeProjects = _prefs.getValue("welcomeProjects") || [];
if (welcomeProjects.indexOf(pathNoSlash) === -1) {
welcomeProjects.push(pathNoSlash);
_prefs.setValue("welcomeProjects", welcomeProjects);
}
}
/**
* If the provided path is to an old welcome project, returns the current one instead.
*/
function updateWelcomeProjectPath(path) {
if (isWelcomeProjectPath(path)) {
return _getWelcomeProjectPath();
} else {
return path;
}
}
/**
* Initial project path is stored in prefs, which defaults to the welcome project on
* first launch.
*/
function getInitialProjectPath() {
return updateWelcomeProjectPath(_prefs.getValue("projectPath"));
}
/**
* Error dialog when max files in index is hit
* @return {Dialog}
*/
function _showMaxFilesDialog() {
return Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_MAX_FILES_TITLE,
Strings.ERROR_MAX_FILES
);
}
function _watchProjectRoot(rootPath) {
FileSystem.on("change", _fileSystemChange);
FileSystem.on("rename", _fileSystemRename);
FileSystem.watch(FileSystem.getDirectoryForPath(rootPath), _shouldShowName, function (err) {
if (err === FileSystemError.TOO_MANY_ENTRIES) {
_showMaxFilesDialog();
} else if (err) {
console.error("Error watching project root: ", rootPath, err);
}
});
// Reset allFiles cache
_allFilesCachePromise = null;
}
/**
* @private
* Close the file system and remove listeners.
* @return {$.Promise} A promise that's resolved when the root is unwatched. Rejected if
* there is no project root or if the unwatch fails.
*/
function _unwatchProjectRoot() {
var result = new $.Deferred();
if (!_projectRoot) {
result.reject();
} else {
FileSystem.off("change", _fileSystemChange);
FileSystem.off("rename", _fileSystemRename);
FileSystem.unwatch(_projectRoot, function (err) {