MenuBar.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// <para>Provides a menu bar that spans the top of a <see cref="Toplevel"/> View with drop-down and cascading menus.</para>
  5. /// <para>
  6. /// By default, any sub-sub-menus (sub-menus of the <see cref="MenuItem"/>s added to <see cref="MenuBarItem"/>s)
  7. /// are displayed in a cascading manner, where each sub-sub-menu pops out of the sub-menu frame (either to the
  8. /// right or left, depending on where the sub-menu is relative to the edge of the screen). By setting
  9. /// <see cref="UseSubMenusSingleFrame"/> to <see langword="true"/>, this behavior can be changed such that all
  10. /// sub-sub-menus are drawn within a single frame below the MenuBar.
  11. /// </para>
  12. /// </summary>
  13. /// <remarks>
  14. /// <para>
  15. /// The <see cref="MenuBar"/> appears on the first row of the <see cref="Toplevel"/> SuperView and uses the full
  16. /// width.
  17. /// </para>
  18. /// <para>See also: <see cref="ContextMenu"/></para>
  19. /// <para>The <see cref="MenuBar"/> provides global hot keys for the application. See <see cref="MenuItem.HotKey"/>.</para>
  20. /// <para>
  21. /// When the menu is created key bindings for each menu item and its sub-menu items are added for each menu
  22. /// item's hot key (both alone AND with AltMask) and shortcut, if defined.
  23. /// </para>
  24. /// <para>
  25. /// If a key press matches any of the menu item's hot keys or shortcuts, the menu item's action is invoked or
  26. /// sub-menu opened.
  27. /// </para>
  28. /// <para>
  29. /// * If the menu bar is not open * Any shortcut defined within the menu will be invoked * Only hot keys defined
  30. /// for the menu bar items will be invoked, and only if Alt is pressed too. * If the menu bar is open * Un-shifted
  31. /// hot keys defined for the menu bar items will be invoked, only if the menu they belong to is open (the menu bar
  32. /// item's text is visible). * Alt-shifted hot keys defined for the menu bar items will be invoked, only if the
  33. /// menu they belong to is open (the menu bar item's text is visible). * If there is a visible hot key that
  34. /// duplicates a shortcut (e.g. _File and Alt-F), the hot key wins.
  35. /// </para>
  36. /// </remarks>
  37. public class MenuBar : View, IDesignable
  38. {
  39. // Spaces before the Title
  40. private static readonly int _leftPadding = 1;
  41. // Spaces after the submenu Title, before Help
  42. private static readonly int _parensAroundHelp = 3;
  43. // Spaces after the Title
  44. private static readonly int _rightPadding = 1;
  45. // The column where the MenuBar starts
  46. private static readonly int _xOrigin = 0;
  47. internal bool _isMenuClosing;
  48. internal bool _isMenuOpening;
  49. internal Menu? _openMenu;
  50. internal List<Menu>? _openSubMenu;
  51. internal int _selected;
  52. internal int _selectedSub;
  53. private bool _initialCanFocus;
  54. private bool _isCleaning;
  55. private View? _lastFocused;
  56. private Menu _ocm;
  57. private View _previousFocused;
  58. private bool _reopen;
  59. private bool _useSubMenusSingleFrame;
  60. /// <summary>Initializes a new instance of the <see cref="MenuBar"/>.</summary>
  61. public MenuBar ()
  62. {
  63. TabStop = TabBehavior.NoStop;
  64. X = 0;
  65. Y = 0;
  66. Width = Dim.Fill ();
  67. Height = 1; // BUGBUG: Views should avoid setting Height as doing so implies Frame.Size == GetContentSize ().
  68. Menus = new MenuBarItem [] { };
  69. //CanFocus = true;
  70. _selected = -1;
  71. _selectedSub = -1;
  72. ColorScheme = Colors.ColorSchemes ["Menu"];
  73. WantMousePositionReports = true;
  74. IsMenuOpen = false;
  75. Added += MenuBar_Added;
  76. // Things this view knows how to do
  77. AddCommand (
  78. Command.Left,
  79. () =>
  80. {
  81. MoveLeft ();
  82. return true;
  83. }
  84. );
  85. AddCommand (
  86. Command.Right,
  87. () =>
  88. {
  89. MoveRight ();
  90. return true;
  91. }
  92. );
  93. AddCommand (
  94. Command.Cancel,
  95. () =>
  96. {
  97. CloseMenuBar ();
  98. return true;
  99. }
  100. );
  101. AddCommand (
  102. Command.Accept,
  103. () =>
  104. {
  105. ProcessMenu (_selected, Menus [_selected]);
  106. return true;
  107. }
  108. );
  109. AddCommand (Command.ToggleExpandCollapse, ctx => Select (Menus.IndexOf (ctx.KeyBinding?.Context)));
  110. AddCommand (Command.Select, ctx =>
  111. {
  112. var res = Run ((ctx.KeyBinding?.Context as MenuItem)?.Action!);
  113. CloseAllMenus ();
  114. return res;
  115. });
  116. // Default key bindings for this view
  117. KeyBindings.Add (Key.CursorLeft, Command.Left);
  118. KeyBindings.Add (Key.CursorRight, Command.Right);
  119. KeyBindings.Add (Key.Esc, Command.Cancel);
  120. KeyBindings.Add (Key.CursorDown, Command.Accept);
  121. KeyBindings.Add (Key.Enter, Command.Accept);
  122. KeyBinding keyBinding = new ([Command.ToggleExpandCollapse], KeyBindingScope.HotKey, -1); // -1 indicates Key was used
  123. KeyBindings.Add (Key, keyBinding);
  124. // TODO: Why do we have two keybindings for opening the menu? Ctrl-Space and Key?
  125. KeyBindings.Add (Key.Space.WithCtrl, keyBinding);
  126. // This is needed for macOS because Key.Space.WithCtrl doesn't work
  127. KeyBindings.Add (Key.Space.WithAlt, keyBinding);
  128. // TODO: Figure out how to make Alt work (on Windows)
  129. //KeyBindings.Add (Key.WithAlt, keyBinding);
  130. }
  131. /// <summary><see langword="true"/> if the menu is open; otherwise <see langword="true"/>.</summary>
  132. public bool IsMenuOpen { get; protected set; }
  133. /// <summary>Gets the view that was last focused before opening the menu.</summary>
  134. public View? LastFocused { get; private set; }
  135. /// <summary>
  136. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the
  137. /// <see cref="MenuBar"/> is visible.
  138. /// </summary>
  139. /// <value>The menu array.</value>
  140. public MenuBarItem [] Menus
  141. {
  142. get => _menus;
  143. set
  144. {
  145. _menus = value;
  146. if (Menus is [])
  147. {
  148. return;
  149. }
  150. // TODO: Hotkeys should not work for sub-menus if they are not visible!
  151. for (var i = 0; i < Menus.Length; i++)
  152. {
  153. MenuBarItem menuBarItem = Menus [i];
  154. if (menuBarItem?.HotKey != Key.Empty)
  155. {
  156. KeyBindings.Remove (menuBarItem!.HotKey);
  157. KeyBinding keyBinding = new ([Command.ToggleExpandCollapse], KeyBindingScope.Focused, menuBarItem);
  158. KeyBindings.Add (menuBarItem!.HotKey, keyBinding);
  159. KeyBindings.Remove (menuBarItem.HotKey.WithAlt);
  160. keyBinding = new ([Command.ToggleExpandCollapse], KeyBindingScope.HotKey, menuBarItem);
  161. KeyBindings.Add (menuBarItem.HotKey.WithAlt, keyBinding);
  162. }
  163. if (menuBarItem?.ShortcutKey != Key.Empty)
  164. {
  165. // Technically this will never run because MenuBarItems don't have shortcuts
  166. // unless the IsTopLevel is true
  167. KeyBindings.Remove (menuBarItem.ShortcutKey);
  168. KeyBinding keyBinding = new ([Command.Select], KeyBindingScope.HotKey, menuBarItem);
  169. KeyBindings.Add (menuBarItem.ShortcutKey, keyBinding);
  170. }
  171. menuBarItem?.AddShortcutKeyBindings (this);
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// The default <see cref="LineStyle"/> for <see cref="Menus"/>'s border. The default is
  177. /// <see cref="LineStyle.Single"/>.
  178. /// </summary>
  179. public LineStyle MenusBorderStyle { get; set; } = LineStyle.Single;
  180. /// <summary>
  181. /// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
  182. /// <para>
  183. /// By default, any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading
  184. /// manner, where each sub-sub-menu pops out of the sub-menu frame (either to the right or left, depending on where
  185. /// the sub-menu is relative to the edge of the screen). By setting <see cref="UseSubMenusSingleFrame"/> to
  186. /// <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are drawn within a single
  187. /// frame below the MenuBar.
  188. /// </para>
  189. /// </summary>
  190. public bool UseSubMenusSingleFrame
  191. {
  192. get => _useSubMenusSingleFrame;
  193. set
  194. {
  195. _useSubMenusSingleFrame = value;
  196. if (value && UseKeysUpDownAsKeysLeftRight)
  197. {
  198. _useKeysUpDownAsKeysLeftRight = false;
  199. SetNeedsDisplay ();
  200. }
  201. }
  202. }
  203. /// <inheritdoc/>
  204. public override bool Visible
  205. {
  206. get => base.Visible;
  207. set
  208. {
  209. base.Visible = value;
  210. if (!value)
  211. {
  212. CloseAllMenus ();
  213. }
  214. }
  215. }
  216. internal Menu? OpenCurrentMenu
  217. {
  218. get => _ocm;
  219. set
  220. {
  221. if (_ocm != value)
  222. {
  223. _ocm = value;
  224. if (_ocm is { } && _ocm._currentChild > -1)
  225. {
  226. OnMenuOpened ();
  227. }
  228. }
  229. }
  230. }
  231. /// <summary>Closes the Menu programmatically if open and not canceled (as though F9 were pressed).</summary>
  232. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false) { return CloseMenu (false, false, ignoreUseSubMenusSingleFrame); }
  233. /// <summary>Raised when all the menu is closed.</summary>
  234. public event EventHandler MenuAllClosed;
  235. /// <summary>Raised when a menu is closing passing <see cref="MenuClosingEventArgs"/>.</summary>
  236. public event EventHandler<MenuClosingEventArgs> MenuClosing;
  237. /// <summary>Raised when a menu is opened.</summary>
  238. public event EventHandler<MenuOpenedEventArgs> MenuOpened;
  239. /// <summary>Raised as a menu is opening.</summary>
  240. public event EventHandler<MenuOpeningEventArgs> MenuOpening;
  241. /// <inheritdoc/>
  242. public override void OnDrawContent (Rectangle viewport)
  243. {
  244. Driver.SetAttribute (GetNormalColor ());
  245. Clear ();
  246. var pos = 0;
  247. for (var i = 0; i < Menus.Length; i++)
  248. {
  249. MenuBarItem menu = Menus [i];
  250. Move (pos, 0);
  251. Attribute hotColor, normalColor;
  252. if (i == _selected && IsMenuOpen)
  253. {
  254. hotColor = i == _selected ? ColorScheme.HotFocus : GetHotNormalColor ();
  255. normalColor = i == _selected ? GetFocusColor () : GetNormalColor ();
  256. }
  257. else
  258. {
  259. hotColor = GetHotNormalColor ();
  260. normalColor = GetNormalColor ();
  261. }
  262. // Note Help on MenuBar is drawn with parens around it
  263. DrawHotString (
  264. string.IsNullOrEmpty (menu.Help) ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ",
  265. hotColor,
  266. normalColor
  267. );
  268. pos += _leftPadding
  269. + menu.TitleLength
  270. + (menu.Help.GetColumns () > 0
  271. ? _leftPadding + menu.Help.GetColumns () + _parensAroundHelp
  272. : 0)
  273. + _rightPadding;
  274. }
  275. //PositionCursor ();
  276. }
  277. /// <summary>Virtual method that will invoke the <see cref="MenuAllClosed"/>.</summary>
  278. public virtual void OnMenuAllClosed () { MenuAllClosed?.Invoke (this, EventArgs.Empty); }
  279. /// <summary>Virtual method that will invoke the <see cref="MenuClosing"/>.</summary>
  280. /// <param name="currentMenu">The current menu to be closed.</param>
  281. /// <param name="reopen">Whether the current menu will be reopened.</param>
  282. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  283. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  284. {
  285. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  286. MenuClosing?.Invoke (this, ev);
  287. return ev;
  288. }
  289. /// <summary>Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.</summary>
  290. public virtual void OnMenuOpened ()
  291. {
  292. MenuItem mi = null;
  293. MenuBarItem parent;
  294. if (OpenCurrentMenu.BarItems.Children != null
  295. && OpenCurrentMenu.BarItems!.Children.Length > 0
  296. && OpenCurrentMenu?._currentChild > -1)
  297. {
  298. parent = OpenCurrentMenu.BarItems;
  299. mi = parent.Children [OpenCurrentMenu._currentChild];
  300. }
  301. else if (OpenCurrentMenu!.BarItems.IsTopLevel)
  302. {
  303. parent = null;
  304. mi = OpenCurrentMenu.BarItems;
  305. }
  306. else
  307. {
  308. parent = _openMenu.BarItems;
  309. mi = parent.Children?.Length > 0 ? parent.Children [_openMenu._currentChild] : null;
  310. }
  311. MenuOpened?.Invoke (this, new (parent, mi));
  312. }
  313. /// <summary>Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.</summary>
  314. /// <param name="currentMenu">The current menu to be replaced.</param>
  315. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  316. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  317. {
  318. var ev = new MenuOpeningEventArgs (currentMenu);
  319. MenuOpening?.Invoke (this, ev);
  320. return ev;
  321. }
  322. /// <summary>Opens the Menu programatically, as though the F9 key were pressed.</summary>
  323. public void OpenMenu ()
  324. {
  325. MenuBar? mbar = GetMouseGrabViewInstance (this);
  326. mbar?.CleanUp ();
  327. if (!Enabled || _openMenu is { })
  328. {
  329. return;
  330. }
  331. _selected = 0;
  332. SetNeedsDisplay ();
  333. _previousFocused = (SuperView is null ? Application.Current?.Focused : SuperView.Focused)!;
  334. OpenMenu (_selected);
  335. if (!SelectEnabledItem (
  336. OpenCurrentMenu!.BarItems.Children,
  337. OpenCurrentMenu._currentChild,
  338. out OpenCurrentMenu._currentChild
  339. )
  340. && !CloseMenu (false))
  341. {
  342. return;
  343. }
  344. if (!OpenCurrentMenu.CheckSubMenu ())
  345. {
  346. return;
  347. }
  348. Application.GrabMouse (this);
  349. }
  350. /// <inheritdoc/>
  351. public override Point? PositionCursor ()
  352. {
  353. if (_selected == -1 && HasFocus && Menus.Length > 0)
  354. {
  355. _selected = 0;
  356. }
  357. var pos = 0;
  358. for (var i = 0; i < Menus.Length; i++)
  359. {
  360. if (i == _selected)
  361. {
  362. pos++;
  363. Move (pos + 1, 0);
  364. return null; // Don't show the cursor
  365. }
  366. pos += _leftPadding
  367. + Menus [i].TitleLength
  368. + (Menus [i].Help.GetColumns () > 0
  369. ? Menus [i].Help.GetColumns () + _parensAroundHelp
  370. : 0)
  371. + _rightPadding;
  372. }
  373. return null; // Don't show the cursor
  374. }
  375. // Activates the menu, handles either first focus, or activating an entry when it was already active
  376. // For mouse events.
  377. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  378. {
  379. _selected = idx;
  380. _selectedSub = sIdx;
  381. if (_openMenu is null)
  382. {
  383. _previousFocused = SuperView is null ? Application.Current?.Focused ?? null : SuperView.Focused;
  384. }
  385. OpenMenu (idx, sIdx, subMenu);
  386. SetNeedsDisplay ();
  387. }
  388. internal void CleanUp ()
  389. {
  390. _isCleaning = true;
  391. if (_openMenu is { })
  392. {
  393. CloseAllMenus ();
  394. }
  395. _openedByAltKey = false;
  396. IsMenuOpen = false;
  397. _selected = -1;
  398. CanFocus = _initialCanFocus;
  399. if (_lastFocused is { })
  400. {
  401. _lastFocused.SetFocus ();
  402. }
  403. SetNeedsDisplay ();
  404. if (Application.MouseGrabView is { } && Application.MouseGrabView is MenuBar && Application.MouseGrabView != this)
  405. {
  406. var menuBar = Application.MouseGrabView as MenuBar;
  407. if (menuBar!.IsMenuOpen)
  408. {
  409. menuBar.CleanUp ();
  410. }
  411. }
  412. Application.UngrabMouse ();
  413. _isCleaning = false;
  414. }
  415. internal void CloseAllMenus ()
  416. {
  417. if (!_isMenuOpening && !_isMenuClosing)
  418. {
  419. if (_openSubMenu is { } && !CloseMenu (false, true, true))
  420. {
  421. return;
  422. }
  423. if (!CloseMenu (false))
  424. {
  425. return;
  426. }
  427. if (LastFocused is { } && LastFocused != this)
  428. {
  429. _selected = -1;
  430. }
  431. Application.UngrabMouse ();
  432. }
  433. if (OpenCurrentMenu is { })
  434. {
  435. OpenCurrentMenu = null;
  436. }
  437. IsMenuOpen = false;
  438. _openedByAltKey = false;
  439. OnMenuAllClosed ();
  440. if (Application.Current is { })
  441. {
  442. // Close others menu bar opened
  443. View? cm = Application.Current!.Subviews.FirstOrDefault (v => v is Menu cm && cm.Host != this && cm.Host.IsMenuOpen);
  444. ((Menu)cm!)?.Host.CleanUp ();
  445. }
  446. }
  447. internal bool CloseMenu (bool reopen, bool isSubMenu, bool ignoreUseSubMenusSingleFrame = false)
  448. {
  449. MenuBarItem? mbi = isSubMenu ? OpenCurrentMenu!.BarItems : _openMenu?.BarItems;
  450. if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { })
  451. {
  452. return false;
  453. }
  454. _isMenuClosing = true;
  455. _reopen = reopen;
  456. MenuClosingEventArgs args = OnMenuClosing (mbi, reopen, isSubMenu);
  457. if (args.Cancel)
  458. {
  459. _isMenuClosing = false;
  460. if (args.CurrentMenu.Parent is { } && _openMenu is { })
  461. {
  462. _openMenu._currentChild =
  463. ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  464. }
  465. return false;
  466. }
  467. switch (isSubMenu)
  468. {
  469. case false:
  470. if (_openMenu is { })
  471. {
  472. Application.Current?.Remove (_openMenu);
  473. }
  474. SetNeedsDisplay ();
  475. if (_previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != OpenCurrentMenu.ToString ())
  476. {
  477. _previousFocused.SetFocus ();
  478. }
  479. _openMenu?.Dispose ();
  480. _openMenu = null;
  481. if (_lastFocused is Menu or MenuBar)
  482. {
  483. _lastFocused = null;
  484. }
  485. LastFocused = _lastFocused;
  486. _lastFocused = null;
  487. if (LastFocused is { CanFocus: true })
  488. {
  489. if (!reopen)
  490. {
  491. _selected = -1;
  492. }
  493. if (_openSubMenu is { })
  494. {
  495. _openSubMenu = null;
  496. }
  497. if (OpenCurrentMenu is { })
  498. {
  499. Application.Current?.Remove (OpenCurrentMenu);
  500. OpenCurrentMenu.Dispose ();
  501. OpenCurrentMenu = null;
  502. }
  503. LastFocused.SetFocus ();
  504. }
  505. else if (_openSubMenu is null || _openSubMenu.Count == 0)
  506. {
  507. CloseAllMenus ();
  508. }
  509. else
  510. {
  511. SetFocus ();
  512. }
  513. IsMenuOpen = false;
  514. break;
  515. case true:
  516. _selectedSub = -1;
  517. SetNeedsDisplay ();
  518. RemoveAllOpensSubMenus ();
  519. OpenCurrentMenu!._previousSubFocused.SetFocus ();
  520. _openSubMenu = null;
  521. IsMenuOpen = true;
  522. break;
  523. }
  524. _reopen = false;
  525. _isMenuClosing = false;
  526. return true;
  527. }
  528. /// <summary>Gets the superview location offset relative to the <see cref="ConsoleDriver"/> location.</summary>
  529. /// <returns>The location offset.</returns>
  530. internal Point GetScreenOffset ()
  531. {
  532. if (Driver is null)
  533. {
  534. return Point.Empty;
  535. }
  536. Rectangle superViewFrame = SuperView?.Frame ?? Application.Screen;
  537. View? sv = SuperView ?? Application.Current;
  538. if (sv is null)
  539. {
  540. // Support Unit Tests
  541. return Point.Empty;
  542. }
  543. Point viewportOffset = sv?.GetViewportOffsetFromFrame () ?? Point.Empty;
  544. return new (
  545. superViewFrame.X - sv.Frame.X - viewportOffset.X,
  546. superViewFrame.Y - sv.Frame.Y - viewportOffset.Y
  547. );
  548. }
  549. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  550. {
  551. switch (isSubMenu)
  552. {
  553. case false:
  554. if (_selected == -1)
  555. {
  556. _selected = 0;
  557. }
  558. else if (_selected + 1 == Menus.Length)
  559. {
  560. _selected = 0;
  561. }
  562. else
  563. {
  564. _selected++;
  565. }
  566. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  567. {
  568. return;
  569. }
  570. OpenMenu (_selected);
  571. SelectEnabledItem (
  572. OpenCurrentMenu!.BarItems.Children,
  573. OpenCurrentMenu._currentChild,
  574. out OpenCurrentMenu._currentChild
  575. );
  576. break;
  577. case true:
  578. if (UseKeysUpDownAsKeysLeftRight)
  579. {
  580. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  581. {
  582. NextMenu (false, ignoreUseSubMenusSingleFrame);
  583. }
  584. }
  585. else
  586. {
  587. MenuBarItem? subMenu = OpenCurrentMenu!._currentChild > -1 && OpenCurrentMenu.BarItems.Children.Length > 0
  588. ? OpenCurrentMenu.BarItems.SubMenu (
  589. OpenCurrentMenu.BarItems.Children [OpenCurrentMenu._currentChild]
  590. )
  591. : null;
  592. if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null)
  593. {
  594. if (_openSubMenu is { } && !CloseMenu (false, true))
  595. {
  596. return;
  597. }
  598. NextMenu (false, ignoreUseSubMenusSingleFrame);
  599. }
  600. else if (subMenu != null
  601. || (OpenCurrentMenu._currentChild > -1
  602. && !OpenCurrentMenu.BarItems
  603. .Children [OpenCurrentMenu._currentChild]
  604. .IsFromSubMenu))
  605. {
  606. _selectedSub++;
  607. OpenCurrentMenu.CheckSubMenu ();
  608. }
  609. else
  610. {
  611. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  612. {
  613. NextMenu (false, ignoreUseSubMenusSingleFrame);
  614. }
  615. return;
  616. }
  617. SetNeedsDisplay ();
  618. if (UseKeysUpDownAsKeysLeftRight)
  619. {
  620. OpenCurrentMenu.CheckSubMenu ();
  621. }
  622. }
  623. break;
  624. }
  625. }
  626. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  627. {
  628. _isMenuOpening = true;
  629. MenuOpeningEventArgs newMenu = OnMenuOpening (Menus [index]);
  630. if (newMenu.Cancel)
  631. {
  632. _isMenuOpening = false;
  633. return;
  634. }
  635. if (newMenu.NewMenuBarItem is { })
  636. {
  637. Menus [index] = newMenu.NewMenuBarItem;
  638. }
  639. var pos = 0;
  640. switch (subMenu)
  641. {
  642. case null:
  643. // Open a submenu below a MenuBar
  644. _lastFocused ??= SuperView is null ? Application.Current?.MostFocused : SuperView.MostFocused;
  645. if (_openSubMenu is { } && !CloseMenu (false, true))
  646. {
  647. return;
  648. }
  649. if (_openMenu is { })
  650. {
  651. Application.Current?.Remove (_openMenu);
  652. _openMenu.Dispose ();
  653. _openMenu = null;
  654. }
  655. // This positions the submenu horizontally aligned with the first character of the
  656. // text belonging to the menu
  657. for (var i = 0; i < index; i++)
  658. {
  659. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  660. }
  661. var locationOffset = Point.Empty;
  662. // if SuperView is null then it's from a ContextMenu
  663. if (SuperView is null)
  664. {
  665. locationOffset = GetScreenOffset ();
  666. }
  667. if (SuperView is { } && SuperView != Application.Current)
  668. {
  669. locationOffset.X += SuperView.Border.Thickness.Left;
  670. locationOffset.Y += SuperView.Border.Thickness.Top;
  671. }
  672. _openMenu = new ()
  673. {
  674. Host = this,
  675. X = Frame.X + pos + locationOffset.X,
  676. Y = Frame.Y + 1 + locationOffset.Y,
  677. BarItems = Menus [index],
  678. Parent = null
  679. };
  680. OpenCurrentMenu = _openMenu;
  681. OpenCurrentMenu._previousSubFocused = _openMenu;
  682. if (Application.Current is { })
  683. {
  684. Application.Current.Add (_openMenu);
  685. }
  686. else
  687. {
  688. _openMenu.BeginInit ();
  689. _openMenu.EndInit ();
  690. }
  691. _openMenu.SetFocus ();
  692. break;
  693. default:
  694. // Opens a submenu next to another submenu (openSubMenu)
  695. if (_openSubMenu is null)
  696. {
  697. _openSubMenu = new ();
  698. }
  699. if (sIndex > -1)
  700. {
  701. RemoveSubMenu (sIndex);
  702. }
  703. else
  704. {
  705. Menu? last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  706. if (!UseSubMenusSingleFrame)
  707. {
  708. locationOffset = GetLocationOffset ();
  709. OpenCurrentMenu = new ()
  710. {
  711. Host = this,
  712. X = last.Frame.Left + last.Frame.Width + locationOffset.X,
  713. Y = last.Frame.Top + locationOffset.Y + last._currentChild,
  714. BarItems = subMenu,
  715. Parent = last
  716. };
  717. }
  718. else
  719. {
  720. Menu? first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  721. // 2 is for the parent and the separator
  722. MenuItem? [] mbi = new MenuItem [2 + subMenu.Children.Length];
  723. mbi [0] = new () { Title = subMenu.Title, Parent = subMenu };
  724. mbi [1] = null;
  725. for (var j = 0; j < subMenu.Children.Length; j++)
  726. {
  727. mbi [j + 2] = subMenu.Children [j];
  728. }
  729. var newSubMenu = new MenuBarItem (mbi) { Parent = subMenu };
  730. OpenCurrentMenu = new ()
  731. {
  732. Host = this, X = first!.Frame.Left, Y = first.Frame.Top, BarItems = newSubMenu
  733. };
  734. last.Visible = false;
  735. Application.GrabMouse (OpenCurrentMenu);
  736. }
  737. OpenCurrentMenu._previousSubFocused = last._previousSubFocused;
  738. _openSubMenu.Add (OpenCurrentMenu);
  739. Application.Current?.Add (OpenCurrentMenu);
  740. if (!OpenCurrentMenu.IsInitialized)
  741. {
  742. // Supports unit tests
  743. OpenCurrentMenu.BeginInit ();
  744. OpenCurrentMenu.EndInit ();
  745. }
  746. }
  747. _selectedSub = _openSubMenu.Count - 1;
  748. if (_selectedSub > -1
  749. && SelectEnabledItem (
  750. OpenCurrentMenu!.BarItems.Children,
  751. OpenCurrentMenu._currentChild,
  752. out OpenCurrentMenu._currentChild
  753. ))
  754. {
  755. OpenCurrentMenu.SetFocus ();
  756. }
  757. break;
  758. }
  759. _isMenuOpening = false;
  760. IsMenuOpen = true;
  761. }
  762. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  763. {
  764. switch (isSubMenu)
  765. {
  766. case false:
  767. if (_selected <= 0)
  768. {
  769. _selected = Menus.Length - 1;
  770. }
  771. else
  772. {
  773. _selected--;
  774. }
  775. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  776. {
  777. return;
  778. }
  779. OpenMenu (_selected);
  780. if (!SelectEnabledItem (
  781. OpenCurrentMenu!.BarItems.Children,
  782. OpenCurrentMenu._currentChild,
  783. out OpenCurrentMenu._currentChild,
  784. false
  785. ))
  786. {
  787. OpenCurrentMenu._currentChild = 0;
  788. }
  789. break;
  790. case true:
  791. if (_selectedSub > -1)
  792. {
  793. _selectedSub--;
  794. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  795. SetNeedsDisplay ();
  796. }
  797. else
  798. {
  799. PreviousMenu ();
  800. }
  801. break;
  802. }
  803. }
  804. internal void RemoveAllOpensSubMenus ()
  805. {
  806. if (_openSubMenu is { })
  807. {
  808. foreach (Menu item in _openSubMenu)
  809. {
  810. Application.Current!.Remove (item);
  811. item.Dispose ();
  812. }
  813. }
  814. }
  815. internal bool Run (Action action)
  816. {
  817. if (action is null)
  818. {
  819. return false;
  820. }
  821. Application.MainLoop!.AddIdle (
  822. () =>
  823. {
  824. action ();
  825. return false;
  826. }
  827. );
  828. return true;
  829. }
  830. internal bool SelectEnabledItem (
  831. IEnumerable<MenuItem>? children,
  832. int current,
  833. out int newCurrent,
  834. bool forward = true
  835. )
  836. {
  837. if (children is null)
  838. {
  839. newCurrent = -1;
  840. return true;
  841. }
  842. IEnumerable<MenuItem> childMenuItems = forward ? children : children.Reverse ();
  843. int count;
  844. IEnumerable<MenuItem> menuItems = childMenuItems as MenuItem [] ?? childMenuItems.ToArray ();
  845. if (forward)
  846. {
  847. count = -1;
  848. }
  849. else
  850. {
  851. count = menuItems.Count ();
  852. }
  853. foreach (MenuItem child in menuItems)
  854. {
  855. if (forward)
  856. {
  857. if (++count < current)
  858. {
  859. continue;
  860. }
  861. }
  862. else
  863. {
  864. if (--count > current)
  865. {
  866. continue;
  867. }
  868. }
  869. if (child is null || !child.IsEnabled ())
  870. {
  871. if (forward)
  872. {
  873. current++;
  874. }
  875. else
  876. {
  877. current--;
  878. }
  879. }
  880. else
  881. {
  882. newCurrent = current;
  883. return true;
  884. }
  885. }
  886. newCurrent = -1;
  887. return false;
  888. }
  889. /// <summary>Called when an item is selected; Runs the action.</summary>
  890. /// <param name="item"></param>
  891. internal bool SelectItem (MenuItem item)
  892. {
  893. if (item?.Action is null)
  894. {
  895. return false;
  896. }
  897. Application.UngrabMouse ();
  898. CloseAllMenus ();
  899. Application.Refresh ();
  900. _openedByAltKey = true;
  901. return Run (item?.Action);
  902. }
  903. private void CloseMenuBar ()
  904. {
  905. if (!CloseMenu (false))
  906. {
  907. return;
  908. }
  909. if (_openedByAltKey)
  910. {
  911. _openedByAltKey = false;
  912. LastFocused?.SetFocus ();
  913. }
  914. SetNeedsDisplay ();
  915. }
  916. private Point GetLocationOffset ()
  917. {
  918. if (MenusBorderStyle != LineStyle.None)
  919. {
  920. return new (0, 1);
  921. }
  922. return new (-2, 0);
  923. }
  924. private void MenuBar_Added (object? sender, SuperViewChangedEventArgs e)
  925. {
  926. _initialCanFocus = CanFocus;
  927. Added -= MenuBar_Added;
  928. }
  929. private void MoveLeft ()
  930. {
  931. _selected--;
  932. if (_selected < 0)
  933. {
  934. _selected = Menus.Length - 1;
  935. }
  936. OpenMenu (_selected);
  937. SetNeedsDisplay ();
  938. }
  939. private void MoveRight ()
  940. {
  941. _selected = (_selected + 1) % Menus.Length;
  942. OpenMenu (_selected);
  943. SetNeedsDisplay ();
  944. }
  945. private void ProcessMenu (int i, MenuBarItem mi)
  946. {
  947. if (_selected < 0 && IsMenuOpen)
  948. {
  949. return;
  950. }
  951. if (mi.IsTopLevel)
  952. {
  953. Point screen = ViewportToScreen (new Point (0, i));
  954. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = mi };
  955. menu.Run (mi.Action);
  956. menu.Dispose ();
  957. }
  958. else
  959. {
  960. Application.GrabMouse (this);
  961. _selected = i;
  962. OpenMenu (i);
  963. if (!SelectEnabledItem (
  964. OpenCurrentMenu!.BarItems.Children,
  965. OpenCurrentMenu._currentChild,
  966. out OpenCurrentMenu._currentChild
  967. )
  968. && !CloseMenu (false))
  969. {
  970. return;
  971. }
  972. if (!OpenCurrentMenu.CheckSubMenu ())
  973. {
  974. return;
  975. }
  976. }
  977. SetNeedsDisplay ();
  978. }
  979. private void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  980. {
  981. if (_openSubMenu == null
  982. || (UseSubMenusSingleFrame
  983. && !ignoreUseSubMenusSingleFrame
  984. && _openSubMenu.Count == 0))
  985. {
  986. return;
  987. }
  988. for (int i = _openSubMenu.Count - 1; i > index; i--)
  989. {
  990. _isMenuClosing = true;
  991. Menu? menu;
  992. if (_openSubMenu.Count - 1 > 0)
  993. {
  994. menu = _openSubMenu [i - 1];
  995. }
  996. else
  997. {
  998. menu = _openMenu;
  999. }
  1000. if (!menu!.Visible)
  1001. {
  1002. menu.Visible = true;
  1003. }
  1004. OpenCurrentMenu = menu;
  1005. OpenCurrentMenu.SetFocus ();
  1006. if (_openSubMenu is { })
  1007. {
  1008. menu = _openSubMenu [i];
  1009. Application.Current!.Remove (menu);
  1010. _openSubMenu.Remove (menu);
  1011. if (Application.MouseGrabView == menu)
  1012. {
  1013. Application.GrabMouse (this);
  1014. }
  1015. menu.Dispose ();
  1016. }
  1017. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1018. }
  1019. if (_openSubMenu!.Count > 0)
  1020. {
  1021. OpenCurrentMenu = _openSubMenu.Last ();
  1022. }
  1023. _isMenuClosing = false;
  1024. }
  1025. #region Keyboard handling
  1026. private Key _key = Key.F9;
  1027. /// <summary>
  1028. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>
  1029. /// .
  1030. /// </summary>
  1031. /// <remarks>
  1032. /// <para>
  1033. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu
  1034. /// bar will be activated and the sub-menu will be opened.
  1035. /// </para>
  1036. /// <para><see cref="Key.Esc"/> will close the menu bar and any open sub-menus.</para>
  1037. /// </remarks>
  1038. public Key Key
  1039. {
  1040. get => _key;
  1041. set
  1042. {
  1043. if (_key == value)
  1044. {
  1045. return;
  1046. }
  1047. KeyBindings.Remove (_key);
  1048. KeyBinding keyBinding = new ([Command.ToggleExpandCollapse], KeyBindingScope.HotKey, -1); // -1 indicates Key was used
  1049. KeyBindings.Add (value, keyBinding);
  1050. _key = value;
  1051. }
  1052. }
  1053. private bool _useKeysUpDownAsKeysLeftRight;
  1054. /// <summary>Used for change the navigation key style.</summary>
  1055. public bool UseKeysUpDownAsKeysLeftRight
  1056. {
  1057. get => _useKeysUpDownAsKeysLeftRight;
  1058. set
  1059. {
  1060. _useKeysUpDownAsKeysLeftRight = value;
  1061. if (value && UseSubMenusSingleFrame)
  1062. {
  1063. UseSubMenusSingleFrame = false;
  1064. SetNeedsDisplay ();
  1065. }
  1066. }
  1067. }
  1068. /// <summary>The specifier character for the hot keys.</summary>
  1069. public new static Rune HotKeySpecifier => (Rune)'_';
  1070. // TODO: This doesn't actually work. Figure out why.
  1071. private bool _openedByAltKey;
  1072. /// <summary>
  1073. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on
  1074. /// whether it has a sub-menu. If the menu is open, it will close the menu bar.
  1075. /// </summary>
  1076. /// <param name="index">The index of the menu bar item to select. -1 if the selection was via <see cref="Key"/>.</param>
  1077. /// <returns></returns>
  1078. private bool Select (int index)
  1079. {
  1080. if (!IsInitialized || !Visible)
  1081. {
  1082. return true;
  1083. }
  1084. // If the menubar is open and the menu that's open is 'index' then close it. Otherwise activate it.
  1085. if (IsMenuOpen)
  1086. {
  1087. if (index == -1)
  1088. {
  1089. CloseAllMenus ();
  1090. return true;
  1091. }
  1092. // Find the index of the open submenu and close the menu if it matches
  1093. for (var i = 0; i < Menus.Length; i++)
  1094. {
  1095. MenuBarItem open = Menus [i];
  1096. if (open is null)
  1097. {
  1098. continue;
  1099. }
  1100. if (open == OpenCurrentMenu!.BarItems && i == index)
  1101. {
  1102. CloseAllMenus ();
  1103. return true;
  1104. }
  1105. }
  1106. }
  1107. if (index == -1)
  1108. {
  1109. OpenMenu ();
  1110. }
  1111. else if (Menus [index].IsTopLevel)
  1112. {
  1113. Run (Menus [index].Action);
  1114. }
  1115. else
  1116. {
  1117. Activate (index);
  1118. }
  1119. return true;
  1120. }
  1121. #endregion Keyboard handling
  1122. #region Mouse Handling
  1123. /// <inheritdoc/>
  1124. internal void LostFocus (View view)
  1125. {
  1126. if (((!(view is MenuBar) && !(view is Menu))) && !_isCleaning && !_reopen)
  1127. {
  1128. CleanUp ();
  1129. }
  1130. return;
  1131. }
  1132. /// <inheritdoc/>
  1133. protected internal override bool OnMouseEvent (MouseEvent me)
  1134. {
  1135. if (!_handled && !HandleGrabView (me, this))
  1136. {
  1137. return false;
  1138. }
  1139. _handled = false;
  1140. if (me.Flags == MouseFlags.Button1Pressed
  1141. || me.Flags == MouseFlags.Button1DoubleClicked
  1142. || me.Flags == MouseFlags.Button1TripleClicked
  1143. || me.Flags == MouseFlags.Button1Clicked
  1144. || (me.Flags == MouseFlags.ReportMousePosition && _selected > -1)
  1145. || (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1))
  1146. {
  1147. int pos = _xOrigin;
  1148. Point locationOffset = default;
  1149. if (SuperView is { })
  1150. {
  1151. locationOffset.X += SuperView.Border.Thickness.Left;
  1152. locationOffset.Y += SuperView.Border.Thickness.Top;
  1153. }
  1154. int cx = me.Position.X - locationOffset.X;
  1155. for (var i = 0; i < Menus.Length; i++)
  1156. {
  1157. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding)
  1158. {
  1159. if (me.Flags == MouseFlags.Button1Clicked)
  1160. {
  1161. if (Menus [i].IsTopLevel)
  1162. {
  1163. Point screen = ViewportToScreen (new Point (0, i));
  1164. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = Menus [i] };
  1165. menu.Run (Menus [i].Action);
  1166. menu.Dispose ();
  1167. }
  1168. else if (!IsMenuOpen)
  1169. {
  1170. Activate (i);
  1171. }
  1172. }
  1173. else if (me.Flags == MouseFlags.Button1Pressed
  1174. || me.Flags == MouseFlags.Button1DoubleClicked
  1175. || me.Flags == MouseFlags.Button1TripleClicked)
  1176. {
  1177. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1178. {
  1179. CloseAllMenus ();
  1180. }
  1181. else if (!Menus [i].IsTopLevel)
  1182. {
  1183. Activate (i);
  1184. }
  1185. }
  1186. else if (_selected != i
  1187. && _selected > -1
  1188. && (me.Flags == MouseFlags.ReportMousePosition
  1189. || (me.Flags is MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)))
  1190. {
  1191. if (IsMenuOpen)
  1192. {
  1193. if (!CloseMenu (true, false))
  1194. {
  1195. return me.Handled = true;
  1196. }
  1197. Activate (i);
  1198. }
  1199. }
  1200. else if (IsMenuOpen)
  1201. {
  1202. if (!UseSubMenusSingleFrame
  1203. || (UseSubMenusSingleFrame
  1204. && OpenCurrentMenu != null
  1205. && OpenCurrentMenu.BarItems.Parent != null
  1206. && OpenCurrentMenu.BarItems.Parent.Parent != Menus [i]))
  1207. {
  1208. Activate (i);
  1209. }
  1210. }
  1211. return me.Handled = true;
  1212. }
  1213. if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked)
  1214. {
  1215. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1216. {
  1217. CloseAllMenus ();
  1218. return me.Handled = true;
  1219. }
  1220. }
  1221. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1222. }
  1223. }
  1224. return false;
  1225. }
  1226. internal bool _handled;
  1227. internal bool _isContextMenuLoading;
  1228. private MenuBarItem [] _menus;
  1229. internal bool HandleGrabView (MouseEvent me, View current)
  1230. {
  1231. if (Application.MouseGrabView is { })
  1232. {
  1233. if (me.View is MenuBar or Menu)
  1234. {
  1235. MenuBar? mbar = GetMouseGrabViewInstance (me.View);
  1236. if (mbar is { })
  1237. {
  1238. if (me.Flags == MouseFlags.Button1Clicked)
  1239. {
  1240. mbar.CleanUp ();
  1241. Application.GrabMouse (me.View);
  1242. }
  1243. else
  1244. {
  1245. _handled = false;
  1246. return false;
  1247. }
  1248. }
  1249. if (me.View != current)
  1250. {
  1251. Application.UngrabMouse ();
  1252. View v = me.View;
  1253. Application.GrabMouse (v);
  1254. MouseEvent nme;
  1255. if (me.Position.Y > -1)
  1256. {
  1257. Point frameLoc = v.ScreenToFrame (me.Position);
  1258. nme = new ()
  1259. {
  1260. Position = frameLoc,
  1261. Flags = me.Flags,
  1262. View = v
  1263. };
  1264. }
  1265. else
  1266. {
  1267. nme = new ()
  1268. {
  1269. Position = new (me.Position.X + current.Frame.X, me.Position.Y + current.Frame.Y),
  1270. Flags = me.Flags, View = v
  1271. };
  1272. }
  1273. v.NewMouseEvent (nme);
  1274. return false;
  1275. }
  1276. }
  1277. else if (!(me.View is MenuBar || me.View is Menu)
  1278. && me.Flags != MouseFlags.ReportMousePosition
  1279. && me.Flags != 0)
  1280. {
  1281. Application.UngrabMouse ();
  1282. if (IsMenuOpen)
  1283. {
  1284. CloseAllMenus ();
  1285. }
  1286. _handled = false;
  1287. return false;
  1288. }
  1289. else
  1290. {
  1291. _handled = false;
  1292. _isContextMenuLoading = false;
  1293. return false;
  1294. }
  1295. }
  1296. else if (!IsMenuOpen
  1297. && (me.Flags == MouseFlags.Button1Pressed
  1298. || me.Flags == MouseFlags.Button1DoubleClicked
  1299. || me.Flags == MouseFlags.Button1TripleClicked
  1300. || me.Flags.HasFlag (
  1301. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1302. )))
  1303. {
  1304. Application.GrabMouse (current);
  1305. }
  1306. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1307. {
  1308. Application.GrabMouse (me.View);
  1309. }
  1310. else
  1311. {
  1312. _handled = false;
  1313. return false;
  1314. }
  1315. _handled = true;
  1316. return true;
  1317. }
  1318. private MenuBar? GetMouseGrabViewInstance (View? view)
  1319. {
  1320. if (view is null || Application.MouseGrabView is null)
  1321. {
  1322. return null;
  1323. }
  1324. MenuBar? hostView = null;
  1325. if (view is MenuBar)
  1326. {
  1327. hostView = (MenuBar)view;
  1328. }
  1329. else if (view is Menu)
  1330. {
  1331. hostView = ((Menu)view).Host;
  1332. }
  1333. View grabView = Application.MouseGrabView;
  1334. MenuBar? hostGrabView = null;
  1335. if (grabView is MenuBar bar)
  1336. {
  1337. hostGrabView = bar;
  1338. }
  1339. else if (grabView is Menu menu)
  1340. {
  1341. hostGrabView = menu.Host;
  1342. }
  1343. return hostView != hostGrabView ? hostGrabView : null;
  1344. }
  1345. #endregion Mouse Handling
  1346. /// <inheritdoc />
  1347. public bool EnableForDesign<TContext> (ref readonly TContext context) where TContext : notnull
  1348. {
  1349. if (context is not Func<string, bool> actionFn)
  1350. {
  1351. actionFn = (s) => true;
  1352. }
  1353. Menus =
  1354. [
  1355. new MenuBarItem (
  1356. "_File",
  1357. new MenuItem []
  1358. {
  1359. new (
  1360. "_New",
  1361. "",
  1362. () => actionFn ("New"),
  1363. null,
  1364. null,
  1365. KeyCode.CtrlMask | KeyCode.N
  1366. ),
  1367. new (
  1368. "_Open",
  1369. "",
  1370. () => actionFn ("Open"),
  1371. null,
  1372. null,
  1373. KeyCode.CtrlMask | KeyCode.O
  1374. ),
  1375. new (
  1376. "_Save",
  1377. "",
  1378. () => actionFn ("Save"),
  1379. null,
  1380. null,
  1381. KeyCode.CtrlMask | KeyCode.S
  1382. ),
  1383. null,
  1384. // Don't use Application.Quit so we can disambiguate between quitting and closing the toplevel
  1385. new (
  1386. "_Quit",
  1387. "",
  1388. () => actionFn ("Quit"),
  1389. null,
  1390. null,
  1391. KeyCode.CtrlMask | KeyCode.Q
  1392. )
  1393. }
  1394. ),
  1395. new MenuBarItem (
  1396. "_Edit",
  1397. new MenuItem []
  1398. {
  1399. new (
  1400. "_Copy",
  1401. "",
  1402. () => actionFn ("Copy"),
  1403. null,
  1404. null,
  1405. KeyCode.CtrlMask | KeyCode.C
  1406. ),
  1407. new (
  1408. "C_ut",
  1409. "",
  1410. () => actionFn ("Cut"),
  1411. null,
  1412. null,
  1413. KeyCode.CtrlMask | KeyCode.X
  1414. ),
  1415. new (
  1416. "_Paste",
  1417. "",
  1418. () => actionFn ("Paste"),
  1419. null,
  1420. null,
  1421. KeyCode.CtrlMask | KeyCode.V
  1422. ),
  1423. new MenuBarItem (
  1424. "_Find and Replace",
  1425. new MenuItem []
  1426. {
  1427. new (
  1428. "F_ind",
  1429. "",
  1430. () => actionFn ("Find"),
  1431. null,
  1432. null,
  1433. KeyCode.CtrlMask | KeyCode.F
  1434. ),
  1435. new (
  1436. "_Replace",
  1437. "",
  1438. () => actionFn ("Replace"),
  1439. null,
  1440. null,
  1441. KeyCode.CtrlMask | KeyCode.H
  1442. ),
  1443. new MenuBarItem (
  1444. "_3rd Level",
  1445. new MenuItem []
  1446. {
  1447. new (
  1448. "_1st",
  1449. "",
  1450. () => actionFn (
  1451. "1"
  1452. ),
  1453. null,
  1454. null,
  1455. KeyCode.F1
  1456. ),
  1457. new (
  1458. "_2nd",
  1459. "",
  1460. () => actionFn (
  1461. "2"
  1462. ),
  1463. null,
  1464. null,
  1465. KeyCode.F2
  1466. )
  1467. }
  1468. ),
  1469. new MenuBarItem (
  1470. "_4th Level",
  1471. new MenuItem []
  1472. {
  1473. new (
  1474. "_5th",
  1475. "",
  1476. () => actionFn (
  1477. "5"
  1478. ),
  1479. null,
  1480. null,
  1481. KeyCode.CtrlMask
  1482. | KeyCode.D5
  1483. ),
  1484. new (
  1485. "_6th",
  1486. "",
  1487. () => actionFn (
  1488. "6"
  1489. ),
  1490. null,
  1491. null,
  1492. KeyCode.CtrlMask
  1493. | KeyCode.D6
  1494. )
  1495. }
  1496. )
  1497. }
  1498. ),
  1499. new (
  1500. "_Select All",
  1501. "",
  1502. () => actionFn ("Select All"),
  1503. null,
  1504. null,
  1505. KeyCode.CtrlMask
  1506. | KeyCode.ShiftMask
  1507. | KeyCode.S
  1508. )
  1509. }
  1510. ),
  1511. new MenuBarItem ("_About", "Top-Level", () => actionFn ("About"))
  1512. ];
  1513. return true;
  1514. }
  1515. }