MenuBar.cs 55 KB

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