MenuBar.cs 61 KB

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