Debian Codegraph @

modules/mono/editor/GodotTools/GodotTools.OpenVisualStudio/Program.cs

raw symbols SCIP
1 using System;
2 using System.IO;
3 using System.Runtime.InteropServices;
4 using System.Runtime.InteropServices.ComTypes;
5 using System.Text.RegularExpressions;
6 using EnvDTE;
7
8 namespace GodotTools.OpenVisualStudio
9 {
10 internal static class Program
11 {
12 [DllImport("ole32.dll")]
13 private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable pprot);
14
15 [DllImport("ole32.dll")]
16 private static extern void CreateBindCtx(int reserved, out IBindCtx ppbc);
17
18 [DllImport("user32.dll")]
19 private static extern bool SetForegroundWindow(IntPtr hWnd);
20
21 private static void ShowHelp()
22 {
23 Console.WriteLine("Opens the file(s) in a Visual Studio instance that is editing the specified solution.");
24 Console.WriteLine("If an existing instance for the solution is not found, a new one is created.");
25 Console.WriteLine();
26 Console.WriteLine("Usage:");
27 Console.WriteLine(@" GodotTools.OpenVisualStudio.exe solution [file[;line[;col]]...]");
28 Console.WriteLine();
29 Console.WriteLine("Lines and columns begin at one. Zero or lower will result in an error.");
30 Console.WriteLine("If a line is specified but a column is not, the line is selected in the text editor.");
31 }
32
33 // STAThread needed, otherwise CoRegisterMessageFilter may return CO_E_NOT_SUPPORTED.
34 [STAThread]
35 private static int Main(string[] args)
36 {
37 if (args.Length == 0 || args[0] == "--help" || args[0] == "-h")
38 {
39 ShowHelp();
40 return 0;
41 }
42
43 string solutionFile = NormalizePath(args[0]);
44
45 var dte = FindInstanceEditingSolution(solutionFile);
46
47 if (dte == null)
48 {
49 dte = TryVisualStudioLaunch("VisualStudio.DTE.18.0") // Visual Studio 18 (2026).
50 ?? TryVisualStudioLaunch("VisualStudio.DTE.17.0"); // Visual Studio 17 (2022).
51
52 if (dte == null)
53 {
54 Console.Error.WriteLine("Could not find a supported Visual Studio version (VS 2026 or VS 2022).");
55 return 1;
56 }
57
58 dte.UserControl = true;
59
60 try
61 {
62 dte.Solution.Open(solutionFile);
63 }
64 catch (ArgumentException)
65 {
66 Console.Error.WriteLine("Solution.Open: Invalid path or file not found");
67 return 1;
68 }
69
70 dte.MainWindow.Visible = true;
71 }
72
73 MessageFilter.Register();
74
75 try
76 {
77 // Open files
78
79 for (int i = 1; i < args.Length; i++)
80 {
81 // Both the line number and the column begin at one
82
83 string[] fileArgumentParts = args[i].Split(';');
84
85 string filePath = NormalizePath(fileArgumentParts[0]);
86
87 try
88 {
89 dte.ItemOperations.OpenFile(filePath);
90 }
91 catch (ArgumentException)
92 {
93 Console.Error.WriteLine("ItemOperations.OpenFile: Invalid path or file not found");
94 return 1;
95 }
96
97 if (fileArgumentParts.Length > 1)
98 {
99 if (int.TryParse(fileArgumentParts[1], out int line))
100 {
101 var textSelection = (TextSelection)dte.ActiveDocument.Selection;
102
103 if (fileArgumentParts.Length > 2)
104 {
105 if (int.TryParse(fileArgumentParts[2], out int column))
106 {
107 textSelection.MoveToLineAndOffset(line, column);
108 }
109 else
110 {
111 Console.Error.WriteLine("The column part of the argument must be a valid integer");
112 return 1;
113 }
114 }
115 else
116 {
117 textSelection.GotoLine(line, Select: true);
118 }
119 }
120 else
121 {
122 Console.Error.WriteLine("The line part of the argument must be a valid integer");
123 return 1;
124 }
125 }
126 }
127 }
128 finally
129 {
130 var mainWindow = dte.MainWindow;
131 mainWindow.Activate();
132 SetForegroundWindow(mainWindow.HWnd);
133
134 MessageFilter.Revoke();
135 }
136
137 return 0;
138 }
139
140 private static DTE? TryVisualStudioLaunch(string version)
141 {
142 try
143 {
144 var visualStudioDteType = Type.GetTypeFromProgID(version, throwOnError: true);
145 var dte = (DTE?)Activator.CreateInstance(visualStudioDteType!);
146
147 return dte;
148 }
149 catch (COMException)
150 {
151 return null;
152 }
153 }
154
155 private static DTE? FindInstanceEditingSolution(string solutionPath)
156 {
157 if (GetRunningObjectTable(0, out IRunningObjectTable pprot) != 0)
158 return null;
159
160 try
161 {
162 pprot.EnumRunning(out IEnumMoniker ppenumMoniker);
163 ppenumMoniker.Reset();
164
165 var moniker = new IMoniker[1];
166
167 while (ppenumMoniker.Next(1, moniker, IntPtr.Zero) == 0)
168 {
169 string ppszDisplayName;
170
171 CreateBindCtx(0, out IBindCtx ppbc);
172
173 try
174 {
175 moniker[0].GetDisplayName(ppbc, null, out ppszDisplayName);
176 }
177 finally
178 {
179 Marshal.ReleaseComObject(ppbc);
180 }
181
182 if (ppszDisplayName == null)
183 continue;
184
185 // The digits after the colon are the process ID.
186 if (!Regex.IsMatch(ppszDisplayName, "!VisualStudio.DTE.1[7-8].0:[0-9]"))
187 continue;
188
189 if (pprot.GetObject(moniker[0], out object ppunkObject) == 0)
190 {
191 if (ppunkObject is DTE dte && dte.Solution.FullName.Length > 0)
192 {
193 if (NormalizePath(dte.Solution.FullName) == solutionPath)
194 return dte;
195 }
196 }
197 }
198 }
199 finally
200 {
201 Marshal.ReleaseComObject(pprot);
202 }
203
204 return null;
205 }
206
207 private static string NormalizePath(string path)
208 {
209 return new Uri(Path.GetFullPath(path)).LocalPath
210 .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
211 .ToUpperInvariant();
212 }
213
214 #region MessageFilter. See: http: //msdn.microsoft.com/en-us/library/ms228772.aspx
215
216 private class MessageFilter : IOleMessageFilter
217 {
218 // Class containing the IOleMessageFilter
219 // thread error-handling functions
220
221 private static IOleMessageFilter? _oldFilter;
222
223 // Start the filter
224 public static void Register()
225 {
226 IOleMessageFilter newFilter = new MessageFilter();
227 int ret = CoRegisterMessageFilter(newFilter, out _oldFilter);
228 if (ret != 0)
229 Console.Error.WriteLine($"CoRegisterMessageFilter failed with error code: {ret}");
230 }
231
232 // Done with the filter, close it
233 public static void Revoke()
234 {
235 int ret = CoRegisterMessageFilter(_oldFilter, out _);
236 if (ret != 0)
237 Console.Error.WriteLine($"CoRegisterMessageFilter failed with error code: {ret}");
238 }
239
240 //
241 // IOleMessageFilter functions
242 // Handle incoming thread requests
243 int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
244 {
245 // Return the flag SERVERCALL_ISHANDLED
246 return 0;
247 }
248
249 // Thread call was rejected, so try again.
250 int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
251 {
252 // flag = SERVERCALL_RETRYLATER
253 if (dwRejectType == 2)
254 {
255 // Retry the thread call immediately if return >= 0 & < 100
256 return 99;
257 }
258
259 // Too busy; cancel call
260 return -1;
261 }
262
263 int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
264 {
265 // Return the flag PENDINGMSG_WAITDEFPROCESS
266 return 2;
267 }
268
269 // Implement the IOleMessageFilter interface
270 [DllImport("ole32.dll")]
271 private static extern int CoRegisterMessageFilter(IOleMessageFilter? newFilter, out IOleMessageFilter? oldFilter);
272 }
273
274 [ComImport(), Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
275 private interface IOleMessageFilter
276 {
277 [PreserveSig]
278 public int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
279
280 [PreserveSig]
281 public int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
282
283 [PreserveSig]
284 public int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
285 }
286
287 #endregion
288 }
289 }