MenuComponent.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //-----------------------------------------------------------------------------
  2. // MenuComponent.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Graphics;
  13. using Microsoft.Xna.Framework.Input;
  14. namespace XnaGraphicsDemo
  15. {
  16. /// <summary>
  17. /// Base class for all the different screens used in the demo. This provides
  18. /// a simple touch menu which can display a list of options, and detect when
  19. /// a menu item is clicked.
  20. /// </summary>
  21. class MenuComponent : DrawableGameComponent
  22. {
  23. // Properties.
  24. /// <summary>
  25. /// Gets the game instance as a DemoGame.
  26. /// </summary>
  27. new public DemoGame Game { get { return (DemoGame)base.Game; } }
  28. /// <returns>The game instance as a DemoGame.</returns>
  29. /// <summary>
  30. /// Gets the SpriteBatch used for drawing.
  31. /// </summary>
  32. public SpriteBatch SpriteBatch { get { return Game.SpriteBatch; } }
  33. /// <returns>The SpriteBatch used for drawing.</returns>
  34. /// <summary>
  35. /// Gets the default font for menu text.
  36. /// </summary>
  37. public SpriteFont Font { get { return Game.Font; } }
  38. /// <returns>The default font for menu text.</returns>
  39. /// <summary>
  40. /// Gets the large font for menu titles.
  41. /// </summary>
  42. public SpriteFont BigFont { get { return Game.BigFont; } }
  43. /// <returns>The large font for menu titles.</returns>
  44. /// <summary>
  45. /// Gets the list of menu entries.
  46. /// </summary>
  47. protected List<MenuEntry> Entries { get; private set; }
  48. /// <returns>The list of menu entries.</returns>
  49. /// <summary>
  50. /// Gets the last touch point position.
  51. /// </summary>
  52. protected Vector2 LastTouchPoint { get; private set; }
  53. /// <returns>The last touch point position.</returns>
  54. // Fields.
  55. /// <summary>
  56. /// Indicates whether a touch is currently active.
  57. /// </summary>
  58. bool touchDown = true;
  59. /// <summary>
  60. /// The index of the currently selected menu entry for navigation.
  61. /// Also used in attract mode to keep everything in sync.
  62. /// </summary>
  63. protected int selectedEntry = 0;
  64. // Static field to track the last selected menu item across all menus
  65. /// <summary>
  66. /// Tracks the last selected menu item across all menus.
  67. /// </summary>
  68. static int lastSelectedMenuItem = 0;
  69. /// <summary>
  70. /// Timer for attract (demo) mode inactivity.
  71. /// </summary>
  72. static TimeSpan attractTimer;
  73. /// <summary>
  74. /// Stores the last mouse input state.
  75. /// </summary>
  76. static MouseState lastInputState = new MouseState(-1, -1, -1, 0, 0, 0, 0, 0);
  77. /// <summary>
  78. /// Stores the last keyboard input state.
  79. /// </summary>
  80. static KeyboardState lastKeyboardState;
  81. /// <summary>
  82. /// Constructor.
  83. /// </summary>
  84. public MenuComponent(DemoGame game)
  85. : base(game)
  86. {
  87. Entries = new List<MenuEntry>();
  88. }
  89. /// <summary>
  90. /// Initializes the menu, computing the screen position of each entry.
  91. /// </summary>
  92. public override void Initialize()
  93. {
  94. Vector2 pos = new Vector2(MenuEntry.Border, 800 - MenuEntry.Border - Entries.Count * MenuEntry.Height);
  95. foreach (MenuEntry entry in Entries)
  96. {
  97. entry.Position = pos;
  98. pos.Y += MenuEntry.Height;
  99. }
  100. base.Initialize();
  101. }
  102. /// <summary>
  103. /// Resets the menu, whenever we transition to or from a different screen.
  104. /// </summary>
  105. virtual public void Reset()
  106. {
  107. if (selectedEntry >= 0)
  108. Entries[selectedEntry].IsFocused = false;
  109. touchDown = true;
  110. // Restore the last selected menu item if valid, otherwise select the first item
  111. selectedEntry = (lastSelectedMenuItem >= 0 && lastSelectedMenuItem < Entries.Count)
  112. ? lastSelectedMenuItem
  113. : 0;
  114. // Set initial keyboard focus
  115. UpdateMenuFocus();
  116. }
  117. /// <summary>
  118. /// Updates the menu state, processing user input.
  119. /// </summary>
  120. public override void Update(GameTime gameTime)
  121. {
  122. // We read input using the mouse API, which will report the first touch point
  123. // when run on the phone, but also works on Windows using a regular mouse.
  124. MouseState input = Game.IsActive ? Mouse.GetState() : new MouseState();
  125. KeyboardState keyboardInput = Game.IsActive ? Keyboard.GetState() : new KeyboardState();
  126. // Handle keyboard input
  127. HandleKeyboardInput(keyboardInput);
  128. // Scale input if we are running in an unusual screen resolution.
  129. int touchX = input.X * 480 / Game.Graphics.PreferredBackBufferWidth;
  130. int touchY = input.Y * 800 / Game.Graphics.PreferredBackBufferHeight;
  131. // Process the input.
  132. if (input.LeftButton == ButtonState.Pressed)
  133. {
  134. HandleTouchDown(touchX, touchY);
  135. }
  136. else
  137. {
  138. HandleTouchUp();
  139. }
  140. HandleAttractMode(gameTime, input, keyboardInput);
  141. }
  142. /// <summary>
  143. /// Handles input while a touch is occurring.
  144. /// </summary>
  145. /// <summary>
  146. /// Handles input while a touch is occurring, updating selection and focus.
  147. /// </summary>
  148. void HandleTouchDown(int touchX, int touchY)
  149. {
  150. // Hit test the touch position against the list of menu items.
  151. int currentEntry = -1;
  152. for (int i = 0; i < Entries.Count; i++)
  153. {
  154. if ((touchY >= Entries[i].Position.Y) && (touchY < Entries[i].Position.Y + MenuEntry.Height))
  155. {
  156. currentEntry = i;
  157. break;
  158. }
  159. }
  160. if (touchDown)
  161. {
  162. // Are we already processing a touch?
  163. if (selectedEntry >= 0)
  164. {
  165. if (currentEntry == selectedEntry || Entries[selectedEntry].IsDraggable)
  166. {
  167. // Pass drag input to the currently selected item.
  168. Entries[selectedEntry].IsFocused = true;
  169. Entries[selectedEntry].OnDragged(touchX - LastTouchPoint.X);
  170. }
  171. else
  172. {
  173. // If the drag moves off the selected item, unfocus it.
  174. Entries[selectedEntry].IsFocused = false;
  175. }
  176. }
  177. else
  178. {
  179. // If the touch was not on any menu item, process a backgroun drag.
  180. OnDrag(new Vector2(touchX, touchY) - LastTouchPoint);
  181. }
  182. }
  183. else
  184. {
  185. // We are not currently processing a touch.
  186. touchDown = true;
  187. selectedEntry = currentEntry;
  188. // Clear keyboard focus when using touch
  189. foreach (MenuEntry entry in Entries)
  190. entry.IsFocused = false;
  191. if (selectedEntry >= 0)
  192. {
  193. // Focus the menu item that has just been touched.
  194. Entries[selectedEntry].IsFocused = true;
  195. }
  196. }
  197. // Store the most recent touch location.
  198. LastTouchPoint = new Vector2(touchX, touchY);
  199. }
  200. /// <summary>
  201. /// Handles input when the touch is released.
  202. /// </summary>
  203. /// <summary>
  204. /// Handles input when the touch is released, triggering click actions if needed.
  205. /// </summary>
  206. void HandleTouchUp()
  207. {
  208. if (touchDown && selectedEntry >= 0 && Entries[selectedEntry].IsFocused)
  209. {
  210. // Save the current selection as the last selected menu item
  211. lastSelectedMenuItem = selectedEntry;
  212. // If we were touching a menu item, and just released it, process the click action.
  213. Entries[selectedEntry].IsFocused = false;
  214. Entries[selectedEntry].OnClicked();
  215. }
  216. touchDown = false;
  217. }
  218. /// <summary>
  219. /// Checks if there's any actual keyboard activity between two keyboard states.
  220. /// </summary>
  221. /// <summary>
  222. /// Checks if there is any keyboard activity between two keyboard states.
  223. /// </summary>
  224. /// <param name="current">The current keyboard state.</param>
  225. /// <param name="previous">The previous keyboard state.</param>
  226. /// <returns>True if there is keyboard activity; otherwise, false.</returns>
  227. bool HasKeyboardActivity(KeyboardState current, KeyboardState previous)
  228. {
  229. // Check if any key was pressed or released
  230. Keys[] currentKeys = current.GetPressedKeys();
  231. Keys[] previousKeys = previous.GetPressedKeys();
  232. // If the number of pressed keys changed, there's activity
  233. if (currentKeys.Length != previousKeys.Length)
  234. return true;
  235. // Check if any different keys are pressed
  236. foreach (Keys key in currentKeys)
  237. {
  238. if (!previous.IsKeyDown(key))
  239. return true;
  240. }
  241. foreach (Keys key in previousKeys)
  242. {
  243. if (!current.IsKeyDown(key))
  244. return true;
  245. }
  246. return false;
  247. }
  248. /// <summary>
  249. /// If no input is provided, we go into an automatic attract mode, which cycles
  250. /// through the various options. This was great for leaving the demo unattended
  251. /// at the kiosk during the MIX10 conference!
  252. /// </summary>
  253. /// <param name="gameTime">The current game time.</param>
  254. /// <param name="input">The current mouse state.</param>
  255. /// <param name="keyboardInput">The current keyboard state.</param>
  256. void HandleAttractMode(GameTime gameTime, MouseState input, KeyboardState keyboardInput)
  257. {
  258. // Check if there's any actual keyboard activity
  259. bool keyboardActivity = HasKeyboardActivity(keyboardInput, lastKeyboardState);
  260. if (input != lastInputState || keyboardActivity || touchDown)
  261. {
  262. // If input has changed, reset the timer.
  263. attractTimer = TimeSpan.FromSeconds(-15);
  264. lastInputState = input;
  265. lastKeyboardState = keyboardInput;
  266. }
  267. else
  268. {
  269. // If no input occurs, increment the timer.
  270. attractTimer += gameTime.ElapsedGameTime;
  271. if (attractTimer > AttractDelay)
  272. {
  273. // Timeout! Run the attract action.
  274. attractTimer = TimeSpan.Zero;
  275. OnAttract();
  276. }
  277. }
  278. }
  279. /// <summary>
  280. /// Allows subclasses to customize their attract behavior. The default is
  281. /// to simulate a click on the last menu entry, which is usually "back".
  282. /// </summary>
  283. protected virtual void OnAttract()
  284. {
  285. Entries[Entries.Count - 1].OnClicked();
  286. }
  287. /// <summary>
  288. /// Allows subclasses to customize how long they wait before cycling through the attract sequence.
  289. /// </summary>
  290. protected virtual TimeSpan AttractDelay { get { return TimeSpan.FromSeconds(10); } }
  291. /// <summary>
  292. /// Draws the list of menu entries.
  293. /// </summary>
  294. public override void Draw(GameTime gameTime)
  295. {
  296. SpriteBatch.Begin(0, null, null, null, null, null, Game.ScaleMatrix);
  297. foreach (MenuEntry entry in Entries)
  298. {
  299. entry.Draw(SpriteBatch, Font, Game.BlankTexture);
  300. }
  301. SpriteBatch.End();
  302. }
  303. /// <summary>
  304. /// Draws the menu title at the top of the screen, optionally with a background color.
  305. /// </summary>
  306. /// <param name="title">The title text to display.</param>
  307. /// <param name="backgroundColor">The background color to use, or null for none.</param>
  308. /// <param name="titleColor">The color to use for the title text.</param>
  309. protected void DrawTitle(string title, Color? backgroundColor, Color titleColor)
  310. {
  311. if (backgroundColor.HasValue)
  312. GraphicsDevice.Clear(backgroundColor.Value);
  313. SpriteBatch.Begin(0, null, null, null, null, null, Game.ScaleMatrix);
  314. SpriteBatch.DrawString(BigFont, title, new Vector2(480, 24), titleColor, MathHelper.PiOver2, Vector2.Zero, 1, 0, 0);
  315. SpriteBatch.End();
  316. }
  317. /// <summary>
  318. /// Handles a drag on the background of the screen. Subclasses can override to implement custom drag behavior.
  319. /// </summary>
  320. /// <param name="delta">The amount the pointer has moved since the last drag event.</param>
  321. protected virtual void OnDrag(Vector2 delta)
  322. {
  323. }
  324. /// <summary>
  325. /// Handles keyboard input for menu navigation and selection.
  326. /// </summary>
  327. /// <param name="keyboardInput">The current keyboard state.</param>
  328. void HandleKeyboardInput(KeyboardState keyboardInput)
  329. {
  330. // Check for new key presses
  331. bool upPressed = keyboardInput.IsKeyDown(Keys.Up) && !lastKeyboardState.IsKeyDown(Keys.Up);
  332. bool downPressed = keyboardInput.IsKeyDown(Keys.Down) && !lastKeyboardState.IsKeyDown(Keys.Down);
  333. bool enterPressed = (keyboardInput.IsKeyDown(Keys.Enter) && !lastKeyboardState.IsKeyDown(Keys.Enter)) ||
  334. (keyboardInput.IsKeyDown(Keys.Space) && !lastKeyboardState.IsKeyDown(Keys.Space));
  335. bool escapePressed = keyboardInput.IsKeyDown(Keys.Escape) && !lastKeyboardState.IsKeyDown(Keys.Escape);
  336. // Handle navigation
  337. if (upPressed && Entries.Count > 0)
  338. {
  339. // Clear touch selection and focus when using keyboard
  340. if (selectedEntry >= 0)
  341. Entries[selectedEntry].IsFocused = false;
  342. selectedEntry--;
  343. if (selectedEntry < 0)
  344. selectedEntry = Entries.Count - 1;
  345. UpdateMenuFocus();
  346. }
  347. else if (downPressed && Entries.Count > 0)
  348. {
  349. // Clear touch selection and focus when using keyboard
  350. if (selectedEntry >= 0)
  351. Entries[selectedEntry].IsFocused = false;
  352. selectedEntry++;
  353. if (selectedEntry >= Entries.Count)
  354. selectedEntry = 0;
  355. UpdateMenuFocus();
  356. }
  357. else if (enterPressed && Entries.Count > 0)
  358. {
  359. // Save the current selection as the last selected menu item
  360. lastSelectedMenuItem = selectedEntry;
  361. // Execute the currently selected menu item
  362. Entries[selectedEntry].OnClicked();
  363. }
  364. else if (escapePressed)
  365. {
  366. // Go back - simulate clicking the last menu entry (usually "back" or "quit")
  367. if (Entries.Count > 0)
  368. Entries[Entries.Count - 1].OnClicked();
  369. }
  370. lastKeyboardState = keyboardInput;
  371. }
  372. /// <summary>
  373. /// Updates the focus state for keyboard navigation, ensuring only the selected entry is focused.
  374. /// </summary>
  375. protected void UpdateMenuFocus()
  376. {
  377. // Clear all focus first
  378. foreach (MenuEntry entry in Entries)
  379. entry.IsFocused = false;
  380. // Set focus on the keyboard-selected item
  381. if (selectedEntry >= 0 && selectedEntry < Entries.Count)
  382. Entries[selectedEntry].IsFocused = true;
  383. }
  384. /// <summary>
  385. /// Gets the currently selected menu item index for keyboard navigation.
  386. /// </summary>
  387. /// <returns>The index of the selected menu item.</returns>
  388. public int GetSelectedIndex()
  389. {
  390. return selectedEntry;
  391. }
  392. /// <summary>
  393. /// Sets the selected menu item index for keyboard navigation, updating focus accordingly.
  394. /// </summary>
  395. /// <param name="index">The index of the menu item to select.</param>
  396. public void SetSelectedIndex(int index)
  397. {
  398. if (index >= 0 && index < Entries.Count)
  399. {
  400. selectedEntry = index;
  401. lastSelectedMenuItem = index;
  402. UpdateMenuFocus();
  403. }
  404. }
  405. }
  406. }