MenuBar.cs 58 KB

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