HTTPUpdateDelegator.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using UnityEngine;
  2. #if NETFX_CORE || BUILD_FOR_WP8
  3. using System.Threading.Tasks;
  4. #endif
  5. namespace BestHTTP
  6. {
  7. /// <summary>
  8. /// Will route some U3D calls to the HTTPManager.
  9. /// </summary>
  10. [ExecuteInEditMode]
  11. public sealed class HTTPUpdateDelegator : MonoBehaviour
  12. {
  13. #region Public Properties
  14. /// <summary>
  15. /// The singleton instance of the HTTPUpdateDelegator
  16. /// </summary>
  17. public static HTTPUpdateDelegator Instance { get; private set; }
  18. /// <summary>
  19. /// True, if the Instance property should hold a valid value.
  20. /// </summary>
  21. public static bool IsCreated { get; private set; }
  22. /// <summary>
  23. /// SaveLocal it true before any CheckInstance() call, or before any request sent to dispatch callbacks on another thread.
  24. /// </summary>
  25. public static bool IsThreaded { get; set; }
  26. /// <summary>
  27. /// It's true if the dispatch thread running.
  28. /// </summary>
  29. public static bool IsThreadRunning { get; private set; }
  30. /// <summary>
  31. /// How much time the plugin should wait between two update call. Its default value 100 ms.
  32. /// </summary>
  33. public static int ThreadFrequencyInMS { get; set; }
  34. /// <summary>
  35. /// Called in the OnApplicationQuit function. If this function returns False, the plugin will not start to
  36. /// shut down itself.
  37. /// </summary>
  38. public static System.Func<bool> OnBeforeApplicationQuit;
  39. public static System.Action<bool> OnApplicationForegroundStateChanged;
  40. #endregion
  41. private static bool IsSetupCalled;
  42. static HTTPUpdateDelegator()
  43. {
  44. ThreadFrequencyInMS = 100;
  45. }
  46. /// <summary>
  47. /// Will create the HTTPUpdateDelegator instance and set it up.
  48. /// </summary>
  49. public static void CheckInstance()
  50. {
  51. try
  52. {
  53. if (!IsCreated)
  54. {
  55. GameObject go = GameObject.Find("HTTP Update Delegator");
  56. if (go != null)
  57. Instance = go.GetComponent<HTTPUpdateDelegator>();
  58. if (Instance == null)
  59. {
  60. go = new GameObject("HTTP Update Delegator");
  61. go.hideFlags = HideFlags.DontSave;
  62. Instance = go.AddComponent<HTTPUpdateDelegator>();
  63. }
  64. IsCreated = true;
  65. #if UNITY_EDITOR
  66. if (!UnityEditor.EditorApplication.isPlaying)
  67. {
  68. UnityEditor.EditorApplication.update -= Instance.Update;
  69. UnityEditor.EditorApplication.update += Instance.Update;
  70. }
  71. #if UNITY_2017_2_OR_NEWER
  72. UnityEditor.EditorApplication.playModeStateChanged -= Instance.OnPlayModeStateChanged;
  73. UnityEditor.EditorApplication.playModeStateChanged += Instance.OnPlayModeStateChanged;
  74. #else
  75. UnityEditor.EditorApplication.playmodeStateChanged -= Instance.OnPlayModeStateChanged;
  76. UnityEditor.EditorApplication.playmodeStateChanged += Instance.OnPlayModeStateChanged;
  77. #endif
  78. #endif
  79. HTTPManager.Logger.Information("HTTPUpdateDelegator", "Instance Created!");
  80. }
  81. }
  82. catch
  83. {
  84. HTTPManager.Logger.Error("HTTPUpdateDelegator", "Please call the BestHTTP.HTTPManager.Setup() from one of Unity's event(eg. awake, start) before you send any request!");
  85. }
  86. }
  87. private void Setup()
  88. {
  89. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  90. Caching.HTTPCacheService.SetupCacheFolder();
  91. #endif
  92. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  93. Cookies.CookieJar.SetupFolder();
  94. Cookies.CookieJar.Load();
  95. #endif
  96. #if UNITY_WEBGL && !UNITY_EDITOR
  97. // Threads are not implemented in WEBGL builds, disable it for now.
  98. IsThreaded = false;
  99. #endif
  100. if (IsThreaded)
  101. {
  102. #if NETFX_CORE
  103. #pragma warning disable 4014
  104. Windows.System.Threading.ThreadPool.RunAsync(ThreadFunc);
  105. #pragma warning restore 4014
  106. #else
  107. System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ThreadFunc));
  108. #endif
  109. }
  110. IsSetupCalled = true;
  111. // Unity doesn't tolerate well if the DontDestroyOnLoad called when purely in editor mode. So, we will set the flag
  112. // only when we are playing, or not in the editor.
  113. if (!Application.isEditor || Application.isPlaying)
  114. GameObject.DontDestroyOnLoad(this.gameObject);
  115. HTTPManager.Logger.Information("HTTPUpdateDelegator", "Setup done!");
  116. }
  117. #if NETFX_CORE
  118. async
  119. #endif
  120. void ThreadFunc(object obj)
  121. {
  122. HTTPManager.Logger.Information ("HTTPUpdateDelegator", "Update Thread Started");
  123. try
  124. {
  125. IsThreadRunning = true;
  126. while (IsThreadRunning)
  127. {
  128. HTTPManager.OnUpdate();
  129. #if NETFX_CORE
  130. await Task.Delay(ThreadFrequencyInMS);
  131. #else
  132. System.Threading.Thread.Sleep(ThreadFrequencyInMS);
  133. #endif
  134. }
  135. }
  136. finally
  137. {
  138. HTTPManager.Logger.Information("HTTPUpdateDelegator", "Update Thread Ended");
  139. }
  140. }
  141. void Update()
  142. {
  143. if (!IsSetupCalled)
  144. {
  145. IsSetupCalled = true;
  146. Setup();
  147. }
  148. if (!IsThreaded)
  149. HTTPManager.OnUpdate();
  150. }
  151. #if UNITY_EDITOR
  152. #if UNITY_2017_2_OR_NEWER
  153. void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange playMode)
  154. {
  155. if (playMode == UnityEditor.PlayModeStateChange.EnteredPlayMode)
  156. UnityEditor.EditorApplication.update -= Update;
  157. else if (playMode == UnityEditor.PlayModeStateChange.ExitingPlayMode)
  158. UnityEditor.EditorApplication.update += Update;
  159. }
  160. #else
  161. void OnPlayModeStateChanged()
  162. {
  163. if (UnityEditor.EditorApplication.isPlaying)
  164. UnityEditor.EditorApplication.update -= Update;
  165. else if (!UnityEditor.EditorApplication.isPlaying)
  166. UnityEditor.EditorApplication.update += Update;
  167. }
  168. #endif
  169. #endif
  170. void OnDisable()
  171. {
  172. HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnDisable Called!");
  173. #if UNITY_EDITOR
  174. if (UnityEditor.EditorApplication.isPlaying)
  175. #endif
  176. OnApplicationQuit();
  177. }
  178. void OnApplicationPause(bool isPaused)
  179. {
  180. if (HTTPUpdateDelegator.OnApplicationForegroundStateChanged != null)
  181. HTTPUpdateDelegator.OnApplicationForegroundStateChanged(isPaused);
  182. }
  183. void OnApplicationQuit()
  184. {
  185. HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnApplicationQuit Called!");
  186. if (OnBeforeApplicationQuit != null)
  187. {
  188. try
  189. {
  190. if (!OnBeforeApplicationQuit())
  191. {
  192. HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnBeforeApplicationQuit call returned false, postponing plugin shutdown.");
  193. return;
  194. }
  195. }
  196. catch(System.Exception ex)
  197. {
  198. HTTPManager.Logger.Exception("HTTPUpdateDelegator", string.Empty, ex);
  199. }
  200. }
  201. IsThreadRunning = false;
  202. if (!IsCreated)
  203. return;
  204. IsCreated = false;
  205. HTTPManager.OnQuit();
  206. #if UNITY_EDITOR
  207. UnityEditor.EditorApplication.update -= Update;
  208. #if UNITY_2017_2_OR_NEWER
  209. UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
  210. #else
  211. UnityEditor.EditorApplication.playmodeStateChanged -= OnPlayModeStateChanged;
  212. #endif
  213. #endif
  214. }
  215. }
  216. }