PopoverMenu.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. namespace Terminal.Gui.Views;
  2. /// <summary>
  3. /// A <see cref="PopoverBaseImpl"/>-derived view that provides a cascading menu.
  4. /// Can be used as a context menu or a drop-down menu as part of <see cref="MenuBar"/>.
  5. /// </summary>
  6. /// <remarks>
  7. /// <para>
  8. /// <b>IMPORTANT:</b> Must be registered with <see cref="Application.Popover"/> via
  9. /// <see cref="ApplicationPopover.Register"/> before calling <see cref="MakeVisible"/> or
  10. /// <see cref="ApplicationPopover.Show"/>.
  11. /// </para>
  12. /// <para>
  13. /// <b>Usage Example:</b>
  14. /// </para>
  15. /// <code>
  16. /// var menu = new PopoverMenu ([
  17. /// new MenuItem ("Cut", Command.Cut),
  18. /// new MenuItem ("Copy", Command.Copy),
  19. /// new MenuItem ("Paste", Command.Paste)
  20. /// ]);
  21. /// Application.Popover?.Register (menu);
  22. /// menu.MakeVisible (); // or Application.Popover?.Show (menu);
  23. /// </code>
  24. /// <para>
  25. /// See <see cref="PopoverBaseImpl"/> and <see cref="IPopover"/> for lifecycle, focus, and keyboard handling details.
  26. /// </para>
  27. /// </remarks>
  28. public class PopoverMenu : PopoverBaseImpl, IDesignable
  29. {
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="PopoverMenu"/> class.
  32. /// </summary>
  33. public PopoverMenu () : this ((Menu?)null) { }
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="PopoverMenu"/> class. If any of the elements of
  36. /// <paramref name="menuItems"/> is <see langword="null"/>, a <see cref="Line"/> will be created instead.
  37. /// </summary>
  38. /// <param name="menuItems">The views to use as menu items. Null elements become separator lines.</param>
  39. /// <remarks>
  40. /// Remember to call <see cref="ApplicationPopover.Register"/> before calling <see cref="MakeVisible"/>.
  41. /// </remarks>
  42. public PopoverMenu (IEnumerable<View>? menuItems) : this (
  43. new Menu (menuItems?.Select (item => item ?? new Line ()))
  44. {
  45. Title = "Popover Root"
  46. })
  47. { }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="PopoverMenu"/> class with the specified menu items.
  50. /// </summary>
  51. /// <param name="menuItems">The menu items to display in the popover.</param>
  52. /// <remarks>
  53. /// Remember to call <see cref="ApplicationPopover.Register"/> before calling <see cref="MakeVisible"/>.
  54. /// </remarks>
  55. public PopoverMenu (IEnumerable<MenuItem>? menuItems) : this (
  56. new Menu (menuItems)
  57. {
  58. Title = "Popover Root"
  59. })
  60. { }
  61. /// <summary>
  62. /// Initializes a new instance of the <see cref="PopoverMenu"/> class with the specified root <see cref="Menu"/>.
  63. /// </summary>
  64. /// <param name="root">The root menu that contains the top-level menu items.</param>
  65. /// <remarks>
  66. /// Remember to call <see cref="ApplicationPopover.Register"/> before calling <see cref="MakeVisible"/>.
  67. /// </remarks>
  68. public PopoverMenu (Menu? root)
  69. {
  70. // Do this to support debugging traces where Title gets set
  71. base.HotKeySpecifier = (Rune)'\xffff';
  72. if (Border is { })
  73. {
  74. Border.Settings &= ~BorderSettings.Title;
  75. }
  76. Key = DefaultKey;
  77. base.Visible = false;
  78. Root = root;
  79. AddCommand (Command.Right, MoveRight);
  80. KeyBindings.Add (Key.CursorRight, Command.Right);
  81. AddCommand (Command.Left, MoveLeft);
  82. KeyBindings.Add (Key.CursorLeft, Command.Left);
  83. // PopoverBaseImpl sets a key binding for Quit, so we
  84. // don't need to do it here.
  85. AddCommand (Command.Quit, Quit);
  86. return;
  87. bool? Quit (ICommandContext? ctx)
  88. {
  89. // Logging.Debug ($"{Title} Command.Quit - {ctx?.Source?.Title}");
  90. if (!Visible)
  91. {
  92. // If we're not visible, the command is not for us
  93. return false;
  94. }
  95. // This ensures the quit command gets propagated to the owner of the popover.
  96. // This is important for MenuBarItems to ensure the MenuBar loses focus when
  97. // the user presses QuitKey to cause the menu to close.
  98. // Note, we override OnAccepting, which will set Visible to false
  99. // Logging.Debug ($"{Title} Command.Quit - Calling RaiseAccepting {ctx?.Source?.Title}");
  100. bool? ret = RaiseAccepting (ctx);
  101. if (Visible && ret is not true)
  102. {
  103. Visible = false;
  104. return true;
  105. }
  106. // If we are Visible, returning true will stop the QuitKey from propagating
  107. // If we are not Visible, returning false will allow the QuitKey to propagate
  108. return Visible;
  109. }
  110. bool? MoveLeft (ICommandContext? ctx)
  111. {
  112. if (Focused == Root)
  113. {
  114. return false;
  115. }
  116. if (MostFocused is MenuItem { SuperView: Menu focusedMenu })
  117. {
  118. focusedMenu.SuperMenuItem?.SetFocus ();
  119. return true;
  120. }
  121. return AdvanceFocus (NavigationDirection.Backward, TabBehavior.TabStop);
  122. }
  123. bool? MoveRight (ICommandContext? ctx)
  124. {
  125. if (MostFocused is MenuItem { SubMenu.Visible: true } focused)
  126. {
  127. focused.SubMenu.SetFocus ();
  128. return true;
  129. }
  130. return false;
  131. }
  132. }
  133. private Key _key = DefaultKey;
  134. /// <summary>
  135. /// Gets or sets the key that will activate the popover menu when it is registered but not visible.
  136. /// </summary>
  137. /// <remarks>
  138. /// This key binding works as a global hotkey when the popover is registered with
  139. /// <see cref="Application.Popover"/>. The default value is <see cref="DefaultKey"/> (<see cref="Key.F10"/> with
  140. /// Shift).
  141. /// </remarks>
  142. public Key Key
  143. {
  144. get => _key;
  145. set
  146. {
  147. Key oldKey = _key;
  148. _key = value;
  149. KeyChanged?.Invoke (this, new (oldKey, _key));
  150. }
  151. }
  152. /// <summary>
  153. /// Raised when the <see cref="Key"/> property is changed.
  154. /// </summary>
  155. public event EventHandler<KeyChangedEventArgs>? KeyChanged;
  156. /// <summary>
  157. /// Gets or sets the default key for activating popover menus. The default value is <see cref="Key.F10"/> with Shift.
  158. /// </summary>
  159. /// <remarks>
  160. /// This is a configuration property that affects all new <see cref="PopoverMenu"/> instances.
  161. /// </remarks>
  162. [ConfigurationProperty (Scope = typeof (SettingsScope))]
  163. public static Key DefaultKey { get; set; } = Key.F10.WithShift;
  164. /// <summary>
  165. /// The mouse flags that will cause the popover menu to be visible. The default is
  166. /// <see cref="MouseFlags.Button3Clicked"/> which is typically the right mouse button.
  167. /// </summary>
  168. public MouseFlags MouseFlags { get; set; } = MouseFlags.Button3Clicked;
  169. /// <summary>
  170. /// Makes the popover menu visible and locates it at <paramref name="idealScreenPosition"/>. The actual position of the
  171. /// menu will be adjusted to ensure the menu fully fits on the screen, with the mouse cursor positioned over
  172. /// the first cell of the first <see cref="MenuItem"/>.
  173. /// </summary>
  174. /// <param name="idealScreenPosition">
  175. /// The ideal screen-relative position for the menu. If <see langword="null"/>, the current mouse position will be
  176. /// used.
  177. /// </param>
  178. /// <remarks>
  179. /// <para>
  180. /// IMPORTANT: The popover must be registered with <see cref="Application.Popover"/> before calling this
  181. /// method.
  182. /// Call <see cref="ApplicationPopover.Register"/> first.
  183. /// </para>
  184. /// <para>
  185. /// This method internally calls <see cref="ApplicationPopover.Show"/>, which will throw
  186. /// <see cref="InvalidOperationException"/> if the popover is not registered.
  187. /// </para>
  188. /// </remarks>
  189. /// <exception cref="InvalidOperationException">Thrown if the popover has not been registered.</exception>
  190. public void MakeVisible (Point? idealScreenPosition = null)
  191. {
  192. if (Visible)
  193. {
  194. // Logging.Debug ($"{Title} - Already Visible");
  195. return;
  196. }
  197. UpdateKeyBindings ();
  198. SetPosition (idealScreenPosition);
  199. App!.Popover?.Show (this);
  200. }
  201. /// <summary>
  202. /// Sets the position of the popover menu at <paramref name="idealScreenPosition"/>. The actual position will be
  203. /// adjusted to ensure the menu fully fits on the screen, with the mouse cursor positioned over the first cell of
  204. /// the first <see cref="MenuItem"/> (if possible).
  205. /// </summary>
  206. /// <param name="idealScreenPosition">
  207. /// The ideal screen-relative position for the menu. If <see langword="null"/>, the current mouse position will be
  208. /// used.
  209. /// </param>
  210. /// <remarks>
  211. /// This method only sets the position; it does not make the popover visible. Use <see cref="MakeVisible"/> to
  212. /// both position and show the popover.
  213. /// </remarks>
  214. public void SetPosition (Point? idealScreenPosition = null)
  215. {
  216. idealScreenPosition ??= App?.Mouse.LastMousePosition;
  217. if (idealScreenPosition is null || Root is null)
  218. {
  219. return;
  220. }
  221. Point pos = idealScreenPosition.Value;
  222. if (!Root.IsInitialized)
  223. {
  224. Root.App ??= App;
  225. Root.BeginInit ();
  226. Root.EndInit ();
  227. Root.Layout ();
  228. }
  229. pos = GetMostVisibleLocationForSubMenu (Root, pos);
  230. Root.X = pos.X;
  231. Root.Y = pos.Y;
  232. }
  233. /// <inheritdoc/>
  234. /// <remarks>
  235. /// When becoming visible, the root menu is added and shown. When becoming hidden, the root menu is removed
  236. /// and the popover is hidden via <see cref="ApplicationPopover.Hide"/>.
  237. /// </remarks>
  238. protected override void OnVisibleChanged ()
  239. {
  240. // Logging.Debug ($"{Title} - Visible: {Visible}");
  241. base.OnVisibleChanged ();
  242. if (Visible)
  243. {
  244. AddAndShowSubMenu (_root);
  245. }
  246. else
  247. {
  248. HideAndRemoveSubMenu (_root);
  249. App?.Popover?.Hide (this);
  250. }
  251. }
  252. private Menu? _root;
  253. /// <summary>
  254. /// Gets or sets the <see cref="Menu"/> that is the root of the popover menu hierarchy.
  255. /// </summary>
  256. /// <remarks>
  257. /// <para>
  258. /// The root menu contains the top-level menu items. Setting this property updates key bindings and
  259. /// event subscriptions for all menus in the hierarchy.
  260. /// </para>
  261. /// <para>
  262. /// When set, all submenus are configured with appropriate event handlers for selection and acceptance.
  263. /// </para>
  264. /// </remarks>
  265. public Menu? Root
  266. {
  267. get => _root;
  268. set
  269. {
  270. if (_root == value)
  271. {
  272. return;
  273. }
  274. HideAndRemoveSubMenu (_root);
  275. _root = value;
  276. if (_root is { })
  277. {
  278. _root.App = App;
  279. }
  280. // TODO: This needs to be done whenever any MenuItem in the menu tree changes to support dynamic menus
  281. // TODO: And it needs to clear the old bindings first
  282. UpdateKeyBindings ();
  283. // TODO: This needs to be done whenever any MenuItem in the menu tree changes to support dynamic menus
  284. IEnumerable<Menu> allMenus = GetAllSubMenus ();
  285. foreach (Menu menu in allMenus)
  286. {
  287. menu.App = App;
  288. menu.Visible = false;
  289. menu.Accepting += MenuOnAccepting;
  290. menu.Accepted += MenuAccepted;
  291. menu.SelectedMenuItemChanged += MenuOnSelectedMenuItemChanged;
  292. }
  293. }
  294. }
  295. private void UpdateKeyBindings ()
  296. {
  297. IEnumerable<MenuItem> all = GetMenuItemsOfAllSubMenus ();
  298. foreach (MenuItem menuItem in all.Where (mi => mi.Command != Command.NotBound))
  299. {
  300. Key? key;
  301. if (menuItem.TargetView is { })
  302. {
  303. // A TargetView implies HotKey
  304. key = menuItem.TargetView.HotKeyBindings.GetFirstFromCommands (menuItem.Command);
  305. }
  306. else
  307. {
  308. // No TargetView implies Application HotKey
  309. key = App?.Keyboard.KeyBindings.GetFirstFromCommands (menuItem.Command);
  310. }
  311. if (key is not { IsValid: true })
  312. {
  313. continue;
  314. }
  315. if (menuItem.Key.IsValid)
  316. {
  317. //Logging.Warning ("Do not specify a Key for MenuItems where a Command is specified. Key will be determined automatically.");
  318. }
  319. menuItem.Key = key;
  320. // Logging.Debug ($"{Title} - HotKey: {menuItem.Key}->{menuItem.Command}");
  321. }
  322. }
  323. /// <inheritdoc/>
  324. /// <remarks>
  325. /// This method checks all menu items in the hierarchy for a matching key binding and invokes the
  326. /// appropriate menu item if found.
  327. /// </remarks>
  328. protected override bool OnKeyDownNotHandled (Key key)
  329. {
  330. // See if any of our MenuItems have this key as Key
  331. IEnumerable<MenuItem> all = GetMenuItemsOfAllSubMenus ();
  332. foreach (MenuItem menuItem in all)
  333. {
  334. if (key != Application.QuitKey && menuItem.Key == key)
  335. {
  336. // Logging.Debug ($"{Title} - key: {key}");
  337. return menuItem.NewKeyDownEvent (key);
  338. }
  339. }
  340. return base.OnKeyDownNotHandled (key);
  341. }
  342. /// <summary>
  343. /// Gets all the submenus in the popover menu hierarchy, including the root menu.
  344. /// </summary>
  345. /// <returns>An enumerable collection of all <see cref="Menu"/> instances in the hierarchy.</returns>
  346. /// <remarks>
  347. /// This method performs a depth-first traversal of the menu tree, starting from <see cref="Root"/>.
  348. /// </remarks>
  349. public IEnumerable<Menu> GetAllSubMenus ()
  350. {
  351. List<Menu> result = [];
  352. if (Root == null)
  353. {
  354. return result;
  355. }
  356. Stack<Menu> stack = new ();
  357. stack.Push (Root);
  358. while (stack.Count > 0)
  359. {
  360. Menu currentMenu = stack.Pop ();
  361. result.Add (currentMenu);
  362. foreach (View subView in currentMenu.SubViews)
  363. {
  364. if (subView is MenuItem { SubMenu: { } } menuItem)
  365. {
  366. stack.Push (menuItem.SubMenu);
  367. }
  368. }
  369. }
  370. return result;
  371. }
  372. /// <summary>
  373. /// Gets all the menu items in the popover menu hierarchy.
  374. /// </summary>
  375. /// <returns>An enumerable collection of all <see cref="MenuItem"/> instances across all menus in the hierarchy.</returns>
  376. /// <remarks>
  377. /// This method traverses all menus returned by <see cref="GetAllSubMenus"/> and collects their menu items.
  378. /// </remarks>
  379. internal IEnumerable<MenuItem> GetMenuItemsOfAllSubMenus ()
  380. {
  381. List<MenuItem> result = [];
  382. foreach (Menu menu in GetAllSubMenus ())
  383. {
  384. foreach (View subView in menu.SubViews)
  385. {
  386. if (subView is MenuItem menuItem)
  387. {
  388. result.Add (menuItem);
  389. }
  390. }
  391. }
  392. return result;
  393. }
  394. /// <summary>
  395. /// Shows the submenu of the specified <see cref="MenuItem"/>, if it has one.
  396. /// </summary>
  397. /// <param name="menuItem">The menu item whose submenu should be shown.</param>
  398. /// <remarks>
  399. /// <para>
  400. /// If another submenu is currently visible at the same level, it will be hidden before showing the new one.
  401. /// </para>
  402. /// <para>
  403. /// The submenu is positioned to the right of the menu item, adjusted to ensure full visibility on screen.
  404. /// </para>
  405. /// </remarks>
  406. internal void ShowSubMenu (MenuItem? menuItem)
  407. {
  408. var menu = menuItem?.SuperView as Menu;
  409. // Logging.Debug ($"{Title} - menuItem: {menuItem?.Title}, menu: {menu?.Title}");
  410. menu?.Layout ();
  411. // If there's a visible peer, remove / hide it
  412. if (menu?.SubViews.FirstOrDefault (v => v is MenuItem { SubMenu.Visible: true }) is MenuItem visiblePeer)
  413. {
  414. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  415. visiblePeer.ForceFocusColors = false;
  416. }
  417. if (menuItem is { SubMenu: { Visible: false } })
  418. {
  419. AddAndShowSubMenu (menuItem.SubMenu);
  420. Point idealLocation = ScreenToViewport (
  421. new (
  422. menuItem.FrameToScreen ().Right - menuItem.SubMenu.GetAdornmentsThickness ().Left,
  423. menuItem.FrameToScreen ().Top - menuItem.SubMenu.GetAdornmentsThickness ().Top));
  424. Point pos = GetMostVisibleLocationForSubMenu (menuItem.SubMenu, idealLocation);
  425. menuItem.SubMenu.X = pos.X;
  426. menuItem.SubMenu.Y = pos.Y;
  427. menuItem.ForceFocusColors = true;
  428. }
  429. }
  430. /// <summary>
  431. /// Calculates the most visible screen-relative location for the specified <paramref name="menu"/>.
  432. /// </summary>
  433. /// <param name="menu">The menu to position.</param>
  434. /// <param name="idealLocation">The ideal screen-relative location.</param>
  435. /// <returns>The adjusted screen-relative position that ensures maximum visibility of the menu.</returns>
  436. /// <remarks>
  437. /// This method adjusts the position to keep the menu fully visible on screen, considering screen boundaries.
  438. /// </remarks>
  439. internal Point GetMostVisibleLocationForSubMenu (Menu menu, Point idealLocation)
  440. {
  441. var pos = Point.Empty;
  442. // Calculate the initial position to the right of the menu item
  443. GetLocationEnsuringFullVisibility (
  444. menu,
  445. idealLocation.X,
  446. idealLocation.Y,
  447. out int nx,
  448. out int ny);
  449. return new (nx, ny);
  450. }
  451. private void AddAndShowSubMenu (Menu? menu)
  452. {
  453. if (menu is { SuperView: null, Visible: false })
  454. {
  455. // Logging.Debug ($"{Title} ({menu?.Title}) - menu.Visible: {menu?.Visible}");
  456. // TODO: Find the menu item below the mouse, if any, and select it
  457. if (!menu!.IsInitialized)
  458. {
  459. menu.App ??= App;
  460. menu.BeginInit ();
  461. menu.EndInit ();
  462. }
  463. menu.ClearFocus ();
  464. base.Add (menu);
  465. // IMPORTANT: This must be done after adding the menu to the super view or Add will try
  466. // to set focus to it.
  467. menu.Visible = true;
  468. menu.Layout ();
  469. }
  470. }
  471. private void HideAndRemoveSubMenu (Menu? menu)
  472. {
  473. if (menu is { Visible: true })
  474. {
  475. // Logging.Debug ($"{Title} ({menu?.Title}) - menu.Visible: {menu?.Visible}");
  476. // If there's a visible submenu, remove / hide it
  477. if (menu.SubViews.FirstOrDefault (v => v is MenuItem { SubMenu.Visible: true }) is MenuItem visiblePeer)
  478. {
  479. HideAndRemoveSubMenu (visiblePeer.SubMenu);
  480. visiblePeer.ForceFocusColors = false;
  481. }
  482. menu.Visible = false;
  483. menu.ClearFocus ();
  484. base.Remove (menu);
  485. if (menu == Root)
  486. {
  487. Visible = false;
  488. }
  489. }
  490. }
  491. private void MenuOnAccepting (object? sender, CommandEventArgs e)
  492. {
  493. var senderView = sender as View;
  494. // Logging.Debug ($"{Title} ({e.Context?.Source?.Title}) Command: {e.Context?.Command} - Sender: {senderView?.GetType ().Name}");
  495. if (e.Context?.Command != Command.HotKey)
  496. {
  497. // Logging.Debug ($"{Title} - Setting Visible = false");
  498. Visible = false;
  499. }
  500. if (e.Context is CommandContext<KeyBinding> keyCommandContext)
  501. {
  502. if (keyCommandContext.Binding.Key is { } && keyCommandContext.Binding.Key == Application.QuitKey && SuperView is { Visible: true })
  503. {
  504. // Logging.Debug ($"{Title} - Setting e.Handled = true - Application.QuitKey/Command = Command.Quit");
  505. e.Handled = true;
  506. }
  507. }
  508. }
  509. private void MenuAccepted (object? sender, CommandEventArgs e)
  510. {
  511. // Logging.Debug ($"{Title} ({e.Context?.Source?.Title}) Command: {e.Context?.Command}");
  512. if (e.Context?.Source is MenuItem { SubMenu: null })
  513. {
  514. HideAndRemoveSubMenu (_root);
  515. }
  516. else if (e.Context?.Source is MenuItem { SubMenu: { } } menuItemWithSubMenu)
  517. {
  518. ShowSubMenu (menuItemWithSubMenu);
  519. }
  520. RaiseAccepted (e.Context);
  521. }
  522. /// <inheritdoc/>
  523. /// <remarks>
  524. /// <para>
  525. /// When the popover is not visible, only hotkey commands are processed.
  526. /// </para>
  527. /// <para>
  528. /// This method raises <see cref="View.Accepted"/> for commands that originate from menu items in the hierarchy.
  529. /// </para>
  530. /// </remarks>
  531. protected override bool OnAccepting (CommandEventArgs args)
  532. {
  533. // Logging.Debug ($"{Title} ({args.Context?.Source?.Title}) Command: {args.Context?.Command}");
  534. // If we're not visible, ignore any keys that are not hotkeys
  535. CommandContext<KeyBinding>? keyCommandContext = args.Context as CommandContext<KeyBinding>? ?? default (CommandContext<KeyBinding>);
  536. if (!Visible && keyCommandContext is { Binding.Key: { } })
  537. {
  538. if (GetMenuItemsOfAllSubMenus ().All (i => i.Key != keyCommandContext.Value.Binding.Key))
  539. {
  540. // Logging.Debug ($"{Title} ({args.Context?.Source?.Title}) Command: {args.Context?.Command} - ignore any keys that are not hotkeys");
  541. return false;
  542. }
  543. }
  544. // Logging.Debug ($"{Title} - calling base.OnAccepting: {args.Context?.Command}");
  545. bool? ret = base.OnAccepting (args);
  546. if (ret is true || args.Handled)
  547. {
  548. return args.Handled = true;
  549. }
  550. // Only raise Accepted if the command came from one of our MenuItems
  551. //if (GetMenuItemsOfAllSubMenus ().Contains (args.Context?.Source))
  552. {
  553. // Logging.Debug ($"{Title} - Calling RaiseAccepted {args.Context?.Command}");
  554. RaiseAccepted (args.Context);
  555. }
  556. // Always return false to enable accepting to continue propagating
  557. return false;
  558. }
  559. private void MenuOnSelectedMenuItemChanged (object? sender, MenuItem? e)
  560. {
  561. // Logging.Debug ($"{Title} - e.Title: {e?.Title}");
  562. ShowSubMenu (e);
  563. }
  564. /// <inheritdoc/>
  565. /// <exception cref="InvalidOperationException">
  566. /// Thrown if attempting to add a <see cref="Menu"/> or <see cref="MenuItem"/> directly to the popover.
  567. /// </exception>
  568. /// <remarks>
  569. /// Do not add <see cref="MenuItem"/> or <see cref="Menu"/> views directly to the popover.
  570. /// Use the <see cref="Root"/> property instead.
  571. /// </remarks>
  572. protected override void OnSubViewAdded (View view)
  573. {
  574. if (Root is null && (view is Menu || view is MenuItem))
  575. {
  576. throw new InvalidOperationException ("Do not add MenuItems or Menus directly to a PopoverMenu. Use the Root property.");
  577. }
  578. base.OnSubViewAdded (view);
  579. }
  580. /// <inheritdoc/>
  581. /// <remarks>
  582. /// This method unsubscribes from all menu events and disposes the root menu.
  583. /// </remarks>
  584. protected override void Dispose (bool disposing)
  585. {
  586. if (disposing)
  587. {
  588. IEnumerable<Menu> allMenus = GetAllSubMenus ();
  589. foreach (Menu menu in allMenus)
  590. {
  591. menu.Accepting -= MenuOnAccepting;
  592. menu.Accepted -= MenuAccepted;
  593. menu.SelectedMenuItemChanged -= MenuOnSelectedMenuItemChanged;
  594. }
  595. _root?.Dispose ();
  596. _root = null;
  597. }
  598. base.Dispose (disposing);
  599. }
  600. /// <summary>
  601. /// Enables the popover menu for use in design-time scenarios.
  602. /// </summary>
  603. /// <typeparam name="TContext">The type of the target view context.</typeparam>
  604. /// <param name="targetView">The target view to associate with the menu commands.</param>
  605. /// <returns><see langword="true"/> if successfully enabled for design; otherwise, <see langword="false"/>.</returns>
  606. /// <remarks>
  607. /// This method creates a default set of menu items (Cut, Copy, Paste, Select All, Quit) for design-time use.
  608. /// It is primarily used for demonstration and testing purposes.
  609. /// </remarks>
  610. public bool EnableForDesign<TContext> (ref TContext targetView) where TContext : notnull
  611. {
  612. // Note: This menu is used by unit tests. If you modify it, you'll likely have to update
  613. // unit tests.
  614. Root = new (
  615. [
  616. new MenuItem (targetView as View, Command.Cut),
  617. new MenuItem (targetView as View, Command.Copy),
  618. new MenuItem (targetView as View, Command.Paste),
  619. new Line (),
  620. new MenuItem (targetView as View, Command.SelectAll),
  621. new Line (),
  622. new MenuItem (targetView as View, Command.Quit)
  623. ])
  624. {
  625. Title = "Popover Demo Root"
  626. };
  627. // NOTE: This is a workaround for the fact that the PopoverMenu is not visible in the designer
  628. // NOTE: without being activated via App?.Popover. But we want it to be visible.
  629. // NOTE: If you use PopoverView.EnableForDesign for real Popover scenarios, change back to false
  630. // NOTE: after calling EnableForDesign.
  631. //Visible = true;
  632. return true;
  633. }
  634. }