NetworkBusyScreen.cs 5.8 KB

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