/
CommonProjectNode.cs
1818 lines (1571 loc) · 72.8 KB
/
CommonProjectNode.cs
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
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Infrastructure;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project.Automation;
using MSBuild = Microsoft.Build.Evaluation;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Project {
public enum CommonImageName {
File = 0,
Project = 1,
SearchPathContainer,
SearchPath,
MissingSearchPath,
StartupFile
}
internal abstract class CommonProjectNode : ProjectNode, IVsProjectSpecificEditorMap2, IVsDeferredSaveProject {
private VSLangProj.VSProject _vsProject = null;
private static ImageList _imageList;
private ProjectDocumentsListenerForStartupFileUpdates _projectDocListenerForStartupFileUpdates;
private int _imageOffset;
private FileSystemWatcher _watcher, _attributesWatcher;
private int _suppressFileWatcherCount;
private bool _isRefreshing;
private bool _showingAllFiles;
private object _automationObject;
private CommonPropertyPage _propPage;
private readonly Dictionary<string, FileSystemEventHandler> _fileChangedHandlers = new Dictionary<string, FileSystemEventHandler>();
private Queue<FileSystemChange> _fileSystemChanges = new Queue<FileSystemChange>();
private object _fileSystemChangesLock = new object();
private readonly Dictionary<string, FileSystemWatcher> _symlinkWatchers = new Dictionary<string, FileSystemWatcher>();
private DiskMerger _currentMerger;
private IdleManager _idleManager;
#if DEV11_OR_LATER
private IVsHierarchyItemManager _hierarchyManager;
private Dictionary<uint, bool> _needBolding;
#else
private readonly HashSet<HierarchyNode> _needBolding = new HashSet<HierarchyNode>();
#endif
private int _idleTriggered;
public CommonProjectNode(IServiceProvider serviceProvider, ImageList imageList)
: base(serviceProvider) {
#if !DEV14_OR_LATER
Contract.Assert(imageList != null);
#endif
CanFileNodesHaveChilds = true;
SupportsProjectDesigner = true;
if (imageList != null) {
_imageList = imageList;
//Store the number of images in ProjectNode so we know the offset of the language icons.
#pragma warning disable 0618
_imageOffset = ImageHandler.ImageList.Images.Count;
foreach (Image img in ImageList.Images) {
ImageHandler.AddImage(img);
}
#pragma warning restore 0618
}
//Initialize a new object to track project document changes so that we can update the StartupFile Property accordingly
_projectDocListenerForStartupFileUpdates = new ProjectDocumentsListenerForStartupFileUpdates(Site, this);
_projectDocListenerForStartupFileUpdates.Init();
#if DEV11_OR_LATER
UpdateHierarchyManager(alwaysCreate: false);
#endif
_idleManager = new IdleManager(Site);
_idleManager.OnIdle += OnIdle;
}
public override int QueryService(ref Guid guidService, out object result) {
if (guidService == typeof(VSLangProj.VSProject).GUID) {
result = VSProject;
return VSConstants.S_OK;
}
return base.QueryService(ref guidService, out result);
}
#region abstract methods
public abstract Type GetProjectFactoryType();
public abstract Type GetEditorFactoryType();
public abstract string GetProjectName();
public virtual CommonFileNode CreateCodeFileNode(ProjectElement item) {
return new CommonFileNode(this, item);
}
public virtual CommonFileNode CreateNonCodeFileNode(ProjectElement item) {
return new CommonNonCodeFileNode(this, item);
}
public abstract string GetFormatList();
public abstract Type GetGeneralPropertyPageType();
public abstract Type GetLibraryManagerType();
#endregion
#region Properties
public int ImageOffset {
get { return _imageOffset; }
}
/// <summary>
/// Get the VSProject corresponding to this project
/// </summary>
protected internal VSLangProj.VSProject VSProject {
get {
if (_vsProject == null)
_vsProject = new OAVSProject(this);
return _vsProject;
}
}
private IVsHierarchy InteropSafeHierarchy {
get {
IntPtr unknownPtr = Utilities.QueryInterfaceIUnknown(this);
if (IntPtr.Zero == unknownPtr) {
return null;
}
try {
IVsHierarchy hier = Marshal.GetObjectForIUnknown(unknownPtr) as IVsHierarchy;
return hier;
} finally {
Marshal.Release(unknownPtr);
}
}
}
/// <summary>
/// Indicates whether the project is currently is busy refreshing its hierarchy.
/// </summary>
public bool IsRefreshing {
get { return _isRefreshing; }
set { _isRefreshing = value; }
}
/// <summary>
/// Language specific project images
/// </summary>
public static ImageList ImageList {
get {
return _imageList;
}
set {
_imageList = value;
}
}
public CommonPropertyPage PropertyPage {
get { return _propPage; }
set { _propPage = value; }
}
#endregion
#region overridden properties
public override bool CanShowAllFiles {
get {
return true;
}
}
public override bool IsShowingAllFiles {
get {
return _showingAllFiles;
}
}
/// <summary>
/// Returns true if the item should be included in search results
/// </summary>
public override bool IsSearchable {
get {
// Starting with 16.0 Preview 2, it is important for the
// project to report as not searchable. Otherwise, find in
// files will return results in project file, and IsItemDirty
// and SaveItem won't work properly.
// See https://github.com/Microsoft/PTVS/issues/4887
return false;
}
}
/// <summary>
/// Since we appended the language images to the base image list in the constructor,
/// this should be the offset in the ImageList of the langauge project icon.
/// </summary>
#if DEV14_OR_LATER
[Obsolete("Use GetIconMoniker() to specify the icon and GetIconHandle() for back-compat")]
#endif
public override int ImageIndex {
get {
return _imageOffset + (int)CommonImageName.Project;
}
}
public override Guid ProjectGuid {
get {
return GetProjectFactoryType().GUID;
}
}
public override string ProjectType {
get {
return GetProjectName();
}
}
internal override object Object {
get {
return VSProject;
}
}
#endregion
#region overridden methods
public override object GetAutomationObject() {
if (_automationObject == null) {
_automationObject = base.GetAutomationObject();
}
return _automationObject;
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == Microsoft.VisualStudioTools.Project.VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case VsCommands2K.ECMD_PUBLISHSELECTION:
if (pCmdText != IntPtr.Zero && NativeMethods.OLECMDTEXT.GetFlags(pCmdText) == NativeMethods.OLECMDTEXT.OLECMDTEXTF.OLECMDTEXTF_NAME) {
NativeMethods.OLECMDTEXT.SetText(pCmdText, "Publish " + this.Caption);
}
if (IsPublishingEnabled) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
} else {
result |= QueryStatusResult.SUPPORTED;
}
return VSConstants.S_OK;
case VsCommands2K.ECMD_PUBLISHSLNCTX:
if (IsPublishingEnabled) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
} else {
result |= QueryStatusResult.SUPPORTED;
}
return VSConstants.S_OK;
case CommonConstants.OpenFolderInExplorerCmdId:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup == SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.AddExistingFolder:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
private bool IsPublishingEnabled {
get {
return !String.IsNullOrWhiteSpace(GetProjectProperty(CommonConstants.PublishUrl));
}
}
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == Microsoft.VisualStudioTools.Project.VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case VsCommands2K.ECMD_PUBLISHSELECTION:
case VsCommands2K.ECMD_PUBLISHSLNCTX:
Publish(PublishProjectOptions.Default, true);
return VSConstants.S_OK;
case CommonConstants.OpenFolderInExplorerCmdId:
Process.Start(this.ProjectHome);
return VSConstants.S_OK;
}
} else if (cmdGroup == SharedCommandGuid) {
switch ((SharedCommands)cmd) {
case SharedCommands.AddExistingFolder:
return AddExistingFolderToNode(this);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal int AddExistingFolderToNode(HierarchyNode parent) {
var dir = Dialogs.BrowseForDirectory(
IntPtr.Zero,
parent.FullPathToChildren,
String.Format("Add Existing Folder - {0}", Caption)
);
if (dir != null) {
DropFilesOrFolders(new[] { dir }, parent);
}
return VSConstants.S_OK;
}
/// <summary>
/// Publishes the project as configured by the user in the Publish option page.
///
/// If async is true this function begins the publishing and returns w/o waiting for it to complete. No errors are reported.
///
/// If async is false this function waits for the publish to finish and raises a PublishFailedException with an
/// inner exception indicating the underlying reason for the publishing failure.
///
/// Returns true if the publish was succeessfully started, false if the project is not configured for publishing
/// </summary>
public virtual bool Publish(PublishProjectOptions publishOptions, bool async) {
string publishUrl = publishOptions.DestinationUrl ?? GetProjectProperty(CommonConstants.PublishUrl);
bool found = false;
if (!String.IsNullOrWhiteSpace(publishUrl)) {
var url = new Url(publishUrl);
if (url.Uri == null) {
var statusBar = (IVsStatusbar)Site.GetService(typeof(SVsStatusbar));
statusBar.SetText(SR.GetString(SR.PublishProjectInvalidUrl, publishUrl));
return false;
}
if (!url.Uri.IsAbsoluteUri) {
// If user entered a relative path, make this an absolute file URL
url = new Url(new Url(PathUtils.EnsureEndSeparator(ProjectHome)), publishUrl);
}
var publishers = ((IComponentModel)Site.GetService(typeof(SComponentModel))).GetExtensions<IProjectPublisher>();
foreach (var publisher in publishers) {
if (publisher.Schema == url.Uri.Scheme) {
var project = new PublishProject(this, publishOptions);
Exception failure = null;
var frame = new DispatcherFrame();
var thread = new System.Threading.Thread(x => {
try {
publisher.PublishFiles(project, url.Uri);
project.Done();
frame.Continue = false;
} catch (Exception e) {
failure = e;
project.Failed(e.Message);
frame.Continue = false;
}
});
thread.Start();
found = true;
if (!async) {
Dispatcher.PushFrame(frame);
if (failure != null) {
throw new PublishFailedException(SR.GetString(SR.PublishProjectFailed, Caption), failure);
}
}
break;
}
}
if (!found) {
var statusBar = (IVsStatusbar)Site.GetService(typeof(SVsStatusbar));
statusBar.SetText(SR.GetString(SR.PublishProjectInvalidScheme, url.Uri.Scheme));
}
} else {
var statusBar = (IVsStatusbar)Site.GetService(typeof(SVsStatusbar));
statusBar.SetText(SR.GetString(SR.PublishProjectNotConfigured));
}
return found;
}
public virtual CommonProjectConfig MakeConfiguration(string activeConfigName) {
return new CommonProjectConfig(this, activeConfigName);
}
/// <summary>
/// As we don't register files/folders in the project file, removing an item is a noop.
/// </summary>
public override int RemoveItem(uint reserved, uint itemId, out int result) {
result = 1;
return VSConstants.S_OK;
}
/// <summary>
/// Overriding main project loading method to inject our hierarachy of nodes.
/// </summary>
protected override void Reload() {
base.Reload();
BoldStartupItem();
OnProjectPropertyChanged += CommonProjectNode_OnProjectPropertyChanged;
// track file creation/deletes and update our glyphs when files start/stop existing for files in the project.
if (_watcher != null) {
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
}
bool? showAllFiles = null;
if (UserBuildProject != null) {
showAllFiles = GetShowAllFilesSetting(UserBuildProject.GetPropertyValue(CommonConstants.ProjectView));
}
_showingAllFiles = showAllFiles ??
GetShowAllFilesSetting(BuildProject.GetPropertyValue(CommonConstants.ProjectView)) ??
false;
_watcher = CreateFileSystemWatcher(ProjectHome);
_attributesWatcher = CreateAttributesWatcher(ProjectHome);
_currentMerger = new DiskMerger(this, this, ProjectHome);
}
/// <summary>
/// Called to ensure that the hierarchy's show all files nodes are in
/// sync with the file system.
/// </summary>
protected void SyncFileSystem() {
if (_currentMerger == null) {
_currentMerger = new DiskMerger(this, this, ProjectHome);
}
while (_currentMerger.ContinueMerge(ParentHierarchy != null)) {
}
_currentMerger = null;
}
internal void BoldStartupItem() {
var startupPath = GetStartupFile();
if (!string.IsNullOrEmpty(startupPath)) {
var startup = FindNodeByFullPath(startupPath);
if (startup != null) {
BoldItem(startup, true);
}
}
}
private FileSystemWatcher CreateFileSystemWatcher(string dir) {
var watcher = new FileSystemWatcher(dir) {
InternalBufferSize = 1024 * 4, // 4k is minimum buffer size
IncludeSubdirectories = true
};
// Set Event Handlers
watcher.Created += new FileSystemEventHandler(FileExistanceChanged);
watcher.Deleted += new FileSystemEventHandler(FileExistanceChanged);
watcher.Renamed += new RenamedEventHandler(FileNameChanged);
watcher.Changed += FileContentsChanged;
#if DEV12_OR_LATER
watcher.Renamed += FileContentsChanged;
#endif
watcher.Error += WatcherError;
// Delay setting EnableRaisingEvents until everything else is initialized.
watcher.EnableRaisingEvents = true;
return watcher;
}
private FileSystemWatcher CreateAttributesWatcher(string dir) {
var watcher = new FileSystemWatcher(dir) {
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.Attributes,
InternalBufferSize = 1024 * 4, // 4k is minimum buffer size
};
// Set Event Handlers
watcher.Changed += FileAttributesChanged;
watcher.Error += WatcherError;
// Delay setting EnableRaisingEvents until everything else is initialized.
watcher.EnableRaisingEvents = true;
return watcher;
}
/// <summary>
/// When the file system watcher buffer overflows we need to scan the entire
/// directory for changes.
/// </summary>
private void WatcherError(object sender, ErrorEventArgs e) {
lock (_fileSystemChanges) {
_fileSystemChanges.Clear(); // none of the other changes matter now, we'll rescan the world
_currentMerger = null; // abort any current merge now that we have a new one
_fileSystemChanges.Enqueue(new FileSystemChange(this, WatcherChangeTypes.All, null, watcher: sender as FileWatcher));
TriggerIdle();
}
}
protected override void Dispose(bool disposing) {
if (disposing) {
#if DEV11_OR_LATER
HierarchyManager = null;
#endif
var pdl = _projectDocListenerForStartupFileUpdates;
_projectDocListenerForStartupFileUpdates = null;
if (pdl != null) {
pdl.Dispose();
}
if (_idleManager != null) {
_idleManager.OnIdle -= OnIdle;
_idleManager.Dispose();
}
}
base.Dispose(disposing);
}
protected internal override int ShowAllFiles() {
Site.GetUIThread().MustBeCalledFromUIThread();
if (!QueryEditProjectFile(false)) {
return VSConstants.E_FAIL;
}
if (_showingAllFiles) {
UpdateShowAllFiles(this, enabled: false);
} else {
UpdateShowAllFiles(this, enabled: true);
ExpandItem(EXPANDFLAGS.EXPF_ExpandFolder);
}
BoldStartupItem();
_showingAllFiles = !_showingAllFiles;
string newPropValue = _showingAllFiles ? CommonConstants.ShowAllFiles : CommonConstants.ProjectFiles;
var projProperty = BuildProject.GetProperty(CommonConstants.ProjectView);
if (projProperty != null &&
!projProperty.IsImported &&
!String.IsNullOrWhiteSpace(projProperty.EvaluatedValue)) {
// setting is persisted in main project file, update it there.
BuildProject.SetProperty(CommonConstants.ProjectView, newPropValue);
} else {
// save setting in user project file
SetUserProjectProperty(CommonConstants.ProjectView, newPropValue);
}
// update project state
return VSConstants.S_OK;
}
private void UpdateShowAllFiles(HierarchyNode node, bool enabled) {
for (var curNode = node.FirstChild; curNode != null; curNode = curNode.NextSibling) {
UpdateShowAllFiles(curNode, enabled);
var allFiles = curNode.ItemNode as AllFilesProjectElement;
if (allFiles != null) {
curNode.IsVisible = enabled;
if (enabled) {
OnItemAdded(node, curNode);
} else {
RaiseItemDeleted(curNode);
}
}
}
}
private static bool? GetShowAllFilesSetting(string showAllFilesValue) {
bool? showAllFiles = null;
string showAllFilesSetting = showAllFilesValue.Trim();
if (String.Equals(showAllFilesSetting, CommonConstants.ProjectFiles)) {
showAllFiles = false;
} else if (String.Equals(showAllFilesSetting, CommonConstants.ShowAllFiles)) {
showAllFiles = true;
}
return showAllFiles;
}
/// <summary>
/// Performs merging of the file system state with the current project hierarchy, bringing them
/// back into sync.
///
/// The class can be created, and ContinueMerge should be called until it returns false, at which
/// point the file system has been merged.
///
/// You can wait between calls to ContinueMerge to enable not blocking the UI.
///
/// If there were changes which came in while the DiskMerger was processing then those changes will still need
/// to be processed after the DiskMerger completes.
/// </summary>
class DiskMerger {
private readonly string _initialDir;
private readonly Stack<DirState> _remainingDirs = new Stack<DirState>();
private readonly CommonProjectNode _project;
private readonly FileWatcher _watcher;
public DiskMerger(CommonProjectNode project, HierarchyNode parent, string dir, FileWatcher watcher = null) {
_project = project;
_initialDir = dir;
_remainingDirs.Push(new DirState(dir, parent));
_watcher = watcher;
}
/// <summary>
/// Continues processing the merge request, performing a portion of the full merge possibly
/// returning before the merge has completed.
///
/// Returns true if the merge needs to continue, or false if the merge has completed.
/// </summary>
public bool ContinueMerge(bool hierarchyCreated = true) {
if (_remainingDirs.Count == 0) { // all done
if (_watcher != null) {
_watcher.EnableRaisingEvents = true;
}
_project.BoldStartupItem();
return false;
}
var dir = _remainingDirs.Pop();
if (!Directory.Exists(dir.Name)) {
return true;
}
HashSet<HierarchyNode> missingChildren = new HashSet<HierarchyNode>(dir.Parent.AllChildren);
IEnumerable<string> dirs;
try {
dirs = Directory.EnumerateDirectories(dir.Name);
} catch {
// directory was deleted, we don't have access, etc...
return true;
}
bool wasExpanded = hierarchyCreated ? dir.Parent.GetIsExpanded() : false;
foreach (var curDir in dirs) {
if (_project.IsFileHidden(curDir)) {
continue;
}
if (IsFileSymLink(curDir)) {
if (IsRecursiveSymLink(dir.Name, curDir)) {
// don't add recursive sym links
continue;
}
// track symlinks, we won't get events on the directory
_project.CreateSymLinkWatcher(curDir);
}
var existing = _project.AddAllFilesFolder(dir.Parent, curDir + Path.DirectorySeparatorChar, hierarchyCreated);
missingChildren.Remove(existing);
_remainingDirs.Push(new DirState(curDir, existing));
}
IEnumerable<string> files;
try {
files = Directory.EnumerateFiles(dir.Name);
} catch {
// directory was deleted, we don't have access, etc...
// We are about to return and some of the previous operations may have affect the Parent's Expanded
// state. Set it back to what it was
if (hierarchyCreated) {
dir.Parent.ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
}
return true;
}
foreach (var file in files) {
if (_project.IsFileHidden(file)) {
continue;
}
missingChildren.Remove(_project.AddAllFilesFile(dir.Parent, file));
}
// remove the excluded children which are no longer there
foreach (var child in missingChildren) {
if (child.ItemNode.IsExcluded) {
_project.RemoveSubTree(child);
}
}
if (hierarchyCreated) {
dir.Parent.ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder);
}
return true;
}
class DirState {
public readonly string Name;
public readonly HierarchyNode Parent;
public DirState(string name, HierarchyNode parent) {
Name = name;
Parent = parent;
}
}
}
private void MergeDiskNodes(HierarchyNode curParent, string dir) {
var merger = new DiskMerger(this, curParent, dir);
while (merger.ContinueMerge(ParentHierarchy != null)) {
}
}
private void RemoveSubTree(HierarchyNode node) {
Site.GetUIThread().MustBeCalledFromUIThread();
foreach (var child in node.AllChildren) {
RemoveSubTree(child);
}
node.Parent.RemoveChild(node);
_diskNodes.Remove(node.Url);
}
private static string GetFinalPathName(string dir) {
using (var dirHandle = NativeMethods.CreateFile(
dir,
NativeMethods.FileDesiredAccess.FILE_LIST_DIRECTORY,
NativeMethods.FileShareFlags.FILE_SHARE_DELETE |
NativeMethods.FileShareFlags.FILE_SHARE_READ |
NativeMethods.FileShareFlags.FILE_SHARE_WRITE,
IntPtr.Zero,
NativeMethods.FileCreationDisposition.OPEN_EXISTING,
NativeMethods.FileFlagsAndAttributes.FILE_FLAG_BACKUP_SEMANTICS,
IntPtr.Zero
)) {
if (!dirHandle.IsInvalid) {
uint pathLen = NativeMethods.MAX_PATH + 1;
uint res;
StringBuilder filePathBuilder;
for (; ; ) {
filePathBuilder = new StringBuilder(checked((int)pathLen));
res = NativeMethods.GetFinalPathNameByHandle(
dirHandle,
filePathBuilder,
pathLen,
0
);
if (res != 0 && res < pathLen) {
// we had enough space, and got the filename.
break;
}
}
if (res != 0) {
Debug.Assert(filePathBuilder.ToString().StartsWith("\\\\?\\", StringComparison.Ordinal));
return filePathBuilder.ToString().Substring(4);
}
}
}
return dir;
}
private static bool IsRecursiveSymLink(string parentDir, string childDir) {
if (IsFileSymLink(parentDir)) {
// figure out the real parent dir so the check below works w/ multiple
// symlinks pointing at each other
parentDir = GetFinalPathName(parentDir);
}
string finalPath = GetFinalPathName(childDir);
// check and see if we're recursing infinitely...
if (CommonUtils.IsSubpathOf(finalPath, parentDir)) {
// skip this file
return true;
}
return false;
}
private static bool IsFileSymLink(string path) {
try {
return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0;
} catch (UnauthorizedAccessException) {
return false;
} catch (DirectoryNotFoundException) {
return false;
} catch (FileNotFoundException) {
return false;
}
}
private bool IsFileHidden(string path) {
if (String.Equals(path, FileName, StringComparison.OrdinalIgnoreCase) ||
String.Equals(path, FileName + ".user", StringComparison.OrdinalIgnoreCase) ||
String.Equals(Path.GetExtension(path), ".sln") ||
String.Equals(Path.GetExtension(path), ".suo")) {
return true;
}
if (!File.Exists(path) && !Directory.Exists(path)) {
// if the file has disappeared avoid the exception...
return true; // Files/directories that don't exist should be hidden. This also fix DiskMerger when adds files that were already deleted
}
try {
return (File.GetAttributes(path) & (FileAttributes.Hidden | FileAttributes.System)) != 0;
} catch (UnauthorizedAccessException) {
return false;
} catch (DirectoryNotFoundException) {
return false;
} catch (FileNotFoundException) {
return false;
}
}
/// <summary>
/// Adds a file which is displayed when Show All Files is enabled
/// </summary>
private HierarchyNode AddAllFilesFile(HierarchyNode curParent, string file) {
var existing = FindNodeByFullPath(file);
if (existing == null) {
var newFile = CreateFileNode(new AllFilesProjectElement(file, GetItemType(file), this));
AddAllFilesNode(curParent, newFile);
return newFile;
}
return existing;
}
/// <summary>
/// Adds a folder which is displayed when Show All files is enabled
/// </summary>
private HierarchyNode AddAllFilesFolder(HierarchyNode curParent, string curDir, bool hierarchyCreated = true) {
var folderNode = FindNodeByFullPath(curDir);
if (folderNode == null) {
folderNode = CreateFolderNode(new AllFilesProjectElement(curDir, "Folder", this));
AddAllFilesNode(curParent, folderNode);
if (hierarchyCreated) {
// Solution Explorer will expand the parent when an item is
// added, which we don't want
folderNode.ExpandItem(EXPANDFLAGS.EXPF_CollapseFolder);
}
}
return folderNode;
}
/// <summary>
/// Initializes and adds a file or folder visible only when Show All files is enabled
/// </summary>
private void AddAllFilesNode(HierarchyNode parent, HierarchyNode newNode) {
newNode.IsVisible = IsShowingAllFiles;
parent.AddChild(newNode);
}
private void FileContentsChanged(object sender, FileSystemEventArgs e) {
if (IsClosed) {
return;
}
FileSystemEventHandler handler;
if (_fileChangedHandlers.TryGetValue(e.FullPath, out handler)) {
handler(sender, e);
}
}
private void FileAttributesChanged(object sender, FileSystemEventArgs e) {
lock (_fileSystemChanges) {
if (NoPendingFileSystemRescan()) {
_fileSystemChanges.Enqueue(new FileSystemChange(this, WatcherChangeTypes.Changed, e.FullPath));
TriggerIdle();
}
}
}
private bool NoPendingFileSystemRescan() {
return _fileSystemChanges.Count == 0 || _fileSystemChanges.Peek()._type != WatcherChangeTypes.All;
}
internal void RegisterFileChangeNotification(FileNode node, FileSystemEventHandler handler) {
_fileChangedHandlers[node.Url] = handler;
}
internal void UnregisterFileChangeNotification(FileNode node) {
_fileChangedHandlers.Remove(node.Url);
}
protected override ReferenceContainerNode CreateReferenceContainerNode() {
return new CommonReferenceContainerNode(this);
}
private void FileNameChanged(object sender, RenamedEventArgs e) {
if (IsClosed) {
return;
}
try {
lock (_fileSystemChanges) {
// we just generate a delete and creation here - we're just updating the hierarchy
// either changing icons or updating the non-project elements, so we don't need to
// generate rename events or anything like that. This saves us from having to
// handle updating the hierarchy in a special way for renames.
if (NoPendingFileSystemRescan()) {
_fileSystemChanges.Enqueue(new FileSystemChange(this, WatcherChangeTypes.Deleted, e.OldFullPath, true));
_fileSystemChanges.Enqueue(new FileSystemChange(this, WatcherChangeTypes.Created, e.FullPath, true));
TriggerIdle();
}
}
} catch (PathTooLongException) {
// A rename event can be reported for a path that's too long, and then access to RenamedEventArgs
// properties will throw this - nothing we can do other than ignoring it.
}
}
private void FileExistanceChanged(object sender, FileSystemEventArgs e) {
if (IsClosed) {
return;
}
lock (_fileSystemChanges) {
if (NoPendingFileSystemRescan()) {
_fileSystemChanges.Enqueue(new FileSystemChange(this, e.ChangeType, e.FullPath));
TriggerIdle();
}
}
}
/// <summary>
/// If VS is already idle, we won't keep getting idle events, so we need to post a
/// new event to the queue to flip away from idle and back again.
/// </summary>
private async void TriggerIdle() {
if (Interlocked.CompareExchange(ref _idleTriggered, 1, 0) == 0) {
await Site.GetUIThread().InvokeAsync(Nop);
}
}
private static readonly Action Nop = () => { };
internal void CreateSymLinkWatcher(string curDir) {
if (!CommonUtils.HasEndSeparator(curDir)) {
curDir = curDir + Path.DirectorySeparatorChar;
}
_symlinkWatchers[curDir] = CreateFileSystemWatcher(curDir);
}
internal bool TryDeactivateSymLinkWatcher(HierarchyNode child) {
FileSystemWatcher watcher;
if (_symlinkWatchers.TryGetValue(child.Url, out watcher)) {
_symlinkWatchers.Remove(child.Url);
watcher.EnableRaisingEvents = false;
watcher.Dispose();
return true;
}
return false;
}
private void OnIdle(object sender, ComponentManagerEventArgs e) {
Interlocked.Exchange(ref _idleTriggered, 0);
do {
#if DEV10
BoldDeferredItems();
#endif
using (new DebugTimer("ProcessFileChanges while Idle", 100)) {
if (IsClosed) {
return;
}
DiskMerger merger;
FileSystemChange change = null;
lock (_fileSystemChanges) {
merger = _currentMerger;
if (merger == null) {
if (_fileSystemChanges.Count == 0) {
break;
}
change = _fileSystemChanges.Dequeue();
}
}
if (merger != null) {
// we have more file merges to process, do this
// before reflecting any other pending updates...
if (!merger.ContinueMerge(ParentHierarchy != null)) {
_currentMerger = null;