PopoverMenu.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Provides a cascading popover menu.
  6. /// </summary>
  7. public class PopoverMenu : PopoverBaseImpl
  8. {
  9. /// <summary>
  10. /// Initializes a new instance of the <see cref="PopoverMenu"/> class.
  11. /// </summary>
  12. public PopoverMenu () : this (null) { }
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="PopoverMenu"/> class with the specified root <see cref="Menuv2"/>.
  15. /// </summary>
  16. public PopoverMenu (Menuv2? root)
  17. {
  18. base.Visible = false;
  19. //base.ColorScheme = Colors.ColorSchemes ["Menu"];
  20. Root = root;
  21. AddCommand (Command.Right, MoveRight);
  22. KeyBindings.Add (Key.CursorRight, Command.Right);
  23. AddCommand (Command.Left, MoveLeft);
  24. KeyBindings.Add (Key.CursorLeft, Command.Left);
  25. // TODO: Remove; for debugging for now
  26. AddCommand (
  27. Command.NotBound,
  28. ctx =>
  29. {
  30. Logging.Trace ($"popoverMenu NotBound: {ctx}");
  31. return false;
  32. });
  33. KeyBindings.Add (DefaultKey, Command.Quit);
  34. KeyBindings.ReplaceCommands (Application.QuitKey, Command.Quit);
  35. AddCommand (
  36. Command.Quit,
  37. ctx =>
  38. {
  39. if (!Visible)
  40. {
  41. return false;
  42. }
  43. Visible = false;
  44. return RaiseAccepted (ctx);
  45. });
  46. return;
  47. bool? MoveLeft (ICommandContext? ctx)
  48. {
  49. if (Focused == Root)
  50. {
  51. return false;
  52. }
  53. if (MostFocused is MenuItemv2 { SuperView: Menuv2 focusedMenu })
  54. {
  55. focusedMenu.SuperMenuItem?.SetFocus ();
  56. return true;
  57. }
  58. return AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop);
  59. }
  60. bool? MoveRight (ICommandContext? ctx)
  61. {
  62. if (Focused == Root)
  63. {
  64. return false;
  65. }
  66. if (MostFocused is MenuItemv2 { SubMenu.Visible: true } focused)
  67. {
  68. focused.SubMenu.SetFocus ();
  69. return true;
  70. }
  71. return AdvanceFocus (NavigationDirection.Forward, TabBehavior.TabStop);
  72. }
  73. }
  74. /// <summary>
  75. /// The mouse flags that will cause the popover menu to be visible. The default is
  76. /// <see cref="MouseFlags.Button3Clicked"/> which is typically the right mouse button.
  77. /// </summary>
  78. public static MouseFlags MouseFlags { get; set; } = MouseFlags.Button3Clicked;
  79. /// <summary>The default key for activating popover menus.</summary>
  80. [SerializableConfigurationProperty (Scope = typeof (SettingsScope))]
  81. public static Key DefaultKey { get; set; } = Key.F10.WithShift;
  82. /// <summary>
  83. /// Makes the popover menu visible and locates it at <paramref name="idealScreenPosition"/>. The actual position of the menu
  84. /// will be adjusted to
  85. /// ensure the menu fully fits on the screen, and the mouse cursor is over the first cell of the
  86. /// first MenuItem.
  87. /// </summary>
  88. /// <param name="idealScreenPosition">If <see langword="null"/>, the current mouse position will be used.</param>
  89. public void MakeVisible (Point? idealScreenPosition = null)
  90. {
  91. UpdateKeyBindings ();
  92. SetPosition (idealScreenPosition);
  93. Application.Popover?.ShowPopover (this);
  94. }
  95. /// <summary>
  96. /// Locates the popover menu at <paramref name="idealScreenPosition"/>. The actual position of the menu will be adjusted to
  97. /// ensure the menu fully fits on the screen, and the mouse cursor is over the first cell of the
  98. /// first MenuItem (if possible).
  99. /// </summary>
  100. /// <param name="idealScreenPosition">If <see langword="null"/>, the current mouse position will be used.</param>
  101. public void SetPosition (Point? idealScreenPosition = null)
  102. {
  103. idealScreenPosition ??= Application.GetLastMousePosition ();
  104. if (idealScreenPosition is { } && Root is { })
  105. {
  106. Point pos = idealScreenPosition.Value;
  107. if (!Root.IsInitialized)
  108. {
  109. Root.BeginInit();
  110. Root.EndInit ();
  111. Root.Layout ();
  112. }
  113. pos = GetMostVisibleLocationForSubMenu (Root, pos);
  114. Root.X = pos.X;
  115. Root.Y = pos.Y;
  116. }
  117. }
  118. /// <inheritdoc/>
  119. protected override void OnVisibleChanged ()
  120. {
  121. base.OnVisibleChanged ();
  122. if (Visible)
  123. {
  124. AddAndShowSubMenu (_root);
  125. }
  126. else
  127. {
  128. HideAndRemoveSubMenu (_root);
  129. Application.Popover?.HidePopover (this);
  130. }
  131. }
  132. private Menuv2? _root;
  133. /// <summary>
  134. /// Gets or sets the <see cref="Menuv2"/> that is the root of the Popover Menu.
  135. /// </summary>
  136. public Menuv2? Root
  137. {
  138. get => _root;
  139. set
  140. {
  141. if (_root == value)
  142. {
  143. return;
  144. }
  145. if (_root is { })
  146. {
  147. _root.Accepting -= MenuOnAccepting;
  148. }
  149. HideAndRemoveSubMenu (_root);
  150. _root = value;
  151. if (_root is { })
  152. {
  153. _root.Accepting += MenuOnAccepting;
  154. }
  155. UpdateKeyBindings ();
  156. IEnumerable<Menuv2> allMenus = GetAllSubMenus ();
  157. foreach (Menuv2 menu in allMenus)
  158. {
  159. menu.Accepting += MenuOnAccepting;
  160. menu.Accepted += MenuAccepted;
  161. menu.SelectedMenuItemChanged += MenuOnSelectedMenuItemChanged;
  162. }
  163. }
  164. }
  165. private void UpdateKeyBindings ()
  166. {
  167. // TODO: This needs to be done whenever any MenuItem in the menu tree changes to support dynamic menus
  168. // TODO: And it needs to clear them first
  169. IEnumerable<MenuItemv2> all = GetMenuItemsOfAllSubMenus ();
  170. foreach (MenuItemv2 menuItem in all.Where(mi => mi.Command != Command.NotBound))
  171. {
  172. if (menuItem.TargetView is { })
  173. {
  174. // A TargetView implies HotKey
  175. // Automatically set MenuItem.Key
  176. Key? key = menuItem.TargetView.HotKeyBindings.GetFirstFromCommands (menuItem.Command);
  177. if (key is { IsValid: true })
  178. {
  179. if (menuItem.Key.IsValid)
  180. {
  181. //Logging.Warning ("Do not specify a Key for MenuItems where a Command is specified. Key will be determined automatically.");
  182. }
  183. menuItem.Key = key;
  184. Logging.Trace ($"HotKey: {menuItem.Key}->{menuItem.Command}");
  185. }
  186. }
  187. else
  188. {
  189. // No TargetView implies Application HotKey
  190. Key? key = Application.KeyBindings.GetFirstFromCommands (menuItem.Command);
  191. if (key is { IsValid: true })
  192. {
  193. if (menuItem.Key.IsValid)
  194. {
  195. // Logging.Warning ("App HotKey: Do not specify a Key for MenuItems where a Command is specified. Key will be determined automatically.");
  196. }
  197. menuItem.Key = key;
  198. Logging.Trace ($"App HotKey: {menuItem.Key}->{menuItem.Command}");
  199. }
  200. }
  201. }
  202. foreach (MenuItemv2 menuItem in all.Where (mi => mi is { Command: Command.NotBound, Key.IsValid: true }))
  203. {
  204. }
  205. }
  206. /// <inheritdoc/>
  207. protected override bool OnKeyDownNotHandled (Key key)
  208. {
  209. // See if any of our MenuItems have this key as Key
  210. IEnumerable<MenuItemv2> all = GetMenuItemsOfAllSubMenus ();
  211. foreach (MenuItemv2 menuItem in all)
  212. {
  213. if (menuItem.Key == key)
  214. {
  215. return menuItem.NewKeyDownEvent (key);
  216. }
  217. }
  218. return base.OnKeyDownNotHandled (key);
  219. }
  220. /// <summary>
  221. /// Gets all the submenus in the PopoverMenu.
  222. /// </summary>
  223. /// <returns></returns>
  224. internal IEnumerable<Menuv2> GetAllSubMenus ()
  225. {
  226. List<Menuv2> result = [];
  227. if (Root == null)
  228. {
  229. return result;
  230. }
  231. Stack<Menuv2> stack = new ();
  232. stack.Push (Root);
  233. while (stack.Count > 0)
  234. {
  235. Menuv2 currentMenu = stack.Pop ();
  236. result.Add (currentMenu);
  237. foreach (View subView in currentMenu.SubViews)
  238. {
  239. if (subView is MenuItemv2 menuItem && menuItem.SubMenu != null)
  240. {
  241. stack.Push (menuItem.SubMenu);
  242. }
  243. }
  244. }
  245. return result;
  246. }
  247. /// <summary>
  248. /// Gets all the MenuItems in the PopoverMenu.
  249. /// </summary>
  250. /// <returns></returns>
  251. internal IEnumerable<MenuItemv2> GetMenuItemsOfAllSubMenus ()
  252. {
  253. List<MenuItemv2> result = [];
  254. foreach (Menuv2 menu in GetAllSubMenus ())
  255. {
  256. foreach (View subView in menu.SubViews)
  257. {
  258. if (subView is MenuItemv2 menuItem)
  259. {
  260. result.Add (menuItem);
  261. }
  262. }
  263. }
  264. return result;
  265. }
  266. /// <summary>
  267. /// Pops up the submenu of the specified MenuItem, if there is one.
  268. /// </summary>
  269. /// <param name="menuItem"></param>
  270. internal void ShowSubMenu (MenuItemv2? menuItem)
  271. {
  272. var menu = menuItem?.SuperView as Menuv2;
  273. if (menu is { })
  274. {
  275. menu.Layout ();
  276. }
  277. // If there's a visible peer, remove / hide it
  278. // Debug.Assert (menu is null || menu?.SubViews.Count (v => v is MenuItemv2 { SubMenu.Visible: true }) < 2);
  279. if (menu?.SubViews.FirstOrDefault (v => v is MenuItemv2 { SubMenu.Visible: true }) is MenuItemv2 visiblePeer)
  280. {
  281. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  282. visiblePeer.ForceFocusColors = false;
  283. }
  284. if (menuItem is { SubMenu: { Visible: false } })
  285. {
  286. AddAndShowSubMenu (menuItem.SubMenu);
  287. Point idealLocation = ScreenToViewport (
  288. new (
  289. menuItem.FrameToScreen ().Right - menuItem.SubMenu.GetAdornmentsThickness ().Left,
  290. menuItem.FrameToScreen ().Top - menuItem.SubMenu.GetAdornmentsThickness ().Top));
  291. Point pos = GetMostVisibleLocationForSubMenu (menuItem.SubMenu, idealLocation);
  292. menuItem.SubMenu.X = pos.X;
  293. menuItem.SubMenu.Y = pos.Y;
  294. menuItem.ForceFocusColors = true;
  295. }
  296. }
  297. /// <summary>
  298. /// Gets the most visible screen-relative location for <paramref name="menu"/>.
  299. /// </summary>
  300. /// <param name="menu">The menu to locate.</param>
  301. /// <param name="idealLocation">Ideal screen-relative location.</param>
  302. /// <returns></returns>
  303. internal Point GetMostVisibleLocationForSubMenu (Menuv2 menu, Point idealLocation)
  304. {
  305. var pos = Point.Empty;
  306. // Calculate the initial position to the right of the menu item
  307. GetLocationEnsuringFullVisibility (
  308. menu,
  309. idealLocation.X,
  310. idealLocation.Y,
  311. out int nx,
  312. out int ny);
  313. return new (nx, ny);
  314. }
  315. private void AddAndShowSubMenu (Menuv2? menu)
  316. {
  317. if (menu is { SuperView: null })
  318. {
  319. // TODO: Find the menu item below the mouse, if any, and select it
  320. // TODO: Enable No Border menu style
  321. menu.Border.LineStyle = LineStyle.Single;
  322. menu.Border.Thickness = new (1);
  323. if (!menu.IsInitialized)
  324. {
  325. menu.BeginInit ();
  326. menu.EndInit ();
  327. }
  328. menu.ClearFocus ();
  329. base.Add (menu);
  330. // IMPORTANT: This must be done after adding the menu to the super view or Add will try
  331. // to set focus to it.
  332. menu.Visible = true;
  333. menu.Layout ();
  334. }
  335. }
  336. private void HideAndRemoveSubMenu (Menuv2? menu)
  337. {
  338. if (menu is { Visible: true })
  339. {
  340. // If there's a visible submenu, remove / hide it
  341. // Debug.Assert (menu.SubViews.Count (v => v is MenuItemv2 { SubMenu.Visible: true }) <= 1);
  342. if (menu.SubViews.FirstOrDefault (v => v is MenuItemv2 { SubMenu.Visible: true }) is MenuItemv2 visiblePeer)
  343. {
  344. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  345. visiblePeer.ForceFocusColors = false;
  346. }
  347. menu.Visible = false;
  348. menu.ClearFocus ();
  349. base.Remove (menu);
  350. if (menu == Root)
  351. {
  352. Visible = false;
  353. }
  354. }
  355. }
  356. private void MenuOnAccepting (object? sender, CommandEventArgs e)
  357. {
  358. if (e.Context?.Command != Command.HotKey)
  359. {
  360. Visible = false;
  361. }
  362. else
  363. {
  364. // This supports the case when a hotkey of a menuitem with a submenu is pressed
  365. e.Cancel = true;
  366. }
  367. Logging.Trace ($"{e.Context?.Source?.Title}");
  368. }
  369. private void MenuAccepted (object? sender, CommandEventArgs e)
  370. {
  371. Logging.Trace ($"{e.Context?.Source?.Title}");
  372. if (e.Context?.Source is MenuItemv2 { SubMenu: null })
  373. {
  374. HideAndRemoveSubMenu (_root);
  375. RaiseAccepted (e.Context);
  376. }
  377. else if (e.Context?.Source is MenuItemv2 { SubMenu: { } } menuItemWithSubMenu)
  378. {
  379. ShowSubMenu (menuItemWithSubMenu);
  380. }
  381. }
  382. /// <summary>
  383. /// Riases the <see cref="OnAccepted"/>/<see cref="Accepted"/> event indicating a menu (or submenu)
  384. /// was accepted and the Menus in the PopoverMenu were hidden. Use this to determine when to hide the PopoverMenu.
  385. /// </summary>
  386. /// <param name="ctx"></param>
  387. /// <returns></returns>
  388. protected bool? RaiseAccepted (ICommandContext? ctx)
  389. {
  390. Logging.Trace ($"RaiseAccepted: {ctx}");
  391. CommandEventArgs args = new () { Context = ctx };
  392. OnAccepted (args);
  393. Accepted?.Invoke (this, args);
  394. return true;
  395. }
  396. /// <summary>
  397. /// Called when the user has accepted an item in this menu (or submenu. This is used to determine when to hide the
  398. /// menu.
  399. /// </summary>
  400. /// <remarks>
  401. /// </remarks>
  402. /// <param name="args"></param>
  403. protected virtual void OnAccepted (CommandEventArgs args) { }
  404. /// <summary>
  405. /// Raised when the user has accepted an item in this menu (or submenu. This is used to determine when to hide the
  406. /// menu.
  407. /// </summary>
  408. /// <remarks>
  409. /// <para>
  410. /// See <see cref="RaiseAccepted"/> for more information.
  411. /// </para>
  412. /// </remarks>
  413. public event EventHandler<CommandEventArgs>? Accepted;
  414. private void MenuOnSelectedMenuItemChanged (object? sender, MenuItemv2? e)
  415. {
  416. //Logging.Trace ($"{e}");
  417. ShowSubMenu (e);
  418. }
  419. /// <inheritdoc/>
  420. protected override void Dispose (bool disposing)
  421. {
  422. if (disposing)
  423. {
  424. IEnumerable<Menuv2> allMenus = GetAllSubMenus ();
  425. foreach (Menuv2 menu in allMenus)
  426. {
  427. menu.Accepting -= MenuOnAccepting;
  428. menu.Accepted -= MenuAccepted;
  429. menu.SelectedMenuItemChanged -= MenuOnSelectedMenuItemChanged;
  430. }
  431. _root?.Dispose ();
  432. _root = null;
  433. }
  434. base.Dispose (disposing);
  435. }
  436. }