CrossCompileCallbacks.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. #if UNITY_EDITOR
  2. using System;
  3. using System.Linq.Expressions;
  4. using System.Reflection;
  5. using UnityEditor;
  6. using UnityEditor.Callbacks;
  7. using UnityEngine;
  8. namespace Kamgam.SkyClouds.URP
  9. {
  10. /// <summary>
  11. /// Allows you to register a callback before compilation
  12. /// which is then executed automatically after compilation.<br />
  13. /// <br />
  14. /// Methods registered are usually executed in FIFO order. Though there
  15. /// is no guarantee that this will always be the case.
  16. /// <example>
  17. /// CrossCompileCallbacks.RegisterCallback(testCallbackA); // It can find the type automatically.
  18. /// CrossCompileCallbacks.RegisterCallback(typeof(YourClass), "testCallbackA");
  19. /// </example>
  20. /// </summary>
  21. public static class CrossCompileCallbacks
  22. {
  23. /// <summary>
  24. /// If set to true then the callbacks will not be called immediately but
  25. /// within the next editor update cycle.<br />
  26. /// Use this to avoid "Calling ... from assembly reloading callbacks are not supported." errors.
  27. /// </summary>
  28. public static bool DelayExecutionAfterCompilation
  29. {
  30. get => SessionState.GetBool(typeName() + ".DelayExecution", false);
  31. set => SessionState.SetBool(typeName() + ".DelayExecution", value);
  32. }
  33. static string typeName() => typeof(CrossCompileCallbacks).FullName;
  34. const string _maxIndexKey = ".MaxIndex";
  35. static string maxIndexKey() => typeName() + _maxIndexKey;
  36. const string _lastReleasedIndexKey = ".LastReleasedIndex";
  37. static string lastReleasedIndexKey() => typeName() + _lastReleasedIndexKey;
  38. const string _indexTypeKey = ".Index[{0}].Type";
  39. static string indexTypeKey(int index) => string.Format(typeName() + _indexTypeKey, index);
  40. const string _indexMethodKey = ".Index[{0}].Method";
  41. static string indexMethodKey(int index) => string.Format(typeName() + _indexMethodKey, index);
  42. static int getMaxIndex()
  43. {
  44. return SessionState.GetInt(maxIndexKey(), -1);
  45. }
  46. static int getNextIndex()
  47. {
  48. int maxIndex;
  49. // Try to reuse an old index (update max index if necessary)
  50. int reusableIndex = SessionState.GetInt(lastReleasedIndexKey(), -1);
  51. if (reusableIndex >= 0)
  52. {
  53. SessionState.SetInt(lastReleasedIndexKey(), -1);
  54. maxIndex = getMaxIndex();
  55. if(maxIndex < reusableIndex)
  56. SessionState.SetInt(maxIndexKey(), reusableIndex);
  57. return reusableIndex;
  58. }
  59. // New index needed (increase max index).
  60. maxIndex = SessionState.GetInt(maxIndexKey(), -1);
  61. maxIndex++;
  62. SessionState.SetInt(maxIndexKey(), maxIndex);
  63. return maxIndex;
  64. }
  65. public static void ReleaseIndex(int index)
  66. {
  67. if (index < 0)
  68. return;
  69. SessionState.SetInt(lastReleasedIndexKey(), index);
  70. SessionState.EraseString(indexTypeKey(index));
  71. SessionState.EraseString(indexMethodKey(index));
  72. // Decrease or erase max index if needed.
  73. int maxIndex = getMaxIndex();
  74. if(index == maxIndex)
  75. {
  76. maxIndex--;
  77. if(maxIndex < 0)
  78. SessionState.EraseInt(maxIndexKey());
  79. else
  80. SessionState.SetInt(maxIndexKey(), maxIndex);
  81. }
  82. }
  83. public static void ReleaseAllOnType(Type type)
  84. {
  85. if (type == null)
  86. return;
  87. int maxIndex = getMaxIndex();
  88. for (int i = maxIndex; i >= 0; i--)
  89. {
  90. string typeName;
  91. GetCallbackInfo(i, out typeName, out _);
  92. if(typeName == type.FullName)
  93. {
  94. ReleaseIndex(i);
  95. }
  96. }
  97. }
  98. /// <summary>
  99. /// Registers a callback and returns an index >= 0 on success and -1 on failure.
  100. /// </summary>
  101. /// <param name="callback">A static method without any parameters.</param>
  102. /// <returns></returns>
  103. public static int RegisterCallback(System.Action callback)
  104. {
  105. if (callback == null)
  106. return -1;
  107. var methodInfo = callback.GetMethodInfo();
  108. if (methodInfo == null)
  109. return -1;
  110. if (!methodInfo.IsStatic)
  111. {
  112. Debug.Log("Method needs to be static.");
  113. return -1;
  114. }
  115. return RegisterCallback(methodInfo.DeclaringType, methodInfo.Name);
  116. }
  117. /// <summary>
  118. /// Registers a callback and returns an index >= 0 on success and -1 on failure.
  119. /// </summary>
  120. /// <param name="type"></param>
  121. /// <param name="staticMethodName">A static method without any parameters.</param>
  122. /// <returns></returns>
  123. public static int RegisterCallback(Type type, string staticMethodName)
  124. {
  125. if (type == null || string.IsNullOrEmpty(staticMethodName))
  126. {
  127. Debug.Assert(type != null);
  128. Debug.Assert(staticMethodName != null);
  129. return -1;
  130. }
  131. // Check if methods has any parameters (that's not supported)
  132. try
  133. {
  134. var flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
  135. var methodInfo = type.GetMethod(staticMethodName, flags);
  136. if (methodInfo == null)
  137. {
  138. Debug.LogError("No static method '" + staticMethodName + "' found in '" + type.FullName + "'.");
  139. return -1;
  140. }
  141. if (methodInfo.GetParameters().Length > 0)
  142. {
  143. Debug.Assert(methodInfo.GetParameters().Length == 0);
  144. return -1;
  145. }
  146. }
  147. catch (System.Exception e)
  148. {
  149. Debug.LogError($"CrossCompileCallbacks: Error while checking '{staticMethodName}' method parameters. Error:\n" + e.Message);
  150. }
  151. int index = getNextIndex();
  152. SessionState.SetString(indexTypeKey(index), type.FullName);
  153. SessionState.SetString(indexMethodKey(index), staticMethodName);
  154. return index;
  155. }
  156. public static void GetCallbackInfo(int index, out string typeName, out string methodName)
  157. {
  158. typeName = SessionState.GetString(indexTypeKey(index), null);
  159. methodName = SessionState.GetString(indexMethodKey(index), null);
  160. }
  161. [DidReloadScripts(-1)]
  162. static void onAfterCompilation()
  163. {
  164. if (DelayExecutionAfterCompilation)
  165. {
  166. EditorApplication.delayCall -= delayedExecuteRegisteredCallbacks;
  167. EditorApplication.delayCall += delayedExecuteRegisteredCallbacks;
  168. }
  169. else
  170. {
  171. executeRegisteredCallbacks();
  172. }
  173. }
  174. static void delayedExecuteRegisteredCallbacks()
  175. {
  176. EditorApplication.delayCall -= delayedExecuteRegisteredCallbacks;
  177. executeRegisteredCallbacks();
  178. }
  179. static void executeRegisteredCallbacks()
  180. {
  181. int maxIndex = getMaxIndex();
  182. for (int i = maxIndex; i >= 0; i--)
  183. {
  184. string typeName;
  185. string methodName;
  186. GetCallbackInfo(i, out typeName, out methodName);
  187. try
  188. {
  189. ReleaseIndex(i);
  190. if (string.IsNullOrEmpty(typeName) || string.IsNullOrEmpty(methodName))
  191. continue;
  192. var methodInfo = findStaticMethod(typeName, methodName);
  193. methodInfo.Invoke(null, null);
  194. }
  195. catch (System.Exception e)
  196. {
  197. string errorMsg = e.Message;
  198. if(errorMsg.Contains("invocation") && e.InnerException != null)
  199. {
  200. errorMsg += "\n" + e.InnerException.Message;
  201. }
  202. Debug.LogError($"CrossCompileCallbacks: Calling '{typeName}.{methodName}' failed. Error:\n" + errorMsg);
  203. }
  204. }
  205. }
  206. static MethodInfo findStaticMethod(string fullTypeName, string methodName)
  207. {
  208. var type = findType(fullTypeName);
  209. if (type == null)
  210. return null;
  211. var flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
  212. var methodInfo = type.GetMethod(methodName, flags);
  213. return methodInfo;
  214. }
  215. static Type findType(string fullTypeName)
  216. {
  217. Debug.Assert(fullTypeName != null);
  218. var assemblies = AppDomain.CurrentDomain.GetAssemblies();
  219. foreach (var assembly in assemblies)
  220. {
  221. Type t = assembly.GetType(fullTypeName, throwOnError: false);
  222. if (t != null)
  223. return t;
  224. }
  225. throw new ArgumentException("Type " + fullTypeName + " doesn't exist in the current app domain.");
  226. }
  227. /// <summary>
  228. /// Utility method to store a static parameterless Action
  229. /// in the SessionState for retrieval at a later time.
  230. /// </summary>
  231. /// <param name="sessionStorageKey"></param>
  232. /// <param name="action"></param>
  233. /// <returns></returns>
  234. public static bool StoreAction(string sessionStorageKey, System.Action action)
  235. {
  236. if (action == null)
  237. return false;
  238. var methodInfo = action.GetMethodInfo();
  239. if (methodInfo == null)
  240. return false;
  241. if (!methodInfo.IsStatic)
  242. {
  243. Debug.Log("Method '"+ methodInfo.Name + "'needs to be static.");
  244. return false;
  245. }
  246. SessionState.SetString(sessionStorageKey + ".Type", methodInfo.DeclaringType.FullName);
  247. SessionState.SetString(sessionStorageKey + ".Method", methodInfo.Name);
  248. return true;
  249. }
  250. /// <summary>
  251. /// Retrieves the Action from the SessionState.
  252. /// </summary>
  253. /// <param name="sessionStorageKey"></param>
  254. /// <returns></returns>
  255. public static System.Action GetStoredAction(string sessionStorageKey)
  256. {
  257. var typeName = SessionState.GetString(sessionStorageKey + ".Type", null);
  258. var methodName = SessionState.GetString(sessionStorageKey + ".Method", null);
  259. if (string.IsNullOrEmpty(typeName) || string.IsNullOrEmpty(methodName))
  260. {
  261. return null;
  262. }
  263. var type = findType(typeName);
  264. if (type == null)
  265. return null;
  266. var methodInfo = findStaticMethod(typeName, methodName);
  267. if (methodInfo == null)
  268. return null;
  269. return (Action) Delegate.CreateDelegate(typeof(Action), methodInfo);
  270. }
  271. public static void ClearStoredAction(string sessionStorageKey)
  272. {
  273. SessionState.EraseString(sessionStorageKey + ".Type");
  274. SessionState.EraseString(sessionStorageKey + ".Method");
  275. }
  276. // Testing
  277. /*
  278. [DidReloadScripts]
  279. static void StartTest()
  280. {
  281. Debug.Log("CrossCompileCallbacks: Starting test.");
  282. RegisterCallback(testCallbackA);
  283. RegisterCallback(typeof(CrossCompileCallbacks), "testCallbackB");
  284. var action = GetStoredAction("storedActionA");
  285. ClearStoredAction("storedActionA");
  286. if (action != null)
  287. action.Invoke();
  288. StoreAction("storedActionA", storedActionA);
  289. }
  290. static void testCallbackA()
  291. {
  292. Debug.Log("Test callback A executed.");
  293. }
  294. static void testCallbackB()
  295. {
  296. Debug.Log("Test callback B executed.");
  297. }
  298. static void storedActionA()
  299. {
  300. Debug.Log("Stored action A executed.");
  301. }
  302. //*/
  303. }
  304. }
  305. #endif