Sin descripción
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.3KB

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 DateTime 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 (!VisualStudioEditor.IsWindows)
  93. return;
  94. AppDomain.CurrentDomain.DomainUnload += (_, __) => action();
  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. if (DateTime.Now.Subtract(client.LastMessage) > TimeSpan.FromMilliseconds(4000))
  122. _clients.Remove(client.EndPoint);
  123. }
  124. }
  125. }
  126. private static void AddMessage(Message message)
  127. {
  128. lock (_incomingLock)
  129. {
  130. _incoming.Enqueue(message);
  131. }
  132. }
  133. private static void ProcessIncoming(Message message)
  134. {
  135. lock (_clientsLock)
  136. {
  137. CheckClient(message);
  138. }
  139. switch (message.Type)
  140. {
  141. case MessageType.Ping:
  142. Answer(message, MessageType.Pong);
  143. break;
  144. case MessageType.Play:
  145. Shutdown();
  146. EditorApplication.isPlaying = true;
  147. break;
  148. case MessageType.Stop:
  149. EditorApplication.isPlaying = false;
  150. break;
  151. case MessageType.Pause:
  152. EditorApplication.isPaused = true;
  153. break;
  154. case MessageType.Unpause:
  155. EditorApplication.isPaused = false;
  156. break;
  157. case MessageType.Build:
  158. // Not used anymore
  159. break;
  160. case MessageType.Refresh:
  161. Refresh();
  162. break;
  163. case MessageType.Version:
  164. Answer(message, MessageType.Version, PackageVersion());
  165. break;
  166. case MessageType.UpdatePackage:
  167. // Not used anymore
  168. break;
  169. case MessageType.ProjectPath:
  170. Answer(message, MessageType.ProjectPath, Path.GetFullPath(Path.Combine(Application.dataPath, "..")));
  171. break;
  172. case MessageType.ExecuteTests:
  173. TestRunnerApiListener.ExecuteTests(message.Value);
  174. break;
  175. case MessageType.RetrieveTestList:
  176. TestRunnerApiListener.RetrieveTestList(message.Value);
  177. break;
  178. case MessageType.ShowUsage:
  179. UsageUtility.ShowUsage(message.Value);
  180. break;
  181. }
  182. }
  183. private static void CheckClient(Message message)
  184. {
  185. var endPoint = message.Origin;
  186. if (!_clients.TryGetValue(endPoint, out var client))
  187. {
  188. client = new Client
  189. {
  190. EndPoint = endPoint,
  191. LastMessage = DateTime.Now
  192. };
  193. _clients.Add(endPoint, client);
  194. }
  195. else
  196. {
  197. client.LastMessage = DateTime.Now;
  198. }
  199. }
  200. internal static string PackageVersion()
  201. {
  202. var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(typeof(VisualStudioIntegration).Assembly);
  203. return package.version;
  204. }
  205. private static void Refresh()
  206. {
  207. // If the user disabled auto-refresh in Unity, do not try to force refresh the Asset database
  208. if (!EditorPrefs.GetBool("kAutoRefresh", true))
  209. return;
  210. if (UnityInstallation.IsInSafeMode)
  211. return;
  212. RunOnceOnUpdate(AssetDatabase.Refresh);
  213. }
  214. private static void OnMessage(Message message)
  215. {
  216. AddMessage(message);
  217. }
  218. private static void Answer(Client client, MessageType answerType, string answerValue)
  219. {
  220. Answer(client.EndPoint, answerType, answerValue);
  221. }
  222. private static void Answer(Message message, MessageType answerType, string answerValue = "")
  223. {
  224. var targetEndPoint = message.Origin;
  225. Answer(
  226. targetEndPoint,
  227. answerType,
  228. answerValue);
  229. }
  230. private static void Answer(IPEndPoint targetEndPoint, MessageType answerType, string answerValue)
  231. {
  232. _messager?.SendMessage(targetEndPoint, answerType, answerValue);
  233. }
  234. private static void Shutdown()
  235. {
  236. if (_messager == null)
  237. return;
  238. _messager.ReceiveMessage -= ReceiveMessage;
  239. _messager.Dispose();
  240. _messager = null;
  241. }
  242. internal static void BroadcastMessage(MessageType type, string value)
  243. {
  244. lock (_clientsLock)
  245. {
  246. foreach (var client in _clients.Values.ToArray())
  247. {
  248. Answer(client, type, value);
  249. }
  250. }
  251. }
  252. }
  253. }