PopoverMenu.cs 17 KB

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