MenuBar.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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 contentArea)
  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. var pos = 0;
  413. for (var i = 0; i < Menus.Length; i++)
  414. {
  415. MenuBarItem menu = Menus [i];
  416. Move (pos, 0);
  417. Attribute hotColor, normalColor;
  418. if (i == _selected && IsMenuOpen)
  419. {
  420. hotColor = i == _selected ? ColorScheme.HotFocus : ColorScheme.HotNormal;
  421. normalColor = i == _selected ? ColorScheme.Focus : GetNormalColor ();
  422. }
  423. else
  424. {
  425. hotColor = ColorScheme.HotNormal;
  426. normalColor = GetNormalColor ();
  427. }
  428. // Note Help on MenuBar is drawn with parens around it
  429. DrawHotString (
  430. string.IsNullOrEmpty (menu.Help) ? $" {menu.Title} " : $" {menu.Title} ({menu.Help}) ",
  431. hotColor,
  432. normalColor
  433. );
  434. pos += _leftPadding
  435. + menu.TitleLength
  436. + (menu.Help.GetColumns () > 0
  437. ? _leftPadding + menu.Help.GetColumns () + _parensAroundHelp
  438. : 0)
  439. + _rightPadding;
  440. }
  441. PositionCursor ();
  442. }
  443. /// <summary>Virtual method that will invoke the <see cref="MenuAllClosed"/>.</summary>
  444. public virtual void OnMenuAllClosed () { MenuAllClosed?.Invoke (this, EventArgs.Empty); }
  445. /// <summary>Virtual method that will invoke the <see cref="MenuClosing"/>.</summary>
  446. /// <param name="currentMenu">The current menu to be closed.</param>
  447. /// <param name="reopen">Whether the current menu will be reopen.</param>
  448. /// <param name="isSubMenu">Whether is a sub-menu or not.</param>
  449. public virtual MenuClosingEventArgs OnMenuClosing (MenuBarItem currentMenu, bool reopen, bool isSubMenu)
  450. {
  451. var ev = new MenuClosingEventArgs (currentMenu, reopen, isSubMenu);
  452. MenuClosing?.Invoke (this, ev);
  453. return ev;
  454. }
  455. /// <summary>Virtual method that will invoke the <see cref="MenuOpened"/> event if it's defined.</summary>
  456. public virtual void OnMenuOpened ()
  457. {
  458. MenuItem mi = null;
  459. MenuBarItem parent;
  460. if (openCurrentMenu.BarItems.Children != null
  461. && openCurrentMenu.BarItems!.Children.Length > 0
  462. && openCurrentMenu?._currentChild > -1)
  463. {
  464. parent = openCurrentMenu.BarItems;
  465. mi = parent.Children [openCurrentMenu._currentChild];
  466. }
  467. else if (openCurrentMenu!.BarItems.IsTopLevel)
  468. {
  469. parent = null;
  470. mi = openCurrentMenu.BarItems;
  471. }
  472. else
  473. {
  474. parent = _openMenu.BarItems;
  475. mi = parent.Children?.Length > 0 ? parent.Children [_openMenu._currentChild] : null;
  476. }
  477. MenuOpened?.Invoke (this, new (parent, mi));
  478. }
  479. /// <summary>Virtual method that will invoke the <see cref="MenuOpening"/> event if it's defined.</summary>
  480. /// <param name="currentMenu">The current menu to be replaced.</param>
  481. /// <returns>Returns the <see cref="MenuOpeningEventArgs"/></returns>
  482. public virtual MenuOpeningEventArgs OnMenuOpening (MenuBarItem currentMenu)
  483. {
  484. var ev = new MenuOpeningEventArgs (currentMenu);
  485. MenuOpening?.Invoke (this, ev);
  486. return ev;
  487. }
  488. /// <summary>Opens the Menu programatically, as though the F9 key were pressed.</summary>
  489. public void OpenMenu ()
  490. {
  491. MenuBar mbar = GetMouseGrabViewInstance (this);
  492. if (mbar is { })
  493. {
  494. mbar.CleanUp ();
  495. }
  496. if (!Enabled || _openMenu is { })
  497. {
  498. return;
  499. }
  500. _selected = 0;
  501. SetNeedsDisplay ();
  502. _previousFocused = SuperView is null ? Application.Current?.Focused : SuperView.Focused;
  503. OpenMenu (_selected);
  504. if (!SelectEnabledItem (
  505. openCurrentMenu.BarItems.Children,
  506. openCurrentMenu._currentChild,
  507. out openCurrentMenu._currentChild
  508. )
  509. && !CloseMenu (false))
  510. {
  511. return;
  512. }
  513. if (!openCurrentMenu.CheckSubMenu ())
  514. {
  515. return;
  516. }
  517. Application.GrabMouse (this);
  518. }
  519. /// <inheritdoc/>
  520. public override void PositionCursor ()
  521. {
  522. if (_selected == -1 && HasFocus && Menus.Length > 0)
  523. {
  524. _selected = 0;
  525. }
  526. var pos = 0;
  527. for (var i = 0; i < Menus.Length; i++)
  528. {
  529. if (i == _selected)
  530. {
  531. pos++;
  532. Move (pos + 1, 0);
  533. return;
  534. }
  535. pos += _leftPadding
  536. + Menus [i].TitleLength
  537. + (Menus [i].Help.GetColumns () > 0
  538. ? Menus [i].Help.GetColumns () + _parensAroundHelp
  539. : 0)
  540. + _rightPadding;
  541. }
  542. }
  543. // Activates the menu, handles either first focus, or activating an entry when it was already active
  544. // For mouse events.
  545. internal void Activate (int idx, int sIdx = -1, MenuBarItem subMenu = null)
  546. {
  547. _selected = idx;
  548. _selectedSub = sIdx;
  549. if (_openMenu is null)
  550. {
  551. _previousFocused = SuperView is null ? Application.Current?.Focused ?? null : SuperView.Focused;
  552. }
  553. OpenMenu (idx, sIdx, subMenu);
  554. SetNeedsDisplay ();
  555. }
  556. internal void CleanUp ()
  557. {
  558. _isCleaning = true;
  559. if (_openMenu is { })
  560. {
  561. CloseAllMenus ();
  562. }
  563. _openedByAltKey = false;
  564. _openedByHotKey = false;
  565. IsMenuOpen = false;
  566. _selected = -1;
  567. CanFocus = _initialCanFocus;
  568. if (_lastFocused is { })
  569. {
  570. _lastFocused.SetFocus ();
  571. }
  572. SetNeedsDisplay ();
  573. Application.UngrabMouse ();
  574. _isCleaning = false;
  575. }
  576. internal void CloseAllMenus ()
  577. {
  578. if (!_isMenuOpening && !_isMenuClosing)
  579. {
  580. if (_openSubMenu is { } && !CloseMenu (false, true, true))
  581. {
  582. return;
  583. }
  584. if (!CloseMenu (false))
  585. {
  586. return;
  587. }
  588. if (LastFocused is { } && LastFocused != this)
  589. {
  590. _selected = -1;
  591. }
  592. Application.UngrabMouse ();
  593. }
  594. if (openCurrentMenu is { })
  595. {
  596. openCurrentMenu = null;
  597. }
  598. IsMenuOpen = false;
  599. _openedByAltKey = false;
  600. _openedByHotKey = false;
  601. OnMenuAllClosed ();
  602. }
  603. internal bool CloseMenu (bool reopen = false, bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  604. {
  605. MenuBarItem mbi = isSubMenu ? openCurrentMenu.BarItems : _openMenu?.BarItems;
  606. if (UseSubMenusSingleFrame && mbi is { } && !ignoreUseSubMenusSingleFrame && mbi.Parent is { })
  607. {
  608. return false;
  609. }
  610. _isMenuClosing = true;
  611. _reopen = reopen;
  612. MenuClosingEventArgs args = OnMenuClosing (mbi, reopen, isSubMenu);
  613. if (args.Cancel)
  614. {
  615. _isMenuClosing = false;
  616. if (args.CurrentMenu.Parent is { })
  617. {
  618. _openMenu._currentChild =
  619. ((MenuBarItem)args.CurrentMenu.Parent).Children.IndexOf (args.CurrentMenu);
  620. }
  621. return false;
  622. }
  623. switch (isSubMenu)
  624. {
  625. case false:
  626. if (_openMenu is { })
  627. {
  628. Application.Current.Remove (_openMenu);
  629. }
  630. SetNeedsDisplay ();
  631. if (_previousFocused is { } && _previousFocused is Menu && _openMenu is { } && _previousFocused.ToString () != openCurrentMenu.ToString ())
  632. {
  633. _previousFocused.SetFocus ();
  634. }
  635. _openMenu?.Dispose ();
  636. _openMenu = null;
  637. if (_lastFocused is Menu || _lastFocused is MenuBar)
  638. {
  639. _lastFocused = null;
  640. }
  641. LastFocused = _lastFocused;
  642. _lastFocused = null;
  643. if (LastFocused is { } && LastFocused.CanFocus)
  644. {
  645. if (!reopen)
  646. {
  647. _selected = -1;
  648. }
  649. if (_openSubMenu is { })
  650. {
  651. _openSubMenu = null;
  652. }
  653. if (openCurrentMenu is { })
  654. {
  655. Application.Current.Remove (openCurrentMenu);
  656. openCurrentMenu.Dispose ();
  657. openCurrentMenu = null;
  658. }
  659. LastFocused.SetFocus ();
  660. }
  661. else if (_openSubMenu is null || _openSubMenu.Count == 0)
  662. {
  663. CloseAllMenus ();
  664. }
  665. else
  666. {
  667. SetFocus ();
  668. PositionCursor ();
  669. }
  670. IsMenuOpen = false;
  671. break;
  672. case true:
  673. _selectedSub = -1;
  674. SetNeedsDisplay ();
  675. RemoveAllOpensSubMenus ();
  676. openCurrentMenu._previousSubFocused.SetFocus ();
  677. _openSubMenu = null;
  678. IsMenuOpen = true;
  679. break;
  680. }
  681. _reopen = false;
  682. _isMenuClosing = false;
  683. return true;
  684. }
  685. /// <summary>Gets the superview location offset relative to the <see cref="ConsoleDriver"/> location.</summary>
  686. /// <returns>The location offset.</returns>
  687. internal Point GetScreenOffset ()
  688. {
  689. if (Driver is null)
  690. {
  691. return Point.Empty;
  692. }
  693. Rectangle superViewFrame = SuperView is null ? Driver.Bounds : SuperView.Frame;
  694. View sv = SuperView is null ? Application.Current : SuperView;
  695. Point boundsOffset = sv.GetBoundsOffset ();
  696. return new (
  697. superViewFrame.X - sv.Frame.X - boundsOffset.X,
  698. superViewFrame.Y - sv.Frame.Y - boundsOffset.Y
  699. );
  700. }
  701. /// <summary>
  702. /// Gets the <see cref="Application.Current"/> location offset relative to the <see cref="ConsoleDriver"/>
  703. /// location.
  704. /// </summary>
  705. /// <returns>The location offset.</returns>
  706. internal Point GetScreenOffsetFromCurrent ()
  707. {
  708. Rectangle screen = Driver.Bounds;
  709. Rectangle currentFrame = Application.Current.Frame;
  710. Point boundsOffset = Application.Top.GetBoundsOffset ();
  711. return new (screen.X - currentFrame.X - boundsOffset.X, screen.Y - currentFrame.Y - boundsOffset.Y);
  712. }
  713. internal void NextMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  714. {
  715. switch (isSubMenu)
  716. {
  717. case false:
  718. if (_selected == -1)
  719. {
  720. _selected = 0;
  721. }
  722. else if (_selected + 1 == Menus.Length)
  723. {
  724. _selected = 0;
  725. }
  726. else
  727. {
  728. _selected++;
  729. }
  730. if (_selected > -1 && !CloseMenu (true, ignoreUseSubMenusSingleFrame))
  731. {
  732. return;
  733. }
  734. OpenMenu (_selected);
  735. SelectEnabledItem (
  736. openCurrentMenu.BarItems.Children,
  737. openCurrentMenu._currentChild,
  738. out openCurrentMenu._currentChild
  739. );
  740. break;
  741. case true:
  742. if (UseKeysUpDownAsKeysLeftRight)
  743. {
  744. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  745. {
  746. NextMenu (false, ignoreUseSubMenusSingleFrame);
  747. }
  748. }
  749. else
  750. {
  751. MenuBarItem subMenu = openCurrentMenu._currentChild > -1 && openCurrentMenu.BarItems.Children.Length > 0
  752. ? openCurrentMenu.BarItems.SubMenu (
  753. openCurrentMenu.BarItems.Children [openCurrentMenu._currentChild]
  754. )
  755. : null;
  756. if ((_selectedSub == -1 || _openSubMenu is null || _openSubMenu?.Count - 1 == _selectedSub) && subMenu is null)
  757. {
  758. if (_openSubMenu is { } && !CloseMenu (false, true))
  759. {
  760. return;
  761. }
  762. NextMenu (false, ignoreUseSubMenusSingleFrame);
  763. }
  764. else if (subMenu != null
  765. || (openCurrentMenu._currentChild > -1
  766. && !openCurrentMenu.BarItems
  767. .Children [openCurrentMenu._currentChild]
  768. .IsFromSubMenu))
  769. {
  770. _selectedSub++;
  771. openCurrentMenu.CheckSubMenu ();
  772. }
  773. else
  774. {
  775. if (CloseMenu (false, true, ignoreUseSubMenusSingleFrame))
  776. {
  777. NextMenu (false, ignoreUseSubMenusSingleFrame);
  778. }
  779. return;
  780. }
  781. SetNeedsDisplay ();
  782. if (UseKeysUpDownAsKeysLeftRight)
  783. {
  784. openCurrentMenu.CheckSubMenu ();
  785. }
  786. }
  787. break;
  788. }
  789. }
  790. internal void OpenMenu (int index, int sIndex = -1, MenuBarItem subMenu = null)
  791. {
  792. _isMenuOpening = true;
  793. MenuOpeningEventArgs newMenu = OnMenuOpening (Menus [index]);
  794. if (newMenu.Cancel)
  795. {
  796. _isMenuOpening = false;
  797. return;
  798. }
  799. if (newMenu.NewMenuBarItem is { })
  800. {
  801. Menus [index] = newMenu.NewMenuBarItem;
  802. }
  803. var pos = 0;
  804. switch (subMenu)
  805. {
  806. case null:
  807. // Open a submenu below a MenuBar
  808. _lastFocused ??= SuperView is null ? Application.Current?.MostFocused : SuperView.MostFocused;
  809. if (_openSubMenu is { } && !CloseMenu (false, true))
  810. {
  811. return;
  812. }
  813. if (_openMenu is { })
  814. {
  815. Application.Current.Remove (_openMenu);
  816. _openMenu.Dispose ();
  817. _openMenu = null;
  818. }
  819. // This positions the submenu horizontally aligned with the first character of the
  820. // text belonging to the menu
  821. for (var i = 0; i < index; i++)
  822. {
  823. pos += Menus [i].TitleLength + (Menus [i].Help.GetColumns () > 0 ? Menus [i].Help.GetColumns () + 2 : 0) + _leftPadding + _rightPadding;
  824. }
  825. var locationOffset = Point.Empty;
  826. // if SuperView is null then it's from a ContextMenu
  827. if (SuperView is null)
  828. {
  829. locationOffset = GetScreenOffset ();
  830. }
  831. if (SuperView is { } && SuperView != Application.Current)
  832. {
  833. locationOffset.X += SuperView.Border.Thickness.Left;
  834. locationOffset.Y += SuperView.Border.Thickness.Top;
  835. }
  836. _openMenu = new()
  837. {
  838. Host = this,
  839. X = Frame.X + pos + locationOffset.X,
  840. Y = Frame.Y + 1 + locationOffset.Y,
  841. BarItems = Menus [index],
  842. Parent = null
  843. };
  844. openCurrentMenu = _openMenu;
  845. openCurrentMenu._previousSubFocused = _openMenu;
  846. Application.Current.Add (_openMenu);
  847. _openMenu.SetFocus ();
  848. break;
  849. default:
  850. // Opens a submenu next to another submenu (openSubMenu)
  851. if (_openSubMenu is null)
  852. {
  853. _openSubMenu = new ();
  854. }
  855. if (sIndex > -1)
  856. {
  857. RemoveSubMenu (sIndex);
  858. }
  859. else
  860. {
  861. Menu last = _openSubMenu.Count > 0 ? _openSubMenu.Last () : _openMenu;
  862. if (!UseSubMenusSingleFrame)
  863. {
  864. locationOffset = GetLocationOffset ();
  865. openCurrentMenu = new()
  866. {
  867. Host = this,
  868. X = last.Frame.Left + last.Frame.Width + locationOffset.X,
  869. Y = last.Frame.Top + locationOffset.Y + last._currentChild,
  870. BarItems = subMenu,
  871. Parent = last
  872. };
  873. }
  874. else
  875. {
  876. Menu first = _openSubMenu.Count > 0 ? _openSubMenu.First () : _openMenu;
  877. // 2 is for the parent and the separator
  878. MenuItem [] mbi = new MenuItem [2 + subMenu.Children.Length];
  879. mbi [0] = new() { Title = subMenu.Title, Parent = subMenu };
  880. mbi [1] = null;
  881. for (var j = 0; j < subMenu.Children.Length; j++)
  882. {
  883. mbi [j + 2] = subMenu.Children [j];
  884. }
  885. var newSubMenu = new MenuBarItem (mbi) { Parent = subMenu };
  886. openCurrentMenu = new()
  887. {
  888. Host = this, X = first.Frame.Left, Y = first.Frame.Top, BarItems = newSubMenu
  889. };
  890. last.Visible = false;
  891. Application.GrabMouse (openCurrentMenu);
  892. }
  893. openCurrentMenu._previousSubFocused = last._previousSubFocused;
  894. _openSubMenu.Add (openCurrentMenu);
  895. Application.Current.Add (openCurrentMenu);
  896. }
  897. _selectedSub = _openSubMenu.Count - 1;
  898. if (_selectedSub > -1
  899. && SelectEnabledItem (
  900. openCurrentMenu.BarItems.Children,
  901. openCurrentMenu._currentChild,
  902. out openCurrentMenu._currentChild
  903. ))
  904. {
  905. openCurrentMenu.SetFocus ();
  906. }
  907. break;
  908. }
  909. _isMenuOpening = false;
  910. IsMenuOpen = true;
  911. }
  912. internal void PreviousMenu (bool isSubMenu = false, bool ignoreUseSubMenusSingleFrame = false)
  913. {
  914. switch (isSubMenu)
  915. {
  916. case false:
  917. if (_selected <= 0)
  918. {
  919. _selected = Menus.Length - 1;
  920. }
  921. else
  922. {
  923. _selected--;
  924. }
  925. if (_selected > -1 && !CloseMenu (true, false, ignoreUseSubMenusSingleFrame))
  926. {
  927. return;
  928. }
  929. OpenMenu (_selected);
  930. if (!SelectEnabledItem (
  931. openCurrentMenu.BarItems.Children,
  932. openCurrentMenu._currentChild,
  933. out openCurrentMenu._currentChild,
  934. false
  935. ))
  936. {
  937. openCurrentMenu._currentChild = 0;
  938. }
  939. break;
  940. case true:
  941. if (_selectedSub > -1)
  942. {
  943. _selectedSub--;
  944. RemoveSubMenu (_selectedSub, ignoreUseSubMenusSingleFrame);
  945. SetNeedsDisplay ();
  946. }
  947. else
  948. {
  949. PreviousMenu ();
  950. }
  951. break;
  952. }
  953. }
  954. internal void RemoveAllOpensSubMenus ()
  955. {
  956. if (_openSubMenu is { })
  957. {
  958. foreach (Menu item in _openSubMenu)
  959. {
  960. Application.Current.Remove (item);
  961. item.Dispose ();
  962. }
  963. }
  964. }
  965. internal bool Run (Action action)
  966. {
  967. if (action is null)
  968. {
  969. return false;
  970. }
  971. Application.MainLoop.AddIdle (
  972. () =>
  973. {
  974. action ();
  975. return false;
  976. }
  977. );
  978. return true;
  979. }
  980. internal bool SelectEnabledItem (
  981. IEnumerable<MenuItem> chldren,
  982. int current,
  983. out int newCurrent,
  984. bool forward = true
  985. )
  986. {
  987. if (chldren is null)
  988. {
  989. newCurrent = -1;
  990. return true;
  991. }
  992. IEnumerable<MenuItem> childrens;
  993. if (forward)
  994. {
  995. childrens = chldren;
  996. }
  997. else
  998. {
  999. childrens = chldren.Reverse ();
  1000. }
  1001. int count;
  1002. if (forward)
  1003. {
  1004. count = -1;
  1005. }
  1006. else
  1007. {
  1008. count = childrens.Count ();
  1009. }
  1010. foreach (MenuItem child in childrens)
  1011. {
  1012. if (forward)
  1013. {
  1014. if (++count < current)
  1015. {
  1016. continue;
  1017. }
  1018. }
  1019. else
  1020. {
  1021. if (--count > current)
  1022. {
  1023. continue;
  1024. }
  1025. }
  1026. if (child is null || !child.IsEnabled ())
  1027. {
  1028. if (forward)
  1029. {
  1030. current++;
  1031. }
  1032. else
  1033. {
  1034. current--;
  1035. }
  1036. }
  1037. else
  1038. {
  1039. newCurrent = current;
  1040. return true;
  1041. }
  1042. }
  1043. newCurrent = -1;
  1044. return false;
  1045. }
  1046. /// <summary>Called when an item is selected; Runs the action.</summary>
  1047. /// <param name="item"></param>
  1048. internal bool SelectItem (MenuItem item)
  1049. {
  1050. if (item?.Action is null)
  1051. {
  1052. return false;
  1053. }
  1054. Application.UngrabMouse ();
  1055. CloseAllMenus ();
  1056. Application.Refresh ();
  1057. _openedByAltKey = true;
  1058. return Run (item?.Action);
  1059. }
  1060. private void CloseMenuBar ()
  1061. {
  1062. if (!CloseMenu (false))
  1063. {
  1064. return;
  1065. }
  1066. if (_openedByAltKey)
  1067. {
  1068. _openedByAltKey = false;
  1069. LastFocused?.SetFocus ();
  1070. }
  1071. SetNeedsDisplay ();
  1072. }
  1073. private Point GetLocationOffset ()
  1074. {
  1075. if (MenusBorderStyle != LineStyle.None)
  1076. {
  1077. return new (0, 1);
  1078. }
  1079. return new (-2, 0);
  1080. }
  1081. private void MenuBar_Added (object sender, SuperViewChangedEventArgs e)
  1082. {
  1083. _initialCanFocus = CanFocus;
  1084. Added -= MenuBar_Added;
  1085. }
  1086. private void MoveLeft ()
  1087. {
  1088. _selected--;
  1089. if (_selected < 0)
  1090. {
  1091. _selected = Menus.Length - 1;
  1092. }
  1093. OpenMenu (_selected);
  1094. SetNeedsDisplay ();
  1095. }
  1096. private void MoveRight ()
  1097. {
  1098. _selected = (_selected + 1) % Menus.Length;
  1099. OpenMenu (_selected);
  1100. SetNeedsDisplay ();
  1101. }
  1102. private void ProcessMenu (int i, MenuBarItem mi)
  1103. {
  1104. if (_selected < 0 && IsMenuOpen)
  1105. {
  1106. return;
  1107. }
  1108. if (mi.IsTopLevel)
  1109. {
  1110. Rectangle screen = BoundsToScreen (new (new (0, i), Size.Empty));
  1111. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = mi };
  1112. menu.Run (mi.Action);
  1113. menu.Dispose ();
  1114. }
  1115. else
  1116. {
  1117. Application.GrabMouse (this);
  1118. _selected = i;
  1119. OpenMenu (i);
  1120. if (!SelectEnabledItem (
  1121. openCurrentMenu.BarItems.Children,
  1122. openCurrentMenu._currentChild,
  1123. out openCurrentMenu._currentChild
  1124. )
  1125. && !CloseMenu (false))
  1126. {
  1127. return;
  1128. }
  1129. if (!openCurrentMenu.CheckSubMenu ())
  1130. {
  1131. return;
  1132. }
  1133. }
  1134. SetNeedsDisplay ();
  1135. }
  1136. private void RemoveSubMenu (int index, bool ignoreUseSubMenusSingleFrame = false)
  1137. {
  1138. if (_openSubMenu == null
  1139. || (UseSubMenusSingleFrame
  1140. && !ignoreUseSubMenusSingleFrame
  1141. && _openSubMenu.Count == 0))
  1142. {
  1143. return;
  1144. }
  1145. for (int i = _openSubMenu.Count - 1; i > index; i--)
  1146. {
  1147. _isMenuClosing = true;
  1148. Menu menu;
  1149. if (_openSubMenu.Count - 1 > 0)
  1150. {
  1151. menu = _openSubMenu [i - 1];
  1152. }
  1153. else
  1154. {
  1155. menu = _openMenu;
  1156. }
  1157. if (!menu.Visible)
  1158. {
  1159. menu.Visible = true;
  1160. }
  1161. openCurrentMenu = menu;
  1162. openCurrentMenu.SetFocus ();
  1163. if (_openSubMenu is { })
  1164. {
  1165. menu = _openSubMenu [i];
  1166. Application.Current.Remove (menu);
  1167. _openSubMenu.Remove (menu);
  1168. menu.Dispose ();
  1169. }
  1170. RemoveSubMenu (i, ignoreUseSubMenusSingleFrame);
  1171. }
  1172. if (_openSubMenu.Count > 0)
  1173. {
  1174. openCurrentMenu = _openSubMenu.Last ();
  1175. }
  1176. _isMenuClosing = false;
  1177. }
  1178. #region Keyboard handling
  1179. private Key _key = Key.F9;
  1180. /// <summary>
  1181. /// The <see cref="Key"/> used to activate or close the menu bar by keyboard. The default is <see cref="Key.F9"/>
  1182. /// .
  1183. /// </summary>
  1184. /// <remarks>
  1185. /// <para>
  1186. /// If the user presses any <see cref="MenuItem.HotKey"/>s defined in the <see cref="MenuBarItem"/>s, the menu
  1187. /// bar will be activated and the sub-menu will be opened.
  1188. /// </para>
  1189. /// <para><see cref="Key.Esc"/> will close the menu bar and any open sub-menus.</para>
  1190. /// </remarks>
  1191. public Key Key
  1192. {
  1193. get => _key;
  1194. set
  1195. {
  1196. if (_key == value)
  1197. {
  1198. return;
  1199. }
  1200. KeyBindings.Remove (_key);
  1201. KeyBindings.Add (value, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  1202. _key = value;
  1203. }
  1204. }
  1205. private bool _useKeysUpDownAsKeysLeftRight;
  1206. /// <summary>Used for change the navigation key style.</summary>
  1207. public bool UseKeysUpDownAsKeysLeftRight
  1208. {
  1209. get => _useKeysUpDownAsKeysLeftRight;
  1210. set
  1211. {
  1212. _useKeysUpDownAsKeysLeftRight = value;
  1213. if (value && UseSubMenusSingleFrame)
  1214. {
  1215. UseSubMenusSingleFrame = false;
  1216. SetNeedsDisplay ();
  1217. }
  1218. }
  1219. }
  1220. private static Rune _shortcutDelimiter = new ('+');
  1221. /// <summary>Sets or gets the shortcut delimiter separator. The default is "+".</summary>
  1222. public static Rune ShortcutDelimiter
  1223. {
  1224. get => _shortcutDelimiter;
  1225. set
  1226. {
  1227. if (_shortcutDelimiter != value)
  1228. {
  1229. _shortcutDelimiter = value == default (Rune) ? new ('+') : value;
  1230. }
  1231. }
  1232. }
  1233. /// <summary>The specifier character for the hot keys.</summary>
  1234. public new static Rune HotKeySpecifier => (Rune)'_';
  1235. // Set in OnInvokingKeyBindings. -1 means no menu item is selected for activation.
  1236. private int _menuBarItemToActivate;
  1237. // Set in OnInvokingKeyBindings. null means no sub-menu is selected for activation.
  1238. private MenuItem _menuItemToSelect;
  1239. private bool _openedByAltKey;
  1240. private bool _openedByHotKey;
  1241. /// <summary>
  1242. /// Called when a key bound to Command.Select is pressed. Either activates the menu item or runs it, depending on
  1243. /// whether it has a sub-menu. If the menu is open, it will close the menu bar.
  1244. /// </summary>
  1245. /// <returns></returns>
  1246. private bool SelectOrRun ()
  1247. {
  1248. if (!IsInitialized || !Visible)
  1249. {
  1250. return true;
  1251. }
  1252. _openedByHotKey = true;
  1253. if (_menuBarItemToActivate != -1)
  1254. {
  1255. Activate (_menuBarItemToActivate);
  1256. }
  1257. else if (_menuItemToSelect is { })
  1258. {
  1259. Run (_menuItemToSelect.Action);
  1260. }
  1261. else
  1262. {
  1263. if (IsMenuOpen && _openMenu is { })
  1264. {
  1265. CloseAllMenus ();
  1266. }
  1267. else
  1268. {
  1269. OpenMenu ();
  1270. }
  1271. }
  1272. return true;
  1273. }
  1274. /// <inheritdoc/>
  1275. public override bool? OnInvokingKeyBindings (Key key)
  1276. {
  1277. // This is a bit of a hack. We want to handle the key bindings for menu bar but
  1278. // InvokeKeyBindings doesn't pass any context so we can't tell which item it is for.
  1279. // So before we call the base class we set SelectedItem appropriately.
  1280. // TODO: Figure out if there's a way to have KeyBindings pass context instead. Maybe a KeyBindingContext property?
  1281. if (KeyBindings.TryGet (key, out _))
  1282. {
  1283. _menuBarItemToActivate = -1;
  1284. _menuItemToSelect = null;
  1285. // Search for shortcuts first. If there's a shortcut, we don't want to activate the menu item.
  1286. for (var i = 0; i < Menus.Length; i++)
  1287. {
  1288. // Recurse through the menu to find one with the shortcut.
  1289. if (FindShortcutInChildMenu (key.KeyCode, Menus [i], out _menuItemToSelect))
  1290. {
  1291. _menuBarItemToActivate = i;
  1292. //keyEvent.Scope = KeyBindingScope.HotKey;
  1293. return base.OnInvokingKeyBindings (key);
  1294. }
  1295. // Now see if any of the menu bar items have a hot key that matches
  1296. // Technically this is not possible because menu bar items don't have
  1297. // shortcuts or Actions. But it's here for completeness.
  1298. KeyCode? shortcut = Menus [i]?.Shortcut;
  1299. if (key == shortcut)
  1300. {
  1301. throw new InvalidOperationException ("Menu bar items cannot have shortcuts");
  1302. }
  1303. }
  1304. // Search for hot keys next.
  1305. for (var i = 0; i < Menus.Length; i++)
  1306. {
  1307. if (IsMenuOpen)
  1308. {
  1309. // We don't need to do anything because `Menu` will handle the key binding.
  1310. //break;
  1311. }
  1312. // No submenu item matched (or the menu is closed)
  1313. // Check if one of the menu bar item has a hot key that matches
  1314. var hotKey = new Key ((char)Menus [i]?.HotKey.Value);
  1315. if (hotKey != Key.Empty)
  1316. {
  1317. bool matches = key == hotKey || key == hotKey.WithAlt || key == hotKey.NoShift.WithAlt;
  1318. if (IsMenuOpen)
  1319. {
  1320. // If the menu is open, only match if Alt is not pressed.
  1321. matches = key == hotKey;
  1322. }
  1323. if (matches)
  1324. {
  1325. _menuBarItemToActivate = i;
  1326. //keyEvent.Scope = KeyBindingScope.HotKey;
  1327. break;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. return base.OnInvokingKeyBindings (key);
  1333. }
  1334. // TODO: Update to use Key instead of KeyCode
  1335. // Recurse the child menus looking for a shortcut that matches the key
  1336. private bool FindShortcutInChildMenu (KeyCode key, MenuBarItem menuBarItem, out MenuItem menuItemToSelect)
  1337. {
  1338. menuItemToSelect = null;
  1339. if (key == KeyCode.Null || menuBarItem?.Children is null)
  1340. {
  1341. return false;
  1342. }
  1343. for (var c = 0; c < menuBarItem.Children.Length; c++)
  1344. {
  1345. MenuItem menuItem = menuBarItem.Children [c];
  1346. if (key == menuItem?.Shortcut)
  1347. {
  1348. menuItemToSelect = menuItem;
  1349. return true;
  1350. }
  1351. MenuBarItem subMenu = menuBarItem.SubMenu (menuItem);
  1352. if (subMenu is { })
  1353. {
  1354. if (FindShortcutInChildMenu (key, subMenu, out menuItemToSelect))
  1355. {
  1356. return true;
  1357. }
  1358. }
  1359. }
  1360. return false;
  1361. }
  1362. #endregion Keyboard handling
  1363. #region Mouse Handling
  1364. /// <inheritdoc/>
  1365. public override bool OnEnter (View view)
  1366. {
  1367. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1368. return base.OnEnter (view);
  1369. }
  1370. /// <inheritdoc/>
  1371. public override bool OnLeave (View view)
  1372. {
  1373. if (((!(view is MenuBar) && !(view is Menu)) || (!(view is MenuBar) && !(view is Menu) && _openMenu is { })) && !_isCleaning && !_reopen)
  1374. {
  1375. CleanUp ();
  1376. }
  1377. return base.OnLeave (view);
  1378. }
  1379. /// <inheritdoc/>
  1380. protected internal override bool OnMouseEvent (MouseEvent me)
  1381. {
  1382. if (!_handled && !HandleGrabView (me, this))
  1383. {
  1384. return false;
  1385. }
  1386. _handled = false;
  1387. if (me.Flags == MouseFlags.Button1Pressed
  1388. || me.Flags == MouseFlags.Button1DoubleClicked
  1389. || me.Flags == MouseFlags.Button1TripleClicked
  1390. || me.Flags == MouseFlags.Button1Clicked
  1391. || (me.Flags == MouseFlags.ReportMousePosition && _selected > -1)
  1392. || (me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) && _selected > -1))
  1393. {
  1394. int pos = _xOrigin;
  1395. Point locationOffset = default;
  1396. if (SuperView is { })
  1397. {
  1398. locationOffset.X += SuperView.Border.Thickness.Left;
  1399. locationOffset.Y += SuperView.Border.Thickness.Top;
  1400. }
  1401. int cx = me.X - locationOffset.X;
  1402. for (var i = 0; i < Menus.Length; i++)
  1403. {
  1404. if (cx >= pos && cx < pos + _leftPadding + Menus [i].TitleLength + Menus [i].Help.GetColumns () + _rightPadding)
  1405. {
  1406. if (me.Flags == MouseFlags.Button1Clicked)
  1407. {
  1408. if (Menus [i].IsTopLevel)
  1409. {
  1410. Rectangle screen = BoundsToScreen (new (new (0, i), Size.Empty));
  1411. var menu = new Menu { Host = this, X = screen.X, Y = screen.Y, BarItems = Menus [i] };
  1412. menu.Run (Menus [i].Action);
  1413. menu.Dispose ();
  1414. }
  1415. else if (!IsMenuOpen)
  1416. {
  1417. Activate (i);
  1418. }
  1419. }
  1420. else if (me.Flags == MouseFlags.Button1Pressed
  1421. || me.Flags == MouseFlags.Button1DoubleClicked
  1422. || me.Flags == MouseFlags.Button1TripleClicked)
  1423. {
  1424. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1425. {
  1426. CloseAllMenus ();
  1427. }
  1428. else if (!Menus [i].IsTopLevel)
  1429. {
  1430. Activate (i);
  1431. }
  1432. }
  1433. else if (_selected != i
  1434. && _selected > -1
  1435. && (me.Flags == MouseFlags.ReportMousePosition
  1436. || (me.Flags == MouseFlags.Button1Pressed && me.Flags == MouseFlags.ReportMousePosition)))
  1437. {
  1438. if (IsMenuOpen)
  1439. {
  1440. if (!CloseMenu (true, false))
  1441. {
  1442. return me.Handled = true;
  1443. }
  1444. Activate (i);
  1445. }
  1446. }
  1447. else if (IsMenuOpen)
  1448. {
  1449. if (!UseSubMenusSingleFrame
  1450. || (UseSubMenusSingleFrame
  1451. && openCurrentMenu != null
  1452. && openCurrentMenu.BarItems.Parent != null
  1453. && openCurrentMenu.BarItems.Parent.Parent != Menus [i]))
  1454. {
  1455. Activate (i);
  1456. }
  1457. }
  1458. return me.Handled = true;
  1459. }
  1460. if (i == Menus.Length - 1 && me.Flags == MouseFlags.Button1Clicked)
  1461. {
  1462. if (IsMenuOpen && !Menus [i].IsTopLevel)
  1463. {
  1464. CloseAllMenus ();
  1465. return me.Handled = true;
  1466. }
  1467. }
  1468. pos += _leftPadding + Menus [i].TitleLength + _rightPadding;
  1469. }
  1470. }
  1471. return false;
  1472. }
  1473. internal bool _handled;
  1474. internal bool _isContextMenuLoading;
  1475. private MenuBarItem [] _menus;
  1476. internal bool HandleGrabView (MouseEvent me, View current)
  1477. {
  1478. if (Application.MouseGrabView is { })
  1479. {
  1480. if (me.View is MenuBar || me.View is Menu)
  1481. {
  1482. MenuBar mbar = GetMouseGrabViewInstance (me.View);
  1483. if (mbar is { })
  1484. {
  1485. if (me.Flags == MouseFlags.Button1Clicked)
  1486. {
  1487. mbar.CleanUp ();
  1488. Application.GrabMouse (me.View);
  1489. }
  1490. else
  1491. {
  1492. _handled = false;
  1493. return false;
  1494. }
  1495. }
  1496. if (me.View != current)
  1497. {
  1498. Application.UngrabMouse ();
  1499. View v = me.View;
  1500. Application.GrabMouse (v);
  1501. MouseEvent nme;
  1502. if (me.Y > -1)
  1503. {
  1504. Point frameLoc = v.ScreenToFrame (me.X, me.Y);
  1505. nme = new ()
  1506. {
  1507. X = frameLoc.X,
  1508. Y = frameLoc.Y,
  1509. Flags = me.Flags,
  1510. View = v
  1511. };
  1512. }
  1513. else
  1514. {
  1515. nme = new () { X = me.X + current.Frame.X, Y = 0, Flags = me.Flags, View = v };
  1516. }
  1517. v.NewMouseEvent (nme);
  1518. return false;
  1519. }
  1520. }
  1521. else if (!_isContextMenuLoading
  1522. && !(me.View is MenuBar || me.View is Menu)
  1523. && me.Flags != MouseFlags.ReportMousePosition
  1524. && me.Flags != 0)
  1525. {
  1526. Application.UngrabMouse ();
  1527. if (IsMenuOpen)
  1528. {
  1529. CloseAllMenus ();
  1530. }
  1531. _handled = false;
  1532. return false;
  1533. }
  1534. else
  1535. {
  1536. _handled = false;
  1537. _isContextMenuLoading = false;
  1538. return false;
  1539. }
  1540. }
  1541. else if (!IsMenuOpen
  1542. && (me.Flags == MouseFlags.Button1Pressed
  1543. || me.Flags == MouseFlags.Button1DoubleClicked
  1544. || me.Flags == MouseFlags.Button1TripleClicked
  1545. || me.Flags.HasFlag (
  1546. MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition
  1547. )))
  1548. {
  1549. Application.GrabMouse (current);
  1550. }
  1551. else if (IsMenuOpen && (me.View is MenuBar || me.View is Menu))
  1552. {
  1553. Application.GrabMouse (me.View);
  1554. }
  1555. else
  1556. {
  1557. _handled = false;
  1558. return false;
  1559. }
  1560. _handled = true;
  1561. return true;
  1562. }
  1563. private MenuBar GetMouseGrabViewInstance (View view)
  1564. {
  1565. if (view is null || Application.MouseGrabView is null)
  1566. {
  1567. return null;
  1568. }
  1569. MenuBar hostView = null;
  1570. if (view is MenuBar)
  1571. {
  1572. hostView = (MenuBar)view;
  1573. }
  1574. else if (view is Menu)
  1575. {
  1576. hostView = ((Menu)view).Host;
  1577. }
  1578. View grabView = Application.MouseGrabView;
  1579. MenuBar hostGrabView = null;
  1580. if (grabView is MenuBar)
  1581. {
  1582. hostGrabView = (MenuBar)grabView;
  1583. }
  1584. else if (grabView is Menu)
  1585. {
  1586. hostGrabView = ((Menu)grabView).Host;
  1587. }
  1588. return hostView != hostGrabView ? hostGrabView : null;
  1589. }
  1590. #endregion Mouse Handling
  1591. }