MenuBar.cs 54 KB

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