MenuBar.cs 60 KB

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