MenuBar.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  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 MouseEventArgs)
  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. // _openMenu.SetRelativeLayout (Application.Screen.Size);
  719. }
  720. else
  721. {
  722. _openMenu.BeginInit ();
  723. _openMenu.EndInit ();
  724. }
  725. _openMenu.SetFocus ();
  726. break;
  727. default:
  728. // Opens a submenu next to another submenu (openSubMenu)
  729. if (_openSubMenu is null)
  730. {
  731. _openSubMenu = new ();
  732. }
  733. if (sIndex > -1)
  734. {
  735. RemoveSubMenu (sIndex);
  736. }
  737. else
  738. {
  739. Menu? last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  740. if (!UseSubMenusSingleFrame)
  741. {
  742. locationOffset = GetLocationOffset ();
  743. OpenCurrentMenu = new ()
  744. {
  745. Host = this,
  746. X = last!.Frame.Left + last.Frame.Width + locationOffset.X,
  747. Y = last.Frame.Top + locationOffset.Y + last._currentChild,
  748. BarItems = subMenu,
  749. Parent = last
  750. };
  751. }
  752. else
  753. {
  754. Menu? first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  755. // 2 is for the parent and the separator
  756. MenuItem? [] mbi = new MenuItem [2 + subMenu.Children!.Length];
  757. mbi [0] = new () { Title = subMenu.Title, Parent = subMenu };
  758. mbi [1] = null;
  759. for (var j = 0; j < subMenu.Children.Length; j++)
  760. {
  761. mbi [j + 2] = subMenu.Children [j];
  762. }
  763. var newSubMenu = new MenuBarItem (mbi!) { Parent = subMenu };
  764. OpenCurrentMenu = new ()
  765. {
  766. Host = this, X = first!.Frame.Left, Y = first.Frame.Top, BarItems = newSubMenu
  767. };
  768. last!.Visible = false;
  769. Application.GrabMouse (OpenCurrentMenu);
  770. }
  771. OpenCurrentMenu._previousSubFocused = last._previousSubFocused;
  772. _openSubMenu.Add (OpenCurrentMenu);
  773. Application.Top?.Add (OpenCurrentMenu);
  774. if (!OpenCurrentMenu.IsInitialized)
  775. {
  776. // Supports unit tests
  777. OpenCurrentMenu.BeginInit ();
  778. OpenCurrentMenu.EndInit ();
  779. }
  780. }
  781. _selectedSub = _openSubMenu.Count - 1;
  782. if (_selectedSub > -1
  783. && SelectEnabledItem (
  784. OpenCurrentMenu!.BarItems!.Children,
  785. OpenCurrentMenu._currentChild,
  786. out OpenCurrentMenu._currentChild
  787. ))
  788. {
  789. OpenCurrentMenu.SetFocus ();
  790. }
  791. break;
  792. }
  793. _isMenuOpening = false;
  794. IsMenuOpen = true;
  795. }
  796. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  797. {
  798. switch (isSubMenu)
  799. {
  800. case false:
  801. if (_selected <= 0)
  802. {
  803. _selected = Menus.Length - 1;
  804. }
  805. else
  806. {
  807. _selected--;
  808. }
  809. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  810. {
  811. return;
  812. }
  813. OpenMenu (_selected);
  814. if (!SelectEnabledItem (
  815. OpenCurrentMenu?.BarItems?.Children,
  816. OpenCurrentMenu!._currentChild,
  817. out OpenCurrentMenu._currentChild,
  818. false
  819. ))
  820. {
  821. OpenCurrentMenu._currentChild = 0;
  822. }
  823. break;
  824. case true:
  825. if (_selectedSub > -1)
  826. {
  827. _selectedSub--;
  828. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  829. SetNeedsDisplay ();
  830. }
  831. else
  832. {
  833. PreviousMenu ();
  834. }
  835. break;
  836. }
  837. }
  838. internal void RemoveAllOpensSubMenus ()
  839. {
  840. if (_openSubMenu is { })
  841. {
  842. foreach (Menu item in _openSubMenu)
  843. {
  844. Application.Top!.Remove (item);
  845. if (Application.MouseGrabView == item)
  846. {
  847. Application.UngrabMouse ();
  848. }
  849. item.Dispose ();
  850. }
  851. }
  852. }
  853. internal bool Run (Action? action)
  854. {
  855. if (action is null)
  856. {
  857. return false;
  858. }
  859. Application.MainLoop!.AddIdle (
  860. () =>
  861. {
  862. action ();
  863. return false;
  864. }
  865. );
  866. return true;
  867. }
  868. internal bool SelectEnabledItem (
  869. MenuItem? []? children,
  870. int current,
  871. out int newCurrent,
  872. bool forward = true
  873. )
  874. {
  875. if (children is null)
  876. {
  877. newCurrent = -1;
  878. return true;
  879. }
  880. IEnumerable<MenuItem?> childMenuItems = forward ? children : children.Reverse ();
  881. int count;
  882. IEnumerable<MenuItem?> menuItems = childMenuItems as MenuItem [] ?? childMenuItems.ToArray ();
  883. if (forward)
  884. {
  885. count = -1;
  886. }
  887. else
  888. {
  889. count = menuItems.Count ();
  890. }
  891. foreach (MenuItem? child in menuItems)
  892. {
  893. if (forward)
  894. {
  895. if (++count < current)
  896. {
  897. continue;
  898. }
  899. }
  900. else
  901. {
  902. if (--count > current)
  903. {
  904. continue;
  905. }
  906. }
  907. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  908. if (child is null || !child.IsEnabled ())
  909. {
  910. if (forward)
  911. {
  912. current++;
  913. }
  914. else
  915. {
  916. current--;
  917. }
  918. }
  919. else
  920. {
  921. newCurrent = current;
  922. return true;
  923. }
  924. }
  925. newCurrent = -1;
  926. return false;
  927. }
  928. /// <summary>Called when an item is selected; Runs the action.</summary>
  929. /// <param name="item"></param>
  930. internal bool SelectItem (MenuItem? item)
  931. {
  932. if (item?.Action is null)
  933. {
  934. return false;
  935. }
  936. Application.UngrabMouse ();
  937. CloseAllMenus ();
  938. Application.Refresh ();
  939. _openedByAltKey = true;
  940. return Run (item.Action);
  941. }
  942. private void CloseMenuBar ()
  943. {
  944. if (!CloseMenu ())
  945. {
  946. return;
  947. }
  948. if (_openedByAltKey)
  949. {
  950. _openedByAltKey = false;
  951. LastFocused?.SetFocus ();
  952. }
  953. SetNeedsDisplay ();
  954. }
  955. private Point GetLocationOffset ()
  956. {
  957. if (MenusBorderStyle != LineStyle.None)
  958. {
  959. return new (0, 1);
  960. }
  961. return new (-2, 0);
  962. }
  963. private void MenuBar_Added (object? sender, SuperViewChangedEventArgs e)
  964. {
  965. _initialCanFocus = CanFocus;
  966. Added -= MenuBar_Added;
  967. }
  968. private void MoveLeft ()
  969. {
  970. _selected--;
  971. if (_selected < 0)
  972. {
  973. _selected = Menus.Length - 1;
  974. }
  975. OpenMenu (_selected);
  976. SetNeedsDisplay ();
  977. }
  978. private void MoveRight ()
  979. {
  980. _selected = (_selected + 1) % Menus.Length;
  981. OpenMenu (_selected);
  982. SetNeedsDisplay ();
  983. }
  984. private bool ProcessMenu (int i, MenuBarItem mi)
  985. {
  986. if (_selected < 0 && IsMenuOpen)
  987. {
  988. return false;
  989. }
  990. if (mi.IsTopLevel)
  991. {
  992. Point screen = ViewportToScreen (new Point (0, i));
  993. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = mi };
  994. menu.Run (mi.Action);
  995. if (Application.MouseGrabView == menu)
  996. {
  997. Application.UngrabMouse ();
  998. }
  999. menu.Dispose ();
  1000. }
  1001. else
  1002. {
  1003. Application.GrabMouse (this);
  1004. _selected = i;
  1005. OpenMenu (i);
  1006. if (!SelectEnabledItem (
  1007. OpenCurrentMenu?.BarItems?.Children,
  1008. OpenCurrentMenu!._currentChild,
  1009. out OpenCurrentMenu._currentChild
  1010. )
  1011. && !CloseMenu ())
  1012. {
  1013. return true;
  1014. }
  1015. if (!OpenCurrentMenu.CheckSubMenu ())
  1016. {
  1017. return true;
  1018. }
  1019. }
  1020. SetNeedsDisplay ();
  1021. return true;
  1022. }
  1023. private void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1024. {
  1025. if (_openSubMenu == null
  1026. || (UseSubMenusSingleFrame
  1027. && !ignoreUseSubMenusSingleFrame
  1028. && _openSubMenu.Count == 0))
  1029. {
  1030. return;
  1031. }
  1032. for (int i = _openSubMenu.Count - 1; i > index; i--)
  1033. {
  1034. _isMenuClosing = true;
  1035. Menu? menu;
  1036. if (_openSubMenu!.Count - 1 > 0)
  1037. {
  1038. menu = _openSubMenu [i - 1];
  1039. }
  1040. else
  1041. {
  1042. menu = _openMenu;
  1043. }
  1044. if (!menu!.Visible)
  1045. {
  1046. menu.Visible = true;
  1047. }
  1048. OpenCurrentMenu = menu;
  1049. OpenCurrentMenu.SetFocus ();
  1050. if (_openSubMenu is { })
  1051. {
  1052. menu = _openSubMenu [i];
  1053. Application.Top!.Remove (menu);
  1054. _openSubMenu.Remove (menu);
  1055. if (Application.MouseGrabView == menu)
  1056. {
  1057. Application.GrabMouse (this);
  1058. }
  1059. menu.Dispose ();
  1060. }
  1061. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1062. }
  1063. if (_openSubMenu!.Count > 0)
  1064. {
  1065. OpenCurrentMenu = _openSubMenu.Last ();
  1066. }
  1067. _isMenuClosing = false;
  1068. }
  1069. #region Keyboard handling
  1070. private Key _key = Key.F9;
  1071. /// <summary>
  1072. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>
  1073. /// .
  1074. /// </summary>
  1075. /// <remarks>
  1076. /// <para>
  1077. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu
  1078. /// bar will be activated and the sub-menu will be opened.
  1079. /// </para>
  1080. /// <para><see cref="Key.Esc"/> will close the menu bar and any open sub-menus.</para>
  1081. /// </remarks>
  1082. public Key Key
  1083. {
  1084. get => _key;
  1085. set
  1086. {
  1087. if (_key == value)
  1088. {
  1089. return;
  1090. }
  1091. KeyBindings.Remove (_key);
  1092. KeyBinding keyBinding = new ([Command.Toggle], KeyBindingScope.HotKey, -1); // -1 indicates Key was used
  1093. KeyBindings.Add (value, keyBinding);
  1094. _key = value;
  1095. }
  1096. }
  1097. private bool _useKeysUpDownAsKeysLeftRight;
  1098. /// <summary>Used for change the navigation key style.</summary>
  1099. public bool UseKeysUpDownAsKeysLeftRight
  1100. {
  1101. get => _useKeysUpDownAsKeysLeftRight;
  1102. set
  1103. {
  1104. _useKeysUpDownAsKeysLeftRight = value;
  1105. if (value && UseSubMenusSingleFrame)
  1106. {
  1107. UseSubMenusSingleFrame = false;
  1108. SetNeedsDisplay ();
  1109. }
  1110. }
  1111. }
  1112. /// <summary>The specifier character for the hot keys.</summary>
  1113. public new static Rune HotKeySpecifier => (Rune)'_';
  1114. // TODO: This doesn't actually work. Figure out why.
  1115. private bool _openedByAltKey;
  1116. /// <summary>
  1117. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on
  1118. /// whether it has a sub-menu. If the menu is open, it will close the menu bar.
  1119. /// </summary>
  1120. /// <param name="index">The index of the menu bar item to select. -1 if the selection was via <see cref="Key"/>.</param>
  1121. /// <returns></returns>
  1122. private bool Select (int index)
  1123. {
  1124. if (!IsInitialized || !Visible)
  1125. {
  1126. return true;
  1127. }
  1128. // If the menubar is open and the menu that's open is 'index' then close it. Otherwise activate it.
  1129. if (IsMenuOpen)
  1130. {
  1131. if (index == -1)
  1132. {
  1133. CloseAllMenus ();
  1134. return true;
  1135. }
  1136. // Find the index of the open submenu and close the menu if it matches
  1137. for (var i = 0; i < Menus.Length; i++)
  1138. {
  1139. MenuBarItem open = Menus [i];
  1140. if (open == OpenCurrentMenu!.BarItems && i == index)
  1141. {
  1142. CloseAllMenus ();
  1143. return true;
  1144. }
  1145. }
  1146. }
  1147. if (index == -1)
  1148. {
  1149. OpenMenu ();
  1150. }
  1151. else if (Menus [index].IsTopLevel)
  1152. {
  1153. Run (Menus [index].Action);
  1154. }
  1155. else
  1156. {
  1157. Activate (index);
  1158. }
  1159. return true;
  1160. }
  1161. #endregion Keyboard handling
  1162. #region Mouse Handling
  1163. internal void LostFocus (View view)
  1164. {
  1165. if (view is not MenuBar && view is not Menu && !_isCleaning && !_reopen)
  1166. {
  1167. CleanUp ();
  1168. }
  1169. }
  1170. /// <inheritdoc/>
  1171. protected override bool OnMouseEvent (MouseEventArgs me)
  1172. {
  1173. if (!_handled && !HandleGrabView (me, this))
  1174. {
  1175. return false;
  1176. }
  1177. _handled = false;
  1178. if (me.Flags == MouseFlags.Button1Pressed
  1179. || me.Flags == MouseFlags.Button1DoubleClicked
  1180. || me.Flags == MouseFlags.Button1TripleClicked
  1181. || me.Flags == MouseFlags.Button1Clicked
  1182. || (me.Flags == MouseFlags.ReportMousePosition && _selected > -1)
  1183. || (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1))
  1184. {
  1185. int pos = _xOrigin;
  1186. Point locationOffset = default;
  1187. if (SuperView is { })
  1188. {
  1189. locationOffset.X += SuperView.Border.Thickness.Left;
  1190. locationOffset.Y += SuperView.Border.Thickness.Top;
  1191. }
  1192. int cx = me.Position.X - locationOffset.X;
  1193. for (var i = 0; i < Menus.Length; i++)
  1194. {
  1195. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding)
  1196. {
  1197. if (me.Flags == MouseFlags.Button1Clicked)
  1198. {
  1199. if (Menus [i].IsTopLevel)
  1200. {
  1201. Point screen = ViewportToScreen (new Point (0, i));
  1202. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = Menus [i] };
  1203. menu.Run (Menus [i].Action);
  1204. if (Application.MouseGrabView == menu)
  1205. {
  1206. Application.UngrabMouse ();
  1207. }
  1208. menu.Dispose ();
  1209. }
  1210. else if (!IsMenuOpen)
  1211. {
  1212. Activate (i);
  1213. }
  1214. }
  1215. else if (me.Flags == MouseFlags.Button1Pressed
  1216. || me.Flags == MouseFlags.Button1DoubleClicked
  1217. || me.Flags == MouseFlags.Button1TripleClicked)
  1218. {
  1219. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1220. {
  1221. CloseAllMenus ();
  1222. }
  1223. else if (!Menus [i].IsTopLevel)
  1224. {
  1225. Activate (i);
  1226. }
  1227. }
  1228. else if (_selected != i
  1229. && _selected > -1
  1230. && (me.Flags == MouseFlags.ReportMousePosition
  1231. || (me.Flags is MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)))
  1232. {
  1233. if (IsMenuOpen)
  1234. {
  1235. if (!CloseMenu (true, false))
  1236. {
  1237. return me.Handled = true;
  1238. }
  1239. Activate (i);
  1240. }
  1241. }
  1242. else if (IsMenuOpen)
  1243. {
  1244. if (!UseSubMenusSingleFrame
  1245. || (UseSubMenusSingleFrame
  1246. && OpenCurrentMenu is { BarItems.Parent: { } }
  1247. && OpenCurrentMenu.BarItems.Parent.Parent != Menus [i]))
  1248. {
  1249. Activate (i);
  1250. }
  1251. }
  1252. return me.Handled = true;
  1253. }
  1254. if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked)
  1255. {
  1256. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1257. {
  1258. CloseAllMenus ();
  1259. return me.Handled = true;
  1260. }
  1261. }
  1262. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1263. }
  1264. }
  1265. return false;
  1266. }
  1267. internal bool _handled;
  1268. internal bool _isContextMenuLoading;
  1269. private MenuBarItem [] _menus = [];
  1270. internal bool HandleGrabView (MouseEventArgs me, View current)
  1271. {
  1272. if (Application.MouseGrabView is { })
  1273. {
  1274. if (me.View is MenuBar or Menu)
  1275. {
  1276. MenuBar? mbar = GetMouseGrabViewInstance (me.View);
  1277. if (mbar is { })
  1278. {
  1279. if (me.Flags == MouseFlags.Button1Clicked)
  1280. {
  1281. mbar.CleanUp ();
  1282. Application.GrabMouse (me.View);
  1283. }
  1284. else
  1285. {
  1286. _handled = false;
  1287. return false;
  1288. }
  1289. }
  1290. if (me.View != current)
  1291. {
  1292. Application.UngrabMouse ();
  1293. View v = me.View;
  1294. Application.GrabMouse (v);
  1295. MouseEventArgs nme;
  1296. if (me.Position.Y > -1)
  1297. {
  1298. Point frameLoc = v.ScreenToFrame (me.Position);
  1299. nme = new ()
  1300. {
  1301. Position = frameLoc,
  1302. Flags = me.Flags,
  1303. View = v
  1304. };
  1305. }
  1306. else
  1307. {
  1308. nme = new ()
  1309. {
  1310. Position = new (me.Position.X + current.Frame.X, me.Position.Y + current.Frame.Y),
  1311. Flags = me.Flags, View = v
  1312. };
  1313. }
  1314. v.NewMouseEvent (nme);
  1315. return false;
  1316. }
  1317. }
  1318. else if (!(me.View is MenuBar || me.View is Menu)
  1319. && me.Flags != MouseFlags.ReportMousePosition
  1320. && me.Flags != 0)
  1321. {
  1322. Application.UngrabMouse ();
  1323. if (IsMenuOpen)
  1324. {
  1325. CloseAllMenus ();
  1326. }
  1327. _handled = false;
  1328. return false;
  1329. }
  1330. else
  1331. {
  1332. _handled = false;
  1333. _isContextMenuLoading = false;
  1334. return false;
  1335. }
  1336. }
  1337. else if (!IsMenuOpen
  1338. && (me.Flags == MouseFlags.Button1Pressed
  1339. || me.Flags == MouseFlags.Button1DoubleClicked
  1340. || me.Flags == MouseFlags.Button1TripleClicked
  1341. || me.Flags.HasFlag (
  1342. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1343. )))
  1344. {
  1345. Application.GrabMouse (current);
  1346. }
  1347. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1348. {
  1349. Application.GrabMouse (me.View);
  1350. }
  1351. else
  1352. {
  1353. _handled = false;
  1354. return false;
  1355. }
  1356. _handled = true;
  1357. return true;
  1358. }
  1359. private MenuBar? GetMouseGrabViewInstance (View? view)
  1360. {
  1361. if (view is null || Application.MouseGrabView is null)
  1362. {
  1363. return null;
  1364. }
  1365. MenuBar? hostView = null;
  1366. if (view is MenuBar)
  1367. {
  1368. hostView = (MenuBar)view;
  1369. }
  1370. else if (view is Menu)
  1371. {
  1372. hostView = ((Menu)view).Host;
  1373. }
  1374. View grabView = Application.MouseGrabView;
  1375. MenuBar? hostGrabView = null;
  1376. if (grabView is MenuBar bar)
  1377. {
  1378. hostGrabView = bar;
  1379. }
  1380. else if (grabView is Menu menu)
  1381. {
  1382. hostGrabView = menu.Host;
  1383. }
  1384. return hostView != hostGrabView ? hostGrabView : null;
  1385. }
  1386. #endregion Mouse Handling
  1387. /// <inheritdoc />
  1388. public bool EnableForDesign<TContext> (ref readonly TContext context) where TContext : notnull
  1389. {
  1390. if (context is not Func<string, bool> actionFn)
  1391. {
  1392. actionFn = (_) => true;
  1393. }
  1394. Menus =
  1395. [
  1396. new MenuBarItem (
  1397. "_File",
  1398. new MenuItem []
  1399. {
  1400. new (
  1401. "_New",
  1402. "",
  1403. () => actionFn ("New"),
  1404. null,
  1405. null,
  1406. KeyCode.CtrlMask | KeyCode.N
  1407. ),
  1408. new (
  1409. "_Open",
  1410. "",
  1411. () => actionFn ("Open"),
  1412. null,
  1413. null,
  1414. KeyCode.CtrlMask | KeyCode.O
  1415. ),
  1416. new (
  1417. "_Save",
  1418. "",
  1419. () => actionFn ("Save"),
  1420. null,
  1421. null,
  1422. KeyCode.CtrlMask | KeyCode.S
  1423. ),
  1424. #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
  1425. null,
  1426. #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
  1427. // Don't use Application.Quit so we can disambiguate between quitting and closing the toplevel
  1428. new (
  1429. "_Quit",
  1430. "",
  1431. () => actionFn ("Quit"),
  1432. null,
  1433. null,
  1434. KeyCode.CtrlMask | KeyCode.Q
  1435. )
  1436. }
  1437. ),
  1438. new MenuBarItem (
  1439. "_Edit",
  1440. new MenuItem []
  1441. {
  1442. new (
  1443. "_Copy",
  1444. "",
  1445. () => actionFn ("Copy"),
  1446. null,
  1447. null,
  1448. KeyCode.CtrlMask | KeyCode.C
  1449. ),
  1450. new (
  1451. "C_ut",
  1452. "",
  1453. () => actionFn ("Cut"),
  1454. null,
  1455. null,
  1456. KeyCode.CtrlMask | KeyCode.X
  1457. ),
  1458. new (
  1459. "_Paste",
  1460. "",
  1461. () => actionFn ("Paste"),
  1462. null,
  1463. null,
  1464. KeyCode.CtrlMask | KeyCode.V
  1465. ),
  1466. new MenuBarItem (
  1467. "_Find and Replace",
  1468. new MenuItem []
  1469. {
  1470. new (
  1471. "F_ind",
  1472. "",
  1473. () => actionFn ("Find"),
  1474. null,
  1475. null,
  1476. KeyCode.CtrlMask | KeyCode.F
  1477. ),
  1478. new (
  1479. "_Replace",
  1480. "",
  1481. () => actionFn ("Replace"),
  1482. null,
  1483. null,
  1484. KeyCode.CtrlMask | KeyCode.H
  1485. ),
  1486. new MenuBarItem (
  1487. "_3rd Level",
  1488. new MenuItem []
  1489. {
  1490. new (
  1491. "_1st",
  1492. "",
  1493. () => actionFn (
  1494. "1"
  1495. ),
  1496. null,
  1497. null,
  1498. KeyCode.F1
  1499. ),
  1500. new (
  1501. "_2nd",
  1502. "",
  1503. () => actionFn (
  1504. "2"
  1505. ),
  1506. null,
  1507. null,
  1508. KeyCode.F2
  1509. )
  1510. }
  1511. ),
  1512. new MenuBarItem (
  1513. "_4th Level",
  1514. new MenuItem []
  1515. {
  1516. new (
  1517. "_5th",
  1518. "",
  1519. () => actionFn (
  1520. "5"
  1521. ),
  1522. null,
  1523. null,
  1524. KeyCode.CtrlMask
  1525. | KeyCode.D5
  1526. ),
  1527. new (
  1528. "_6th",
  1529. "",
  1530. () => actionFn (
  1531. "6"
  1532. ),
  1533. null,
  1534. null,
  1535. KeyCode.CtrlMask
  1536. | KeyCode.D6
  1537. )
  1538. }
  1539. )
  1540. }
  1541. ),
  1542. new (
  1543. "_Select All",
  1544. "",
  1545. () => actionFn ("Select All"),
  1546. null,
  1547. null,
  1548. KeyCode.CtrlMask
  1549. | KeyCode.ShiftMask
  1550. | KeyCode.S
  1551. )
  1552. }
  1553. ),
  1554. new MenuBarItem ("_About", "Top-Level", () => actionFn ("About"))
  1555. ];
  1556. return true;
  1557. }
  1558. }