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.

VisualStudioIntegration.cs 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 UnityEngine;
  15. using MessageType = Microsoft.Unity.VisualStudio.Editor.Messaging.MessageType;
  16. namespace Microsoft.Unity.VisualStudio.Editor
  17. {
  18. [InitializeOnLoad]
  19. internal class VisualStudioIntegration
  20. {
  21. class Client
  22. {
  23. public IPEndPoint EndPoint { get; set; }
  24. public double LastMessage { get; set; }
  25. }
  26. private static Messager _messager;
  27. private static readonly Queue<Message> _incoming = new Queue<Message>();
  28. private static readonly Dictionary<IPEndPoint, Client> _clients = new Dictionary<IPEndPoint, Client>();
  29. private static readonly object _incomingLock = new object();
  30. private static readonly object _clientsLock = new object();
  31. static VisualStudioIntegration()
  32. {
  33. if (!VisualStudioEditor.IsEnabled)
  34. return;
  35. RunOnceOnUpdate(() =>
  36. {
  37. // Despite using ReuseAddress|!ExclusiveAddressUse, we can fail here:
  38. // - if another application is using this port with exclusive access
  39. // - or if the firewall is not properly configured
  40. var messagingPort = MessagingPort();
  41. try
  42. {
  43. _messager = Messager.BindTo(messagingPort);
  44. _messager.ReceiveMessage += ReceiveMessage;
  45. }
  46. catch (SocketException)
  47. {
  48. // We'll have a chance to try to rebind on next domain reload
  49. 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.");
  50. }
  51. RunOnShutdown(Shutdown);
  52. });
  53. EditorApplication.update += OnUpdate;
  54. CheckLegacyAssemblies();
  55. }
  56. private static void CheckLegacyAssemblies()
  57. {
  58. var checkList = new HashSet<string>(new[] { KnownAssemblies.UnityVS, KnownAssemblies.Messaging, KnownAssemblies.Bridge });
  59. try
  60. {
  61. var assemblies = AppDomain
  62. .CurrentDomain
  63. .GetAssemblies()
  64. .Where(a => checkList.Contains(a.GetName().Name));
  65. foreach (var assembly in assemblies)
  66. {
  67. // for now we only want to warn against local assemblies, do not check externals.
  68. var relativePath = FileUtility.MakeRelativeToProjectPath(assembly.Location);
  69. if (relativePath == null)
  70. continue;
  71. Debug.LogWarning($"Project contains legacy assembly that could interfere with the Visual Studio Package. You should delete {relativePath}");
  72. }
  73. }
  74. catch (Exception)
  75. {
  76. // abandon legacy check
  77. }
  78. }
  79. private static void RunOnceOnUpdate(Action action)
  80. {
  81. var callback = null as EditorApplication.CallbackFunction;
  82. callback = () =>
  83. {
  84. EditorApplication.update -= callback;
  85. action();
  86. };
  87. EditorApplication.update += callback;
  88. }
  89. private static void RunOnShutdown(Action action)
  90. {
  91. // Mono on OSX has all kinds of quirks on AppDomain shutdown
  92. #if UNITY_EDITOR_WIN
  93. AppDomain.CurrentDomain.DomainUnload += (_, __) => action();
  94. #endif
  95. }
  96. private static int DebuggingPort()
  97. {
  98. return 56000 + (System.Diagnostics.Process.GetCurrentProcess().Id % 1000);
  99. }
  100. private static int MessagingPort()
  101. {
  102. return DebuggingPort() + 2;
  103. }
  104. private static void ReceiveMessage(object sender, MessageEventArgs args)
  105. {
  106. OnMessage(args.Message);
  107. }
  108. private static void OnUpdate()
  109. {
  110. lock (_incomingLock)
  111. {
  112. while (_incoming.Count > 0)
  113. {
  114. ProcessIncoming(_incoming.Dequeue());
  115. }
  116. }
  117. lock (_clientsLock)
  118. {
  119. foreach (var client in _clients.Values.ToArray())
  120. {
  121. // EditorApplication.timeSinceStartup: The time since the editor was started, in seconds, not reset when starting play mode.
  122. if (EditorApplication.timeSinceStartup - client.LastMessage > 4)
  123. _clients.Remove(client.EndPoint);
  124. }
  125. }
  126. }
  127. private static void AddMessage(Message message)
  128. {
  129. lock (_incomingLock)
  130. {
  131. _incoming.Enqueue(message);
  132. }
  133. }
  134. private static void ProcessIncoming(Message message)
  135. {
  136. lock (_clientsLock)
  137. {
  138. CheckClient(message);
  139. }
  140. switch (message.Type)
  141. {
  142. case MessageType.Ping:
  143. Answer(message, MessageType.Pong);
  144. break;
  145. case MessageType.Play:
  146. Shutdown();
  147. EditorApplication.isPlaying = true;
  148. break;
  149. case MessageType.Stop:
  150. EditorApplication.isPlaying = false;
  151. break;
  152. case MessageType.Pause:
  153. EditorApplication.isPaused = true;
  154. break;
  155. case MessageType.Unpause:
  156. EditorApplication.isPaused = false;
  157. break;
  158. case MessageType.Build:
  159. // Not used anymore
  160. break;
  161. case MessageType.Refresh:
  162. Refresh();
  163. break;
  164. case MessageType.Version:
  165. Answer(message, MessageType.Version, PackageVersion());
  166. break;
  167. case MessageType.UpdatePackage:
  168. // Not used anymore
  169. break;
  170. case MessageType.ProjectPath:
  171. Answer(message, MessageType.ProjectPath, Path.GetFullPath(Path.Combine(Application.dataPath, "..")));
  172. break;
  173. case MessageType.ExecuteTests:
  174. TestRunnerApiListener.ExecuteTests(message.Value);
  175. break;
  176. case MessageType.RetrieveTestList:
  177. TestRunnerApiListener.RetrieveTestList(message.Value);
  178. break;
  179. case MessageType.ShowUsage:
  180. UsageUtility.ShowUsage(message.Value);
  181. break;
  182. }
  183. }
  184. private static void CheckClient(Message message)
  185. {
  186. var endPoint = message.Origin;
  187. if (!_clients.TryGetValue(endPoint, out var client))
  188. {
  189. client = new Client
  190. {
  191. EndPoint = endPoint,
  192. LastMessage = EditorApplication.timeSinceStartup
  193. };
  194. _clients.Add(endPoint, client);
  195. }
  196. else
  197. {
  198. client.LastMessage = EditorApplication.timeSinceStartup;
  199. }
  200. }
  201. internal static string PackageVersion()
  202. {
  203. var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(VisualStudioIntegration).Assembly);
  204. return package.version;
  205. }
  206. private static void Refresh()
  207. {
  208. // If the user disabled auto-refresh in Unity, do not try to force refresh the Asset database
  209. if (!EditorPrefs.GetBool("kAutoRefresh", true))
  210. return;
  211. if (UnityInstallation.IsInSafeMode)
  212. return;
  213. RunOnceOnUpdate(AssetDatabase.Refresh);
  214. }
  215. private static void OnMessage(Message message)
  216. {
  217. AddMessage(message);
  218. }
  219. private static void Answer(Client client, MessageType answerType, string answerValue)
  220. {
  221. Answer(client.EndPoint, answerType, answerValue);
  222. }
  223. private static void Answer(Message message, MessageType answerType, string answerValue = "")
  224. {
  225. var targetEndPoint = message.Origin;
  226. Answer(
  227. targetEndPoint,
  228. answerType,
  229. answerValue);
  230. }
  231. private static void Answer(IPEndPoint targetEndPoint, MessageType answerType, string answerValue)
  232. {
  233. _messager?.SendMessage(targetEndPoint, answerType, answerValue);
  234. }
  235. private static void Shutdown()
  236. {
  237. if (_messager == null)
  238. return;
  239. _messager.ReceiveMessage -= ReceiveMessage;
  240. _messager.Dispose();
  241. _messager = null;
  242. }
  243. internal static void BroadcastMessage(MessageType type, string value)
  244. {
  245. lock (_clientsLock)
  246. {
  247. foreach (var client in _clients.Values.ToArray())
  248. {
  249. Answer(client, type, value);
  250. }
  251. }
  252. }
  253. }
  254. }