VisualStudioIntegration.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using Microsoft.Unity.VisualStudio.Editor.Messaging;
  12. using Microsoft.Unity.VisualStudio.Editor.Testing;
  13. using UnityEditor;
  14. using UnityEditor.PackageManager;
  15. using UnityEditor.PackageManager.Requests;
  16. using UnityEngine;
  17. using MessageType = Microsoft.Unity.VisualStudio.Editor.Messaging.MessageType;
  18. namespace Microsoft.Unity.VisualStudio.Editor
  19. {
  20. [InitializeOnLoad]
  21. internal class VisualStudioIntegration
  22. {
  23. class Client
  24. {
  25. public IPEndPoint EndPoint { get; set; }
  26. public DateTime LastMessage { get; set; }
  27. }
  28. private static Messager _messager;
  29. private static readonly Queue<Message> _incoming = new Queue<Message>();
  30. private static readonly Dictionary<IPEndPoint, Client> _clients = new Dictionary<IPEndPoint, Client>();
  31. private static readonly object _incomingLock = new object();
  32. private static readonly object _clientsLock = new object();
  33. private static ListRequest _listRequest;
  34. static VisualStudioIntegration()
  35. {
  36. if (!VisualStudioEditor.IsEnabled)
  37. return;
  38. _listRequest = UnityEditor.PackageManager.Client.List();
  39. RunOnceOnUpdate(() =>
  40. {
  41. // Despite using ReuseAddress|!ExclusiveAddressUse, we can fail here:
  42. // - if another application is using this port with exclusive access
  43. // - or if the firewall is not properly configured
  44. var messagingPort = MessagingPort();
  45. try
  46. {
  47. _messager = Messager.BindTo(messagingPort);
  48. _messager.ReceiveMessage += ReceiveMessage;
  49. }
  50. catch (SocketException)
  51. {
  52. // We'll have a chance to try to rebind on next domain reload
  53. Debug.LogWarning($"Unable to use UDP port {messagingPort} for VS/Unity messaging. You should check if another process is already bound to this port or if your firewall settings are compatible.");
  54. }
  55. RunOnShutdown(Shutdown);
  56. });
  57. EditorApplication.update += OnUpdate;
  58. CheckLegacyAssemblies();
  59. }
  60. private static void CheckLegacyAssemblies()
  61. {
  62. var checkList = new HashSet<string>(new[] { KnownAssemblies.UnityVS, KnownAssemblies.Messaging, KnownAssemblies.Bridge });
  63. try
  64. {
  65. var assemblies = AppDomain
  66. .CurrentDomain
  67. .GetAssemblies()
  68. .Where(a => checkList.Contains(a.GetName().Name));
  69. foreach (var assembly in assemblies)
  70. {
  71. // for now we only want to warn against local assemblies, do not check externals.
  72. var relativePath = FileUtility.MakeRelativeToProjectPath(assembly.Location);
  73. if (relativePath == null)
  74. continue;
  75. Debug.LogWarning($"Project contains legacy assembly that could interfere with the Visual Studio Package. You should delete {relativePath}");
  76. }
  77. }
  78. catch (Exception)
  79. {
  80. // abandon legacy check
  81. }
  82. }
  83. private static void RunOnceOnUpdate(Action action)
  84. {
  85. var callback = null as EditorApplication.CallbackFunction;
  86. callback = () =>
  87. {
  88. EditorApplication.update -= callback;
  89. action();
  90. };
  91. EditorApplication.update += callback;
  92. }
  93. private static void RunOnShutdown(Action action)
  94. {
  95. // Mono on OSX has all kinds of quirks on AppDomain shutdown
  96. if (!VisualStudioEditor.IsWindows)
  97. return;
  98. AppDomain.CurrentDomain.DomainUnload += (_, __) => action();
  99. }
  100. private static int DebuggingPort()
  101. {
  102. return 56000 + (System.Diagnostics.Process.GetCurrentProcess().Id % 1000);
  103. }
  104. private static int MessagingPort()
  105. {
  106. return DebuggingPort() + 2;
  107. }
  108. private static void ReceiveMessage(object sender, MessageEventArgs args)
  109. {
  110. OnMessage(args.Message);
  111. }
  112. private static void HandleListRequestCompletion()
  113. {
  114. const string packageName = "com.unity.ide.visualstudio";
  115. if (_listRequest.Status == StatusCode.Success)
  116. {
  117. var package = _listRequest.Result.FirstOrDefault(p => p.name == packageName);
  118. if (package != null
  119. && Version.TryParse(package.version, out var packageVersion)
  120. && Version.TryParse(package.versions.latest, out var latestVersion)
  121. && packageVersion < latestVersion)
  122. {
  123. Debug.LogWarning($"Visual Studio Editor Package version {package.versions.latest} is available, we strongly encourage you to update from the Unity Package Manager for a better Visual Studio integration");
  124. }
  125. }
  126. _listRequest = null;
  127. }
  128. private static void OnUpdate()
  129. {
  130. if (_listRequest != null && _listRequest.IsCompleted)
  131. {
  132. HandleListRequestCompletion();
  133. }
  134. lock (_incomingLock)
  135. {
  136. while (_incoming.Count > 0)
  137. {
  138. ProcessIncoming(_incoming.Dequeue());
  139. }
  140. }
  141. lock (_clientsLock)
  142. {
  143. foreach (var client in _clients.Values.ToArray())
  144. {
  145. if (DateTime.Now.Subtract(client.LastMessage) > TimeSpan.FromMilliseconds(4000))
  146. _clients.Remove(client.EndPoint);
  147. }
  148. }
  149. }
  150. private static void AddMessage(Message message)
  151. {
  152. lock (_incomingLock)
  153. {
  154. _incoming.Enqueue(message);
  155. }
  156. }
  157. private static void ProcessIncoming(Message message)
  158. {
  159. lock (_clientsLock)
  160. {
  161. CheckClient(message);
  162. }
  163. switch (message.Type)
  164. {
  165. case MessageType.Ping:
  166. Answer(message, MessageType.Pong);
  167. break;
  168. case MessageType.Play:
  169. Shutdown();
  170. EditorApplication.isPlaying = true;
  171. break;
  172. case MessageType.Stop:
  173. EditorApplication.isPlaying = false;
  174. break;
  175. case MessageType.Pause:
  176. EditorApplication.isPaused = true;
  177. break;
  178. case MessageType.Unpause:
  179. EditorApplication.isPaused = false;
  180. break;
  181. case MessageType.Build:
  182. // Not used anymore
  183. break;
  184. case MessageType.Refresh:
  185. Refresh();
  186. break;
  187. case MessageType.Version:
  188. Answer(message, MessageType.Version, PackageVersion());
  189. break;
  190. case MessageType.UpdatePackage:
  191. // Not used anymore
  192. break;
  193. case MessageType.ProjectPath:
  194. Answer(message, MessageType.ProjectPath, Path.GetFullPath(Path.Combine(Application.dataPath, "..")));
  195. break;
  196. case MessageType.ExecuteTests:
  197. TestRunnerApiListener.ExecuteTests(message.Value);
  198. break;
  199. case MessageType.RetrieveTestList:
  200. TestRunnerApiListener.RetrieveTestList(message.Value);
  201. break;
  202. case MessageType.ShowUsage:
  203. UsageUtility.ShowUsage(message.Value);
  204. break;
  205. }
  206. }
  207. private static void CheckClient(Message message)
  208. {
  209. var endPoint = message.Origin;
  210. if (!_clients.TryGetValue(endPoint, out var client))
  211. {
  212. client = new Client
  213. {
  214. EndPoint = endPoint,
  215. LastMessage = DateTime.Now
  216. };
  217. _clients.Add(endPoint, client);
  218. }
  219. else
  220. {
  221. client.LastMessage = DateTime.Now;
  222. }
  223. }
  224. internal static string PackageVersion()
  225. {
  226. var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(VisualStudioIntegration).Assembly);
  227. return package.version;
  228. }
  229. private static void Refresh()
  230. {
  231. // If the user disabled auto-refresh in Unity, do not try to force refresh the Asset database
  232. if (!EditorPrefs.GetBool("kAutoRefresh", true))
  233. return;
  234. RunOnceOnUpdate(AssetDatabase.Refresh);
  235. }
  236. private static void OnMessage(Message message)
  237. {
  238. AddMessage(message);
  239. }
  240. private static void Answer(Client client, MessageType answerType, string answerValue)
  241. {
  242. Answer(client.EndPoint, answerType, answerValue);
  243. }
  244. private static void Answer(Message message, MessageType answerType, string answerValue = "")
  245. {
  246. var targetEndPoint = message.Origin;
  247. Answer(
  248. targetEndPoint,
  249. answerType,
  250. answerValue);
  251. }
  252. private static void Answer(IPEndPoint targetEndPoint, MessageType answerType, string answerValue)
  253. {
  254. _messager?.SendMessage(targetEndPoint, answerType, answerValue);
  255. }
  256. private static void Shutdown()
  257. {
  258. if (_messager == null)
  259. return;
  260. _messager.ReceiveMessage -= ReceiveMessage;
  261. _messager.Dispose();
  262. _messager = null;
  263. }
  264. internal static void BroadcastMessage(MessageType type, string value)
  265. {
  266. lock (_clientsLock)
  267. {
  268. foreach (var client in _clients.Values.ToArray())
  269. {
  270. Answer(client, type, value);
  271. }
  272. }
  273. }
  274. }
  275. }