MenuBar.cs 62 KB

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