SampleSelector.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP;
  5. using BestHTTP.Statistics;
  6. using BestHTTP.Examples;
  7. /// <summary>
  8. /// A class to describe an Example and store it's metadata.
  9. /// </summary>
  10. public sealed class SampleDescriptor
  11. {
  12. public bool IsLabel { get; set; }
  13. public Type Type { get; set; }
  14. public string DisplayName { get; set; }
  15. public string Description { get; set; }
  16. public string CodeBlock { get; set; }
  17. public bool IsSelected { get; set; }
  18. public GameObject UnityObject { get; set; }
  19. public bool IsRunning { get { return UnityObject != null; } }
  20. public SampleDescriptor(Type type, string displayName, string description, string codeBlock)
  21. {
  22. this.Type = type;
  23. this.DisplayName = displayName;
  24. this.Description = description;
  25. this.CodeBlock = codeBlock;
  26. }
  27. public void CreateUnityObject()
  28. {
  29. if (UnityObject != null)
  30. return;
  31. UnityObject = new GameObject(DisplayName);
  32. UnityObject.AddComponent(Type);
  33. #if UNITY_WEBPLAYER
  34. if (!string.IsNullOrEmpty(CodeBlock))
  35. Application.ExternalCall("ShowCodeBlock", CodeBlock);
  36. else
  37. Application.ExternalCall("HideCodeBlock");
  38. #endif
  39. }
  40. public void DestroyUnityObject()
  41. {
  42. if (UnityObject != null)
  43. {
  44. #if UNITY_WEBPLAYER
  45. Application.ExternalCall("HideCodeBlock");
  46. #endif
  47. UnityEngine.Object.Destroy(UnityObject);
  48. UnityObject = null;
  49. }
  50. }
  51. }
  52. public class SampleSelector : MonoBehaviour
  53. {
  54. public const int statisticsHeight = 160;
  55. List<SampleDescriptor> Samples = new List<SampleDescriptor>();
  56. public static SampleDescriptor SelectedSample;
  57. Vector2 scrollPos;
  58. void Awake()
  59. {
  60. HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
  61. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  62. BestHTTP.HTTPManager.UseAlternateSSLDefaultValue = true;
  63. #endif
  64. #if UNITY_SAMSUNGTV
  65. SamsungTV.touchPadMode = SamsungTV.TouchPadMode.Mouse;
  66. // Create a red 'cursor' to see where we are pointing to
  67. Texture2D tex = new Texture2D(8, 8, TextureFormat.RGB24, false);
  68. for (int i = 0; i < tex.width; ++i)
  69. for (int cv = 0; cv < tex.height; ++cv)
  70. tex.SetPixel(i, cv, Color.red);
  71. tex.Apply(false, true);
  72. Cursor.SetCursor(tex, Vector2.zero, CursorMode.Auto);
  73. #endif
  74. #if UNITY_WEBPLAYER
  75. #if !BESTHTTP_DISABLE_PROXY
  76. // Set up a global proxy in webplayer builds to breach the Socket Policy Service restriction
  77. BestHTTP.HTTPManager.Proxy = new BestHTTP.HTTPProxy(new Uri("http://u3assets.cloudapp.net:8888"), null, true);
  78. #endif
  79. #endif
  80. Samples.Add(new SampleDescriptor(null, "HTTP Samples", string.Empty, string.Empty) { IsLabel = true } );
  81. Samples.Add(new SampleDescriptor(typeof(TextureDownloadSample), "Texture Download", "With HTTPManager.MaxConnectionPerServer you can control how many requests can be processed per server parallel.\n\nFeatures demoed in this example:\n-Parallel requests to the same server\n-Controlling the parallelization\n-Automatic Caching\n-Create a Texture2D from the downloaded data", CodeBlocks.TextureDownloadSample));
  82. Samples.Add(new SampleDescriptor(typeof(AssetBundleSample), "AssetBundle Download", "A small example that shows a possible way to download an AssetBundle and load a resource from it.\n\nFeatures demoed in this example:\n-Using HTTPRequest without a callback\n-Using HTTPRequest in a Coroutine\n-Loading an AssetBundle from the downloaded bytes\n-Automatic Caching", CodeBlocks.AssetBundleSample));
  83. #if !UNITY_WEBGL || UNITY_EDITOR
  84. Samples.Add(new SampleDescriptor(typeof(LargeFileDownloadSample), "Large File Download", "This example demonstrates how you can download a (large) file and continue the download after the connection is aborted.\n\nFeatures demoed in this example:\n-Setting up a streamed download\n-How to access the downloaded data while the download is in progress\n-Setting the HTTPRequest's StreamFragmentSize to controll the frequency and size of the fragments\n-How to use the SetRangeHeader to continue a previously disconnected download\n-How to disable the local, automatic caching", CodeBlocks.LargeFileDownloadSample));
  85. #endif
  86. #if !BESTHTTP_DISABLE_WEBSOCKET
  87. Samples.Add(new SampleDescriptor(null, "WebSocket Samples", string.Empty, string.Empty) { IsLabel = true });
  88. Samples.Add(new SampleDescriptor(typeof(WebSocketSample), "Echo", "A WebSocket demonstration that connects to a WebSocket echo service.\n\nFeatures demoed in this example:\n-Basic usage of the WebSocket class", CodeBlocks.WebSocketSample));
  89. #endif
  90. #if !BESTHTTP_DISABLE_SOCKETIO
  91. Samples.Add(new SampleDescriptor(null, "Socket.IO Samples", string.Empty, string.Empty) { IsLabel = true });
  92. Samples.Add(new SampleDescriptor(typeof(SocketIOChatSample), "Chat", "This example uses the Socket.IO implementation to connect to the official Chat demo server(http://chat.socket.io/).\n\nFeatures demoed in this example:\n-Instantiating and setting up a SocketManager to connect to a Socket.IO server\n-Changing SocketOptions property\n-Subscribing to Socket.IO events\n-Sending custom events to the server", CodeBlocks.SocketIOChatSample));
  93. Samples.Add(new SampleDescriptor(typeof(SocketIOWePlaySample), "WePlay", "This example uses the Socket.IO implementation to connect to the official WePlay demo server(http://weplay.io/).\n\nFeatures demoed in this example:\n-Instantiating and setting up a SocketManager to connect to a Socket.IO server\n-Subscribing to Socket.IO events\n-Receiving binary data\n-How to load a texture from the received binary data\n-How to disable payload decoding for fine tune for some speed\n-Sending custom events to the server", CodeBlocks.SocketIOWePlaySample));
  94. #endif
  95. #if !BESTHTTP_DISABLE_SIGNALR
  96. Samples.Add(new SampleDescriptor(null, "SignalR Samples", string.Empty, string.Empty) { IsLabel = true });
  97. Samples.Add(new SampleDescriptor(typeof(SimpleStreamingSample), "Simple Streaming", "A very simple example of a background thread that broadcasts the server time to all connected clients every two seconds.\n\nFeatures demoed in this example:\n-Subscribing and handling non-hub messages", CodeBlocks.SignalR_SimpleStreamingSample));
  98. Samples.Add(new SampleDescriptor(typeof(ConnectionAPISample), "Connection API", "Demonstrates all features of the lower-level connection API including starting and stopping, sending and receiving messages, and managing groups.\n\nFeatures demoed in this example:\n-Instantiating and setting up a SignalR Connection to connect to a SignalR server\n-Changing the default Json encoder\n-Subscribing to state changes\n-Receiving and handling of non-hub messages\n-Sending non-hub messages\n-Managing groups", CodeBlocks.SignalR_ConnectionAPISample));
  99. Samples.Add(new SampleDescriptor(typeof(ConnectionStatusSample), "Connection Status", "Demonstrates how to handle the events that are raised when connections connect, reconnect and disconnect from the Hub API.\n\nFeatures demoed in this example:\n-Connecting to a Hub\n-Setting up a callback for Hub events\n-Handling server-sent method call requests\n-Calling a Hub-method on the server-side\n-Opening and closing the SignalR Connection", CodeBlocks.SignalR_ConnectionStatusSample));
  100. Samples.Add(new SampleDescriptor(typeof(DemoHubSample), "Demo Hub", "A contrived example that exploits every feature of the Hub API.\n\nFeatures demoed in this example:\n-Creating and using wrapper Hub classes to encapsulate hub functions and events\n-Handling long running server-side functions by handling progress messages\n-Groups\n-Handling server-side functions with return value\n-Handling server-side functions throwing Exceptions\n-Calling server-side functions with complex type parameters\n-Calling server-side functions with array parameters\n-Calling overloaded server-side functions\n-Changing Hub states\n-Receiving and handling hub state changes\n-Calling server-side functions implemented in VB .NET", CodeBlocks.SignalR_DemoHubSample));
  101. #if !UNITY_WEBGL
  102. Samples.Add(new SampleDescriptor(typeof(AuthenticationSample), "Authentication", "Demonstrates how to use the authorization features of the Hub API to restrict certain Hubs and methods to specific users.\n\nFeatures demoed in this example:\n-Creating and using wrapper Hub classes to encapsulate hub functions and events\n-Create and use a Header-based authenticator to access protected APIs\n-SignalR over HTTPS", CodeBlocks.SignalR_AuthenticationSample));
  103. #endif
  104. #endif
  105. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  106. Samples.Add(new SampleDescriptor(null, "Plugin Samples", string.Empty, string.Empty) { IsLabel = true });
  107. Samples.Add(new SampleDescriptor(typeof(CacheMaintenanceSample), "Cache Maintenance", "With this demo you can see how you can use the HTTPCacheService's BeginMaintainence function to delete too old cached entities and keep the cache size under a specified value.\n\nFeatures demoed in this example:\n-How to set up a HTTPCacheMaintananceParams\n-How to call the BeginMaintainence function", CodeBlocks.CacheMaintenanceSample));
  108. #endif
  109. SelectedSample = Samples[1];
  110. }
  111. void Start()
  112. {
  113. GUIHelper.ClientArea = new Rect(0, SampleSelector.statisticsHeight + 5, Screen.width, Screen.height - SampleSelector.statisticsHeight - 50);
  114. }
  115. void Update()
  116. {
  117. if (Input.GetKeyDown(KeyCode.Escape))
  118. {
  119. if (SelectedSample != null && SelectedSample.IsRunning)
  120. SelectedSample.DestroyUnityObject();
  121. else
  122. Application.Quit();
  123. }
  124. if (Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return))
  125. {
  126. if (SelectedSample != null && !SelectedSample.IsRunning)
  127. SelectedSample.CreateUnityObject();
  128. }
  129. }
  130. void OnGUI()
  131. {
  132. var stats = HTTPManager.GetGeneralStatistics(StatisticsQueryFlags.All);
  133. // Connection statistics
  134. GUIHelper.DrawArea(new Rect(0, 0, Screen.width / 3, statisticsHeight), false, () =>
  135. {
  136. // Header
  137. GUIHelper.DrawCenteredText("Connections");
  138. GUILayout.Space(5);
  139. GUIHelper.DrawRow("Sum:", stats.Connections.ToString());
  140. GUIHelper.DrawRow("Active:", stats.ActiveConnections.ToString());
  141. GUIHelper.DrawRow("Free:", stats.FreeConnections.ToString());
  142. GUIHelper.DrawRow("Recycled:", stats.RecycledConnections.ToString());
  143. GUIHelper.DrawRow("Requests in queue:", stats.RequestsInQueue.ToString());
  144. });
  145. // Cache statistics
  146. GUIHelper.DrawArea(new Rect(Screen.width / 3, 0, Screen.width / 3, statisticsHeight), false, () =>
  147. {
  148. GUIHelper.DrawCenteredText("Cache");
  149. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  150. if (!BestHTTP.Caching.HTTPCacheService.IsSupported)
  151. {
  152. #endif
  153. GUI.color = Color.yellow;
  154. GUIHelper.DrawCenteredText("Disabled in WebPlayer, WebGL & Samsung Smart TV Builds!");
  155. GUI.color = Color.white;
  156. #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
  157. }
  158. else
  159. {
  160. GUILayout.Space(5);
  161. GUIHelper.DrawRow("Cached entities:", stats.CacheEntityCount.ToString());
  162. GUIHelper.DrawRow("Sum Size (bytes): ", stats.CacheSize.ToString("N0"));
  163. GUILayout.BeginVertical();
  164. GUILayout.FlexibleSpace();
  165. if (GUILayout.Button("Clear Cache"))
  166. BestHTTP.Caching.HTTPCacheService.BeginClear();
  167. GUILayout.EndVertical();
  168. }
  169. #endif
  170. });
  171. // Cookie statistics
  172. GUIHelper.DrawArea(new Rect((Screen.width / 3) * 2, 0, Screen.width / 3, statisticsHeight), false, () =>
  173. {
  174. GUIHelper.DrawCenteredText("Cookies");
  175. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  176. if (!BestHTTP.Cookies.CookieJar.IsSavingSupported)
  177. {
  178. #endif
  179. GUI.color = Color.yellow;
  180. GUIHelper.DrawCenteredText("Saving and loading from disk is disabled in WebPlayer, WebGL & Samsung Smart TV Builds!");
  181. GUI.color = Color.white;
  182. #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
  183. }
  184. else
  185. {
  186. GUILayout.Space(5);
  187. GUIHelper.DrawRow("Cookies:", stats.CookieCount.ToString());
  188. GUIHelper.DrawRow("Estimated size (bytes):", stats.CookieJarSize.ToString("N0"));
  189. GUILayout.BeginVertical();
  190. GUILayout.FlexibleSpace();
  191. if (GUILayout.Button("Clear Cookies"))
  192. BestHTTP.Cookies.CookieJar.Clear();
  193. GUILayout.EndVertical();
  194. }
  195. #endif
  196. });
  197. if (SelectedSample == null || (SelectedSample != null && !SelectedSample.IsRunning))
  198. {
  199. // Draw the list of samples
  200. GUIHelper.DrawArea(new Rect(0, statisticsHeight + 5, SelectedSample == null ? Screen.width : Screen.width / 3, Screen.height - statisticsHeight - 5), false, () =>
  201. {
  202. scrollPos = GUILayout.BeginScrollView(scrollPos);
  203. for (int i = 0; i < Samples.Count; ++i)
  204. DrawSample(Samples[i]);
  205. GUILayout.EndScrollView();
  206. });
  207. if (SelectedSample != null)
  208. DrawSampleDetails(SelectedSample);
  209. }
  210. else if (SelectedSample != null && SelectedSample.IsRunning)
  211. {
  212. GUILayout.BeginArea(new Rect(0, Screen.height - 50, Screen.width, 50), string.Empty);
  213. GUILayout.FlexibleSpace();
  214. GUILayout.BeginHorizontal();
  215. GUILayout.FlexibleSpace();
  216. GUILayout.BeginVertical();
  217. GUILayout.FlexibleSpace();
  218. if (GUILayout.Button("Back", GUILayout.MinWidth(100)))
  219. SelectedSample.DestroyUnityObject();
  220. GUILayout.FlexibleSpace();
  221. GUILayout.EndVertical();
  222. GUILayout.EndHorizontal();
  223. GUILayout.EndArea();
  224. }
  225. }
  226. private void DrawSample(SampleDescriptor sample)
  227. {
  228. if (sample.IsLabel)
  229. {
  230. GUILayout.Space(15);
  231. GUIHelper.DrawCenteredText(sample.DisplayName);
  232. GUILayout.Space(5);
  233. }
  234. else if (GUILayout.Button(sample.DisplayName))
  235. {
  236. sample.IsSelected = true;
  237. if (SelectedSample != null)
  238. SelectedSample.IsSelected = false;
  239. SelectedSample = sample;
  240. }
  241. }
  242. private void DrawSampleDetails(SampleDescriptor sample)
  243. {
  244. Rect area = new Rect(Screen.width / 3, statisticsHeight + 5, (Screen.width / 3) * 2, Screen.height - statisticsHeight - 5);
  245. GUI.Box(area, string.Empty);
  246. GUILayout.BeginArea(area);
  247. GUILayout.BeginVertical();
  248. GUIHelper.DrawCenteredText(sample.DisplayName);
  249. GUILayout.Space(5);
  250. GUILayout.Label(sample.Description);
  251. GUILayout.FlexibleSpace();
  252. if (GUILayout.Button("Start Sample"))
  253. sample.CreateUnityObject();
  254. GUILayout.EndVertical();
  255. GUILayout.EndArea();
  256. }
  257. }