RiderScriptEditor.cs 14.7 KB
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 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Packages.Rider.Editor.ProjectGeneration;
using Packages.Rider.Editor.Util;
using Unity.CodeEditor;
using UnityEditor;
using UnityEditor.Build;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace Packages.Rider.Editor
{
  [InitializeOnLoad]
  internal class RiderScriptEditor : IExternalCodeEditor
  {
    IDiscovery m_Discoverability;
    IGenerator m_ProjectGeneration;
    RiderInitializer m_Initiliazer = new RiderInitializer();

    static RiderScriptEditor()
    {
      try
      {
        // todo: make ProjectGeneration lazy
        var projectGeneration = new ProjectGeneration.ProjectGeneration();
        var editor = new RiderScriptEditor(new Discovery(), projectGeneration);
        CodeEditor.Register(editor);
        var path = GetEditorRealPath(CurrentEditor);

        if (IsRiderInstallation(path))
        {
          RiderPathLocator.RiderInfo[] installations = null;

          if (!RiderScriptEditorData.instance.initializedOnce)
          {
            installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
            // is likely outdated
            if (installations.Any() && installations.All(a => GetEditorRealPath(a.Path) != path))
            {
              if (RiderPathLocator.GetIsToolbox(path)) // is toolbox - update
              {
                var toolboxInstallations = installations.Where(a => a.IsToolbox).ToArray();
                if (toolboxInstallations.Any())
                {
                  var newEditor = toolboxInstallations.Last().Path;
                  CodeEditor.SetExternalScriptEditor(newEditor);
                  path = newEditor;
                }
                else
                {
                  var newEditor = installations.Last().Path;
                  CodeEditor.SetExternalScriptEditor(newEditor);
                  path = newEditor;
                }
              }
              else // is non toolbox - notify
              {
                var newEditorName = installations.Last().Presentation;
                Debug.LogWarning($"Consider updating External Editor in Unity to Rider {newEditorName}.");
              }
            }

            ShowWarningOnUnexpectedScriptEditor(path);
            RiderScriptEditorData.instance.initializedOnce = true;
          }

          if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed
          {
            if (installations == null)
              installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
            if (installations.Any())
            {
              var newEditor = installations.Last().Path;
              CodeEditor.SetExternalScriptEditor(newEditor);
              path = newEditor;
            }
          }

          RiderScriptEditorData.instance.Init();

          editor.CreateSolutionIfDoesntExist();
          if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
          {
            editor.m_Initiliazer.Initialize(path);
          }

          RiderFileSystemWatcher.InitWatcher(
            Directory.GetCurrentDirectory(), "*.*", (sender, args) =>
            {
              var extension = Path.GetExtension(args.Name);
              if (extension == ".sln" || extension == ".csproj")
                RiderScriptEditorData.instance.hasChanges = true;
            });

          RiderFileSystemWatcher.InitWatcher(
            Path.Combine(Directory.GetCurrentDirectory(), "Library"),
            "EditorOnlyScriptingUserSettings.json",
            (sender, args) => { RiderScriptEditorData.instance.hasChanges = true; });

          RiderFileSystemWatcher.InitWatcher(
            Path.Combine(Directory.GetCurrentDirectory(), "Packages"),
            "manifest.json", (sender, args) => { RiderScriptEditorData.instance.hasChanges = true; });

          // can't switch to non-deprecated api, because UnityEditor.Build.BuildPipelineInterfaces.processors is internal
#pragma warning disable 618
          EditorUserBuildSettings.activeBuildTargetChanged += () =>
#pragma warning restore 618
          {
            RiderScriptEditorData.instance.hasChanges = true;
          };
        }
      }
      catch (Exception e)
      {
        Debug.LogException(e);
      }
    }

    private static void ShowWarningOnUnexpectedScriptEditor(string path)
    {
      // Show warning, when Unity was started from Rider, but external editor is different https://github.com/JetBrains/resharper-unity/issues/1127
      try
      {
        var args = Environment.GetCommandLineArgs();
        var commandlineParser = new CommandLineParser(args);
        if (commandlineParser.Options.ContainsKey("-riderPath"))
        {
          var originRiderPath = commandlineParser.Options["-riderPath"];
          var originRealPath = GetEditorRealPath(originRiderPath);
          var originVersion = RiderPathLocator.GetBuildNumber(originRealPath);
          var version = RiderPathLocator.GetBuildNumber(path);
          if (originVersion != null && originVersion != version)
          {
            Debug.LogWarning("Unity was started by a version of Rider that is not the current default external editor. Advanced integration features cannot be enabled.");
            Debug.Log($"Unity was started by Rider {originVersion}, but external editor is set to: {path}");
          }
        }
      }
      catch (Exception e)
      {
        Debug.LogException(e);
      }
    }

    internal static string GetEditorRealPath(string path)
    {
      if (string.IsNullOrEmpty(path))
      {
        return path;
      }

      if (!FileSystemUtil.EditorPathExists(path))
        return path;

      if (SystemInfo.operatingSystemFamily != OperatingSystemFamily.Windows)
      {
        var realPath = FileSystemUtil.GetFinalPathName(path);

        // case of snap installation
        if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux)
        {
          if (new FileInfo(path).Name.ToLowerInvariant() == "rider" &&
              new FileInfo(realPath).Name.ToLowerInvariant() == "snap")
          {
            var snapInstallPath = "/snap/rider/current/bin/rider.sh";
            if (new FileInfo(snapInstallPath).Exists)
              return snapInstallPath;
          }
        }

        // in case of symlink
        return realPath;
      }

      return path;
    }

    public RiderScriptEditor(IDiscovery discovery, IGenerator projectGeneration)
    {
      m_Discoverability = discovery;
      m_ProjectGeneration = projectGeneration;
    }

    private static string[] defaultExtensions
    {
      get
      {
        var customExtensions = new[] {"json", "asmdef", "log", "xaml"};
        return EditorSettings.projectGenerationBuiltinExtensions.Concat(EditorSettings.projectGenerationUserExtensions)
          .Concat(customExtensions).Distinct().ToArray();
      }
    }

    private static string[] HandledExtensions
    {
      get
      {
        return HandledExtensionsString.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.TrimStart('.', '*'))
          .ToArray();
      } 
    }

    private static string HandledExtensionsString
    {
      get { return EditorPrefs.GetString("Rider_UserExtensions", string.Join(";", defaultExtensions));}
      set { EditorPrefs.SetString("Rider_UserExtensions", value); }
    }

    private static bool SupportsExtension(string path)
    {
      var extension = Path.GetExtension(path);
      if (string.IsNullOrEmpty(extension))
        return false;
      // cs is a default extension, which should always be handled
      return extension == ".cs" || HandledExtensions.Contains(extension.TrimStart('.'));
    }

    public void OnGUI()
    {
      if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
      {
        HandledExtensionsString = EditorGUILayout.TextField(new GUIContent("Extensions handled: "), HandledExtensionsString);
      }

      EditorGUILayout.LabelField("Generate .csproj files for:");
      EditorGUI.indentLevel++;
      SettingsButton(ProjectGenerationFlag.Embedded, "Embedded packages", "");
      SettingsButton(ProjectGenerationFlag.Local, "Local packages", "");
      SettingsButton(ProjectGenerationFlag.Registry, "Registry packages", "");
      SettingsButton(ProjectGenerationFlag.Git, "Git packages", "");
      SettingsButton(ProjectGenerationFlag.BuiltIn, "Built-in packages", "");
#if UNITY_2019_3_OR_NEWER
      SettingsButton(ProjectGenerationFlag.LocalTarBall, "Local tarball", "");
#endif
      SettingsButton(ProjectGenerationFlag.Unknown, "Packages from unknown sources", "");
      SettingsButton(ProjectGenerationFlag.PlayerAssemblies, "Player projects", "For each player project generate an additional csproj with the name 'project-player.csproj'");
      RegenerateProjectFiles();
      EditorGUI.indentLevel--;
    }

    void RegenerateProjectFiles()
    {
      var rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(new GUILayoutOption[] {}));
      rect.width = 252;
      if (GUI.Button(rect, "Regenerate project files"))
      {
        m_ProjectGeneration.Sync();
      }
    }

    void SettingsButton(ProjectGenerationFlag preference, string guiMessage, string toolTip)
    {
      var prevValue = m_ProjectGeneration.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(preference);
      var newValue = EditorGUILayout.Toggle(new GUIContent(guiMessage, toolTip), prevValue);
      if (newValue != prevValue)
      {
        m_ProjectGeneration.AssemblyNameProvider.ToggleProjectGeneration(preference);
      }
    }

    public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles,
      string[] importedFiles)
    {
      m_ProjectGeneration.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles),
        importedFiles);
    }

    public void SyncAll()
    {
      AssetDatabase.Refresh();
      m_ProjectGeneration.SyncIfNeeded(new string[] { }, new string[] { });
    }

    public void Initialize(string editorInstallationPath) // is called each time ExternalEditor is changed
    {
      RiderScriptEditorData.instance.Invalidate(editorInstallationPath);
      m_ProjectGeneration.Sync(); // regenerate csproj and sln for new editor
    }

    public bool OpenProject(string path, int line, int column)
    {
      if (path != "" && !SupportsExtension(path)) // Assets - Open C# Project passes empty path here
      {
        return false;
      }
      
      if (path == "" && SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
      {
        // there is a bug in DllImplementation - use package implementation here instead https://github.cds.internal.unity3d.com/unity/com.unity.ide.rider/issues/21
        return OpenOSXApp(path, line, column);
      }

      if (!IsUnityScript(path))
      {
        m_ProjectGeneration.SyncIfNeeded(affectedFiles: new string[] { }, new string[] { });
        var fastOpenResult = EditorPluginInterop.OpenFileDllImplementation(path, line, column);
        if (fastOpenResult)
          return true;
      }

      if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
      {
        return OpenOSXApp(path, line, column);
      }

      var solution = GetSolutionFile(path); // TODO: If solution file doesn't exist resync.
      solution = solution == "" ? "" : $"\"{solution}\"";
      var process = new Process
      {
        StartInfo = new ProcessStartInfo
        {
          FileName = CodeEditor.CurrentEditorInstallation,
          Arguments = $"{solution} -l {line} \"{path}\"",
          UseShellExecute = true,
        }
      };

      process.Start();

      return true;
    }

    private bool OpenOSXApp(string path, int line, int column)
    {
      var solution = GetSolutionFile(path);
      solution = solution == "" ? "" : $"\"{solution}\"";
      var pathArguments = path == "" ? "" : $"-l {line} \"{path}\"";
      var process = new Process
      {
        StartInfo = new ProcessStartInfo
        {
          FileName = "open",
          Arguments = $"-n -j \"{CodeEditor.CurrentEditorInstallation}\" --args {solution} {pathArguments}",
          CreateNoWindow = true,
          UseShellExecute = true,
        }
      };

      process.Start();

      return true;
    }

    private string GetSolutionFile(string path)
    {
      if (IsUnityScript(path))
      {
        return Path.Combine(GetBaseUnityDeveloperFolder(), "Projects/CSharp/Unity.CSharpProjects.gen.sln");
      }

      var solutionFile = m_ProjectGeneration.SolutionFile();
      if (File.Exists(solutionFile))
      {
        return solutionFile;
      }

      return "";
    }

    static bool IsUnityScript(string path)
    {
      if (UnityEditor.Unsupported.IsDeveloperBuild())
      {
        var baseFolder = GetBaseUnityDeveloperFolder().Replace("\\", "/");
        var lowerPath = path.ToLowerInvariant().Replace("\\", "/");

        if (lowerPath.Contains((baseFolder + "/Runtime").ToLowerInvariant())
          || lowerPath.Contains((baseFolder + "/Editor").ToLowerInvariant()))
        {
          return true;
        }
      }

      return false;
    }

    static string GetBaseUnityDeveloperFolder()
    {
      return Directory.GetParent(EditorApplication.applicationPath).Parent.Parent.FullName;
    }

    public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation)
    {
      if (FileSystemUtil.EditorPathExists(editorPath) && IsRiderInstallation(editorPath))
      {
        var info = new RiderPathLocator.RiderInfo(editorPath, false);
        installation = new CodeEditor.Installation
        {
          Name = info.Presentation,
          Path = info.Path
        };
        return true;
      }

      installation = default;
      return false;
    }

    public static bool IsRiderInstallation(string path)
    {
      if (IsAssetImportWorkerProcess())
        return false;
      
      if (string.IsNullOrEmpty(path))
      {
        return false;
      }

      var fileInfo = new FileInfo(path);
      var filename = fileInfo.Name.ToLowerInvariant();
      return filename.StartsWith("rider", StringComparison.Ordinal);
    }

    private static bool IsAssetImportWorkerProcess()
    {
#if UNITY_2020_2_OR_NEWER
      return UnityEditor.AssetDatabase.IsAssetImportWorkerProcess();
#elif UNITY_2019_3_OR_NEWER
      return UnityEditor.Experimental.AssetDatabaseExperimental.IsAssetImportWorkerProcess();
#else
      return false;
#endif
    }

    public static string CurrentEditor // works fast, doesn't validate if executable really exists
      => EditorPrefs.GetString("kScriptsDefaultApp");

    public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback();

    private void CreateSolutionIfDoesntExist()
    {
      if (!m_ProjectGeneration.HasSolutionBeenGenerated())
      {
        m_ProjectGeneration.Sync();
      }
    }
  }
}