-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathVisualStudioForWindowsInstallation.cs
380 lines (315 loc) · 10.8 KB
/
VisualStudioForWindowsInstallation.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
#if UNITY_EDITOR_WIN
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using Unity.CodeEditor;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
using IOPath = System.IO.Path;
namespace Microsoft.Unity.VisualStudio.Editor
{
internal class VisualStudioForWindowsInstallation : VisualStudioInstallation
{
// C# language version support for Visual Studio
private static readonly VersionPair[] WindowsVersionTable =
{
// VisualStudio 2022
new VersionPair(17,4, /* => */ 11,0),
new VersionPair(17,0, /* => */ 10,0),
// VisualStudio 2019
new VersionPair(16,8, /* => */ 9,0),
new VersionPair(16,0, /* => */ 8,0),
// VisualStudio 2017
new VersionPair(15,7, /* => */ 7,3),
new VersionPair(15,5, /* => */ 7,2),
new VersionPair(15,3, /* => */ 7,1),
new VersionPair(15,0, /* => */ 7,0),
};
private static string _vsWherePath = null;
private static readonly IGenerator _generator = new LegacyStyleProjectGeneration();
public override bool SupportsAnalyzers
{
get
{
return Version >= new Version(16, 3);
}
}
public override Version LatestLanguageVersionSupported
{
get
{
return GetLatestLanguageVersionSupported(WindowsVersionTable);
}
}
private static string ReadRegistry(RegistryKey hive, string keyName, string valueName)
{
try
{
var unitykey = hive.OpenSubKey(keyName);
var result = (string)unitykey?.GetValue(valueName);
return result;
}
catch (Exception)
{
return null;
}
}
private string GetWindowsBridgeFromRegistry()
{
var keyName = $"Software\\Microsoft\\Microsoft Visual Studio {Version.Major}.0 Tools for Unity";
const string valueName = "UnityExtensionPath";
var bridge = ReadRegistry(Registry.CurrentUser, keyName, valueName);
if (string.IsNullOrEmpty(bridge))
bridge = ReadRegistry(Registry.LocalMachine, keyName, valueName);
return bridge;
}
private string GetExtensionPath()
{
const string extensionName = "Visual Studio Tools for Unity";
const string extensionAssembly = "SyntaxTree.VisualStudio.Unity.dll";
var vsDirectory = IOPath.GetDirectoryName(Path);
var vstuDirectory = IOPath.Combine(vsDirectory, "Extensions", "Microsoft", extensionName);
if (File.Exists(IOPath.Combine(vstuDirectory, extensionAssembly)))
return vstuDirectory;
return null;
}
public override string[] GetAnalyzers()
{
var vstuPath = GetExtensionPath();
if (string.IsNullOrEmpty(vstuPath))
return Array.Empty<string>();
var analyzers = GetAnalyzers(vstuPath);
if (analyzers?.Length > 0)
return analyzers;
var bridge = GetWindowsBridgeFromRegistry();
if (File.Exists(bridge))
return GetAnalyzers(IOPath.Combine(IOPath.GetDirectoryName(bridge), ".."));
return Array.Empty<string>();
}
public override IGenerator ProjectGenerator
{
get
{
return _generator;
}
}
private static bool IsCandidateForDiscovery(string path)
{
return File.Exists(path) && Regex.IsMatch(path, "devenv.exe$", RegexOptions.IgnoreCase);
}
public static bool TryDiscoverInstallation(string editorPath, out IVisualStudioInstallation installation)
{
installation = null;
if (string.IsNullOrEmpty(editorPath))
return false;
if (!IsCandidateForDiscovery(editorPath))
return false;
// On windows we use the executable directly, so we can query extra information
if (!File.Exists(editorPath))
return false;
// VS preview are not using the isPrerelease flag so far
// On Windows FileDescription contains "Preview", but not on Mac
var vi = FileVersionInfo.GetVersionInfo(editorPath);
var version = new Version(vi.ProductVersion);
var isPrerelease = vi.IsPreRelease || string.Concat(editorPath, "/" + vi.FileDescription).ToLower().Contains("preview");
installation = new VisualStudioForWindowsInstallation()
{
IsPrerelease = isPrerelease,
Name = $"{FormatProductName(vi.FileDescription)} [{version.ToString(3)}]",
Path = editorPath,
Version = version
};
return true;
}
public static string FormatProductName(string productName)
{
if (string.IsNullOrEmpty(productName))
return string.Empty;
return productName.Replace("Microsoft ", string.Empty);
}
public static IEnumerable<IVisualStudioInstallation> GetVisualStudioInstallations()
{
foreach (var installation in QueryVsWhere())
yield return installation;
}
#region VsWhere Json Schema
#pragma warning disable CS0649
[Serializable]
internal class VsWhereResult
{
public VsWhereEntry[] entries;
public static VsWhereResult FromJson(string json)
{
return JsonUtility.FromJson<VsWhereResult>("{ \"" + nameof(VsWhereResult.entries) + "\": " + json + " }");
}
public IEnumerable<VisualStudioInstallation> ToVisualStudioInstallations()
{
foreach (var entry in entries)
{
yield return new VisualStudioForWindowsInstallation
{
Name = $"{FormatProductName(entry.displayName)} [{entry.catalog.productDisplayVersion}]",
Path = entry.productPath,
IsPrerelease = entry.isPrerelease,
Version = Version.Parse(entry.catalog.buildVersion)
};
}
}
}
[Serializable]
internal class VsWhereEntry
{
public string displayName;
public bool isPrerelease;
public string productPath;
public VsWhereCatalog catalog;
}
[Serializable]
internal class VsWhereCatalog
{
public string productDisplayVersion; // non parseable like "16.3.0 Preview 3.0"
public string buildVersion;
}
#pragma warning restore CS3021
#endregion
private static IEnumerable<VisualStudioInstallation> QueryVsWhere()
{
var progpath = _vsWherePath;
if (string.IsNullOrWhiteSpace(progpath))
return Enumerable.Empty<VisualStudioInstallation>();
const string arguments = "-prerelease -format json";
// We've seen issues with json parsing in utf8 mode and with specific non-UTF code pages like 949 (Korea)
// So try with utf8 first, then fallback to non utf8 in case of an issue
// See https://github.com/microsoft/vswhere/issues/264
try
{
return QueryVsWhere(progpath, $"{arguments} -utf8");
}
catch
{
return QueryVsWhere(progpath, $"{arguments}");
}
}
private static IEnumerable<VisualStudioInstallation> QueryVsWhere(string progpath, string arguments)
{
var result = ProcessRunner.StartAndWaitForExit(progpath, arguments);
if (!result.Success)
throw new Exception($"Failure while running vswhere: {result.Error}");
// Do not catch any JsonException here, this will be handled by the caller
return VsWhereResult
.FromJson(result.Output)
.ToVisualStudioInstallations();
}
private enum COMIntegrationState
{
Running,
DisplayProgressBar,
ClearProgressBar,
Exited
}
public override void CreateExtraFiles(string projectDirectory)
{
// See https://devblogs.microsoft.com/setup/configure-visual-studio-across-your-organization-with-vsconfig/
// We create a .vsconfig file to make sure our ManagedGame workload is installed
try
{
var vsConfigFile = IOPath.Combine(projectDirectory.NormalizePathSeparators(), ".vsconfig");
if (File.Exists(vsConfigFile))
return;
const string content = @"{
""version"": ""1.0"",
""components"": [
""Microsoft.VisualStudio.Workload.ManagedGame""
]
}
";
File.WriteAllText(vsConfigFile, content);
}
catch (IOException)
{
}
}
public override bool Open(string path, int line, int column, string solution)
{
var progpath = FileUtility.GetPackageAssetFullPath("Editor", "COMIntegration", "Release", "COMIntegration.exe");
if (string.IsNullOrWhiteSpace(progpath))
return false;
string absolutePath = "";
if (!string.IsNullOrWhiteSpace(path))
{
absolutePath = IOPath.GetFullPath(path);
}
// We remove all invalid chars from the solution filename, but we cannot prevent the user from using a specific path for the Unity project
// So process the fullpath to make it compatible with VS
if (!string.IsNullOrWhiteSpace(solution))
{
solution = $"\"{solution}\"";
solution = solution.Replace("^", "^^");
}
var psi = ProcessRunner.ProcessStartInfoFor(progpath, $"\"{CodeEditor.CurrentEditorInstallation}\" {solution} \"{absolutePath}\" {line}");
psi.StandardOutputEncoding = System.Text.Encoding.Unicode;
psi.StandardErrorEncoding = System.Text.Encoding.Unicode;
// inter thread communication
var messages = new BlockingCollection<COMIntegrationState>();
var asyncStart = AsyncOperation<ProcessRunnerResult>.Run(
() => ProcessRunner.StartAndWaitForExit(psi, onOutputReceived: data => OnOutputReceived(data, messages)),
e => new ProcessRunnerResult {Success = false, Error = e.Message, Output = string.Empty},
() => messages.Add(COMIntegrationState.Exited)
);
MonitorCOMIntegration(messages);
var result = asyncStart.Result;
if (!result.Success && !string.IsNullOrWhiteSpace(result.Error))
Debug.LogError($"Error while starting Visual Studio: {result.Error}");
return result.Success;
}
private static void MonitorCOMIntegration(BlockingCollection<COMIntegrationState> messages)
{
var displayingProgress = false;
COMIntegrationState state;
do
{
state = messages.Take();
switch (state)
{
case COMIntegrationState.ClearProgressBar:
EditorUtility.ClearProgressBar();
displayingProgress = false;
break;
case COMIntegrationState.DisplayProgressBar:
EditorUtility.DisplayProgressBar("Opening Visual Studio", "Starting up Visual Studio, this might take some time.", .5f);
displayingProgress = true;
break;
}
} while (state != COMIntegrationState.Exited);
// Make sure the progress bar is properly cleared in case of COMIntegration failure
if (displayingProgress)
EditorUtility.ClearProgressBar();
}
private static readonly COMIntegrationState[] ProgressBarCommands = {COMIntegrationState.DisplayProgressBar, COMIntegrationState.ClearProgressBar};
private static void OnOutputReceived(string data, BlockingCollection<COMIntegrationState> messages)
{
if (data == null)
return;
foreach (var cmd in ProgressBarCommands)
{
if (data.IndexOf(cmd.ToString(), StringComparison.OrdinalIgnoreCase) >= 0)
messages.Add(cmd);
}
}
public static void Initialize()
{
_vsWherePath = FileUtility.GetPackageAssetFullPath("Editor", "VSWhere", "vswhere.exe");
}
}
}
#endif