MenuBar.cs 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  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 = [];
  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. SuperViewChanged += MenuBar_SuperViewChanged;
  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. if (IsMenuOpen)
  100. {
  101. CloseMenuBar ();
  102. return true;
  103. }
  104. return false;
  105. }
  106. );
  107. AddCommand (
  108. Command.Accept,
  109. (ctx) =>
  110. {
  111. if (Menus.Length > 0)
  112. {
  113. ProcessMenu (_selected, Menus [_selected]);
  114. }
  115. return RaiseAccepting (ctx);
  116. }
  117. );
  118. AddCommand (Command.Toggle, ctx =>
  119. {
  120. CloseOtherOpenedMenuBar ();
  121. if (ctx is not CommandContext<KeyBinding> keyCommandContext)
  122. {
  123. return false;
  124. }
  125. return Select (Menus.IndexOf (keyCommandContext.Binding.Data));
  126. });
  127. AddCommand (Command.Select, ctx =>
  128. {
  129. if (ctx is not CommandContext<KeyBinding> keyCommandContext)
  130. {
  131. return false ;
  132. }
  133. if (keyCommandContext.Binding.Data is MouseEventArgs)
  134. {
  135. // HACK: Work around the fact that View.MouseClick always invokes Select
  136. return false;
  137. }
  138. var res = Run ((keyCommandContext.Binding.Data as MenuItem)?.Action!);
  139. CloseAllMenus ();
  140. return res;
  141. });
  142. // Default key bindings for this view
  143. KeyBindings.Add (Key.CursorLeft, Command.Left);
  144. KeyBindings.Add (Key.CursorRight, Command.Right);
  145. KeyBindings.Add (Key.Esc, Command.Cancel);
  146. KeyBindings.Add (Key.CursorDown, Command.Accept);
  147. KeyBinding keyBinding = new ([Command.Toggle], this, data: -1); // -1 indicates Key was used
  148. HotKeyBindings.Add (Key, keyBinding);
  149. // TODO: Why do we have two keybindings for opening the menu? Ctrl-Space and Key?
  150. HotKeyBindings.Add (Key.Space.WithCtrl, keyBinding);
  151. // This is needed for macOS because Key.Space.WithCtrl doesn't work
  152. HotKeyBindings.Add (Key.Space.WithAlt, keyBinding);
  153. // TODO: Figure out how to make Alt work (on Windows)
  154. //KeyBindings.Add (Key.WithAlt, keyBinding);
  155. }
  156. /// <summary><see langword="true"/> if the menu is open; otherwise <see langword="true"/>.</summary>
  157. public bool IsMenuOpen { get; protected set; }
  158. /// <summary>Gets the view that was last focused before opening the menu.</summary>
  159. public View? LastFocused { get; private set; }
  160. /// <summary>
  161. /// Gets or sets the array of <see cref="MenuBarItem"/>s for the menu. Only set this after the
  162. /// <see cref="MenuBar"/> is visible.
  163. /// </summary>
  164. /// <value>The menu array.</value>
  165. public MenuBarItem [] Menus
  166. {
  167. get => _menus;
  168. set
  169. {
  170. _menus = value;
  171. if (Menus is [])
  172. {
  173. return;
  174. }
  175. // TODO: Hotkeys should not work for sub-menus if they are not visible!
  176. for (var i = 0; i < Menus.Length; i++)
  177. {
  178. MenuBarItem menuBarItem = Menus [i];
  179. if (menuBarItem.HotKey != Key.Empty)
  180. {
  181. HotKeyBindings.Remove (menuBarItem.HotKey!);
  182. KeyBinding keyBinding = new ([Command.Toggle], this, menuBarItem);
  183. HotKeyBindings.Add (menuBarItem.HotKey!, keyBinding);
  184. HotKeyBindings.Remove (menuBarItem.HotKey!.WithAlt);
  185. keyBinding = new ([Command.Toggle], this, data: menuBarItem);
  186. HotKeyBindings.Add (menuBarItem.HotKey.WithAlt, keyBinding);
  187. }
  188. if (menuBarItem.ShortcutKey != Key.Empty)
  189. {
  190. // Technically this will never run because MenuBarItems don't have shortcuts
  191. // unless the IsTopLevel is true
  192. HotKeyBindings.Remove (menuBarItem.ShortcutKey!);
  193. KeyBinding keyBinding = new ([Command.Select], this, data: menuBarItem);
  194. HotKeyBindings.Add (menuBarItem.ShortcutKey!, keyBinding);
  195. }
  196. menuBarItem.AddShortcutKeyBindings (this);
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// The default <see cref="LineStyle"/> for <see cref="Menus"/>'s border. The default is
  202. /// <see cref="LineStyle.Single"/>.
  203. /// </summary>
  204. public LineStyle MenusBorderStyle { get; set; } = LineStyle.Single;
  205. /// <summary>
  206. /// Gets or sets if the sub-menus must be displayed in a single or multiple frames.
  207. /// <para>
  208. /// By default, any sub-sub-menus (sub-menus of the main <see cref="MenuItem"/>s) are displayed in a cascading
  209. /// manner, where each sub-sub-menu pops out of the sub-menu frame (either to the right or left, depending on where
  210. /// the sub-menu is relative to the edge of the screen). By setting <see cref="UseSubMenusSingleFrame"/> to
  211. /// <see langword="true"/>, this behavior can be changed such that all sub-sub-menus are drawn within a single
  212. /// frame below the MenuBar.
  213. /// </para>
  214. /// </summary>
  215. public bool UseSubMenusSingleFrame
  216. {
  217. get => _useSubMenusSingleFrame;
  218. set
  219. {
  220. _useSubMenusSingleFrame = value;
  221. if (value && UseKeysUpDownAsKeysLeftRight)
  222. {
  223. _useKeysUpDownAsKeysLeftRight = false;
  224. SetNeedsDraw ();
  225. }
  226. }
  227. }
  228. /// <inheritdoc/>
  229. public override bool Visible
  230. {
  231. get => base.Visible;
  232. set
  233. {
  234. base.Visible = value;
  235. if (!value)
  236. {
  237. CloseAllMenus ();
  238. }
  239. }
  240. }
  241. internal Menu? OpenCurrentMenu
  242. {
  243. get => _ocm;
  244. set
  245. {
  246. if (_ocm != value)
  247. {
  248. _ocm = value!;
  249. if (_ocm is { _currentChild: > -1 })
  250. {
  251. OnMenuOpened ();
  252. }
  253. }
  254. }
  255. }
  256. /// <summary>Closes the Menu programmatically if open and not canceled (as though F9 were pressed).</summary>
  257. public bool CloseMenu (bool ignoreUseSubMenusSingleFrame = false) { return CloseMenu (false, false, ignoreUseSubMenusSingleFrame); }
  258. /// <summary>Raised when all the menu is closed.</summary>
  259. public event EventHandler? MenuAllClosed;
  260. /// <summary>Raised when a menu is closing passing <see cref="MenuClosingEventArgs"/>.</summary>
  261. public event EventHandler<MenuClosingEventArgs>? MenuClosing;
  262. /// <summary>Raised when a menu is opened.</summary>
  263. public event EventHandler<MenuOpenedEventArgs>? MenuOpened;
  264. /// <summary>Raised as a menu is opening.</summary>
  265. public event EventHandler<MenuOpeningEventArgs>? MenuOpening;
  266. /// <inheritdoc/>
  267. protected override bool OnDrawingContent ()
  268. {
  269. var pos = 0;
  270. for (var i = 0; i < Menus.Length; i++)
  271. {
  272. MenuBarItem menu = Menus [i];
  273. Move (pos, 0);
  274. Attribute hotColor, normalColor;
  275. if (i == _selected && IsMenuOpen)
  276. {
  277. hotColor = i == _selected ? ColorScheme!.HotFocus : GetHotNormalColor ();
  278. normalColor = i == _selected ? GetFocusColor () : GetNormalColor ();
  279. }
  280. else
  281. {
  282. hotColor = GetHotNormalColor ();
  283. normalColor = GetNormalColor ();
  284. }
  285. // Note Help on MenuBar is drawn with parens around it
  286. DrawHotString (
  287. string.IsNullOrEmpty (menu.Help) ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ",
  288. hotColor,
  289. normalColor
  290. );
  291. pos += _leftPadding
  292. + menu.TitleLength
  293. + (menu.Help.GetColumns () > 0
  294. ? _leftPadding + menu.Help.GetColumns () + _parensAroundHelp
  295. : 0)
  296. + _rightPadding;
  297. }
  298. //PositionCursor ();
  299. return true;
  300. }
  301. /// <summary>Virtual method that will invoke the <see cref="MenuAllClosed"/>.</summary>
  302. public virtual void OnMenuAllClosed () { MenuAllClosed?.Invoke (this, EventArgs.Empty); }
  303. /// <summary>Virtual method that will invoke the <see cref="MenuClosing"/>.</summary>
  304. /// <param name="currentMenu">The current menu to be closed.</param>
  305. /// <param name="reopen">Whether the current menu will be reopened.</param>
  306. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  307. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  308. {
  309. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  310. MenuClosing?.Invoke (this, ev);
  311. return ev;
  312. }
  313. /// <summary>Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.</summary>
  314. public virtual void OnMenuOpened ()
  315. {
  316. MenuItem? mi = null;
  317. MenuBarItem? parent;
  318. if (OpenCurrentMenu?.BarItems?.Children is { Length: > 0 }
  319. && OpenCurrentMenu?._currentChild > -1)
  320. {
  321. parent = OpenCurrentMenu.BarItems;
  322. mi = parent.Children [OpenCurrentMenu._currentChild];
  323. }
  324. else if (OpenCurrentMenu!.BarItems!.IsTopLevel)
  325. {
  326. parent = null;
  327. mi = OpenCurrentMenu.BarItems;
  328. }
  329. else
  330. {
  331. parent = _openMenu?.BarItems;
  332. if (OpenCurrentMenu?._currentChild > -1)
  333. {
  334. mi = parent?.Children?.Length > 0 ? parent.Children [_openMenu!._currentChild] : null;
  335. }
  336. }
  337. MenuOpened?.Invoke (this, new (parent, mi));
  338. }
  339. /// <summary>Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.</summary>
  340. /// <param name="currentMenu">The current menu to be replaced.</param>
  341. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  342. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  343. {
  344. var ev = new MenuOpeningEventArgs (currentMenu);
  345. MenuOpening?.Invoke (this, ev);
  346. return ev;
  347. }
  348. /// <summary>Opens the Menu programatically, as though the F9 key were pressed.</summary>
  349. public void OpenMenu ()
  350. {
  351. MenuBar? mbar = GetMouseGrabViewInstance (this);
  352. mbar?.CleanUp ();
  353. CloseOtherOpenedMenuBar ();
  354. if (!Enabled || _openMenu is { })
  355. {
  356. return;
  357. }
  358. _selected = 0;
  359. SetNeedsDraw ();
  360. _previousFocused = (SuperView is null ? Application.Top?.Focused : SuperView.Focused)!;
  361. OpenMenu (_selected);
  362. if (!SelectEnabledItem (
  363. OpenCurrentMenu?.BarItems?.Children,
  364. OpenCurrentMenu!._currentChild,
  365. out OpenCurrentMenu._currentChild
  366. )
  367. && !CloseMenu ())
  368. {
  369. return;
  370. }
  371. if (!OpenCurrentMenu.CheckSubMenu ())
  372. {
  373. return;
  374. }
  375. Application.GrabMouse (this);
  376. }
  377. /// <inheritdoc/>
  378. public override Point? PositionCursor ()
  379. {
  380. if (_selected == -1 && HasFocus && Menus.Length > 0)
  381. {
  382. _selected = 0;
  383. }
  384. var pos = 0;
  385. for (var i = 0; i < Menus.Length; i++)
  386. {
  387. if (i == _selected)
  388. {
  389. pos++;
  390. Move (pos + 1, 0);
  391. return null; // Don't show the cursor
  392. }
  393. pos += _leftPadding
  394. + Menus [i].TitleLength
  395. + (Menus [i].Help.GetColumns () > 0
  396. ? Menus [i].Help.GetColumns () + _parensAroundHelp
  397. : 0)
  398. + _rightPadding;
  399. }
  400. return null; // Don't show the cursor
  401. }
  402. // Activates the menu, handles either first focus, or activating an entry when it was already active
  403. // For mouse events.
  404. internal void Activate (int idx, int sIdx = -1, MenuBarItem? subMenu = null!)
  405. {
  406. _selected = idx;
  407. _selectedSub = sIdx;
  408. if (_openMenu is null)
  409. {
  410. _previousFocused = (SuperView is null ? Application.Top?.Focused ?? null : SuperView.Focused)!;
  411. }
  412. OpenMenu (idx, sIdx, subMenu);
  413. SetNeedsDraw ();
  414. }
  415. internal void CleanUp ()
  416. {
  417. _isCleaning = true;
  418. if (_openMenu is { })
  419. {
  420. CloseAllMenus ();
  421. }
  422. _openedByAltKey = false;
  423. IsMenuOpen = false;
  424. _selected = -1;
  425. CanFocus = _initialCanFocus;
  426. if (_lastFocused is { })
  427. {
  428. _lastFocused.SetFocus ();
  429. }
  430. SetNeedsDraw ();
  431. if (Application.MouseGrabView is { } && Application.MouseGrabView is MenuBar && Application.MouseGrabView != this)
  432. {
  433. var menuBar = Application.MouseGrabView as MenuBar;
  434. if (menuBar!.IsMenuOpen)
  435. {
  436. menuBar.CleanUp ();
  437. }
  438. }
  439. Application.UngrabMouse ();
  440. _isCleaning = false;
  441. }
  442. internal void CloseAllMenus ()
  443. {
  444. if (!_isMenuOpening && !_isMenuClosing)
  445. {
  446. if (_openSubMenu is { } && !CloseMenu (false, true, true))
  447. {
  448. return;
  449. }
  450. if (!CloseMenu ())
  451. {
  452. return;
  453. }
  454. if (LastFocused is { } && LastFocused != this)
  455. {
  456. _selected = -1;
  457. }
  458. Application.UngrabMouse ();
  459. }
  460. if (OpenCurrentMenu is { })
  461. {
  462. OpenCurrentMenu = null;
  463. }
  464. IsMenuOpen = false;
  465. _openedByAltKey = false;
  466. OnMenuAllClosed ();
  467. CloseOtherOpenedMenuBar ();
  468. }
  469. private void CloseOtherOpenedMenuBar ()
  470. {
  471. if (SuperView is { })
  472. {
  473. // Close others menu bar opened
  474. Menu? menu = SuperView.SubViews.FirstOrDefault (v => v is Menu m && m.Host != this && m.Host.IsMenuOpen) as Menu;
  475. menu?.Host.CleanUp ();
  476. }
  477. }
  478. internal bool CloseMenu (bool reopen, bool isSubMenu, bool ignoreUseSubMenusSingleFrame = false)
  479. {
  480. MenuBarItem? mbi = isSubMenu ? OpenCurrentMenu!.BarItems : _openMenu?.BarItems;
  481. if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { })
  482. {
  483. return false;
  484. }
  485. _isMenuClosing = true;
  486. _reopen = reopen;
  487. MenuClosingEventArgs args = OnMenuClosing (mbi!, reopen, isSubMenu);
  488. if (args.Cancel)
  489. {
  490. _isMenuClosing = false;
  491. if (args.CurrentMenu.Parent is { } && _openMenu is { })
  492. {
  493. _openMenu._currentChild =
  494. ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  495. }
  496. return false;
  497. }
  498. switch (isSubMenu)
  499. {
  500. case false:
  501. if (_openMenu is { })
  502. {
  503. SuperView?.Remove (_openMenu);
  504. }
  505. SetNeedsDraw ();
  506. if (_previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != OpenCurrentMenu!.ToString ())
  507. {
  508. _previousFocused.SetFocus ();
  509. }
  510. if (Application.MouseGrabView == _openMenu)
  511. {
  512. Application.UngrabMouse();
  513. }
  514. _openMenu?.Dispose ();
  515. _openMenu = null;
  516. if (_lastFocused is Menu or MenuBar)
  517. {
  518. _lastFocused = null;
  519. }
  520. LastFocused = _lastFocused;
  521. _lastFocused = null;
  522. if (LastFocused is { CanFocus: true })
  523. {
  524. if (!reopen)
  525. {
  526. _selected = -1;
  527. }
  528. if (_openSubMenu is { })
  529. {
  530. _openSubMenu = null;
  531. }
  532. if (OpenCurrentMenu is { })
  533. {
  534. SuperView?.Remove (OpenCurrentMenu);
  535. if (Application.MouseGrabView == OpenCurrentMenu)
  536. {
  537. Application.UngrabMouse ();
  538. }
  539. OpenCurrentMenu.Dispose ();
  540. OpenCurrentMenu = null;
  541. }
  542. LastFocused.SetFocus ();
  543. }
  544. else if (_openSubMenu is null || _openSubMenu.Count == 0)
  545. {
  546. CloseAllMenus ();
  547. }
  548. else
  549. {
  550. SetFocus ();
  551. }
  552. IsMenuOpen = false;
  553. break;
  554. case true:
  555. _selectedSub = -1;
  556. SetNeedsDraw ();
  557. RemoveAllOpensSubMenus ();
  558. OpenCurrentMenu!._previousSubFocused!.SetFocus ();
  559. _openSubMenu = null;
  560. IsMenuOpen = true;
  561. break;
  562. }
  563. _reopen = false;
  564. _isMenuClosing = false;
  565. return true;
  566. }
  567. /// <summary>Gets the superview location offset relative to the <see cref="IConsoleDriver"/> location.</summary>
  568. /// <returns>The location offset.</returns>
  569. internal Point GetScreenOffset ()
  570. {
  571. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  572. if (Driver is null)
  573. {
  574. return Point.Empty;
  575. }
  576. Rectangle superViewFrame = SuperView?.Frame ?? Application.Screen;
  577. View? sv = SuperView ?? Application.Top;
  578. if (sv is null)
  579. {
  580. // Support Unit Tests
  581. return Point.Empty;
  582. }
  583. Point viewportOffset = sv.GetViewportOffsetFromFrame ();
  584. return new (
  585. superViewFrame.X - sv.Frame.X - viewportOffset.X,
  586. superViewFrame.Y - sv.Frame.Y - viewportOffset.Y
  587. );
  588. }
  589. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  590. {
  591. switch (isSubMenu)
  592. {
  593. case false:
  594. if (_selected == -1)
  595. {
  596. _selected = 0;
  597. }
  598. else if (_selected + 1 == Menus.Length)
  599. {
  600. _selected = 0;
  601. }
  602. else
  603. {
  604. _selected++;
  605. }
  606. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  607. {
  608. return;
  609. }
  610. OpenMenu (_selected);
  611. SelectEnabledItem (
  612. OpenCurrentMenu?.BarItems?.Children,
  613. OpenCurrentMenu!._currentChild,
  614. out OpenCurrentMenu._currentChild
  615. );
  616. break;
  617. case true:
  618. if (UseKeysUpDownAsKeysLeftRight)
  619. {
  620. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  621. {
  622. NextMenu (false, ignoreUseSubMenusSingleFrame);
  623. }
  624. }
  625. else
  626. {
  627. MenuBarItem? subMenu = OpenCurrentMenu!._currentChild > -1 && OpenCurrentMenu.BarItems?.Children!.Length > 0
  628. ? OpenCurrentMenu.BarItems.SubMenu (
  629. OpenCurrentMenu.BarItems.Children? [OpenCurrentMenu._currentChild]!
  630. )
  631. : null;
  632. if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null)
  633. {
  634. if (_openSubMenu is { } && !CloseMenu (false, true))
  635. {
  636. return;
  637. }
  638. NextMenu (false, ignoreUseSubMenusSingleFrame);
  639. }
  640. else if (subMenu != null
  641. || (OpenCurrentMenu._currentChild > -1
  642. && !OpenCurrentMenu.BarItems!
  643. .Children! [OpenCurrentMenu._currentChild]!
  644. .IsFromSubMenu))
  645. {
  646. _selectedSub++;
  647. OpenCurrentMenu.CheckSubMenu ();
  648. }
  649. else
  650. {
  651. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  652. {
  653. NextMenu (false, ignoreUseSubMenusSingleFrame);
  654. }
  655. return;
  656. }
  657. SetNeedsDraw ();
  658. if (UseKeysUpDownAsKeysLeftRight)
  659. {
  660. OpenCurrentMenu.CheckSubMenu ();
  661. }
  662. }
  663. break;
  664. }
  665. }
  666. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem? subMenu = null!)
  667. {
  668. _isMenuOpening = true;
  669. MenuOpeningEventArgs newMenu = OnMenuOpening (Menus [index]);
  670. if (newMenu.Cancel)
  671. {
  672. _isMenuOpening = false;
  673. return;
  674. }
  675. if (newMenu.NewMenuBarItem is { })
  676. {
  677. Menus [index] = newMenu.NewMenuBarItem;
  678. }
  679. var pos = 0;
  680. switch (subMenu)
  681. {
  682. case null:
  683. // Open a submenu below a MenuBar
  684. _lastFocused ??= SuperView is null ? Application.Top?.MostFocused : SuperView.MostFocused;
  685. if (_openSubMenu is { } && !CloseMenu (false, true))
  686. {
  687. return;
  688. }
  689. if (_openMenu is { })
  690. {
  691. SuperView?.Remove (_openMenu);
  692. if (Application.MouseGrabView == _openMenu)
  693. {
  694. Application.UngrabMouse ();
  695. }
  696. _openMenu.Dispose ();
  697. _openMenu = null;
  698. }
  699. // This positions the submenu horizontally aligned with the first character of the
  700. // text belonging to the menu
  701. for (var i = 0; i < index; i++)
  702. {
  703. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  704. }
  705. _openMenu = new ()
  706. {
  707. Host = this,
  708. X = Frame.X + pos,
  709. Y = Frame.Y + 1,
  710. BarItems = Menus [index],
  711. Parent = null
  712. };
  713. OpenCurrentMenu = _openMenu;
  714. OpenCurrentMenu._previousSubFocused = _openMenu;
  715. if (SuperView is { })
  716. {
  717. SuperView.Add (_openMenu);
  718. // _openMenu.SetRelativeLayout (Application.Screen.Size);
  719. }
  720. else
  721. {
  722. _openMenu.BeginInit ();
  723. _openMenu.EndInit ();
  724. }
  725. _openMenu.SetFocus ();
  726. break;
  727. default:
  728. // Opens a submenu next to another submenu (openSubMenu)
  729. if (_openSubMenu is null)
  730. {
  731. _openSubMenu = new ();
  732. }
  733. if (sIndex > -1)
  734. {
  735. RemoveSubMenu (sIndex);
  736. }
  737. else
  738. {
  739. Menu? last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  740. if (!UseSubMenusSingleFrame)
  741. {
  742. OpenCurrentMenu = new ()
  743. {
  744. Host = this,
  745. X = last!.Frame.Left + last.Frame.Width,
  746. Y = last.Frame.Top + last._currentChild + 1,
  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. SuperView?.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. SetNeedsDraw ();
  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. SuperView?.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.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.LayoutAndDraw (true);
  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. SetNeedsDraw ();
  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_SuperViewChanged (object? sender, SuperViewChangedEventArgs _)
  963. {
  964. _initialCanFocus = CanFocus;
  965. SuperViewChanged -= MenuBar_SuperViewChanged;
  966. }
  967. private void MoveLeft ()
  968. {
  969. _selected--;
  970. if (_selected < 0)
  971. {
  972. _selected = Menus.Length - 1;
  973. }
  974. OpenMenu (_selected);
  975. SetNeedsDraw ();
  976. }
  977. private void MoveRight ()
  978. {
  979. _selected = (_selected + 1) % Menus.Length;
  980. OpenMenu (_selected);
  981. SetNeedsDraw ();
  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. SetNeedsDraw ();
  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. SuperView!.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. HotKeyBindings.Remove (_key);
  1091. KeyBinding keyBinding = new ([Command.Toggle], this, data: -1); // -1 indicates Key was used
  1092. HotKeyBindings.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. SetNeedsDraw ();
  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. View v = current;
  1292. Application.UngrabMouse ();
  1293. if (((Menu)me.View).Host.SuperView is { } && ((Menu)me.View).Host.SuperView!.InternalSubViews.Contains(me.View))
  1294. {
  1295. v = me.View;
  1296. }
  1297. Application.GrabMouse (v);
  1298. MouseEventArgs nme;
  1299. if (me.Position.Y > -1)
  1300. {
  1301. Point frameLoc = v.ScreenToFrame (me.Position);
  1302. nme = new ()
  1303. {
  1304. Position = frameLoc,
  1305. Flags = me.Flags,
  1306. View = v
  1307. };
  1308. }
  1309. else
  1310. {
  1311. nme = new ()
  1312. {
  1313. Position = new (me.Position.X + current.Frame.X, me.Position.Y + current.Frame.Y),
  1314. Flags = me.Flags, View = v
  1315. };
  1316. }
  1317. v.NewMouseEvent (nme);
  1318. return false;
  1319. }
  1320. }
  1321. else if (!(me.View is MenuBar || me.View is Menu)
  1322. && me.Flags != MouseFlags.ReportMousePosition
  1323. && me.Flags != 0)
  1324. {
  1325. Application.UngrabMouse ();
  1326. if (IsMenuOpen)
  1327. {
  1328. CloseAllMenus ();
  1329. }
  1330. _handled = false;
  1331. return false;
  1332. }
  1333. else
  1334. {
  1335. _handled = false;
  1336. _isContextMenuLoading = false;
  1337. return false;
  1338. }
  1339. }
  1340. else if (!IsMenuOpen
  1341. && (me.Flags == MouseFlags.Button1Pressed
  1342. || me.Flags == MouseFlags.Button1DoubleClicked
  1343. || me.Flags == MouseFlags.Button1TripleClicked
  1344. || me.Flags.HasFlag (
  1345. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1346. )))
  1347. {
  1348. Application.GrabMouse (current);
  1349. }
  1350. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1351. {
  1352. Application.GrabMouse (me.View);
  1353. }
  1354. else
  1355. {
  1356. _handled = false;
  1357. return false;
  1358. }
  1359. _handled = true;
  1360. return true;
  1361. }
  1362. private MenuBar? GetMouseGrabViewInstance (View? view)
  1363. {
  1364. if (view is null || Application.MouseGrabView is null)
  1365. {
  1366. return null;
  1367. }
  1368. MenuBar? hostView = null;
  1369. if (view is MenuBar)
  1370. {
  1371. hostView = (MenuBar)view;
  1372. }
  1373. else if (view is Menu)
  1374. {
  1375. hostView = ((Menu)view).Host;
  1376. }
  1377. View grabView = Application.MouseGrabView;
  1378. MenuBar? hostGrabView = null;
  1379. if (grabView is MenuBar bar)
  1380. {
  1381. hostGrabView = bar;
  1382. }
  1383. else if (grabView is Menu menu)
  1384. {
  1385. hostGrabView = menu.Host;
  1386. }
  1387. return hostView != hostGrabView ? hostGrabView : null;
  1388. }
  1389. #endregion Mouse Handling
  1390. /// <inheritdoc />
  1391. public bool EnableForDesign<TContext> (ref readonly TContext context) where TContext : notnull
  1392. {
  1393. if (context is not Func<string, bool> actionFn)
  1394. {
  1395. actionFn = (_) => true;
  1396. }
  1397. Menus =
  1398. [
  1399. new MenuBarItem (
  1400. "_File",
  1401. new MenuItem []
  1402. {
  1403. new (
  1404. "_New",
  1405. "",
  1406. () => actionFn ("New"),
  1407. null,
  1408. null,
  1409. KeyCode.CtrlMask | KeyCode.N
  1410. ),
  1411. new (
  1412. "_Open",
  1413. "",
  1414. () => actionFn ("Open"),
  1415. null,
  1416. null,
  1417. KeyCode.CtrlMask | KeyCode.O
  1418. ),
  1419. new (
  1420. "_Save",
  1421. "",
  1422. () => actionFn ("Save"),
  1423. null,
  1424. null,
  1425. KeyCode.CtrlMask | KeyCode.S
  1426. ),
  1427. #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
  1428. null,
  1429. #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
  1430. // Don't use Application.Quit so we can disambiguate between quitting and closing the toplevel
  1431. new (
  1432. "_Quit",
  1433. "",
  1434. () => actionFn ("Quit"),
  1435. null,
  1436. null,
  1437. KeyCode.CtrlMask | KeyCode.Q
  1438. )
  1439. }
  1440. ),
  1441. new MenuBarItem (
  1442. "_Edit",
  1443. new MenuItem []
  1444. {
  1445. new (
  1446. "_Copy",
  1447. "",
  1448. () => actionFn ("Copy"),
  1449. null,
  1450. null,
  1451. KeyCode.CtrlMask | KeyCode.C
  1452. ),
  1453. new (
  1454. "C_ut",
  1455. "",
  1456. () => actionFn ("Cut"),
  1457. null,
  1458. null,
  1459. KeyCode.CtrlMask | KeyCode.X
  1460. ),
  1461. new (
  1462. "_Paste",
  1463. "",
  1464. () => actionFn ("Paste"),
  1465. null,
  1466. null,
  1467. KeyCode.CtrlMask | KeyCode.V
  1468. ),
  1469. new MenuBarItem (
  1470. "_Find and Replace",
  1471. new MenuItem []
  1472. {
  1473. new (
  1474. "F_ind",
  1475. "",
  1476. () => actionFn ("Find"),
  1477. null,
  1478. null,
  1479. KeyCode.CtrlMask | KeyCode.F
  1480. ),
  1481. new (
  1482. "_Replace",
  1483. "",
  1484. () => actionFn ("Replace"),
  1485. null,
  1486. null,
  1487. KeyCode.CtrlMask | KeyCode.H
  1488. ),
  1489. new MenuBarItem (
  1490. "_3rd Level",
  1491. new MenuItem []
  1492. {
  1493. new (
  1494. "_1st",
  1495. "",
  1496. () => actionFn (
  1497. "1"
  1498. ),
  1499. null,
  1500. null,
  1501. KeyCode.F1
  1502. ),
  1503. new (
  1504. "_2nd",
  1505. "",
  1506. () => actionFn (
  1507. "2"
  1508. ),
  1509. null,
  1510. null,
  1511. KeyCode.F2
  1512. )
  1513. }
  1514. ),
  1515. new MenuBarItem (
  1516. "_4th Level",
  1517. new MenuItem []
  1518. {
  1519. new (
  1520. "_5th",
  1521. "",
  1522. () => actionFn (
  1523. "5"
  1524. ),
  1525. null,
  1526. null,
  1527. KeyCode.CtrlMask
  1528. | KeyCode.D5
  1529. ),
  1530. new (
  1531. "_6th",
  1532. "",
  1533. () => actionFn (
  1534. "6"
  1535. ),
  1536. null,
  1537. null,
  1538. KeyCode.CtrlMask
  1539. | KeyCode.D6
  1540. )
  1541. }
  1542. )
  1543. }
  1544. ),
  1545. new (
  1546. "_Select All",
  1547. "",
  1548. () => actionFn ("Select All"),
  1549. null,
  1550. null,
  1551. KeyCode.CtrlMask
  1552. | KeyCode.ShiftMask
  1553. | KeyCode.S
  1554. )
  1555. }
  1556. ),
  1557. new MenuBarItem ("_About", "Top-Level", () => actionFn ("About"))
  1558. ];
  1559. return true;
  1560. }
  1561. }