MenuBar.cs 59 KB

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