MenuBar.cs 62 KB

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