-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathProjectManager.js
More file actions
2468 lines (2231 loc) · 98.1 KB
/
ProjectManager.js
File metadata and controls
2468 lines (2231 loc) · 98.1 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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2012 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
// @INCLUDE_IN_API_DOCS
/**
* ProjectManager glues together the project model and file tree view and integrates as needed with other parts
* of Brackets. 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, but working set files still open
* - projectClose -- *just* before `_projectRoot` changes; working set already cleared
* & project root unwatched
* - 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)
*
* To listen for events, do something like this: (see EventDispatcher for details on this pattern)
* ProjectManager.on("eventname", handler);
*/
/*global Phoenix, path*/
define(function (require, exports, module) {
require("utils/Global");
const _ = require("thirdparty/lodash");
// Load dependent modules
const AppInit = require("utils/AppInit"),
Async = require("utils/Async"),
PreferencesDialogs = require("preferences/PreferencesDialogs"),
PreferencesManager = require("preferences/PreferencesManager"),
DocumentManager = require("document/DocumentManager"),
MainViewManager = require("view/MainViewManager"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
EventDispatcher = require("utils/EventDispatcher"),
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"),
FileUtils = require("file/FileUtils"),
FileSystemError = require("filesystem/FileSystemError"),
Urls = require("i18n!nls/urls"),
FileSyncManager = require("project/FileSyncManager"),
ProjectModel = require("project/ProjectModel"),
FileTreeView = require("project/FileTreeView"),
WorkingSetView = require("project/WorkingSetView"),
ViewUtils = require("utils/ViewUtils"),
ZipUtils = require("utils/ZipUtils"),
Metrics = require("utils/Metrics");
// Needed to ensure that menus are set up when we need them.
// See #10115
require("command/DefaultMenus");
/**
* Triggered before the project closes.
* @type {string}
*/
const EVENT_PROJECT_BEFORE_CLOSE = "beforeProjectClose";
/**
* Triggered when the project has closed.
* @type {string}
*/
const EVENT_PROJECT_CLOSE = "projectClose";
/**
* Triggered when opening a project file fails.
* @type {string}
*/
const EVENT_PROJECT_OPEN_FAILED = "projectFileOpenFailed";
/**
* Triggered when a project is opened.
* @type {string}
*/
const EVENT_PROJECT_OPEN = "projectOpen";
/**
* Triggered after a project is successfully opened.
* @type {string}
*/
const EVENT_AFTER_PROJECT_OPEN = "afterProjectOpen";
/**
* Triggered after startup files (from OS or CLI) are loaded.
* Note: This may occur before extensions are loaded, so check `isStartupFilesLoaded()`.
* @type {string}
*/
const EVENT_AFTER_STARTUP_FILES_LOADED = "startupFilesLoaded";
// on boot, we load files that have been passed in from os either with `open with` from os file explorer or
// as cli from terminal. EVENT_AFTER_STARTUP_FILES_LOADED is trigerred after those files have been loaded.
// Note that this may be trigerred before any extensions get loaded, so always a good idea to check for
// isStartupFilesLoaded()
/**
* Triggered when the project is refreshed.
* @type {string}
*/
const EVENT_PROJECT_REFRESH = "projectRefresh";
/**
* Triggered when content in the project changes.
* @type {string}
*/
const EVENT_CONTENT_CHANGED = "contentChanged";
// This will capture all file/folder changes in projects except renames. If you want to track renames,
// use EVENT_PROJECT_PATH_CHANGED_OR_RENAMED to track all changes or EVENT_PROJECT_FILE_RENAMED too.
/**
* Triggered when any file or folder in the project changes, excluding renames.
* @type {string}
*/
const EVENT_PROJECT_FILE_CHANGED = "projectFileChanged";
/**
* Triggered specifically when a project file is renamed.
* @type {string}
*/
const EVENT_PROJECT_FILE_RENAMED = "projectFileRenamed";
// the path changed event differs in the sense that all events returned by this will be a path.
/**
* Triggered when paths in the project are changed or renamed.
* @type {string}
*/
const EVENT_PROJECT_CHANGED_OR_RENAMED_PATH = "projectChangedPath";
EventDispatcher.setLeakThresholdForEvent(EVENT_PROJECT_OPEN, 25);
const CLIPBOARD_SYNC_KEY = "phoenix.clipboard";
/**
* @private
* Filename to use for project settings files.
* @type {string}
*/
const SETTINGS_FILENAME = "." + PreferencesManager.SETTINGS_FILENAME,
SETTINGS_FILENAME_BRACKETS = "." + PreferencesManager.SETTINGS_FILENAME_BRACKETS;
/**
* Name of the preferences for sorting directories first
* @private
* @type {string}
*/
var SORT_DIRECTORIES_FIRST = "sortDirectoriesFirst";
/**
* @private
* Forward declarations to make JSLint happy.
*/
var _fileSystemChange,
_fileSystemRename,
_showErrorDialog,
_saveTreeState,
_renderTreeSync,
_renderTree;
/**
* @const
* @private
* Error context to show the correct error message
* @type {int}
*/
const ERR_TYPE_CREATE = 1,
ERR_TYPE_CREATE_EXISTS = 2,
ERR_TYPE_RENAME = 3,
ERR_TYPE_DELETE = 4,
ERR_TYPE_LOADING_PROJECT = 5,
ERR_TYPE_LOADING_PROJECT_NATIVE = 6,
ERR_TYPE_MAX_FILES = 7,
ERR_TYPE_OPEN_DIALOG = 8,
ERR_TYPE_INVALID_FILENAME = 9,
ERR_TYPE_MOVE = 10,
ERR_TYPE_PASTE = 11,
ERR_TYPE_PASTE_FAILED = 12,
ERR_TYPE_DUPLICATE_FAILED = 13,
ERR_TYPE_DOWNLOAD_FAILED = 14;
/**
* @private
* Reference to the tree control container div. Initialized by
* htmlReady handler
* @type {jQueryObject}
*/
var $projectTreeContainer;
/**
* @private
*
* Reference to the container of the Preact component. Everything in this
* node is managed by Preact.
* @type {Element}
*/
var fileTreeViewContainer;
/**
* @private
*
* Does the file tree currently have the focus?
*
* @return {boolean} `true` if the file tree has the focus
*/
function _hasFileSelectionFocus() {
return FileViewController.getFileSelectionFocus() === FileViewController.PROJECT_MANAGER;
}
/**
* @private
* Singleton ProjectModel object.
* @type {ProjectModel.ProjectModel}
*/
var model = new ProjectModel.ProjectModel({
focused: _hasFileSelectionFocus()
});
/**
* @private
* @type {boolean}
* A flag to remember when user has been warned about too many files, so they
* are only warned once per project/session.
*/
var _projectWarnedForTooManyFiles = false;
/**
* @private
*
* Event handler which displays an error based on a problem creating a file.
*
* @param {$.Event} e jQuery event object
* @param {{type:any,isFolder:boolean}} errorInfo Information passed in the error events
*/
function _displayCreationError(e, errorInfo) {
window.setTimeout(function () {
var error = errorInfo.type,
isFolder = errorInfo.isFolder,
name = errorInfo.name;
if (error === FileSystemError.ALREADY_EXISTS) {
_showErrorDialog(ERR_TYPE_CREATE_EXISTS, isFolder, null, name);
} else if (error === ProjectModel.ERROR_INVALID_FILENAME) {
_showErrorDialog(ERR_TYPE_INVALID_FILENAME, isFolder, ProjectModel._invalidChars);
} else {
var errString = error === FileSystemError.NOT_WRITABLE ?
Strings.NO_MODIFICATION_ALLOWED_ERR :
StringUtils.format(Strings.GENERIC_ERROR, error);
_showErrorDialog(ERR_TYPE_CREATE, isFolder, errString, name).getPromise();
}
}, 10);
}
/**
* @private
*
* Reverts to the previous selection (useful if there's an error).
*
* @param {string|File} previousPath The previously selected path.
* @param {boolean} switchToWorkingSet True if we need to switch focus to the Working Set
*/
function _revertSelection(previousPath, switchToWorkingSet) {
model.setSelected(previousPath);
if (switchToWorkingSet) {
FileViewController.setFileViewFocus(FileViewController.WORKING_SET_VIEW);
}
}
/**
* @constructor
* @private
*
* Manages the interaction between the view and the model. This is loosely structured in
* the style of [Flux](https://github.com/facebook/flux), but the initial implementation did
* not need all of the parts of Flux yet. This ActionCreator could be replaced later with
* a real ActionCreator that talks to a Dispatcher.
*
* Most of the methods just delegate to the ProjectModel. Some are responsible for integration
* with other parts of Brackets.
*
* @param {ProjectModel} model store (in Flux terminology) with the project data
*/
function ActionCreator(model) {
this.model = model;
this._bindEvents();
}
/**
* @private
*
* Listen to events on the ProjectModel and cause the appropriate behavior within the rest of the system.
*/
ActionCreator.prototype._bindEvents = function () {
// Change events are the standard Flux signal to rerender the view. Note that
// current Flux style is to have the view itself listen to the Store for change events
// and re-render itself.
this.model.on(ProjectModel.EVENT_CHANGE, function () {
_renderTree();
});
// The "should select" event signals that we need to open the document based on file tree
// activity.
this.model.on(ProjectModel.EVENT_SHOULD_SELECT, function (e, data) {
if (data.add) {
FileViewController.openFileAndAddToWorkingSet(data.path).fail(_.partial(_revertSelection, data.previousPath, !data.hadFocus));
} else {
FileViewController.openAndSelectDocument(data.path, FileViewController.PROJECT_MANAGER).fail(_.partial(_revertSelection, data.previousPath, !data.hadFocus));
}
});
this.model.on(ProjectModel.EVENT_SHOULD_FOCUS, function () {
FileViewController.setFileViewFocus(FileViewController.PROJECT_MANAGER);
});
this.model.on(ProjectModel.ERROR_CREATION, _displayCreationError);
};
/**
* Sets the directory at the given path to open in the tree and saves the open nodes to view state.
*
* See `ProjectModel.setDirectoryOpen`
* @private
*/
ActionCreator.prototype.setDirectoryOpen = function (path, open) {
this.model.setDirectoryOpen(path, open).then(_saveTreeState);
};
/**
* See `ProjectModel.setSelected`
* @private
*/
ActionCreator.prototype.setSelected = function (path, doNotOpen) {
this.model.setSelected(path, doNotOpen);
};
/**
* See `ProjectModel.selectInWorkingSet`
* @private
*/
ActionCreator.prototype.selectInWorkingSet = function (path) {
this.model.selectInWorkingSet(path);
};
/**
* See `FileViewController.openWithExternalApplication`
* @private
*/
ActionCreator.prototype.openWithExternalApplication = function (path) {
FileViewController.openWithExternalApplication(path);
};
/**
* See `ProjectModel.setContext`
* @private
*/
ActionCreator.prototype.setContext = function (path) {
this.model.setContext(path);
};
/**
* See `ProjectModel.restoreContext`
* @private
*/
ActionCreator.prototype.restoreContext = function () {
this.model.restoreContext();
};
/**
* See `ProjectModel.startRename`
* @private
*/
ActionCreator.prototype.startRename = function (path, isMoved) {
// This is very not Flux-like, which is a sign that Flux may not be the
// right choice here *or* that this architecture needs to evolve subtly
// in how errors are reported (more like the create case).
// See #9284.
renameItemInline(path, isMoved);
};
/**
* See `ProjectModel.setRenameValue`
* @private
*/
ActionCreator.prototype.setRenameValue = function (path) {
this.model.setRenameValue(path);
};
/**
* See `ProjectModel.cancelRename`
* @private
*/
ActionCreator.prototype.cancelRename = function () {
this.model.cancelRename();
};
/**
* See `ProjectModel.performRename`
* @private
*/
ActionCreator.prototype.performRename = function () {
return this.model.performRename();
};
/**
* See `ProjectModel.startCreating`
* @private
*/
ActionCreator.prototype.startCreating = function (basedir, newName, isFolder) {
return this.model.startCreating(basedir, newName, isFolder);
};
/**
* See `ProjectModel.setSortDirectoriesFirst`
* @private
*/
ActionCreator.prototype.setSortDirectoriesFirst = function (sortDirectoriesFirst) {
this.model.setSortDirectoriesFirst(sortDirectoriesFirst);
};
/**
* See `ProjectModel.setFocused`
* @private
*/
ActionCreator.prototype.setFocused = function (focused) {
this.model.setFocused(focused);
};
/**
* See `ProjectModel.setCurrentFile`
* @private
*/
ActionCreator.prototype.setCurrentFile = function (curFile) {
this.model.setCurrentFile(curFile);
};
/**
* See `ProjectModel.toggleSubdirectories`
* @private
*/
ActionCreator.prototype.toggleSubdirectories = function (path, openOrClose) {
this.model.toggleSubdirectories(path, openOrClose).then(_saveTreeState);
};
/**
* See `ProjectModel.closeSubtree`
* @private
*/
ActionCreator.prototype.closeSubtree = function (path) {
this.model.closeSubtree(path);
_saveTreeState();
};
ActionCreator.prototype.dragItem = function (path) {
// Close open menus on drag and clear the context, but only if there's a menu open.
if ($(".dropdown.open").length > 0) {
Menus.closeAll();
this.setContext(null);
}
// Close directory, if dragged item is directory
if (_.last(path) === '/') {
this.setDirectoryOpen(path, false);
}
};
/**
* Moves the item in the oldPath to the newDirectory directory
* @private
*/
ActionCreator.prototype.moveItem = function (oldPath, newDirectory) {
var fileName = FileUtils.getBaseName(oldPath),
newPath = newDirectory + fileName,
self = this;
// If item dropped onto itself or onto its parent directory, return
if (oldPath === newDirectory || FileUtils.getParentPath(oldPath) === newDirectory) {
return;
}
// Add trailing slash if directory is moved
if (_.last(oldPath) === '/') {
newPath = ProjectModel._ensureTrailingSlash(newPath);
}
this.startRename(oldPath, true);
this.setRenameValue(newPath);
this.performRename();
this.setDirectoryOpen(newDirectory, true);
};
/**
* See `ProjectModel.refresh`
* @private
*/
ActionCreator.prototype.refresh = function () {
this.model.refresh();
};
/**
* @private
* @type {ActionCreator}
*
* Singleton actionCreator that is used for dispatching changes to the ProjectModel.
*/
var actionCreator = new ActionCreator(model);
/**
* Returns the File or Directory corresponding to the item that was right-clicked on in the file tree menu.
* @return {?(File|Directory)}
*/
function getFileTreeContext() {
var selectedEntry = model.getContext();
return selectedEntry;
}
/**
* 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 context, then file tree selection, else use working set
var selectedEntry = getFileTreeContext();
if (!selectedEntry) {
selectedEntry = model.getSelected();
}
if (!selectedEntry) {
selectedEntry = MainViewManager.getCurrentlyViewedFile();
}
return selectedEntry;
}
/**
* @private
*
* Handler for changes in the focus between working set and file tree view.
*/
function _fileViewControllerChange() {
actionCreator.setFocused(_hasFileSelectionFocus());
_renderTree();
}
/**
* @private
*
* Handler for changes in document selection.
*/
function _documentSelectionFocusChange() {
var curFullPath = MainViewManager.getCurrentlyViewedPath(MainViewManager.ACTIVE_PANE);
if (curFullPath && _hasFileSelectionFocus()) {
actionCreator.setSelected(curFullPath, true);
} else {
actionCreator.setSelected(null);
}
_fileViewControllerChange();
}
/**
* @private
*
* Handler for changes to which file is currently viewed.
*
* @param {Object} e jQuery event object
* @param {File} curFile Currently viewed file.
*/
function _currentFileChange(e, curFile) {
actionCreator.setCurrentFile(curFile);
}
/**
* 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 model.getBaseUrl();
}
/**
* Sets the encoded Base URL of the currently loaded project.
* @param {String}
*/
function setBaseUrl(projectBaseUrl) {
projectBaseUrl = model.setBaseUrl(projectBaseUrl);
PreferencesManager.setViewState("project.baseUrl", projectBaseUrl, PreferencesManager.STATE_PROJECT_CONTEXT);
}
/**
* Returns true if absPath lies within the project, false otherwise.
* Does not support paths containing ".."
* @param {string|FileSystemEntry} absPathOrEntry
* @return {boolean}
*/
function isWithinProject(absPathOrEntry) {
return model.isWithinProject(absPathOrEntry);
}
/**
* Returns an array of files that is within the project from the supplied list of paths.
* @param {string|FileSystemEntry[]} absPathOrEntryArray array which can be either a string path or FileSystemEntry
* @return {string|FileSystemEntry[]} A array that contains only files paths that are in the project
*/
function filterProjectFiles(absPathOrEntryArray) {
if(!absPathOrEntryArray){
return absPathOrEntryArray;
}
let filteredPaths = [];
absPathOrEntryArray.forEach(function (file) {
if(isWithinProject(file)){
filteredPaths.push(file);
}
});
return filteredPaths;
}
/**
* 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) {
return model.makeProjectRelativeIfPossible(absPath);
}
/**
* Gets a generally displayable path that can be shown to the user in most cases.
* Gets the project relative path if possible. If paths is not in project, then if its a platform path(Eg. in tauri)
* it will return the full platform path. If not, then it will return a mount relative path for fs access mount
* folders opened in the bowser. at last, falling back to vfs path. This should only be used for display purposes
* as this path will be changed by phcode depending on the situation in the future.
* @param fullPath
* @returns {string}
*/
function getProjectRelativeOrDisplayPath(fullPath) {
return Phoenix.app.getDisplayPath(makeProjectRelativeIfPossible(fullPath));
}
/**
* 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 model.projectRoot;
}
/**
* @private
*
* Sets the project root to the given directory, resetting the ProjectModel and file tree in the process.
*
* @param {Directory} rootEntry directory object for the project root
* @return {$.Promise} resolved when the project is done setting up
*/
function _setProjectRoot(rootEntry) {
var d = new $.Deferred();
model.setProjectRoot(rootEntry).then(function () {
d.resolve();
model.reopenNodes(PreferencesManager.getViewState("project.treeState", PreferencesManager.STATE_PROJECT_CONTEXT));
});
return d.promise();
}
/**
* @private
*
* Saves the project path.
*/
var _saveProjectPath = function () {
// save the current project
PreferencesManager.setViewState("projectPath", model.projectRoot.fullPath);
};
/**
* @private
* Save tree state.
*/
_saveTreeState = function () {
const openNodes = model.getOpenNodes();
// Store the open nodes by their full path and persist to storage
PreferencesManager.setViewState("project.treeState", openNodes, PreferencesManager.STATE_PROJECT_CONTEXT);
};
/**
* @private
*
* Displays an error dialog for problems when working with files in the file tree.
*
* @param {number} errType type of error that occurred
* @param {boolean} isFolder did the error occur because of a folder operation?
* @param {string} error message with detail about the error
* @param {string} path path to file or folder that had the error
* @return {Dialog|null} Dialog if the error message was created
*/
_showErrorDialog = function (errType, isFolder, error, path, dstPath) {
var titleType = isFolder ? Strings.DIRECTORY_TITLE : Strings.FILE_TITLE,
entryType = isFolder ? Strings.DIRECTORY : Strings.FILE,
title,
message;
path = Phoenix.app.getDisplayPath(path);
path = StringUtils.breakableUrl(path);
switch (errType) {
case ERR_TYPE_CREATE:
title = StringUtils.format(Strings.ERROR_CREATING_FILE_TITLE, titleType);
message = StringUtils.format(Strings.ERROR_CREATING_FILE, entryType, path, error);
break;
case ERR_TYPE_CREATE_EXISTS:
title = StringUtils.format(Strings.INVALID_FILENAME_TITLE, titleType);
message = StringUtils.format(Strings.ENTRY_WITH_SAME_NAME_EXISTS, path);
break;
case ERR_TYPE_RENAME:
title = StringUtils.format(Strings.ERROR_RENAMING_FILE_TITLE, titleType);
message = StringUtils.format(Strings.ERROR_RENAMING_FILE, path, error, entryType);
break;
case ERR_TYPE_MOVE:
title = StringUtils.format(Strings.ERROR_MOVING_FILE_TITLE, titleType);
message = StringUtils.format(Strings.ERROR_MOVING_FILE, path, error, entryType);
break;
case ERR_TYPE_DELETE:
title = StringUtils.format(Strings.ERROR_DELETING_FILE_TITLE, titleType);
message = StringUtils.format(Strings.ERROR_DELETING_FILE, path, error, entryType);
break;
case ERR_TYPE_LOADING_PROJECT:
title = Strings.ERROR_LOADING_PROJECT;
message = StringUtils.format(Strings.READ_DIRECTORY_ENTRIES_ERROR, path, error);
break;
case ERR_TYPE_LOADING_PROJECT_NATIVE:
title = Strings.ERROR_LOADING_PROJECT;
message = StringUtils.format(Strings.REQUEST_NATIVE_FILE_SYSTEM_ERROR, path, error);
break;
case ERR_TYPE_MAX_FILES:
title = Strings.ERROR_MAX_FILES_TITLE;
message = Strings.ERROR_MAX_FILES;
break;
case ERR_TYPE_OPEN_DIALOG:
title = Strings.ERROR_LOADING_PROJECT;
message = StringUtils.format(Strings.OPEN_DIALOG_ERROR, error);
break;
case ERR_TYPE_INVALID_FILENAME:
title = StringUtils.format(Strings.INVALID_FILENAME_TITLE, isFolder ? Strings.DIRECTORY_NAME : Strings.FILENAME);
message = StringUtils.format(Strings.INVALID_FILENAME_MESSAGE, isFolder ? Strings.DIRECTORY_NAMES_LEDE : Strings.FILENAMES_LEDE, error);
break;
case ERR_TYPE_PASTE:
title = StringUtils.format(Strings.CANNOT_PASTE_TITLE, titleType);
message = StringUtils.format(Strings.ENTRY_WITH_SAME_NAME_EXISTS, path);
break;
case ERR_TYPE_PASTE_FAILED:
title = StringUtils.format(Strings.CANNOT_PASTE_TITLE, titleType);
message = StringUtils.format(Strings.ERR_TYPE_PASTE_FAILED, path, dstPath);
break;
case ERR_TYPE_DUPLICATE_FAILED:
title = StringUtils.format(Strings.CANNOT_DUPLICATE_TITLE, titleType);
message = StringUtils.format(Strings.ERR_TYPE_DUPLICATE_FAILED, path);
break;
case ERR_TYPE_DOWNLOAD_FAILED:
title = StringUtils.format(Strings.CANNOT_DOWNLOAD_TITLE, titleType);
message = StringUtils.format(Strings.ERR_TYPE_DOWNLOAD_FAILED, path);
break;
}
if (title && message) {
return Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
title,
message
);
}
return null;
};
var _RENDER_DEBOUNCE_TIME = 100;
/**
* @private
*
* Rerender the file tree view.
*
* @param {boolean} forceRender Force the tree to rerender. Should only be needed by extensions that call rerenderTree.
*/
_renderTreeSync = function (forceRender) {
var projectRoot = getProjectRoot();
if (!projectRoot) {
return;
}
model.setScrollerInfo($projectTreeContainer[0].scrollWidth, $projectTreeContainer.scrollTop(), $projectTreeContainer.scrollLeft(), $projectTreeContainer.offset().top);
FileTreeView.render(fileTreeViewContainer, model._viewModel, projectRoot, actionCreator, forceRender, brackets.platform);
};
_renderTree = _.debounce(_renderTreeSync, _RENDER_DEBOUNCE_TIME);
/**
*
* Returns the full path to the welcome project, which we open on first launch.
*
* @param {string} sampleUrl URL for getting started project
* @param {string} initialPath Path to Brackets directory (see FileUtils.getNativeBracketsDirectoryPath())
* @return {!string} fullPath reference
*/
function getWelcomeProjectPath() {
return ProjectModel._ensureTrailingSlash(Phoenix.VFS.getDefaultProjectDir());
}
function getPlaceholderProjectPath() {
return "/no_project_loaded/";
}
function getExploreProjectPath() {
return `${getLocalProjectsPath()}explore/`;
}
/**
* The folder where all the system managed projects live
* @returns {string}
*/
function getLocalProjectsPath() {
return Phoenix.VFS.getUserProjectsDirectory();
}
/**
* Adds the path to the list of welcome projects we've ever seen, if not on the list already.
* @private
* @param {string} path Path to possibly add
*/
function addWelcomeProjectPath(path) {
var welcomeProjects = ProjectModel._addWelcomeProjectPath(path,
PreferencesManager.getViewState("welcomeProjects"));
PreferencesManager.setViewState("welcomeProjects", welcomeProjects);
}
/**
* 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.
*
* @param {string} path Path to check to see if it's a welcome project path
* @return {boolean} true if this is a welcome project path
*/
function isWelcomeProjectPath(path) {
return ProjectModel._isWelcomeProjectPath(path, getWelcomeProjectPath(), PreferencesManager.getViewState("welcomeProjects"));
}
/**
* If the provided path is to an old welcome project, returns the current one instead.
*/
function updateWelcomeProjectPath(path) {
if (isWelcomeProjectPath(path)) {
return getWelcomeProjectPath();
}
return path;
}
/**
* @deprecated use getStartupProjectPath instead. Can be removed anytime after 2-Apr-2023.
* Initial project path is stored in prefs, which defaults to the welcome project on
* first launch.
* @private
*/
function getInitialProjectPath() {
return updateWelcomeProjectPath(PreferencesManager.getViewState("projectPath"));
}
async function _dirExists(fullPath) {
try {
const {entry} = await FileSystem.resolveAsync(fullPath);
return entry.isDirectory;
} catch (e) {
return false;
}
}
async function _safeCheckFolder(absOrRelativePath, relativeToDir=null) {
try{
let folderToOpen;
if(!relativeToDir){
folderToOpen = Phoenix.VFS.getTauriVirtualPath(absOrRelativePath);
const dirExists = await _dirExists(folderToOpen);
if(dirExists){
return folderToOpen;
}
} else {
folderToOpen = window.path.join(Phoenix.VFS.getTauriVirtualPath(relativeToDir), absOrRelativePath);
const dirExists = await _dirExists(folderToOpen);
if(dirExists){
return folderToOpen;
}
}
} catch (e) {
console.warn("error opening folder at path", absOrRelativePath, relativeToDir);
}
return null;
}
async function _getStartupProjectFromCLIArgs() {
const cliArgs= await Phoenix.app.getCommandLineArgs();
const args = cliArgs && cliArgs.args,
cwd = cliArgs && cliArgs.cwd;
if(!args || args.length <= 1){ // the second arg is the folder we have to open
return null;
}
try{
let folderToOpen = args[1];
folderToOpen = await _safeCheckFolder(args[1]);
if(folderToOpen){
Metrics.countEvent(Metrics.EVENT_TYPE.PLATFORM, 'openWith', "folder");
return folderToOpen;
}
folderToOpen = await _safeCheckFolder(args[1], cwd);
if(folderToOpen){
Metrics.countEvent(Metrics.EVENT_TYPE.PLATFORM, 'openWith', "folder");
}
return folderToOpen;
} catch (e) {
console.error("Error getting startupProjectPath from CLI args", e);
}
return null;
}
/**
* Initial project path is stored in prefs, which defaults to the welcome project on
* first launch.
*/
async function getStartupProjectPath() {
let startupProjectPath = await _getStartupProjectFromCLIArgs();
if(startupProjectPath){
return startupProjectPath;
}
startupProjectPath = updateWelcomeProjectPath(PreferencesManager.getViewState("projectPath"));
if(startupProjectPath && _isProjectSafeToStartup(startupProjectPath)){
const dirExists = await _dirExists(startupProjectPath);
if(dirExists){
return startupProjectPath;
}
}
return getWelcomeProjectPath();
}
function _mergeProjectGitIgnores(rootPath, gitIgnoreFilters) {
// this is an approximation to the gitIgnore spec to transform child git ignores to be
// relative to the project root.
let mergedGitIgnoreFile= "";
for(let filter of gitIgnoreFilters){
if(!filter.gitIgnoreContent){
continue;
}
const projectRelativePath = makeProjectRelativeIfPossible(filter.basePath);
if(!projectRelativePath){
// this is the .gitignore file in the root folder, do nothing.
mergedGitIgnoreFile = `${mergedGitIgnoreFile}\n${filter.gitIgnoreContent}`;
} else {
let lines =[];
// Transform each line to be relative to the project directory
for(let line of filter.gitIgnoreContent.split('\n')) {
if (!line.trim() || line.startsWith('#')){
lines.push(line); // empty lines and comments push as is
} else {
// Handle negated patterns like `!node_modules`