MenuBar.cs 58 KB

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