MenuBar.cs 61 KB

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