NetworkBusyScreen.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. //-----------------------------------------------------------------------------
  2. // NetworkBusyScreen.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Content;
  10. using Microsoft.Xna.Framework.Graphics;
  11. using System.Threading.Tasks;
  12. using Microsoft.Xna.Framework.Input;
  13. namespace NetworkStateManagement
  14. {
  15. /// <summary>
  16. /// When an asynchronous network operation (for instance searching for or joining a
  17. /// session) is in progress, this screen displays a busy indicator and blocks input.
  18. /// It monitors a Task&lt;T&gt; returned by the async call, showing the indicator while
  19. /// the task is running. When the task completes, it raises an event with the
  20. /// operation result (or null on failure), then automatically dismisses itself.
  21. /// Because this screen sits on top while the async operation is in progress, it
  22. /// captures all user input to prevent interaction with underlying screens until
  23. /// the operation completes.
  24. /// </summary>
  25. class NetworkBusyScreen<T> : GameScreen
  26. {
  27. readonly Task<T> task;
  28. readonly System.Threading.CancellationTokenSource cts;
  29. bool completionRaised;
  30. Texture2D gradientTexture;
  31. Texture2D catTexture;
  32. event EventHandler<OperationCompletedEventArgs> operationCompleted;
  33. public event EventHandler<OperationCompletedEventArgs> OperationCompleted
  34. {
  35. add { operationCompleted += value; }
  36. remove { operationCompleted -= value; }
  37. }
  38. /// <summary>
  39. /// Constructs a network busy screen for the specified asynchronous operation.
  40. /// Accepts a Task&lt;T&gt; representing the in-flight operation.
  41. /// </summary>
  42. public NetworkBusyScreen(Task<T> task)
  43. {
  44. this.task = task;
  45. this.cts = null;
  46. IsPopup = true;
  47. TransitionOnTime = TimeSpan.FromSeconds(0.1);
  48. TransitionOffTime = TimeSpan.FromSeconds(0.2);
  49. }
  50. /// <summary>
  51. /// Overload that accepts a CancellationTokenSource to allow user cancellation.
  52. /// </summary>
  53. public NetworkBusyScreen(Task<T> task, System.Threading.CancellationTokenSource cts)
  54. {
  55. this.task = task;
  56. this.cts = cts;
  57. IsPopup = true;
  58. TransitionOnTime = TimeSpan.FromSeconds(0.1);
  59. TransitionOffTime = TimeSpan.FromSeconds(0.2);
  60. }
  61. /// <summary>
  62. /// Loads graphics content for this screen. This uses the shared ContentManager
  63. /// provided by the Game class, so the content will remain loaded forever.
  64. /// Whenever a subsequent NetworkBusyScreen tries to load this same content,
  65. /// it will just get back another reference to the already loaded data.
  66. /// </summary>
  67. public override void LoadContent()
  68. {
  69. ContentManager content = ScreenManager.Game.Content;
  70. gradientTexture = content.Load<Texture2D>("gradient");
  71. catTexture = content.Load<Texture2D>("cat");
  72. }
  73. /// <summary>
  74. /// Updates the NetworkBusyScreen, checking whether the underlying Task has
  75. /// completed and raising OperationCompleted when it does.
  76. /// </summary>
  77. public override void Update(GameTime gameTime, bool otherScreenHasFocus,
  78. bool coveredByOtherScreen)
  79. {
  80. base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
  81. // Optional: allow user to cancel (Esc or B)
  82. if (!completionRaised && cts != null)
  83. {
  84. var kb = Keyboard.GetState();
  85. if (kb.IsKeyDown(Keys.Escape))
  86. {
  87. cts.Cancel();
  88. }
  89. var gp = GamePad.GetState(PlayerIndex.One);
  90. if (gp.IsConnected && gp.IsButtonDown(Buttons.B))
  91. {
  92. cts.Cancel();
  93. }
  94. }
  95. // Has our asynchronous operation completed?
  96. if (!completionRaised && task != null && task.IsCompleted)
  97. {
  98. object resultObject = default(T);
  99. Exception error = null;
  100. try
  101. {
  102. // Accessing Result will throw if the task faulted/canceled.
  103. // We catch here and allow handlers to present error UI.
  104. resultObject = task.Result;
  105. }
  106. catch (Exception ex)
  107. {
  108. // Leave result as default (usually null) to signal failure to handlers.
  109. error = (task?.Exception?.GetBaseException()) ?? ex;
  110. }
  111. var handler = operationCompleted;
  112. if (handler != null)
  113. {
  114. handler(this, new OperationCompletedEventArgs(resultObject, error));
  115. }
  116. completionRaised = true;
  117. // Clear handlers to avoid reentry if this screen lingers during transition off
  118. operationCompleted = null;
  119. ExitScreen();
  120. }
  121. }
  122. /// <summary>
  123. /// Draws the NetworkBusyScreen.
  124. /// </summary>
  125. public override void Draw(GameTime gameTime)
  126. {
  127. SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
  128. SpriteFont font = ScreenManager.Font;
  129. string message = Resources.NetworkBusy;
  130. const int hPad = 32;
  131. const int vPad = 16;
  132. // Center the message text in the viewport.
  133. Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
  134. Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);
  135. Vector2 textSize = font.MeasureString(message);
  136. // Add enough room to spin a cat.
  137. Vector2 catSize = new Vector2(catTexture.Width);
  138. textSize.X = Math.Max(textSize.X, catSize.X);
  139. textSize.Y += catSize.Y + vPad;
  140. Vector2 textPosition = (viewportSize - textSize) / 2;
  141. // The background includes a border somewhat larger than the text itself.
  142. Rectangle backgroundRectangle = new Rectangle((int)textPosition.X - hPad,
  143. (int)textPosition.Y - vPad,
  144. (int)textSize.X + hPad * 2,
  145. (int)textSize.Y + vPad * 2);
  146. // Fade the popup alpha during transitions.
  147. Color color = Color.White * TransitionAlpha;
  148. spriteBatch.Begin();
  149. // Draw the background rectangle.
  150. spriteBatch.Draw(gradientTexture, backgroundRectangle, color);
  151. // Draw the message box text.
  152. spriteBatch.DrawString(font, message, textPosition, color);
  153. // Draw the spinning cat progress indicator.
  154. float catRotation = (float)gameTime.TotalGameTime.TotalSeconds * 3;
  155. Vector2 catPosition = new Vector2(textPosition.X + textSize.X / 2,
  156. textPosition.Y + textSize.Y -
  157. catSize.Y / 2);
  158. spriteBatch.Draw(catTexture, catPosition, null, color, catRotation,
  159. catSize / 2, 1, SpriteEffects.None, 0);
  160. spriteBatch.End();
  161. }
  162. }
  163. }