MenuBar.cs 60 KB

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