No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RiderScriptEditor.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using JetBrains.Annotations;
  6. using Packages.Rider.Editor.ProjectGeneration;
  7. using Packages.Rider.Editor.Util;
  8. using Unity.CodeEditor;
  9. using UnityEditor;
  10. using UnityEngine;
  11. using Debug = UnityEngine.Debug;
  12. namespace Packages.Rider.Editor
  13. {
  14. [InitializeOnLoad]
  15. internal class RiderScriptEditor : IExternalCodeEditor
  16. {
  17. IDiscovery m_Discoverability;
  18. static IGenerator m_ProjectGeneration;
  19. RiderInitializer m_Initiliazer = new RiderInitializer();
  20. static RiderScriptEditor()
  21. {
  22. try
  23. {
  24. // todo: make ProjectGeneration lazy
  25. var projectGeneration = new ProjectGeneration.ProjectGeneration();
  26. var editor = new RiderScriptEditor(new Discovery(), projectGeneration);
  27. CodeEditor.Register(editor);
  28. var path = GetEditorRealPath(CurrentEditor);
  29. if (IsRiderInstallation(path))
  30. {
  31. RiderPathLocator.RiderInfo[] installations = null;
  32. if (!RiderScriptEditorData.instance.initializedOnce)
  33. {
  34. installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
  35. // is likely outdated
  36. if (installations.Any() && installations.All(a => GetEditorRealPath(a.Path) != path))
  37. {
  38. if (RiderPathLocator.GetIsToolbox(path)) // is toolbox - update
  39. {
  40. var toolboxInstallations = installations.Where(a => a.IsToolbox).ToArray();
  41. if (toolboxInstallations.Any())
  42. {
  43. var newEditor = toolboxInstallations.Last().Path;
  44. CodeEditor.SetExternalScriptEditor(newEditor);
  45. path = newEditor;
  46. }
  47. else
  48. {
  49. var newEditor = installations.Last().Path;
  50. CodeEditor.SetExternalScriptEditor(newEditor);
  51. path = newEditor;
  52. }
  53. }
  54. else // is non toolbox - notify
  55. {
  56. var newEditorName = installations.Last().Presentation;
  57. Debug.LogWarning($"Consider updating External Editor in Unity to {newEditorName}.");
  58. }
  59. }
  60. ShowWarningOnUnexpectedScriptEditor(path);
  61. RiderScriptEditorData.instance.initializedOnce = true;
  62. }
  63. if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed
  64. {
  65. if (installations == null)
  66. installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
  67. if (installations.Any())
  68. {
  69. var newEditor = installations.Last().Path;
  70. CodeEditor.SetExternalScriptEditor(newEditor);
  71. path = newEditor;
  72. }
  73. }
  74. RiderScriptEditorData.instance.Init();
  75. editor.CreateSolutionIfDoesntExist();
  76. if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
  77. {
  78. editor.m_Initiliazer.Initialize(path);
  79. }
  80. // can't switch to non-deprecated api, because UnityEditor.Build.BuildPipelineInterfaces.processors is internal
  81. #pragma warning disable 618
  82. EditorUserBuildSettings.activeBuildTargetChanged += () =>
  83. #pragma warning restore 618
  84. {
  85. RiderScriptEditorData.instance.hasChanges = true;
  86. };
  87. }
  88. }
  89. catch (Exception e)
  90. {
  91. Debug.LogException(e);
  92. }
  93. }
  94. private static void ShowWarningOnUnexpectedScriptEditor(string path)
  95. {
  96. // Show warning, when Unity was started from Rider, but external editor is different https://github.com/JetBrains/resharper-unity/issues/1127
  97. try
  98. {
  99. var args = Environment.GetCommandLineArgs();
  100. var commandlineParser = new CommandLineParser(args);
  101. if (commandlineParser.Options.ContainsKey("-riderPath"))
  102. {
  103. var originRiderPath = commandlineParser.Options["-riderPath"];
  104. var originRealPath = GetEditorRealPath(originRiderPath);
  105. var originVersion = RiderPathLocator.GetBuildNumber(originRealPath);
  106. var version = RiderPathLocator.GetBuildNumber(path);
  107. if (originVersion != null && originVersion != version)
  108. {
  109. Debug.LogWarning("Unity was started by a version of Rider that is not the current default external editor. Advanced integration features cannot be enabled.");
  110. Debug.Log($"Unity was started by Rider {originVersion}, but external editor is set to: {path}");
  111. }
  112. }
  113. }
  114. catch (Exception e)
  115. {
  116. Debug.LogException(e);
  117. }
  118. }
  119. internal static string GetEditorRealPath(string path)
  120. {
  121. if (string.IsNullOrEmpty(path))
  122. {
  123. return path;
  124. }
  125. if (!FileSystemUtil.EditorPathExists(path))
  126. return path;
  127. if (SystemInfo.operatingSystemFamily != OperatingSystemFamily.Windows)
  128. {
  129. var realPath = FileSystemUtil.GetFinalPathName(path);
  130. // case of snap installation
  131. if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux)
  132. {
  133. if (new FileInfo(path).Name.ToLowerInvariant() == "rider" &&
  134. new FileInfo(realPath).Name.ToLowerInvariant() == "snap")
  135. {
  136. var snapInstallPath = "/snap/rider/current/bin/rider.sh";
  137. if (new FileInfo(snapInstallPath).Exists)
  138. return snapInstallPath;
  139. }
  140. }
  141. // in case of symlink
  142. return realPath;
  143. }
  144. return path;
  145. }
  146. public RiderScriptEditor(IDiscovery discovery, IGenerator projectGeneration)
  147. {
  148. m_Discoverability = discovery;
  149. m_ProjectGeneration = projectGeneration;
  150. }
  151. public void OnGUI()
  152. {
  153. if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
  154. {
  155. GUILayout.BeginHorizontal();
  156. var style = GUI.skin.label;
  157. var text = "Customize handled extensions in";
  158. EditorGUILayout.LabelField(text, style, GUILayout.Width(style.CalcSize(new GUIContent(text)).x));
  159. if (PluginSettings.LinkButton("Project Settings | Editor | Additional extensions to include"))
  160. {
  161. SettingsService.OpenProjectSettings("Project/Editor"); // how do I focus "Additional extensions to include"?
  162. }
  163. GUILayout.EndHorizontal();
  164. }
  165. EditorGUILayout.LabelField("Generate .csproj files for:");
  166. EditorGUI.indentLevel++;
  167. SettingsButton(ProjectGenerationFlag.Embedded, "Embedded packages", "");
  168. SettingsButton(ProjectGenerationFlag.Local, "Local packages", "");
  169. SettingsButton(ProjectGenerationFlag.Registry, "Registry packages", "");
  170. SettingsButton(ProjectGenerationFlag.Git, "Git packages", "");
  171. SettingsButton(ProjectGenerationFlag.BuiltIn, "Built-in packages", "");
  172. #if UNITY_2019_3_OR_NEWER
  173. SettingsButton(ProjectGenerationFlag.LocalTarBall, "Local tarball", "");
  174. #endif
  175. SettingsButton(ProjectGenerationFlag.Unknown, "Packages from unknown sources", "");
  176. SettingsButton(ProjectGenerationFlag.PlayerAssemblies, "Player projects", "For each player project generate an additional csproj with the name 'project-player.csproj'");
  177. RegenerateProjectFiles();
  178. EditorGUI.indentLevel--;
  179. }
  180. void RegenerateProjectFiles()
  181. {
  182. var rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(new GUILayoutOption[] {}));
  183. rect.width = 252;
  184. if (GUI.Button(rect, "Regenerate project files"))
  185. {
  186. m_ProjectGeneration.Sync();
  187. }
  188. }
  189. void SettingsButton(ProjectGenerationFlag preference, string guiMessage, string toolTip)
  190. {
  191. var prevValue = m_ProjectGeneration.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(preference);
  192. var newValue = EditorGUILayout.Toggle(new GUIContent(guiMessage, toolTip), prevValue);
  193. if (newValue != prevValue)
  194. {
  195. m_ProjectGeneration.AssemblyNameProvider.ToggleProjectGeneration(preference);
  196. }
  197. }
  198. public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles,
  199. string[] importedFiles)
  200. {
  201. m_ProjectGeneration.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles),
  202. importedFiles);
  203. }
  204. public void SyncAll()
  205. {
  206. AssetDatabase.Refresh();
  207. m_ProjectGeneration.SyncIfNeeded(new string[] { }, new string[] { });
  208. }
  209. [UsedImplicitly]
  210. public static void SyncSolution() // generate-the-sln-file-via-script-or-command-line
  211. {
  212. m_ProjectGeneration.Sync();
  213. }
  214. [UsedImplicitly] // called from Rider EditorPlugin with reflection
  215. public static void SyncIfNeeded(bool checkProjectFiles)
  216. {
  217. AssetDatabase.Refresh();
  218. m_ProjectGeneration.SyncIfNeeded(new string[] { }, new string[] { }, checkProjectFiles);
  219. }
  220. [UsedImplicitly]
  221. public static void SyncSolutionAndOpenExternalEditor()
  222. {
  223. m_ProjectGeneration.Sync();
  224. CodeEditor.CurrentEditor.OpenProject();
  225. }
  226. public void Initialize(string editorInstallationPath) // is called each time ExternalEditor is changed
  227. {
  228. var prevEditorBuildNumber = RiderScriptEditorData.instance.prevEditorBuildNumber;
  229. RiderScriptEditorData.instance.Invalidate(editorInstallationPath, true);
  230. if (prevEditorBuildNumber.ToVersion() != RiderScriptEditorData.instance.editorBuildNumber.ToVersion()) // in Unity 2019.3 any change in preference causes `Initialize` call
  231. {
  232. m_ProjectGeneration.Sync(); // regenerate csproj and sln for new editor
  233. if (prevEditorBuildNumber == null) // avoid reloading at first start
  234. return;
  235. #if UNITY_2019_3_OR_NEWER
  236. EditorUtility.RequestScriptReload(); // EditorPlugin would get loaded
  237. #else
  238. UnityEditorInternal.InternalEditorUtility.RequestScriptReload();
  239. #endif
  240. }
  241. }
  242. public bool OpenProject(string path, int line, int column)
  243. {
  244. var projectGeneration = (ProjectGeneration.ProjectGeneration) m_ProjectGeneration;
  245. // Assets - Open C# Project passes empty path here
  246. if (path != "" && !projectGeneration.HasValidExtension(path))
  247. {
  248. return false;
  249. }
  250. if (!IsUnityScript(path))
  251. {
  252. m_ProjectGeneration.SyncIfNeeded(affectedFiles: new string[] { }, new string[] { });
  253. var fastOpenResult = EditorPluginInterop.OpenFileDllImplementation(path, line, column);
  254. if (fastOpenResult)
  255. return true;
  256. }
  257. if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
  258. {
  259. return OpenOSXApp(path, line, column);
  260. }
  261. var solution = GetSolutionFile(path); // TODO: If solution file doesn't exist resync.
  262. solution = solution == "" ? "" : $"\"{solution}\"";
  263. var process = new Process
  264. {
  265. StartInfo = new ProcessStartInfo
  266. {
  267. FileName = CodeEditor.CurrentEditorInstallation,
  268. Arguments = $"{solution} -l {line} \"{path}\"",
  269. UseShellExecute = true,
  270. }
  271. };
  272. process.Start();
  273. return true;
  274. }
  275. private bool OpenOSXApp(string path, int line, int column)
  276. {
  277. var solution = GetSolutionFile(path);
  278. solution = solution == "" ? "" : $"\"{solution}\"";
  279. var pathArguments = path == "" ? "" : $"-l {line} \"{path}\"";
  280. var process = new Process
  281. {
  282. StartInfo = new ProcessStartInfo
  283. {
  284. FileName = "open",
  285. Arguments = $"-n -j \"{CodeEditor.CurrentEditorInstallation}\" --args {solution} {pathArguments}",
  286. CreateNoWindow = true,
  287. UseShellExecute = true,
  288. }
  289. };
  290. process.Start();
  291. return true;
  292. }
  293. private string GetSolutionFile(string path)
  294. {
  295. if (IsUnityScript(path))
  296. {
  297. return Path.Combine(GetBaseUnityDeveloperFolder(), "Projects/CSharp/Unity.CSharpProjects.gen.sln");
  298. }
  299. var solutionFile = m_ProjectGeneration.SolutionFile();
  300. if (File.Exists(solutionFile))
  301. {
  302. return solutionFile;
  303. }
  304. return "";
  305. }
  306. static bool IsUnityScript(string path)
  307. {
  308. if (UnityEditor.Unsupported.IsDeveloperBuild())
  309. {
  310. var baseFolder = GetBaseUnityDeveloperFolder().Replace("\\", "/");
  311. var lowerPath = path.ToLowerInvariant().Replace("\\", "/");
  312. if (lowerPath.Contains((baseFolder + "/Runtime").ToLowerInvariant())
  313. || lowerPath.Contains((baseFolder + "/Editor").ToLowerInvariant()))
  314. {
  315. return true;
  316. }
  317. }
  318. return false;
  319. }
  320. static string GetBaseUnityDeveloperFolder()
  321. {
  322. return Directory.GetParent(EditorApplication.applicationPath).Parent.Parent.FullName;
  323. }
  324. public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation)
  325. {
  326. if (FileSystemUtil.EditorPathExists(editorPath) && IsRiderInstallation(editorPath))
  327. {
  328. var info = new RiderPathLocator.RiderInfo(editorPath, false);
  329. installation = new CodeEditor.Installation
  330. {
  331. Name = info.Presentation,
  332. Path = info.Path
  333. };
  334. return true;
  335. }
  336. installation = default;
  337. return false;
  338. }
  339. public static bool IsRiderInstallation(string path)
  340. {
  341. if (IsAssetImportWorkerProcess())
  342. return false;
  343. #if UNITY_2021_1_OR_NEWER
  344. if (UnityEditor.MPE.ProcessService.level == UnityEditor.MPE.ProcessLevel.Secondary)
  345. return false;
  346. #elif UNITY_2020_2_OR_NEWER
  347. if (UnityEditor.MPE.ProcessService.level == UnityEditor.MPE.ProcessLevel.Slave)
  348. return false;
  349. #elif UNITY_2020_1_OR_NEWER
  350. if (Unity.MPE.ProcessService.level == Unity.MPE.ProcessLevel.UMP_SLAVE)
  351. return false;
  352. #endif
  353. if (string.IsNullOrEmpty(path))
  354. return false;
  355. var fileInfo = new FileInfo(path);
  356. var filename = fileInfo.Name.ToLowerInvariant();
  357. return filename.StartsWith("rider", StringComparison.Ordinal);
  358. }
  359. private static bool IsAssetImportWorkerProcess()
  360. {
  361. #if UNITY_2020_2_OR_NEWER
  362. return UnityEditor.AssetDatabase.IsAssetImportWorkerProcess();
  363. #elif UNITY_2019_3_OR_NEWER
  364. return UnityEditor.Experimental.AssetDatabaseExperimental.IsAssetImportWorkerProcess();
  365. #else
  366. return false;
  367. #endif
  368. }
  369. public static string CurrentEditor // works fast, doesn't validate if executable really exists
  370. => EditorPrefs.GetString("kScriptsDefaultApp");
  371. public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback();
  372. private void CreateSolutionIfDoesntExist()
  373. {
  374. if (!m_ProjectGeneration.HasSolutionBeenGenerated())
  375. {
  376. m_ProjectGeneration.Sync();
  377. }
  378. }
  379. }
  380. }