-
Notifications
You must be signed in to change notification settings - Fork 11
/
ShellService.cs
2518 lines (2144 loc) · 66.4 KB
/
ShellService.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
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Input;
using DPackRx.CodeModel;
using DPackRx.Extensions;
using DPackRx.Language;
using DPackRx.Options;
using DPackRx.Package;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.VCProjectEngine;
using VSLangProj;
using VsWebSite;
using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper;
using VSPackage = Microsoft.VisualStudio.Shell.Package;
namespace DPackRx.Services
{
/// <summary>
/// Combined service that accesses Visual Studio and DTE APIs and thus is untestable.
/// It's broken into smaller logically grouped sub-services.
/// </summary>
public class ShellService : IShellHelperService, IShellStatusBarService, IShellReferenceService,
IShellSelectionService, IShellProjectService, IShellCodeModelService
{
#region Fields
private readonly IServiceProvider _serviceProvider;
private readonly ILog _log;
private readonly ILanguageService _languageService;
private DTE _dte;
private IFileTypeResolver _fileTypeResolver;
private readonly bool _webInteropAvailable;
private readonly bool _cppInteropAvailable;
private const string LOG_CATEGORY = "Shell";
internal const int DEFAULT_WAIT_MSECS = 1000;
internal const string PROJECT_ITEM_KIND_SETUP = "{54435603-DBB4-11D2-8724-00A0C9A8B90C}";
internal const string TEXT_DOCUMENT = "TextDocument";
private const string ELEMENT_TYPE = "vsCMElement";
private const string KIND_CLASS = "Class";
private const string KIND_MODULE = "Module";
private const string KIND_STRUCT = "Structure";
private const string KIND_ENUM = "Enumeration";
private const string KIND_INTERFACE = "Interface";
private const string KIND_METHOD = "Method";
private const string KIND_PROPERTY = "Property";
private const string KIND_VARIABLE = "Variable";
private const string KIND_EVENT = "Event";
private const string KIND_DELEGATE = "Delegate";
#endregion
public ShellService(IServiceProvider serviceProvider, ILog log, ILanguageService languageService)
{
_serviceProvider = serviceProvider;
_log = log;
_languageService = languageService;
try
{
TestWebInterop();
_webInteropAvailable = true;
}
catch
{
_webInteropAvailable = false;
_log.LogMessage("Web Interop is not available", LOG_CATEGORY);
}
try
{
TestCPPInterop();
_cppInteropAvailable = true;
}
catch
{
_cppInteropAvailable = false;
_log.LogMessage("C++ Interop is not available", LOG_CATEGORY);
}
}
#region IShellHelperService Members
/// <summary>
/// Returns untyped DTE instance.
/// </summary>
public object GetDTE()
{
ThreadHelper.ThrowIfNotOnUIThread();
return GetDTEInternal();
}
/// <summary>
/// Returns selected Solution Explorer item path.
/// </summary>
public string GetSelectedItemPath()
{
ThreadHelper.ThrowIfNotOnUIThread();
var dte = GetDTEInternal();
string path = null;
var selectedItems = dte.SelectedItems;
if ((selectedItems != null) && (selectedItems.Count >= 1) &&
(selectedItems.SelectionContainer != null) && (selectedItems.SelectionContainer.Count >= 1))
{
var item = selectedItems.Item(1).ProjectItem;
var project = selectedItems.Item(1).Project;
var obj = selectedItems.SelectionContainer.Item(1);
if (item != null) // file or folder
{
path = Path.GetDirectoryName(item.get_FileNames(1));
if (string.IsNullOrEmpty(path) && (item.ContainingProject != null))
{
GetProjectPath(item.ContainingProject, out path, out _);
if (!string.IsNullOrEmpty(path) &&
item.Kind.Equals(VSConstants.ItemTypeGuid.PhysicalFolder_string, StringComparison.OrdinalIgnoreCase))
path = Path.Combine(path, item.Name);
}
}
else if (project != null) // project
{
GetProjectPath(project, out path, out _);
}
else if (obj is Reference) // reference
{
var reference = (Reference)obj;
try
{
var referencePath = reference.Path;
if (!string.IsNullOrEmpty(referencePath) && Path.IsPathRooted(referencePath))
path = Path.GetDirectoryName(referencePath);
}
catch
{
// Do nothing
}
}
else // solution
{
var solutionPath = dte.Solution.FullName;
if (!string.IsNullOrEmpty(solutionPath) && Path.IsPathRooted(solutionPath))
path = Path.GetDirectoryName(solutionPath);
}
}
return path;
}
/// <summary>
/// Returns selected Solution Explorer project path.
/// </summary>
public string GetCurrentProjectPath()
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!GetSelectionProject(out Project project, out _, out _, out _) ||
(project == null))
return null;
try
{
return project.FullName;
}
catch (Exception ex)
{
_log.LogMessage(ex, LOG_CATEGORY);
return null;
}
}
/// <summary>
/// Selects currently open document in Solution Explorer.
/// </summary>
public bool SelectSolutionExplorerDocument(out string documentName)
{
ThreadHelper.ThrowIfNotOnUIThread();
var dteDocument = GetActiveDocument() as Document;
if (dteDocument == null)
{
documentName = string.Empty;
return false;
}
documentName = GetActiveFileName();
var projectItem = GetDocumentProjectItem(dteDocument);
if ((projectItem == null) || !SelectSolutionExplorerItem(projectItem))
return false;
return true;
}
/// <summary>
/// Collapses all projects in Solution Explorer.
/// </summary>
public void CollapseAllProjects()
{
ThreadHelper.ThrowIfNotOnUIThread();
_log.LogMessage("Collapse all projects - enter", LOG_CATEGORY);
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
try
{
var dte = GetDTEInternal();
var solution = dte.Solution;
var solutionName = GetSolutionName(solution);
_log.LogMessage($"Collapse all projects - solution {solutionName}", LOG_CATEGORY);
var solutionWindow = dte.Windows.Item(EnvDTE.Constants.vsWindowKindSolutionExplorer);
if (solutionWindow == null)
{
_log.LogMessage("Collapse all projects - failed to retrieve Solution Explorer window", LOG_CATEGORY);
return;
}
solutionWindow.Activate();
var hierarchy = dte.ActiveWindow.Object as UIHierarchy;
if (hierarchy != null)
{
var solutionItem = hierarchy.GetItem(solutionName);
UIHierarchyItems solutionItems;
if (solutionItem != null)
solutionItems = solutionItem.UIHierarchyItems;
else
solutionItems = null;
if ((solutionItems != null) && (solutionItems.Count > 0))
{
foreach (UIHierarchyItem item in solutionItems)
{
CollapseAllRecursively(hierarchy, item);
}
// Select top item
solutionItems.Item(1).Select(vsUISelectionType.vsUISelectionTypeSelect);
}
else
{
_log.LogMessage("Collapse all projects - no solution items detected", LOG_CATEGORY);
}
}
}
finally
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
_log.LogMessage("Collapse all projects - exit", LOG_CATEGORY);
}
/// <summary>
/// Opens a given file name editor navigating to line and column.
/// </summary>
public bool OpenFileAt(string fileName, int line, int column)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException(nameof(fileName));
if ((line <= 0) || (column <= 0))
return false;
ThreadHelper.ThrowIfNotOnUIThread();
var textView = GetTextView(fileName);
if (textView == null)
return false;
if (textView.SetCaretPos(line - 1, column - 1) != VSConstants.S_OK) // text view coordinates are 0-based
return false;
textView.CenterLines(line - 1, 1);
return true;
}
/// <summary>
/// Opens given file editors.
/// </summary>
public void OpenFiles(IEnumerable<IExtensibilityItem> files)
{
if ((files == null) || (files.Count() == 0))
return;
ThreadHelper.ThrowIfNotOnUIThread();
if (files.Count() > 1)
{
files.ForEach(f => ActivateItem(f, false, false));
ActivateWindow(files.First(), false);
}
else
{
ActivateItem(files.First(), true, false);
}
}
/// <summary>
/// Opens given file designers.
/// </summary>
public void OpenDesignerFiles(IEnumerable<IExtensibilityItem> files)
{
if ((files == null) || (files.Count() == 0))
return;
ThreadHelper.ThrowIfNotOnUIThread();
if (files.Count() > 1)
{
files.ForEach(f => ActivateItem(f, false, true));
ActivateWindow(files.First(), true);
}
else
{
ActivateItem(files.First(), true, true);
}
}
/// <summary>
/// Assigns package shortcuts.
/// </summary>
public bool AssignShortcuts()
{
ThreadHelper.ThrowIfNotOnUIThread();
var oldCursor = Mouse.OverrideCursor;
Mouse.SetCursor(Cursors.Wait);
try
{
var dte = GetDTEInternal();
var scope = GetGlobalScopeName(dte);
if (string.IsNullOrEmpty(scope))
{
_log.LogMessage("Failed to retrieve global scope name", LOG_CATEGORY);
return false;
}
var fields = typeof(CommandIDs).GetFields(BindingFlags.Public | BindingFlags.Static).ToList();
var attribs = new List<CommandNameAttribute>(fields.Count);
fields.ForEach(f => attribs.Add((CommandNameAttribute)f.GetCustomAttribute(typeof(CommandNameAttribute))));
foreach (var attrib in attribs)
{
if (!string.IsNullOrEmpty(attrib.Binding))
{
try
{
var command = dte.Commands.Item(attrib.Name, 1);
if (command != null)
command.Bindings = $"{scope}::{attrib.Binding}";
else
_log.LogMessage($"Command {attrib.Name} is not available", LOG_CATEGORY);
}
catch (Exception ex)
{
_log.LogMessage($"Error assigning shortcut for {attrib.Name} command and {attrib.Binding} binding", ex, LOG_CATEGORY);
}
}
}
// Process all VS commands
var shell = _serviceProvider.GetService<IVsUIShell5, SVsUIShell>();
var scopes = new Dictionary<string, string>();
foreach (var attrib in CommandBindings.Commands)
{
try
{
var command = dte.Commands.Item(attrib.Name, 1);
if (command != null)
{
var binding = attrib.Binding;
// Resolve optional scope binding
if (string.IsNullOrEmpty(attrib.Scope))
{
binding = $"{scope}::{binding}";
}
else
{
var resolvedScope = string.Empty;
if (scopes.ContainsKey(attrib.Scope))
resolvedScope = scopes[attrib.Scope];
else
{
var bindingGuide = new Guid(attrib.Scope);
resolvedScope = shell.GetKeyBindingScope(ref bindingGuide);
if (!string.IsNullOrEmpty(resolvedScope))
{
scopes.Add(attrib.Scope, resolvedScope);
_log.LogMessage($"VS command {attrib.Name} - resolved {attrib.Scope} scope to {resolvedScope}", LOG_CATEGORY);
}
}
if (string.IsNullOrEmpty(resolvedScope))
{
_log.LogMessage($"VS command {attrib.Name} - could not resolve {attrib.Scope} scope", LOG_CATEGORY);
continue;
}
binding = $"{resolvedScope}::{binding}";
}
command.Bindings = binding;
}
else
{
_log.LogMessage($"VS command {attrib.Name} is not available", LOG_CATEGORY);
}
}
catch (Exception ex)
{
_log.LogMessage($"Error assigning shortcut for VS {attrib.Name} command and {attrib.Binding} binding with {attrib.Scope} scope", ex, LOG_CATEGORY);
}
}
_log.LogMessage("Assigned shortcuts", LOG_CATEGORY);
return true;
}
catch (Exception ex)
{
_log.LogMessage($"Error assigning shortcuts: {ex.Message}", ex, LOG_CATEGORY);
return false;
}
finally
{
Mouse.SetCursor(oldCursor);
}
}
/// <summary>
/// Shows options setting page.
/// </summary>
public void ShowOptions<T>() where T : OptionsBase
{
var package = _serviceProvider.GetService<VSPackage>();
package.ShowOptionPage(typeof(T));
}
/// <summary>
/// Executes built-in command.
/// </summary>
/// <param name="command">Internal command name.</param>
/// <param name="arguments">Optional command arguments.</param>
public void ExecuteCommand(string command, string arguments = null)
{
if (string.IsNullOrEmpty(command))
throw new ArgumentNullException(nameof(command));
ThreadHelper.ThrowIfNotOnUIThread();
var dte = GetDTEInternal();
try
{
dte.ExecuteCommand(command);
}
catch (Exception ex)
{
_log.LogMessage($"Error executing {command} command: {ex.Message}", ex, LOG_CATEGORY);
}
}
#endregion
#region IShellStatusBarService Members
/// <summary>
/// Sets status bar text.
/// </summary>
public void SetStatusBarText(string text)
{
if (string.IsNullOrEmpty(text))
return;
ThreadHelper.ThrowIfNotOnUIThread();
GetDTEInternal().StatusBar.Text = text;
}
#endregion
#region IShellReferenceService Members
/// <summary>
/// Returns current project references.
/// </summary>
public ICollection<ProjectReference> GetProjectReferences(bool selectedOnly)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!GetSelectionProject(out _, out VSProject vsProject, out _, out SelectedItems selectedItems))
return null;
List<string> selectedNames = null;
if (selectedOnly)
{
selectedNames = new List<string>(selectedItems.Count);
for (var index = 1; index <= selectedItems.Count; index++)
{
selectedNames.Add(selectedItems.Item(index).Name);
}
}
var references = new List<ProjectReference>();
for (var index = 1; index <= vsProject.References.Count; index++)
{
var reference = vsProject.References.Item(index);
if (reference.Type == prjReferenceType.prjReferenceTypeAssembly)
{
if ((reference.Name == null) || reference.Name.Equals("mscorlib", StringComparison.OrdinalIgnoreCase))
continue;
if ((selectedNames == null) || (selectedNames.Contains(reference.Name)))
{
if (!string.IsNullOrEmpty(reference.Path))
{
var projectReference = new ProjectReference { Name = reference.Name, Path = reference.Path };
if (reference.SourceProject != null)
projectReference.ReferencingProjectName = reference.SourceProject.UniqueName;
references.Add(projectReference);
}
}
}
}
return references;
}
/// <summary>
/// Adds project reference to current project.
/// </summary>
public bool AddProjectReference(string projectName)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!GetSelectionProject(out Project project, out _, out IVsSolution solution, out _))
return false;
var result = solution.GetProjectOfUniqueName(projectName, out IVsHierarchy referenceHierarchy);
if ((result == VSConstants.S_OK) && (referenceHierarchy != null))
{
var referenceProject = GetProjectFromHierarchy(referenceHierarchy);
if ((referenceProject != null) && (referenceProject != project) && !IsAlreadyReferenced(project, referenceProject.Name))
{
try
{
var vsProj = project?.Object as VSProject;
return (vsProj != null) && (vsProj.References.AddProject(referenceProject) != null);
}
catch (Exception ex)
{
_log.LogMessage($"Error referencing project: {projectName}", ex, LOG_CATEGORY);
return false;
}
}
}
return false;
}
/// <summary>
/// Adds assembly references to current project.
/// </summary>
public bool AddAssemblyReference(string fileName)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (!GetSelectionProject(out Project project, out _, out _, out _))
return false;
if (IsAlreadyReferenced(project, fileName))
return true;
try
{
var vsProj = project?.Object as VSProject;
return (vsProj != null) && (vsProj.References.Add(fileName) != null);
}
catch (Exception ex)
{
_log.LogMessage($"Error referencing project assembly: {fileName}", ex, LOG_CATEGORY);
throw;
}
}
#endregion
#region IShellSelectionService Members
/// <summary>
/// Checks whether selection context is active.
/// </summary>
public bool IsContextActive(ContextType context)
{
ThreadHelper.ThrowIfNotOnUIThread();
switch (context)
{
case ContextType.SolutionExistsAndFullyLoaded:
return IsContextActiveInternal(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid);
case ContextType.SolutionHasProjects:
return IsContextActiveInternal(VSConstants.UICONTEXT_SolutionExists) && (
IsContextActiveInternal(VSConstants.UICONTEXT_SolutionHasSingleProject) ||
IsContextActiveInternal(VSConstants.UICONTEXT_SolutionHasMultipleProjects));
case ContextType.SolutionExists:
return IsContextActiveInternal(VSConstants.UICONTEXT_SolutionExists);
case ContextType.CodeWindow:
return IsContextActiveInternal(VSConstants.UICONTEXT_CodeWindow);
case ContextType.TextEditor:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidTextEditor));
case ContextType.XMLTextEditor:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidXMLTextEditor));
case ContextType.CSSTextEditor:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidCSSTextEditor));
case ContextType.HTMLCodeView:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidHTMLCodeView));
case ContextType.HTMLSourceView:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidHTMLSourceView));
case ContextType.HTMLSourceEditor:
return IsContextActiveInternal(new Guid(ContextGuids.vsContextGuidHTMLSourceEditor));
case ContextType.XamlEditor:
return IsContextActiveInternal(new Guid(GUIDs.GUID_XAML_LANGUAGE_SERVICE));
case ContextType.NewXamlEditor:
return IsContextActiveInternal(new Guid(GUIDs.GUID_NEW_XAML_LANGUAGE_SERVICE));
case ContextType.XamlDesigner:
return IsContextActiveInternal(new Guid(GUIDs.GUID_XAML_DESIGNER));
default:
_log.LogMessage($"Invalid selection context: {context}", LOG_CATEGORY);
return false;
}
}
/// <summary>
/// Returns active document's untyped Project instance.
/// </summary>
public object GetActiveProject()
{
ThreadHelper.ThrowIfNotOnUIThread();
Document document = GetActiveDocument() as Document;
if (document == null)
return null;
return document.ProjectItem?.ContainingProject;
}
/// <summary>
/// Returns active document's untyped ProjectItem instance.
/// </summary>
public object GetActiveItem()
{
ThreadHelper.ThrowIfNotOnUIThread();
Document document = GetActiveDocument() as Document;
if (document == null)
return null;
return document.ProjectItem;
}
/// <summary>
/// Returns active document's untyped Document instance.
/// </summary>
public object GetActiveDocument()
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
var document = GetDTEInternal().ActiveDocument;
return document;
}
catch
{
// Exception's raised when project properties document is active
return null;
}
}
/// <summary>
/// Returns active document's untyped Window instance.
/// </summary>
public object GetActiveWindow()
{
ThreadHelper.ThrowIfNotOnUIThread();
var dteDocument = GetActiveDocument() as Document;
if (dteDocument == null)
return null;
try
{
var window = dteDocument.ActiveWindow;
return window;
}
catch
{
// Exception's raised when project properties document is active
return null;
}
}
/// <summary>
/// Returns active document's file name.
/// </summary>
public string GetActiveFileName()
{
ThreadHelper.ThrowIfNotOnUIThread();
var document = GetActiveDocument() as Document;
if (document != null)
return document.FullName;
else
return null;
}
/// <summary>
/// Returns active document's cursor position.
/// </summary>
public Position GetActiveFilePosition()
{
ThreadHelper.ThrowIfNotOnUIThread();
var textManager = _serviceProvider.GetService<IVsTextManager, SVsTextManager>();
if (textManager.GetActiveView(Convert.ToInt32(true), null, out IVsTextView textView) != VSConstants.S_OK)
return Position.Empty;
if (textView.GetCaretPos(out int line, out int column) != VSConstants.S_OK)
return Position.Empty;
return new Position(line + 1, column + 1); // text view coordinates are 0-based
}
/// <summary>
/// Sets active document's cursor position.
/// </summary>
public bool SetActiveFilePosition(int line, int column)
{
ThreadHelper.ThrowIfNotOnUIThread();
if ((line <= 0) || (column <= 0))
return false;
var textManager = _serviceProvider.GetService<IVsTextManager, SVsTextManager>();
if (textManager.GetActiveView(Convert.ToInt32(true), null, out IVsTextView textView) != VSConstants.S_OK)
return false;
if (textView.SetCaretPos(line - 1, column - 1) != VSConstants.S_OK) // text view coordinates are 0-based
return false;
textView.CenterLines(line - 1, 1);
return true;
}
#endregion
#region IShellProjectService Members
/// <summary>
/// Checks whether untyped Project instance is a qualified project.
/// </summary>
public bool IsProject(object project)
{
ThreadHelper.ThrowIfNotOnUIThread();
var dteProject = GetProjectInternal(project, false);
return (dteProject != null) &&
//(dteProject.Kind != EnvDTE.Constants.vsProjectKindSolutionItems) && // commented out because it prevented misc files from showing up in File Browser
(dteProject.Kind != EnvDTE.Constants.vsProjectKindUnmodeled) &&
(dteProject.Kind != EnvDTE.Constants.vsProjectKindMisc);
}
/// <summary>
/// Checks whether untyped Project instance is a qualified classic ASP.NET web project.
/// </summary>
public bool IsWebProject(object project)
{
ThreadHelper.ThrowIfNotOnUIThread();
return _webInteropAvailable && IsWebProjectInternal(GetProjectInternal(project));
}
/// <summary>
/// Checks whether untyped ProjectItem instance is a qualified classic ASP.NET web project item.
/// </summary>
public bool IsWebProjectItem(object projectItem)
{
ThreadHelper.ThrowIfNotOnUIThread();
return _webInteropAvailable && IsWebProjectItemInternal(GetProjectItemInternal(projectItem));
}
// TODO: re-evaluate for removal as deffered loading's been deprecated and it's obsolete now
#pragma warning disable CS0618
/// <summary>
/// Checks whether untyped Project instance project load's deferred, ie project hasn't been fully loaded yet.
/// </summary>
public bool IsProjectLoadDeferred(object project, out bool loaded)
{
ThreadHelper.ThrowIfNotOnUIThread();
loaded = false;
if (project == null)
return false;
var dteProject = GetProjectInternal(project);
// Deffered load is not applicable to solution projects
if (dteProject.Kind.Equals(EnvDTE.Constants.vsProjectKindSolutionItems, StringComparison.OrdinalIgnoreCase))
return false;
var serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(GetDTEInternal() as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
if (serviceProvider == null)
return false;
var solution = serviceProvider.GetService<IVsSolution, SVsSolution>(false);
if ((solution == null) || !(solution is IVsSolution4))
return false;
if ((solution.GetProperty((int)__VSPROPID7.VSPROPID_DeferredProjectCount, out object deferredCount) != VSConstants.S_OK) ||
!(deferredCount is int) || ((int)deferredCount == 0))
return false;
IVsHierarchy hierarchy = GetVsHierarchy(dteProject);
if (hierarchy == null)
return false;
if ((hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID9.VSHPROPID_IsDeferred, out object deferred) != VSConstants.S_OK) ||
!(deferred is bool) || !(bool)deferred)
return false;
_log.LogMessage($"Project '{dteProject?.Name}' load is deferred", LOG_CATEGORY);
if (hierarchy.GetGuidProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out Guid projectGuid) != VSConstants.S_OK)
return false;
int result = ((IVsSolution4)solution).EnsureProjectIsLoaded(projectGuid, (uint)__VSBSLFLAGS.VSBSLFLAGS_None);
if (result == VSConstants.S_OK)
{
loaded = true;
_log.LogMessage($"Deferred project '{dteProject?.Name}' is loaded", LOG_CATEGORY);
}
else
{
_log.LogMessage($"Failed to load deferred project '{dteProject?.Name}' - error {result}", LOG_CATEGORY);
return true;
}
return false;
}
#pragma warning restore CS0618
/// <summary>
/// Checks whether untyped ProjectItem instance is a qualified C++ project item.
/// </summary>
public bool IsCppFile(object projectItem)
{
ThreadHelper.ThrowIfNotOnUIThread();
if (_cppInteropAvailable)
return IsCppFileInternal(projectItem);
else
return false;
}
/// <summary>
/// Returns untyped Project instance project name.
/// </summary>
public string GetFriendlyProjectName(object project)
{
ThreadHelper.ThrowIfNotOnUIThread();
var dteProject = GetProjectInternal(project);
string result;
try
{
result = dteProject.Name;
}
catch
{
return string.Empty;
}
if (!string.IsNullOrEmpty(result) && IsWebProject(dteProject))
{
webType webSiteType;
try
{
Properties props = dteProject.Properties;
if (props == null)
return result;
Property prop = props.Item("WebSiteType");
if (prop == null)
return result;
else
webSiteType = (webType)prop.Value;
}
catch
{
return result;
}
switch (webSiteType)
{
case webType.webTypeLocalhost:
case webType.webTypeFrontPage:
case webType.webTypeFTP:
Uri uri;
if (Uri.TryCreate(result, UriKind.RelativeOrAbsolute, out uri))
{
if ((uri != null) && uri.IsAbsoluteUri)
{
result = uri.AbsolutePath;
if ((result.Length >= 2) &&
result.StartsWith("/", StringComparison.OrdinalIgnoreCase) &&
result.EndsWith("/", StringComparison.OrdinalIgnoreCase))
result = result.Substring(1, result.Length - 2); // strip leading and trailing '/'
else
if (result.StartsWith("/", StringComparison.OrdinalIgnoreCase))
result = result.Substring(1, result.Length - 1); // strip leading '/'
else
if (result.EndsWith("/", StringComparison.OrdinalIgnoreCase))
result = result.Substring(0, result.Length - 1); // strip trailing '/'
}
}
break;
case webType.webTypeFileSystem:
if (result.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase))
result = result.Substring(0, result.Length - 1);
result = Path.GetFileName(result);
break;
}
}
return result;
}
/// <summary>
/// Returns untyped Project instance project path and full name.
/// </summary>
public void GetProjectPath(object project, out string projectPath, out string projectFullName)
{
ThreadHelper.ThrowIfNotOnUIThread();
var dteProject = GetProjectInternal(project);
var projectName = GetFriendlyProjectName(project);
if (string.IsNullOrEmpty(projectName))
{
projectPath = string.Empty;
projectFullName = string.Empty;
}
else
{
// Don't even attempt getting full name on projects that don't support extensibility
// code model. Those include DB projects, Script debug time projects, etc.
if (dteProject.Kind != EnvDTE.Constants.vsProjectKindUnmodeled)
{
try
{
projectFullName = dteProject.FullName;
}
catch
{
projectFullName = string.Empty;
}
}
else
projectFullName = string.Empty;
// Safety check for projects like setups, etc...
if (!string.IsNullOrEmpty(projectFullName))
{