MenuBar.cs 61 KB

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