PopoverMenu.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. /// all other content. Can be used as a context menu or a drop-down
  6. /// menu as part of <see cref="MenuBar"/> as part of <see cref="MenuBar"/>.
  7. /// </summary>
  8. /// <remarks>
  9. /// <para>
  10. /// To use as a context menu, register the popover menu with <see cref="Application.Popover"/> and call
  11. /// <see cref="MakeVisible"/>.
  12. /// </para>
  13. /// </remarks>
  14. public class PopoverMenu : PopoverBaseImpl, IDesignable
  15. {
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="PopoverMenu"/> class.
  18. /// </summary>
  19. public PopoverMenu () : this ((Menuv2?)null) { }
  20. /// <inheritdoc/>
  21. public PopoverMenu (IEnumerable<View>? menuItems) : this (new Menuv2 (menuItems)) { }
  22. /// <inheritdoc/>
  23. public PopoverMenu (IEnumerable<MenuItemv2>? menuItems) : this (new Menuv2 (menuItems)) { }
  24. /// <summary>
  25. /// Initializes a new instance of the <see cref="PopoverMenu"/> class with the specified root <see cref="Menuv2"/>.
  26. /// </summary>
  27. public PopoverMenu (Menuv2? root)
  28. {
  29. Key = DefaultKey;
  30. base.Visible = false;
  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 (Key, 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 false;
  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 false; //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. // TODO: This needs to be done whenever any MenuItem in the menu tree changes to support dynamic menus
  180. // TODO: And it needs to clear the old bindings first
  181. UpdateKeyBindings ();
  182. // TODO: This needs to be done whenever any MenuItem in the menu tree changes to support dynamic menus
  183. IEnumerable<Menuv2> allMenus = GetAllSubMenus ();
  184. foreach (Menuv2 menu in allMenus)
  185. {
  186. menu.Accepting += MenuOnAccepting;
  187. menu.Accepted += MenuAccepted;
  188. menu.SelectedMenuItemChanged += MenuOnSelectedMenuItemChanged;
  189. }
  190. }
  191. }
  192. private void UpdateKeyBindings ()
  193. {
  194. IEnumerable<MenuItemv2> all = GetMenuItemsOfAllSubMenus ();
  195. foreach (MenuItemv2 menuItem in all.Where (mi => mi.Command != Command.NotBound))
  196. {
  197. Key? key;
  198. if (menuItem.TargetView is { })
  199. {
  200. // A TargetView implies HotKey
  201. key = menuItem.TargetView.HotKeyBindings.GetFirstFromCommands (menuItem.Command);
  202. }
  203. else
  204. {
  205. // No TargetView implies Application HotKey
  206. key = Application.KeyBindings.GetFirstFromCommands (menuItem.Command);
  207. }
  208. if (key is not { IsValid: true })
  209. {
  210. continue;
  211. }
  212. if (menuItem.Key.IsValid)
  213. {
  214. //Logging.Warning ("Do not specify a Key for MenuItems where a Command is specified. Key will be determined automatically.");
  215. }
  216. menuItem.Key = key;
  217. //Logging.Trace ($"HotKey: {menuItem.Key}->{menuItem.Command}");
  218. }
  219. }
  220. /// <inheritdoc/>
  221. protected override bool OnKeyDownNotHandled (Key key)
  222. {
  223. // See if any of our MenuItems have this key as Key
  224. IEnumerable<MenuItemv2> all = GetMenuItemsOfAllSubMenus ();
  225. foreach (MenuItemv2 menuItem in all)
  226. {
  227. if (menuItem.Key == key)
  228. {
  229. return menuItem.NewKeyDownEvent (key);
  230. }
  231. }
  232. return base.OnKeyDownNotHandled (key);
  233. }
  234. /// <summary>
  235. /// Gets all the submenus in the PopoverMenu.
  236. /// </summary>
  237. /// <returns></returns>
  238. internal IEnumerable<Menuv2> GetAllSubMenus ()
  239. {
  240. List<Menuv2> result = [];
  241. if (Root == null)
  242. {
  243. return result;
  244. }
  245. Stack<Menuv2> stack = new ();
  246. stack.Push (Root);
  247. while (stack.Count > 0)
  248. {
  249. Menuv2 currentMenu = stack.Pop ();
  250. result.Add (currentMenu);
  251. foreach (View subView in currentMenu.SubViews)
  252. {
  253. if (subView is MenuItemv2 menuItem && menuItem.SubMenu != null)
  254. {
  255. stack.Push (menuItem.SubMenu);
  256. }
  257. }
  258. }
  259. return result;
  260. }
  261. /// <summary>
  262. /// Gets all the MenuItems in the PopoverMenu.
  263. /// </summary>
  264. /// <returns></returns>
  265. internal IEnumerable<MenuItemv2> GetMenuItemsOfAllSubMenus ()
  266. {
  267. List<MenuItemv2> result = [];
  268. foreach (Menuv2 menu in GetAllSubMenus ())
  269. {
  270. foreach (View subView in menu.SubViews)
  271. {
  272. if (subView is MenuItemv2 menuItem)
  273. {
  274. result.Add (menuItem);
  275. }
  276. }
  277. }
  278. return result;
  279. }
  280. /// <summary>
  281. /// Pops up the submenu of the specified MenuItem, if there is one.
  282. /// </summary>
  283. /// <param name="menuItem"></param>
  284. internal void ShowSubMenu (MenuItemv2? menuItem)
  285. {
  286. var menu = menuItem?.SuperView as Menuv2;
  287. menu?.Layout ();
  288. // If there's a visible peer, remove / hide it
  289. if (menu?.SubViews.FirstOrDefault (v => v is MenuItemv2 { SubMenu.Visible: true }) is MenuItemv2 visiblePeer)
  290. {
  291. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  292. visiblePeer.ForceFocusColors = false;
  293. }
  294. if (menuItem is { SubMenu: { Visible: false } })
  295. {
  296. AddAndShowSubMenu (menuItem.SubMenu);
  297. Point idealLocation = ScreenToViewport (
  298. new (
  299. menuItem.FrameToScreen ().Right - menuItem.SubMenu.GetAdornmentsThickness ().Left,
  300. menuItem.FrameToScreen ().Top - menuItem.SubMenu.GetAdornmentsThickness ().Top));
  301. Point pos = GetMostVisibleLocationForSubMenu (menuItem.SubMenu, idealLocation);
  302. menuItem.SubMenu.X = pos.X;
  303. menuItem.SubMenu.Y = pos.Y;
  304. menuItem.ForceFocusColors = true;
  305. }
  306. }
  307. /// <summary>
  308. /// Gets the most visible screen-relative location for <paramref name="menu"/>.
  309. /// </summary>
  310. /// <param name="menu">The menu to locate.</param>
  311. /// <param name="idealLocation">Ideal screen-relative location.</param>
  312. /// <returns></returns>
  313. internal Point GetMostVisibleLocationForSubMenu (Menuv2 menu, Point idealLocation)
  314. {
  315. var pos = Point.Empty;
  316. // Calculate the initial position to the right of the menu item
  317. GetLocationEnsuringFullVisibility (
  318. menu,
  319. idealLocation.X,
  320. idealLocation.Y,
  321. out int nx,
  322. out int ny);
  323. return new (nx, ny);
  324. }
  325. private void AddAndShowSubMenu (Menuv2? menu)
  326. {
  327. if (menu is { SuperView: null })
  328. {
  329. // TODO: Find the menu item below the mouse, if any, and select it
  330. // TODO: Enable No Border menu style
  331. menu.Border!.LineStyle = LineStyle.Single;
  332. menu.Border.Thickness = new (1);
  333. if (!menu.IsInitialized)
  334. {
  335. menu.BeginInit ();
  336. menu.EndInit ();
  337. }
  338. menu.ClearFocus ();
  339. base.Add (menu);
  340. // IMPORTANT: This must be done after adding the menu to the super view or Add will try
  341. // to set focus to it.
  342. menu.Visible = true;
  343. menu.Layout ();
  344. }
  345. }
  346. private void HideAndRemoveSubMenu (Menuv2? menu)
  347. {
  348. if (menu is { Visible: true })
  349. {
  350. // If there's a visible submenu, remove / hide it
  351. if (menu.SubViews.FirstOrDefault (v => v is MenuItemv2 { SubMenu.Visible: true }) is MenuItemv2 visiblePeer)
  352. {
  353. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  354. visiblePeer.ForceFocusColors = false;
  355. }
  356. menu.Visible = false;
  357. menu.ClearFocus ();
  358. base.Remove (menu);
  359. if (menu == Root)
  360. {
  361. Visible = false;
  362. }
  363. }
  364. }
  365. private void MenuOnAccepting (object? sender, CommandEventArgs e)
  366. {
  367. var senderView = sender as View;
  368. Logging.Trace ($"Sender: {senderView?.GetType ().Name}, {e.Context?.Source?.Title}");
  369. if (e.Context?.Command != Command.HotKey)
  370. {
  371. Visible = false;
  372. }
  373. // This supports the case when a hotkey of a menuitem with a submenu is pressed
  374. //e.Cancel = true;
  375. }
  376. private void MenuAccepted (object? sender, CommandEventArgs e)
  377. {
  378. //Logging.Trace ($"{e.Context?.Source?.Title}");
  379. if (e.Context?.Source is MenuItemv2 { SubMenu: null })
  380. {
  381. HideAndRemoveSubMenu (_root);
  382. RaiseAccepted (e.Context);
  383. }
  384. else if (e.Context?.Source is MenuItemv2 { SubMenu: { } } menuItemWithSubMenu)
  385. {
  386. ShowSubMenu (menuItemWithSubMenu);
  387. }
  388. }
  389. /// <summary>
  390. /// Raises the <see cref="OnAccepted"/>/<see cref="Accepted"/> event indicating a menu (or submenu)
  391. /// was accepted and the Menus in the PopoverMenu were hidden. Use this to determine when to hide the PopoverMenu.
  392. /// </summary>
  393. /// <param name="ctx"></param>
  394. /// <returns></returns>
  395. protected bool? RaiseAccepted (ICommandContext? ctx)
  396. {
  397. //Logging.Trace ($"RaiseAccepted: {ctx}");
  398. CommandEventArgs args = new () { Context = ctx };
  399. OnAccepted (args);
  400. Accepted?.Invoke (this, args);
  401. return true;
  402. }
  403. /// <summary>
  404. /// Called when the user has accepted an item in this menu (or submenu. This is used to determine when to hide the
  405. /// menu.
  406. /// </summary>
  407. /// <remarks>
  408. /// </remarks>
  409. /// <param name="args"></param>
  410. protected virtual void OnAccepted (CommandEventArgs args) { }
  411. /// <summary>
  412. /// Raised when the user has accepted an item in this menu (or submenu. This is used to determine when to hide the
  413. /// menu.
  414. /// </summary>
  415. /// <remarks>
  416. /// <para>
  417. /// See <see cref="RaiseAccepted"/> for more information.
  418. /// </para>
  419. /// </remarks>
  420. public event EventHandler<CommandEventArgs>? Accepted;
  421. private void MenuOnSelectedMenuItemChanged (object? sender, MenuItemv2? e)
  422. {
  423. Logging.Trace ($"e: {e?.Title}");
  424. ShowSubMenu (e);
  425. }
  426. /// <inheritdoc/>
  427. protected override void OnSubViewAdded (View view)
  428. {
  429. if (Root is null && (view is Menuv2 || view is MenuItemv2))
  430. {
  431. throw new InvalidOperationException ("Do not add MenuItems or Menus directly to a PopoverMenu. Use the Root property.");
  432. }
  433. base.OnSubViewAdded (view);
  434. }
  435. /// <inheritdoc/>
  436. protected override void Dispose (bool disposing)
  437. {
  438. if (disposing)
  439. {
  440. IEnumerable<Menuv2> allMenus = GetAllSubMenus ();
  441. foreach (Menuv2 menu in allMenus)
  442. {
  443. menu.Accepting -= MenuOnAccepting;
  444. menu.Accepted -= MenuAccepted;
  445. menu.SelectedMenuItemChanged -= MenuOnSelectedMenuItemChanged;
  446. }
  447. _root?.Dispose ();
  448. _root = null;
  449. }
  450. base.Dispose (disposing);
  451. }
  452. /// <inheritdoc/>
  453. public bool EnableForDesign<TContext> (ref readonly TContext context) where TContext : notnull
  454. {
  455. Root = new (
  456. [
  457. new MenuItemv2 (this, Command.Cut),
  458. new MenuItemv2 (this, Command.Copy),
  459. new MenuItemv2 (this, Command.Paste),
  460. new Line (),
  461. new MenuItemv2 (this, Command.SelectAll)
  462. ]);
  463. Visible = true;
  464. return true;
  465. }
  466. }