VisualStudioEditor.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Unity Technologies.
  3. * Copyright (c) Microsoft Corporation. All rights reserved.
  4. * Licensed under the MIT License. See License.txt in the project root for license information.
  5. *--------------------------------------------------------------------------------------------*/
  6. using System;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Runtime.InteropServices;
  11. using System.Runtime.CompilerServices;
  12. using UnityEditor;
  13. using UnityEngine;
  14. using Unity.CodeEditor;
  15. [assembly: InternalsVisibleTo("Unity.VisualStudio.EditorTests")]
  16. [assembly: InternalsVisibleTo("Unity.VisualStudio.Standalone.EditorTests")]
  17. [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
  18. namespace Microsoft.Unity.VisualStudio.Editor
  19. {
  20. [InitializeOnLoad]
  21. public class VisualStudioEditor : IExternalCodeEditor
  22. {
  23. internal static bool IsOSX => Application.platform == RuntimePlatform.OSXEditor;
  24. internal static bool IsWindows => !IsOSX && Path.DirectorySeparatorChar == FileUtility.WinSeparator && Environment.NewLine == "\r\n";
  25. CodeEditor.Installation[] IExternalCodeEditor.Installations => _discoverInstallations.Result
  26. .Select(i => i.ToCodeEditorInstallation())
  27. .ToArray();
  28. private static readonly AsyncOperation<IVisualStudioInstallation[]> _discoverInstallations;
  29. private readonly IGenerator _generator = new ProjectGeneration();
  30. static VisualStudioEditor()
  31. {
  32. if (!UnityInstallation.IsMainUnityEditorProcess)
  33. return;
  34. if (IsWindows)
  35. Discovery.FindVSWhere();
  36. CodeEditor.Register(new VisualStudioEditor());
  37. _discoverInstallations = AsyncOperation<IVisualStudioInstallation[]>.Run(DiscoverInstallations);
  38. }
  39. private static IVisualStudioInstallation[] DiscoverInstallations()
  40. {
  41. try
  42. {
  43. return Discovery
  44. .GetVisualStudioInstallations()
  45. .ToArray();
  46. }
  47. catch (Exception ex)
  48. {
  49. UnityEngine.Debug.LogError($"Error detecting Visual Studio installations: {ex}");
  50. return Array.Empty<IVisualStudioInstallation>();
  51. }
  52. }
  53. internal static bool IsEnabled => CodeEditor.CurrentEditor is VisualStudioEditor && UnityInstallation.IsMainUnityEditorProcess;
  54. // this one seems legacy and not used anymore
  55. // keeping it for now given it is public, so we need a major bump to remove it
  56. public void CreateIfDoesntExist()
  57. {
  58. if (!_generator.HasSolutionBeenGenerated())
  59. _generator.Sync();
  60. }
  61. public void Initialize(string editorInstallationPath)
  62. {
  63. }
  64. internal virtual bool TryGetVisualStudioInstallationForPath(string editorPath, bool searchInstallations, out IVisualStudioInstallation installation)
  65. {
  66. if (searchInstallations)
  67. {
  68. // lookup for well known installations
  69. foreach (var candidate in _discoverInstallations.Result)
  70. {
  71. if (!string.Equals(Path.GetFullPath(editorPath), Path.GetFullPath(candidate.Path), StringComparison.OrdinalIgnoreCase))
  72. continue;
  73. installation = candidate;
  74. return true;
  75. }
  76. }
  77. return Discovery.TryDiscoverInstallation(editorPath, out installation);
  78. }
  79. public virtual bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation)
  80. {
  81. var result = TryGetVisualStudioInstallationForPath(editorPath, searchInstallations: false, out var vsi);
  82. installation = vsi == null ? default : vsi.ToCodeEditorInstallation();
  83. return result;
  84. }
  85. public void OnGUI()
  86. {
  87. GUILayout.BeginHorizontal();
  88. GUILayout.FlexibleSpace();
  89. var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(GetType().Assembly);
  90. var style = new GUIStyle
  91. {
  92. richText = true,
  93. margin = new RectOffset(0, 4, 0, 0)
  94. };
  95. GUILayout.Label($"<size=10><color=grey>{package.displayName} v{package.version} enabled</color></size>", style);
  96. GUILayout.EndHorizontal();
  97. EditorGUILayout.LabelField("Generate .csproj files for:");
  98. EditorGUI.indentLevel++;
  99. SettingsButton(ProjectGenerationFlag.Embedded, "Embedded packages", "");
  100. SettingsButton(ProjectGenerationFlag.Local, "Local packages", "");
  101. SettingsButton(ProjectGenerationFlag.Registry, "Registry packages", "");
  102. SettingsButton(ProjectGenerationFlag.Git, "Git packages", "");
  103. SettingsButton(ProjectGenerationFlag.BuiltIn, "Built-in packages", "");
  104. SettingsButton(ProjectGenerationFlag.LocalTarBall, "Local tarball", "");
  105. SettingsButton(ProjectGenerationFlag.Unknown, "Packages from unknown sources", "");
  106. SettingsButton(ProjectGenerationFlag.PlayerAssemblies, "Player projects", "For each player project generate an additional csproj with the name 'project-player.csproj'");
  107. RegenerateProjectFiles();
  108. EditorGUI.indentLevel--;
  109. }
  110. void RegenerateProjectFiles()
  111. {
  112. var rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(new GUILayoutOption[] { }));
  113. rect.width = 252;
  114. if (GUI.Button(rect, "Regenerate project files"))
  115. {
  116. _generator.Sync();
  117. }
  118. }
  119. void SettingsButton(ProjectGenerationFlag preference, string guiMessage, string toolTip)
  120. {
  121. var prevValue = _generator.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(preference);
  122. var newValue = EditorGUILayout.Toggle(new GUIContent(guiMessage, toolTip), prevValue);
  123. if (newValue != prevValue)
  124. {
  125. _generator.AssemblyNameProvider.ToggleProjectGeneration(preference);
  126. }
  127. }
  128. public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, string[] importedFiles)
  129. {
  130. _generator.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles), importedFiles);
  131. foreach (var file in importedFiles.Where(a => Path.GetExtension(a) == ".pdb"))
  132. {
  133. var pdbFile = FileUtility.GetAssetFullPath(file);
  134. // skip Unity packages like com.unity.ext.nunit
  135. if (pdbFile.IndexOf($"{Path.DirectorySeparatorChar}com.unity.", StringComparison.OrdinalIgnoreCase) > 0)
  136. continue;
  137. var asmFile = Path.ChangeExtension(pdbFile, ".dll");
  138. if (!File.Exists(asmFile) || !Image.IsAssembly(asmFile))
  139. continue;
  140. if (Symbols.IsPortableSymbolFile(pdbFile))
  141. continue;
  142. UnityEngine.Debug.LogWarning($"Unity is only able to load mdb or portable-pdb symbols. {file} is using a legacy pdb format.");
  143. }
  144. }
  145. public void SyncAll()
  146. {
  147. _generator.Sync();
  148. }
  149. bool IsSupportedPath(string path)
  150. {
  151. // Path is empty with "Open C# Project", as we only want to open the solution without specific files
  152. if (string.IsNullOrEmpty(path))
  153. return true;
  154. // cs, uxml, uss, shader, compute, cginc, hlsl, glslinc, template are part of Unity builtin extensions
  155. // txt, xml, fnt, cd are -often- par of Unity user extensions
  156. // asdmdef is mandatory included
  157. if (_generator.IsSupportedFile(path))
  158. return true;
  159. return false;
  160. }
  161. private static void CheckCurrentEditorInstallation()
  162. {
  163. var editorPath = CodeEditor.CurrentEditorInstallation;
  164. try
  165. {
  166. if (Discovery.TryDiscoverInstallation(editorPath, out _))
  167. return;
  168. }
  169. catch (IOException)
  170. {
  171. }
  172. UnityEngine.Debug.LogWarning($"Visual Studio executable {editorPath} is not found. Please change your settings in Edit > Preferences > External Tools.");
  173. }
  174. public bool OpenProject(string path, int line, int column)
  175. {
  176. CheckCurrentEditorInstallation();
  177. if (!IsSupportedPath(path))
  178. return false;
  179. if (!IsProjectGeneratedFor(path, out var missingFlag))
  180. UnityEngine.Debug.LogWarning($"You are trying to open {path} outside a generated project. This might cause problems with IntelliSense and debugging. To avoid this, you can change your .csproj preferences in Edit > Preferences > External Tools and enable {GetProjectGenerationFlagDescription(missingFlag)} generation.");
  181. if (IsOSX)
  182. return OpenOSXApp(path, line, column);
  183. if (IsWindows)
  184. return OpenWindowsApp(path, line);
  185. return false;
  186. }
  187. private static string GetProjectGenerationFlagDescription(ProjectGenerationFlag flag)
  188. {
  189. switch (flag)
  190. {
  191. case ProjectGenerationFlag.BuiltIn:
  192. return "Built-in packages";
  193. case ProjectGenerationFlag.Embedded:
  194. return "Embedded packages";
  195. case ProjectGenerationFlag.Git:
  196. return "Git packages";
  197. case ProjectGenerationFlag.Local:
  198. return "Local packages";
  199. case ProjectGenerationFlag.LocalTarBall:
  200. return "Local tarball";
  201. case ProjectGenerationFlag.PlayerAssemblies:
  202. return "Player projects";
  203. case ProjectGenerationFlag.Registry:
  204. return "Registry packages";
  205. case ProjectGenerationFlag.Unknown:
  206. return "Packages from unknown sources";
  207. default:
  208. return string.Empty;
  209. }
  210. }
  211. private bool IsProjectGeneratedFor(string path, out ProjectGenerationFlag missingFlag)
  212. {
  213. missingFlag = ProjectGenerationFlag.None;
  214. // No need to check when opening the whole solution
  215. if (string.IsNullOrEmpty(path))
  216. return true;
  217. // We only want to check for cs scripts
  218. if (ProjectGeneration.ScriptingLanguageForFile(path) != ScriptingLanguage.CSharp)
  219. return true;
  220. // Even on windows, the package manager requires relative path + unix style separators for queries
  221. var basePath = _generator.ProjectDirectory;
  222. var relativePath = FileUtility
  223. .NormalizeWindowsToUnix(path)
  224. .Replace(basePath, string.Empty)
  225. .Trim(FileUtility.UnixSeparator);
  226. var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(relativePath);
  227. if (packageInfo == null)
  228. return true;
  229. var source = packageInfo.source;
  230. if (!Enum.TryParse<ProjectGenerationFlag>(source.ToString(), out var flag))
  231. return true;
  232. if (_generator.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(flag))
  233. return true;
  234. // Return false if we found a source not flagged for generation
  235. missingFlag = flag;
  236. return false;
  237. }
  238. private bool OpenWindowsApp(string path, int line)
  239. {
  240. var progpath = FileUtility.GetPackageAssetFullPath("Editor", "COMIntegration", "Release", "COMIntegration.exe");
  241. if (string.IsNullOrWhiteSpace(progpath))
  242. return false;
  243. string absolutePath = "";
  244. if (!string.IsNullOrWhiteSpace(path))
  245. {
  246. absolutePath = Path.GetFullPath(path);
  247. }
  248. // We remove all invalid chars from the solution filename, but we cannot prevent the user from using a specific path for the Unity project
  249. // So process the fullpath to make it compatible with VS
  250. var solution = GetOrGenerateSolutionFile(path);
  251. if (!string.IsNullOrWhiteSpace(solution))
  252. {
  253. solution = $"\"{solution}\"";
  254. solution = solution.Replace("^", "^^");
  255. }
  256. var process = new Process
  257. {
  258. StartInfo = new ProcessStartInfo
  259. {
  260. FileName = progpath,
  261. Arguments = $"\"{CodeEditor.CurrentEditorInstallation}\" {solution} \"{absolutePath}\" {line}",
  262. CreateNoWindow = true,
  263. UseShellExecute = false,
  264. RedirectStandardOutput = true,
  265. StandardOutputEncoding = System.Text.Encoding.Unicode,
  266. RedirectStandardError = true,
  267. StandardErrorEncoding = System.Text.Encoding.Unicode,
  268. }
  269. };
  270. var result = process.Start();
  271. while (!process.StandardOutput.EndOfStream)
  272. {
  273. var outputLine = process.StandardOutput.ReadLine();
  274. if (outputLine == "displayProgressBar")
  275. {
  276. EditorUtility.DisplayProgressBar("Opening Visual Studio", "Starting up Visual Studio, this might take some time.", .5f);
  277. }
  278. if (outputLine == "clearprogressbar")
  279. {
  280. EditorUtility.ClearProgressBar();
  281. }
  282. }
  283. var errorOutput = process.StandardError.ReadToEnd();
  284. if (!string.IsNullOrEmpty(errorOutput))
  285. {
  286. Console.WriteLine("Error: \n" + errorOutput);
  287. }
  288. process.WaitForExit();
  289. return result;
  290. }
  291. [DllImport("AppleEventIntegration")]
  292. static extern bool OpenVisualStudio(string appPath, string solutionPath, string filePath, int line);
  293. bool OpenOSXApp(string path, int line, int column)
  294. {
  295. string absolutePath = "";
  296. if (!string.IsNullOrWhiteSpace(path))
  297. {
  298. absolutePath = Path.GetFullPath(path);
  299. }
  300. var solution = GetOrGenerateSolutionFile(path);
  301. return OpenVisualStudio(CodeEditor.CurrentEditorInstallation, solution, absolutePath, line);
  302. }
  303. private string GetOrGenerateSolutionFile(string path)
  304. {
  305. _generator.Sync();
  306. return _generator.SolutionFile();
  307. }
  308. }
  309. }