MenuBar.cs 61 KB

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