- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenFileCustomCommand.cs
More file actions
Latest commit
290 lines (243 loc) · 9.49 KB
/
Copy pathOpenFileCustomCommand.cs
File metadata and controls
290 lines (243 loc) · 9.49 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
//
// Copyright 2020 - Jeffrey "botman" Broome
//
usingSystem;
usingSystem.ComponentModel.Design;
usingSystem.Globalization;
usingMicrosoft.VisualStudio.Shell;
usingMicrosoft.VisualStudio.Shell.Interop;
usingTask=System.Threading.Tasks.Task;
usingMicrosoft.VisualStudio;
usingSystem.Collections.Generic;
usingSystem.IO;
usingEnvDTE;
usingEnvDTE80;
// Some useful docs:
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivssolution2.getprojectfilesinsolution?view=visualstudiosdk-2019
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivssolution.getprojectenum?view=visualstudiosdk-2019
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivshierarchy?view=visualstudiosdk-2019
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.ivshierarchyitem?view=visualstudiosdk-2019
namespaceOpenFileByName
{
staticclassGlobals
{
publicstaticboolbSingleton=false;// singleton to prevent opening multiple dialog boxes at once (since dialog box is no longer modal)
publicstaticstringinput="";
}
// NOTE: For IVsHierarchy node objects, the node (IVsHierarchyItem) 'itemid' has a limited lifetime and it is NOT safe to keep them and use then
// without using IVsHierarchy.AdviseHierarchyEvents to listen for changes. See the remarks here:
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivshierarchy?view=visualstudiosdk-2019
/// <summary>
/// Command handler
/// </summary>
internalsealedclassOpenFileCustomCommand
{
/// <summary>
/// Command ID.
/// </summary>
publicconstintCommandId=0x0100;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
publicstaticreadonlyGuidCommandSet=newGuid("963cca7e-1714-4ba5-8252-dbb5857e5929");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
privatereadonlyAsyncPackagepackage;
publicstaticHashSet<string>SolutionFilenames=null;
publicstaticchar[]InvalidChars;
publicstaticboolbForceUpdate=false;// set when files or projects in the solution are added, removed, or moved.
/// <summary>
/// Initializes a new instance of the <see cref="OpenFileCustomCommand"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
/// <param name="commandService">Command service to add command to, not null.</param>
privateOpenFileCustomCommand(AsyncPackagepackage,OleMenuCommandServicecommandService)
{
this.package=package??thrownewArgumentNullException(nameof(package));
commandService=commandService??thrownewArgumentNullException(nameof(commandService));
varmenuCommandID=newCommandID(CommandSet,CommandId);
varmenuItem=newMenuCommand(this.Execute,menuCommandID);
commandService.AddCommand(menuItem);
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
publicstaticOpenFileCustomCommandInstance
{
get;
privateset;
}
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
privateMicrosoft.VisualStudio.Shell.IAsyncServiceProviderServiceProvider
{
get
{
returnthis.package;
}
}
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner package, not null.</param>
publicstaticasyncTaskInitializeAsync(AsyncPackagepackage)
{
// Switch to the main thread - the call to AddCommand in OpenFileCustomCommand's constructor requires
// the UI thread.
awaitThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
OleMenuCommandServicecommandService=awaitpackage.GetServiceAsync(typeof(IMenuCommandService))asOleMenuCommandService;
Instance=newOpenFileCustomCommand(package,commandService);
}
/// <summary>
/// This function is the callback used to execute the command when the menu item is clicked.
/// See the constructor to see how the menu item is associated with this function using
/// OleMenuCommandService service and MenuCommand class.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event args.</param>
privatevoidExecute(objectsender,EventArgse)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
if(Globals.bSingleton)
{
return;
}
InvalidChars=Path.GetInvalidPathChars();// get characters not allowed in file paths
if((SolutionFilenames==null)||bForceUpdate)
{
try
{
SolutionFilenames=newHashSet<string>();
IVsSolution2solution=Package.GetGlobalService(typeof(SVsSolution))asIVsSolution2;
IVsHierarchysolutionHierarchy=(IVsHierarchy)solution;
IVsProjectProject=null;
GetFilesInSolutionRecursive(solutionHierarchy,VSConstants.VSITEMID_ROOT,refProject,refSolutionFilenames);
}
catch
{
}
}
try
{
if(Properties.Settings.Default.UseSelectedText)
{
DTE2dte2=Package.GetGlobalService(typeof(DTE))asDTE2;
if((dte2!=null)&&(dte2.ActiveDocument!=null))
{
TextSelectionselection=dte2.ActiveDocument.SelectionasTextSelection;
if((selection!=null)&&(selection.Text!="")&&(selection.Text.Length<260))// 260 is MAX_PATH
{
Globals.input=selection.Text;
}
}
}
}
catch
{
}
OpenFileDialogopenFileDialog=newOpenFileByName.OpenFileDialog(Globals.input);
Globals.bSingleton=true;
openFileDialog.Show();// don't use a modal dialog so we can set focus to opened documents
}
catch(Exceptionex)
{
Console.WriteLine("Execute Exception: {0}",ex.Message);
}
}
privatevoidGetFilesInSolutionRecursive(IVsHierarchyhierarchy,uintitemId,refIVsProjectProject,refHashSet<string>SolutionFilenames)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
// NOTE: If itemId == VSConstants.VSITEMID_ROOT then this hierarchy is a solution, project, or folder in the Solution Explorer
if(hierarchy==null)
{
return;
}
objectChildObject=null;
// Get the first visible child node
if(hierarchy.GetProperty(itemId,(int)__VSHPROPID.VSHPROPID_FirstVisibleChild,outChildObject)==VSConstants.S_OK)
{
while(ChildObject!=null)
{
if((ChildObjectisint)&&((uint)(int)ChildObject==VSConstants.VSITEMID_NIL))
{
break;
}
uintvisibleChildNodeId=Convert.ToUInt32(ChildObject);
GuidnestedHierarchyGuid=typeof(IVsHierarchy).GUID;
IntPtrnestedHiearchyValue=IntPtr.Zero;
uintnestedItemIdValue=0;
// see if the child node has a nested hierarchy (i.e. is it a project?, is it a folder?, etc.)...
if((hierarchy.GetNestedHierarchy(visibleChildNodeId,refnestedHierarchyGuid,outnestedHiearchyValue,outnestedItemIdValue)==VSConstants.S_OK)&&
(nestedHiearchyValue!=IntPtr.Zero&&nestedItemIdValue==VSConstants.VSITEMID_ROOT))
{
// Get the new hierarchy
IVsHierarchynestedHierarchy=System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(nestedHiearchyValue)asIVsHierarchy;
System.Runtime.InteropServices.Marshal.Release(nestedHiearchyValue);
if(nestedHierarchy!=null)
{
IVsProjectNewProject=(IVsProject)nestedHierarchy;
if(NewProject!=null)
{
// recurse into the new nested hierarchy to handle children...
GetFilesInSolutionRecursive(nestedHierarchy,VSConstants.VSITEMID_ROOT,refNewProject,refSolutionFilenames);
}
}
}
else
{
stringprojectFilename="";
try
{
if(Project.GetMkDocument(visibleChildNodeId,outprojectFilename)==VSConstants.S_OK)
{
if((projectFilename!=null)&&(projectFilename.Length>0)&&
(!projectFilename.EndsWith("\\"))&&// some invalid "filenames" will end with '\\'
(projectFilename.IndexOfAny(InvalidChars)==-1)&&
// (File.Exists(projectFilename))) // File.Exists is too slow for very large projects (thousands of files)
(projectFilename.IndexOf(":",StringComparison.OrdinalIgnoreCase)==1))// make sure filename is of the form: drive letter followed by colon
{
SolutionFilenames.Add(projectFilename);
}
}
}
catch(Exceptionex)
{
Console.WriteLine("Exception: {0}",ex.Message);
}
objectNodeChildObject=null;
// see if this regular node has children...
if(hierarchy.GetProperty(visibleChildNodeId,(int)__VSHPROPID.VSHPROPID_FirstVisibleChild,outNodeChildObject)==VSConstants.S_OK)
{
if(NodeChildObject!=null)
{
if((NodeChildObjectisint)&&((uint)(int)NodeChildObject!=VSConstants.VSITEMID_NIL))
{
// recurse into the regular node to handle children...
GetFilesInSolutionRecursive(hierarchy,visibleChildNodeId,refProject,refSolutionFilenames);
}
}
}
}
ChildObject=null;
// Get the next visible sibling node
if(hierarchy.GetProperty(visibleChildNodeId,(int)__VSHPROPID.VSHPROPID_NextVisibleSibling,outChildObject)!=VSConstants.S_OK)
{
break;
}
}
}
}
catch(Exceptionex)
{
Console.WriteLine("Exception: {0}",ex.Message);
}
}
}
}