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. AssetDatabase.Refresh();
  148. _generator.Sync();
  149. }
  150. bool IsSupportedPath(string path)
  151. {
  152. // Path is empty with "Open C# Project", as we only want to open the solution without specific files
  153. if (string.IsNullOrEmpty(path))
  154. return true;
  155. // cs, uxml, uss, shader, compute, cginc, hlsl, glslinc, template are part of Unity builtin extensions
  156. // txt, xml, fnt, cd are -often- par of Unity user extensions
  157. // asdmdef is mandatory included
  158. if (_generator.IsSupportedFile(path))
  159. return true;
  160. return false;
  161. }
  162. private static void CheckCurrentEditorInstallation()
  163. {
  164. var editorPath = CodeEditor.CurrentEditorInstallation;
  165. try
  166. {
  167. if (Discovery.TryDiscoverInstallation(editorPath, out _))
  168. return;
  169. }
  170. catch (IOException)
  171. {
  172. }
  173. UnityEngine.Debug.LogWarning($"Visual Studio executable {editorPath} is not found. Please change your settings in Edit > Preferences > External Tools.");
  174. }
  175. public bool OpenProject(string path, int line, int column)
  176. {
  177. CheckCurrentEditorInstallation();
  178. if (!IsSupportedPath(path))
  179. return false;
  180. if (!IsProjectGeneratedFor(path, out var missingFlag))
  181. 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.");
  182. if (IsOSX)
  183. return OpenOSXApp(path, line, column);
  184. if (IsWindows)
  185. return OpenWindowsApp(path, line);
  186. return false;
  187. }
  188. private static string GetProjectGenerationFlagDescription(ProjectGenerationFlag flag)
  189. {
  190. switch (flag)
  191. {
  192. case ProjectGenerationFlag.BuiltIn:
  193. return "Built-in packages";
  194. case ProjectGenerationFlag.Embedded:
  195. return "Embedded packages";
  196. case ProjectGenerationFlag.Git:
  197. return "Git packages";
  198. case ProjectGenerationFlag.Local:
  199. return "Local packages";
  200. case ProjectGenerationFlag.LocalTarBall:
  201. return "Local tarball";
  202. case ProjectGenerationFlag.PlayerAssemblies:
  203. return "Player projects";
  204. case ProjectGenerationFlag.Registry:
  205. return "Registry packages";
  206. case ProjectGenerationFlag.Unknown:
  207. return "Packages from unknown sources";
  208. default:
  209. return string.Empty;
  210. }
  211. }
  212. private bool IsProjectGeneratedFor(string path, out ProjectGenerationFlag missingFlag)
  213. {
  214. missingFlag = ProjectGenerationFlag.None;
  215. // No need to check when opening the whole solution
  216. if (string.IsNullOrEmpty(path))
  217. return true;
  218. // We only want to check for cs scripts
  219. if (ProjectGeneration.ScriptingLanguageForFile(path) != ScriptingLanguage.CSharp)
  220. return true;
  221. // Even on windows, the package manager requires relative path + unix style separators for queries
  222. var basePath = _generator.ProjectDirectory;
  223. var relativePath = FileUtility
  224. .NormalizeWindowsToUnix(path)
  225. .Replace(basePath, string.Empty)
  226. .Trim(FileUtility.UnixSeparator);
  227. var packageInfo = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(relativePath);
  228. if (packageInfo == null)
  229. return true;
  230. var source = packageInfo.source;
  231. if (!Enum.TryParse<ProjectGenerationFlag>(source.ToString(), out var flag))
  232. return true;
  233. if (_generator.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(flag))
  234. return true;
  235. // Return false if we found a source not flagged for generation
  236. missingFlag = flag;
  237. return false;
  238. }
  239. private bool OpenWindowsApp(string path, int line)
  240. {
  241. var progpath = FileUtility.GetPackageAssetFullPath("Editor", "COMIntegration", "Release", "COMIntegration.exe");
  242. if (string.IsNullOrWhiteSpace(progpath))
  243. return false;
  244. string absolutePath = "";
  245. if (!string.IsNullOrWhiteSpace(path))
  246. {
  247. absolutePath = Path.GetFullPath(path);
  248. }
  249. // We remove all invalid chars from the solution filename, but we cannot prevent the user from using a specific path for the Unity project
  250. // So process the fullpath to make it compatible with VS
  251. var solution = GetOrGenerateSolutionFile(path);
  252. if (!string.IsNullOrWhiteSpace(solution))
  253. {
  254. solution = $"\"{solution}\"";
  255. solution = solution.Replace("^", "^^");
  256. }
  257. var process = new Process
  258. {
  259. StartInfo = new ProcessStartInfo
  260. {
  261. FileName = progpath,
  262. Arguments = $"\"{CodeEditor.CurrentEditorInstallation}\" {solution} \"{absolutePath}\" {line}",
  263. CreateNoWindow = true,
  264. UseShellExecute = false,
  265. RedirectStandardOutput = true,
  266. RedirectStandardError = true,
  267. }
  268. };
  269. var result = process.Start();
  270. while (!process.StandardOutput.EndOfStream)
  271. {
  272. var outputLine = process.StandardOutput.ReadLine();
  273. if (outputLine == "displayProgressBar")
  274. {
  275. EditorUtility.DisplayProgressBar("Opening Visual Studio", "Starting up Visual Studio, this might take some time.", .5f);
  276. }
  277. if (outputLine == "clearprogressbar")
  278. {
  279. EditorUtility.ClearProgressBar();
  280. }
  281. }
  282. var errorOutput = process.StandardError.ReadToEnd();
  283. if (!string.IsNullOrEmpty(errorOutput))
  284. {
  285. Console.WriteLine("Error: \n" + errorOutput);
  286. }
  287. process.WaitForExit();
  288. return result;
  289. }
  290. [DllImport("AppleEventIntegration")]
  291. static extern bool OpenVisualStudio(string appPath, string solutionPath, string filePath, int line);
  292. bool OpenOSXApp(string path, int line, int column)
  293. {
  294. string absolutePath = "";
  295. if (!string.IsNullOrWhiteSpace(path))
  296. {
  297. absolutePath = Path.GetFullPath(path);
  298. }
  299. var solution = GetOrGenerateSolutionFile(path);
  300. return OpenVisualStudio(CodeEditor.CurrentEditorInstallation, solution, absolutePath, line);
  301. }
  302. private string GetOrGenerateSolutionFile(string path)
  303. {
  304. _generator.Sync();
  305. return _generator.SolutionFile();
  306. }
  307. }
  308. }