MenuBar.cs 61 KB

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