MenuBar.cs 58 KB

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