Repository navigation
Expand file tree
/
Copy pathSolutionManager.cs
More file actions
556 lines (481 loc) · 19 KB
/
Copy pathSolutionManager.cs
File metadata and controls
556 lines (481 loc) · 19 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
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
namespace NuGet.VisualStudio
{
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(ISolutionManager))]
public class SolutionManager : ISolutionManager, IVsSelectionEvents
{
private readonly DTE _dte;
private readonly SolutionEvents _solutionEvents;
private readonly IVsMonitorSelection _vsMonitorSelection;
private readonly uint _solutionLoadedUICookie;
private readonly IVsSolution _vsSolution;
private bool _initNeeded;
private ProjectCache _projectCache;
public SolutionManager()
: this(
ServiceLocator.GetInstance<DTE>(),
ServiceLocator.GetGlobalService<SVsSolution, IVsSolution>(),
ServiceLocator.GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>())
{
}
internal SolutionManager(DTE dte, IVsSolution vsSolution, IVsMonitorSelection vsMonitorSelection)
{
if (dte == null)
{
throw new ArgumentNullException("dte");
}
_initNeeded = true;
_dte = dte;
_vsSolution = vsSolution;
_vsMonitorSelection = vsMonitorSelection;
// Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
_solutionEvents = _dte.Events.SolutionEvents;
// can be null in unit tests
if (vsMonitorSelection != null)
{
Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
_vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);
uint cookie;
int hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie);
ErrorHandler.ThrowOnFailure(hr);
}
_solutionEvents.BeforeClosing += OnBeforeClosing;
_solutionEvents.AfterClosing += OnAfterClosing;
_solutionEvents.ProjectAdded += OnProjectAdded;
_solutionEvents.ProjectRemoved += OnProjectRemoved;
_solutionEvents.ProjectRenamed += OnProjectRenamed;
// Run the init on another thread to avoid an endless loop of SolutionManager -> Project System -> VSPackageManager -> SolutionManager
ThreadPool.QueueUserWorkItem(new WaitCallback(Init));
}
public string DefaultProjectName
{
get;
set;
}
public Project DefaultProject
{
get
{
if (String.IsNullOrEmpty(DefaultProjectName))
{
return null;
}
Project project = GetProject(DefaultProjectName);
Debug.Assert(project != null, "Invalid default project");
return project;
}
}
[Import]
internal Lazy<IDeleteOnRestartManager> DeleteOnRestartManager { get; set; }
public event EventHandler SolutionOpened;
public event EventHandler SolutionClosing;
public event EventHandler SolutionClosed;
public event EventHandler<ProjectEventArgs> ProjectAdded;
/// <summary>
/// Gets a value indicating whether there is a solution open in the IDE.
/// </summary>
public bool IsSolutionOpen
{
get
{
return _dte != null &&
_dte.Solution != null &&
_dte.Solution.IsOpen &&
!IsSolutionSavedAsRequired();
}
}
/// <summary>
/// Checks whether the current solution is saved to disk, as opposed to be in memory.
/// </summary>
private bool IsSolutionSavedAsRequired()
{
// Check if user is doing File - New File without saving the solution.
object value;
_vsSolution.GetProperty((int)(__VSPROPID.VSPROPID_IsSolutionSaveAsRequired), out value);
if ((bool)value)
{
return true;
}
// Check if user unchecks the "Tools - Options - Project & Soltuions - Save new projects when created" option
_vsSolution.GetProperty((int)(__VSPROPID2.VSPROPID_DeferredSaveSolution), out value);
return (bool)value;
}
public string SolutionDirectory
{
get
{
if (!IsSolutionOpen)
{
return null;
}
string solutionFilePath = GetSolutionFilePath();
if (String.IsNullOrEmpty(solutionFilePath))
{
return null;
}
return Path.GetDirectoryName(solutionFilePath);
}
}
public IFileSystem SolutionFileSystem
{
get
{
string path = SolutionDirectory;
if (string.IsNullOrEmpty(path))
{
return null;
}
return new PhysicalFileSystem(path);
}
}
private string GetSolutionFilePath()
{
// Use .Properties.Item("Path") instead of .FullName because .FullName might not be
// available if the solution is just being created
string solutionFilePath = null;
Property property = _dte.Solution.Properties.Item("Path");
if (property == null)
{
return null;
}
try
{
// When using a temporary solution, (such as by saying File -> New File), querying this value throws.
// Since we wouldn't be able to do manage any packages at this point, we return null. Consumers of this property typically
// use a String.IsNullOrEmpty check either way, so it's alright.
solutionFilePath = (string)property.Value;
}
catch (COMException)
{
return null;
}
return solutionFilePath;
}
public bool IsSourceControlBound
{
get
{
return GetIsSourceControlBound();
}
}
private bool GetIsSourceControlBound()
{
if (!IsSolutionOpen)
{
return false;
}
string solutionFilePath = GetSolutionFilePath();
Debug.Assert(!String.IsNullOrEmpty(solutionFilePath));
SourceControl2 sourceControl = (SourceControl2)_dte.SourceControl;
if (sourceControl != null)
{
try
{
return sourceControl.GetBindings(solutionFilePath) != null;
}
catch (NotImplementedException)
{
}
}
return false;
}
/// <summary>
/// Gets a list of supported projects currently loaded in the solution
/// </summary>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1024:UsePropertiesWhereAppropriate",
Justification = "This method is potentially expensive if the cache is not constructed yet.")]
public IEnumerable<Project> GetProjects()
{
if (IsSolutionOpen)
{
EnsureProjectCache();
return _projectCache.GetProjects();
}
else
{
return Enumerable.Empty<Project>();
}
}
public string GetProjectSafeName(Project project)
{
if (project == null)
{
throw new ArgumentNullException("project");
}
// Try searching for simple names first
string name = project.GetName();
if (GetProject(name) == project)
{
return name;
}
return project.GetCustomUniqueName();
}
public Project GetProject(string projectSafeName)
{
if (IsSolutionOpen)
{
EnsureProjectCache();
Project project;
if (_projectCache.TryGetProject(projectSafeName, out project))
{
return project;
}
}
return null;
}
private void OnAfterClosing()
{
if (SolutionClosed != null)
{
SolutionClosed(this, EventArgs.Empty);
}
}
private void OnBeforeClosing()
{
DefaultProjectName = null;
_projectCache = null;
if (SolutionClosing != null)
{
SolutionClosing(this, EventArgs.Empty);
}
}
private void OnProjectRenamed(Project project, string oldName)
{
if (!String.IsNullOrEmpty(oldName))
{
EnsureProjectCache();
if (project.IsSupported())
{
RemoveProjectFromCache(oldName);
AddProjectToCache(project);
}
else if (project.IsSolutionFolder())
{
// In the case where a solution directory was changed, project FullNames are unchanged.
// We only need to invalidate the projects under the current tree so as to sync the CustomUniqueNames.
foreach (var item in project.GetSupportedChildProjects())
{
RemoveProjectFromCache(item.FullName);
AddProjectToCache(item);
}
}
}
}
private void OnProjectRemoved(Project project)
{
RemoveProjectFromCache(project.FullName);
}
private void OnProjectAdded(Project project)
{
if (project.IsSupported() && !project.IsParentProjectExplicitlyUnsupported())
{
EnsureProjectCache();
AddProjectToCache(project);
if (ProjectAdded != null)
{
ProjectAdded(this, new ProjectEventArgs(project));
}
}
}
private void Init(object state)
{
try
{
if (_initNeeded && _dte.Solution.IsOpen)
{
InvokeOnUIThread(() => OnSolutionOpened());
}
}
catch (Exception)
{
}
}
/// <summary>
/// Invokes the action on the UI thread if one exists.
/// </summary>
private void InvokeOnUIThread(Action action)
{
if (Application.Current != null)
{
Application.Current.Dispatcher.Invoke(action);
}
else
{
action();
}
}
private void OnSolutionOpened()
{
// we can skip the init if this has already been called
_initNeeded = false;
// although the SolutionOpened event fires, the solution may be only in memory (e.g. when
// doing File - New File). In that case, we don't want to act on the event.
if (!IsSolutionOpen)
{
return;
}
EnsureProjectCache();
SetDefaultProject();
if (SolutionOpened != null)
{
SolutionOpened(this, EventArgs.Empty);
}
}
private void EnsureProjectCache()
{
if (IsSolutionOpen && _projectCache == null)
{
_projectCache = new ProjectCache();
var allProjects = _dte.Solution.GetAllProjects();
foreach (Project project in allProjects)
{
AddProjectToCache(project);
}
}
}
private void AddProjectToCache(Project project)
{
if (!project.IsSupported())
{
return;
}
ProjectName oldProjectName;
_projectCache.TryGetProjectNameByShortName(project.GetName(), out oldProjectName);
ProjectName newProjectName = _projectCache.AddProject(project);
if (String.IsNullOrEmpty(DefaultProjectName) ||
newProjectName.ShortName.Equals(DefaultProjectName, StringComparison.OrdinalIgnoreCase))
{
DefaultProjectName = oldProjectName != null ?
oldProjectName.CustomUniqueName :
newProjectName.ShortName;
}
}
private void RemoveProjectFromCache(string name)
{
// Do nothing if the cache hasn't been set up
if (_projectCache == null)
{
return;
}
ProjectName projectName;
_projectCache.TryGetProjectName(name, out projectName);
// Remove the project from the cache
_projectCache.RemoveProject(name);
if (!_projectCache.Contains(DefaultProjectName))
{
DefaultProjectName = null;
}
// for LightSwitch project, the main project is not added to _projectCache, but it is called on removal.
// in that case, projectName is null.
if (projectName != null &&
projectName.CustomUniqueName.Equals(DefaultProjectName, StringComparison.OrdinalIgnoreCase) &&
!_projectCache.IsAmbiguous(projectName.ShortName))
{
DefaultProjectName = projectName.ShortName;
}
}
private void SetDefaultProject()
{
// when a new solution opens, we set its startup project as the default project in NuGet Console
var solutionBuild = (SolutionBuild2)_dte.Solution.SolutionBuild;
if (solutionBuild.StartupProjects != null)
{
IEnumerable<object> startupProjects = (IEnumerable<object>)solutionBuild.StartupProjects;
string startupProjectName = startupProjects.Cast<string>().FirstOrDefault();
if (!String.IsNullOrEmpty(startupProjectName))
{
ProjectName projectName;
if (_projectCache.TryGetProjectName(startupProjectName, out projectName))
{
DefaultProjectName = _projectCache.IsAmbiguous(projectName.ShortName) ?
projectName.CustomUniqueName :
projectName.ShortName;
}
}
}
}
// REVIEW: This might be inefficient, see what we can do with caching projects until references change
public IEnumerable<Project> GetDependentProjects(Project project)
{
if (project == null)
{
throw new ArgumentNullException("project");
}
var dependentProjects = new Dictionary<string, List<Project>>();
// Get all of the projects in the solution and build the reverse graph. i.e.
// if A has a project reference to B (A -> B) the this will return B -> A
// We need to run this on the ui thread so that it doesn't freeze for websites. Since there might be a
// large number of references.
ThreadHelper.Generic.Invoke(() =>
{
foreach (var proj in GetProjects())
{
if (proj.SupportsReferences())
{
foreach (var referencedProject in proj.GetReferencedProjects())
{
AddDependentProject(dependentProjects, referencedProject, proj);
}
}
}
});
List<Project> dependents;
if (dependentProjects.TryGetValue(project.GetUniqueName(), out dependents))
{
return dependents;
}
return Enumerable.Empty<Project>();
}
private static void AddDependentProject(IDictionary<string, List<Project>> dependentProjects, Project project, Project dependent)
{
string uniqueName = project.GetUniqueName();
List<Project> dependents;
if (!dependentProjects.TryGetValue(uniqueName, out dependents))
{
dependents = new List<Project>();
dependentProjects[uniqueName] = dependents;
}
dependents.Add(dependent);
}
#region IVsSelectionEvents implementation
public int OnCmdUIContextChanged(uint dwCmdUICookie, int fActive)
{
if (dwCmdUICookie == _solutionLoadedUICookie && fActive == 1)
{
OnSolutionOpened();
// We must call DeleteMarkedPackageDirectories outside of OnSolutionOpened, because OnSolutionOpened might be called in the constructor
// and DeleteOnRestartManager requires VsFileSystemProvider and RepositorySetings which both have dependencies on SolutionManager.
// In practice, this code gets executed even when a solution is opened directly during Visual Studio startup.
DeleteOnRestartManager.Value.DeleteMarkedPackageDirectories();
}
return VSConstants.S_OK;
}
public int OnElementValueChanged(uint elementid, object varValueOld, object varValueNew)
{
return VSConstants.S_OK;
}
public int OnSelectionChanged(IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew)
{
return VSConstants.S_OK;
}
#endregion
}
}