MenuBar.cs 58 KB

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