2
0

Menu.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. namespace Terminal.Gui;
  2. /// <summary>Specifies how a <see cref="MenuItem"/> shows selection state.</summary>
  3. [Flags]
  4. public enum MenuItemCheckStyle
  5. {
  6. /// <summary>The menu item will be shown normally, with no check indicator. The default.</summary>
  7. NoCheck = 0b_0000_0000,
  8. /// <summary>The menu item will indicate checked/un-checked state (see <see cref="Checked"/>).</summary>
  9. Checked = 0b_0000_0001,
  10. /// <summary>The menu item is part of a menu radio group (see <see cref="Checked"/>) and will indicate selected state.</summary>
  11. Radio = 0b_0000_0010
  12. }
  13. /// <summary>
  14. /// A <see cref="MenuItem"/> has title, an associated help text, and an action to execute on activation. MenuItems
  15. /// can also have a checked indicator (see <see cref="Checked"/>).
  16. /// </summary>
  17. public class MenuItem
  18. {
  19. private readonly ShortcutHelper _shortcutHelper;
  20. private bool _allowNullChecked;
  21. private MenuItemCheckStyle _checkType;
  22. private string _title;
  23. // TODO: Update to use Key instead of KeyCode
  24. /// <summary>Initializes a new instance of <see cref="MenuItem"/></summary>
  25. public MenuItem (KeyCode shortcut = KeyCode.Null) : this ("", "", null, null, null, shortcut) { }
  26. // TODO: Update to use Key instead of KeyCode
  27. /// <summary>Initializes a new instance of <see cref="MenuItem"/>.</summary>
  28. /// <param name="title">Title for the menu item.</param>
  29. /// <param name="help">Help text to display.</param>
  30. /// <param name="action">Action to invoke when the menu item is activated.</param>
  31. /// <param name="canExecute">Function to determine if the action can currently be executed.</param>
  32. /// <param name="parent">The <see cref="Parent"/> of this menu item.</param>
  33. /// <param name="shortcut">The <see cref="Shortcut"/> keystroke combination.</param>
  34. public MenuItem (
  35. string title,
  36. string help,
  37. Action action,
  38. Func<bool> canExecute = null,
  39. MenuItem parent = null,
  40. KeyCode shortcut = KeyCode.Null
  41. )
  42. {
  43. Title = title ?? "";
  44. Help = help ?? "";
  45. Action = action;
  46. CanExecute = canExecute;
  47. Parent = parent;
  48. _shortcutHelper = new ShortcutHelper ();
  49. if (shortcut != KeyCode.Null)
  50. {
  51. Shortcut = shortcut;
  52. }
  53. }
  54. /// <summary>Gets or sets the action to be invoked when the menu item is triggered.</summary>
  55. /// <value>Method to invoke.</value>
  56. public Action Action { get; set; }
  57. /// <summary>
  58. /// Used only if <see cref="CheckType"/> is of <see cref="MenuItemCheckStyle.Checked"/> type. If
  59. /// <see langword="true"/> allows <see cref="Checked"/> to be null, true or false. If <see langword="false"/> only
  60. /// allows <see cref="Checked"/> to be true or false.
  61. /// </summary>
  62. public bool AllowNullChecked
  63. {
  64. get => _allowNullChecked;
  65. set
  66. {
  67. _allowNullChecked = value;
  68. Checked ??= false;
  69. }
  70. }
  71. /// <summary>
  72. /// Gets or sets the action to be invoked to determine if the menu can be triggered. If <see cref="CanExecute"/>
  73. /// returns <see langword="true"/> the menu item will be enabled. Otherwise, it will be disabled.
  74. /// </summary>
  75. /// <value>Function to determine if the action is can be executed or not.</value>
  76. public Func<bool> CanExecute { get; set; }
  77. /// <summary>
  78. /// Sets or gets whether the <see cref="MenuItem"/> shows a check indicator or not. See
  79. /// <see cref="MenuItemCheckStyle"/>.
  80. /// </summary>
  81. public bool? Checked { set; get; }
  82. /// <summary>
  83. /// Sets or gets the <see cref="MenuItemCheckStyle"/> of a menu item where <see cref="Checked"/> is set to
  84. /// <see langword="true"/>.
  85. /// </summary>
  86. public MenuItemCheckStyle CheckType
  87. {
  88. get => _checkType;
  89. set
  90. {
  91. _checkType = value;
  92. if (_checkType == MenuItemCheckStyle.Checked && !_allowNullChecked && Checked is null)
  93. {
  94. Checked = false;
  95. }
  96. }
  97. }
  98. /// <summary>Gets or sets arbitrary data for the menu item.</summary>
  99. /// <remarks>This property is not used internally.</remarks>
  100. public object Data { get; set; }
  101. /// <summary>Gets or sets the help text for the menu item. The help text is drawn to the right of the <see cref="Title"/>.</summary>
  102. /// <value>The help text.</value>
  103. public string Help { get; set; }
  104. /// <summary>Gets the parent for this <see cref="MenuItem"/>.</summary>
  105. /// <value>The parent.</value>
  106. public MenuItem Parent { get; set; }
  107. /// <summary>Gets or sets the title of the menu item .</summary>
  108. /// <value>The title.</value>
  109. public string Title
  110. {
  111. get => _title;
  112. set
  113. {
  114. if (_title == value)
  115. {
  116. return;
  117. }
  118. _title = value;
  119. GetHotKey ();
  120. }
  121. }
  122. /// <summary>Gets if this <see cref="MenuItem"/> is from a sub-menu.</summary>
  123. internal bool IsFromSubMenu => Parent != null;
  124. internal int TitleLength => GetMenuBarItemLength (Title);
  125. //
  126. // ┌─────────────────────────────┐
  127. // │ Quit Quit UI Catalog Ctrl+Q │
  128. // └─────────────────────────────┘
  129. // ┌─────────────────┐
  130. // │ ◌ TopLevel Alt+T │
  131. // └─────────────────┘
  132. // TODO: Replace the `2` literals with named constants
  133. internal int Width => 1
  134. + // space before Title
  135. TitleLength
  136. + 2
  137. + // space after Title - BUGBUG: This should be 1
  138. (Checked == true || CheckType.HasFlag (MenuItemCheckStyle.Checked) || CheckType.HasFlag (MenuItemCheckStyle.Radio)
  139. ? 2
  140. : 0)
  141. + // check glyph + space
  142. (Help.GetColumns () > 0 ? 2 + Help.GetColumns () : 0)
  143. + // Two spaces before Help
  144. (ShortcutTag.GetColumns () > 0
  145. ? 2 + ShortcutTag.GetColumns ()
  146. : 0); // Pad two spaces before shortcut tag (which are also aligned right)
  147. /// <summary>Merely a debugging aid to see the interaction with main.</summary>
  148. public bool GetMenuBarItem () { return IsFromSubMenu; }
  149. /// <summary>Merely a debugging aid to see the interaction with main.</summary>
  150. public MenuItem GetMenuItem () { return this; }
  151. /// <summary>
  152. /// Returns <see langword="true"/> if the menu item is enabled. This method is a wrapper around
  153. /// <see cref="CanExecute"/>.
  154. /// </summary>
  155. public bool IsEnabled () { return CanExecute?.Invoke () ?? true; }
  156. /// <summary>
  157. /// Toggle the <see cref="Checked"/> between three states if <see cref="AllowNullChecked"/> is
  158. /// <see langword="true"/> or between two states if <see cref="AllowNullChecked"/> is <see langword="false"/>.
  159. /// </summary>
  160. public void ToggleChecked ()
  161. {
  162. if (_checkType != MenuItemCheckStyle.Checked)
  163. {
  164. throw new InvalidOperationException ("This isn't a Checked MenuItemCheckStyle!");
  165. }
  166. bool? previousChecked = Checked;
  167. if (AllowNullChecked)
  168. {
  169. Checked = previousChecked switch
  170. {
  171. null => true,
  172. true => false,
  173. false => null
  174. };
  175. }
  176. else
  177. {
  178. Checked = !Checked;
  179. }
  180. }
  181. private static int GetMenuBarItemLength (string title)
  182. {
  183. return title.EnumerateRunes ()
  184. .Where (ch => ch != MenuBar.HotKeySpecifier)
  185. .Sum (ch => Math.Max (ch.GetColumns (), 1));
  186. }
  187. #region Keyboard Handling
  188. // TODO: Update to use Key instead of Rune
  189. /// <summary>
  190. /// The HotKey is used to activate a <see cref="MenuItem"/> with the keyboard. HotKeys are defined by prefixing the
  191. /// <see cref="Title"/> of a MenuItem with an underscore ('_').
  192. /// <para>
  193. /// Pressing Alt-Hotkey for a <see cref="MenuBarItem"/> (menu items on the menu bar) works even if the menu is
  194. /// not active). Once a menu has focus and is active, pressing just the HotKey will activate the MenuItem.
  195. /// </para>
  196. /// <para>
  197. /// For example for a MenuBar with a "_File" MenuBarItem that contains a "_New" MenuItem, Alt-F will open the
  198. /// File menu. Pressing the N key will then activate the New MenuItem.
  199. /// </para>
  200. /// <para>See also <see cref="Shortcut"/> which enable global key-bindings to menu items.</para>
  201. /// </summary>
  202. public Rune HotKey { get; set; }
  203. private void GetHotKey ()
  204. {
  205. var nextIsHot = false;
  206. foreach (char x in _title)
  207. {
  208. if (x == MenuBar.HotKeySpecifier.Value)
  209. {
  210. nextIsHot = true;
  211. }
  212. else
  213. {
  214. if (nextIsHot)
  215. {
  216. HotKey = (Rune)char.ToUpper (x);
  217. break;
  218. }
  219. nextIsHot = false;
  220. HotKey = default (Rune);
  221. }
  222. }
  223. }
  224. // TODO: Update to use Key instead of KeyCode
  225. /// <summary>
  226. /// Shortcut defines a key binding to the MenuItem that will invoke the MenuItem's action globally for the
  227. /// <see cref="View"/> that is the parent of the <see cref="MenuBar"/> or <see cref="ContextMenu"/> this
  228. /// <see cref="MenuItem"/>.
  229. /// <para>
  230. /// The <see cref="KeyCode"/> will be drawn on the MenuItem to the right of the <see cref="Title"/> and
  231. /// <see cref="Help"/> text. See <see cref="ShortcutTag"/>.
  232. /// </para>
  233. /// </summary>
  234. public KeyCode Shortcut
  235. {
  236. get => _shortcutHelper.Shortcut;
  237. set
  238. {
  239. if (_shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == KeyCode.Null))
  240. {
  241. _shortcutHelper.Shortcut = value;
  242. }
  243. }
  244. }
  245. /// <summary>Gets the text describing the keystroke combination defined by <see cref="Shortcut"/>.</summary>
  246. public string ShortcutTag => _shortcutHelper.Shortcut == KeyCode.Null
  247. ? string.Empty
  248. : Key.ToString (_shortcutHelper.Shortcut, MenuBar.ShortcutDelimiter);
  249. #endregion Keyboard Handling
  250. }
  251. /// <summary>
  252. /// An internal class used to represent a menu pop-up menu. Created and managed by <see cref="MenuBar"/> and
  253. /// <see cref="ContextMenu"/>.
  254. /// </summary>
  255. internal sealed class Menu : View
  256. {
  257. private readonly MenuBarItem _barItems;
  258. private readonly MenuBar _host;
  259. internal int _currentChild;
  260. internal View _previousSubFocused;
  261. internal static Rectangle MakeFrame (int x, int y, MenuItem [] items, Menu parent = null)
  262. {
  263. if (items is null || items.Length == 0)
  264. {
  265. return Rectangle.Empty;
  266. }
  267. int minX = x;
  268. int minY = y;
  269. const int borderOffset = 2; // This 2 is for the space around
  270. int maxW = (items.Max (z => z?.Width) ?? 0) + borderOffset;
  271. int maxH = items.Length + borderOffset;
  272. if (parent is { } && x + maxW > Driver.Cols)
  273. {
  274. minX = Math.Max (parent.Frame.Right - parent.Frame.Width - maxW, 0);
  275. }
  276. if (y + maxH > Driver.Rows)
  277. {
  278. minY = Math.Max (Driver.Rows - maxH, 0);
  279. }
  280. return new (minX, minY, maxW, maxH);
  281. }
  282. internal required MenuBar Host
  283. {
  284. get => _host;
  285. init
  286. {
  287. ArgumentNullException.ThrowIfNull (value);
  288. _host = value;
  289. }
  290. }
  291. internal required MenuBarItem BarItems
  292. {
  293. get => _barItems;
  294. init
  295. {
  296. ArgumentNullException.ThrowIfNull (value);
  297. _barItems = value;
  298. // Debugging aid so ToString() is helpful
  299. Text = _barItems.Title;
  300. }
  301. }
  302. internal Menu Parent { get; init; }
  303. public override void BeginInit ()
  304. {
  305. base.BeginInit ();
  306. Frame = MakeFrame (Frame.X, Frame.Y, _barItems?.Children, Parent);
  307. if (_barItems is { IsTopLevel: true })
  308. {
  309. // This is a standalone MenuItem on a MenuBar
  310. ColorScheme = _host.ColorScheme;
  311. CanFocus = true;
  312. }
  313. else
  314. {
  315. _currentChild = -1;
  316. for (var i = 0; i < _barItems!.Children?.Length; i++)
  317. {
  318. if (_barItems.Children [i]?.IsEnabled () == true)
  319. {
  320. _currentChild = i;
  321. break;
  322. }
  323. }
  324. ColorScheme = _host.ColorScheme;
  325. CanFocus = true;
  326. WantMousePositionReports = _host.WantMousePositionReports;
  327. }
  328. BorderStyle = _host.MenusBorderStyle;
  329. AddCommand (
  330. Command.Right,
  331. () =>
  332. {
  333. _host.NextMenu (
  334. !_barItems.IsTopLevel
  335. || (_barItems.Children != null
  336. && _barItems!.Children.Length > 0
  337. && _currentChild > -1
  338. && _currentChild < _barItems.Children.Length
  339. && _barItems.Children [_currentChild].IsFromSubMenu),
  340. _barItems!.Children != null
  341. && _barItems.Children.Length > 0
  342. && _currentChild > -1
  343. && _host.UseSubMenusSingleFrame
  344. && _barItems.SubMenu (
  345. _barItems.Children [_currentChild]
  346. )
  347. != null
  348. );
  349. return true;
  350. }
  351. );
  352. AddKeyBindings (_barItems);
  353. #if SUPPORT_ALT_TO_ACTIVATE_MENU
  354. Initialized += (s, e) =>
  355. {
  356. if (SuperView is { })
  357. {
  358. SuperView.KeyUp += SuperView_KeyUp;
  359. }
  360. };
  361. #endif
  362. }
  363. public Menu ()
  364. {
  365. if (Application.Current is { })
  366. {
  367. Application.Current.DrawContentComplete += Current_DrawContentComplete;
  368. Application.Current.SizeChanging += Current_TerminalResized;
  369. }
  370. Application.MouseEvent += Application_RootMouseEvent;
  371. // Things this view knows how to do
  372. AddCommand (Command.LineUp, () => MoveUp ());
  373. AddCommand (Command.LineDown, () => MoveDown ());
  374. AddCommand (
  375. Command.Left,
  376. () =>
  377. {
  378. _host.PreviousMenu (true);
  379. return true;
  380. }
  381. );
  382. AddCommand (
  383. Command.Cancel,
  384. () =>
  385. {
  386. CloseAllMenus ();
  387. return true;
  388. }
  389. );
  390. AddCommand (
  391. Command.Accept,
  392. () =>
  393. {
  394. RunSelected ();
  395. return true;
  396. }
  397. );
  398. AddCommand (Command.Select, () => _host?.SelectItem (_menuItemToSelect));
  399. AddCommand (Command.ToggleExpandCollapse, () => SelectOrRun ());
  400. AddCommand (Command.HotKey, () => _host?.SelectItem (_menuItemToSelect));
  401. // Default key bindings for this view
  402. KeyBindings.Add (Key.CursorUp, Command.LineUp);
  403. KeyBindings.Add (Key.CursorDown, Command.LineDown);
  404. KeyBindings.Add (Key.CursorLeft, Command.Left);
  405. KeyBindings.Add (Key.CursorRight, Command.Right);
  406. KeyBindings.Add (Key.Esc, Command.Cancel);
  407. KeyBindings.Add (Key.Enter, Command.Accept);
  408. KeyBindings.Add (Key.F9, KeyBindingScope.HotKey, Command.ToggleExpandCollapse);
  409. KeyBindings.Add (
  410. KeyCode.CtrlMask | KeyCode.Space,
  411. KeyBindingScope.HotKey,
  412. Command.ToggleExpandCollapse
  413. );
  414. }
  415. #if SUPPORT_ALT_TO_ACTIVATE_MENU
  416. void SuperView_KeyUp (object sender, KeyEventArgs e)
  417. {
  418. if (SuperView is null || SuperView.CanFocus == false || SuperView.Visible == false)
  419. {
  420. return;
  421. }
  422. _host.AltKeyUpHandler (e);
  423. }
  424. #endif
  425. private void AddKeyBindings (MenuBarItem menuBarItem)
  426. {
  427. if (menuBarItem is null || menuBarItem.Children is null)
  428. {
  429. return;
  430. }
  431. foreach (MenuItem menuItem in menuBarItem.Children.Where (m => m is { }))
  432. {
  433. KeyBindings.Add ((KeyCode)menuItem.HotKey.Value, Command.ToggleExpandCollapse);
  434. KeyBindings.Add (
  435. (KeyCode)menuItem.HotKey.Value | KeyCode.AltMask,
  436. Command.ToggleExpandCollapse
  437. );
  438. if (menuItem.Shortcut != KeyCode.Null)
  439. {
  440. KeyBindings.Add (menuItem.Shortcut, KeyBindingScope.HotKey, Command.Select);
  441. }
  442. MenuBarItem subMenu = menuBarItem.SubMenu (menuItem);
  443. AddKeyBindings (subMenu);
  444. }
  445. }
  446. private int _menuBarItemToActivate = -1;
  447. private MenuItem _menuItemToSelect;
  448. /// <summary>Called when a key bound to Command.Select is pressed. This means a hot key was pressed.</summary>
  449. /// <returns></returns>
  450. private bool SelectOrRun ()
  451. {
  452. if (!IsInitialized || !Visible)
  453. {
  454. return true;
  455. }
  456. if (_menuBarItemToActivate != -1)
  457. {
  458. _host.Activate (1, _menuBarItemToActivate);
  459. }
  460. else if (_menuItemToSelect is { })
  461. {
  462. var m = _menuItemToSelect as MenuBarItem;
  463. if (m?.Children?.Length > 0)
  464. {
  465. MenuItem item = _barItems.Children [_currentChild];
  466. if (item is null)
  467. {
  468. return true;
  469. }
  470. bool disabled = item is null || !item.IsEnabled ();
  471. if (!disabled && (_host.UseSubMenusSingleFrame || !CheckSubMenu ()))
  472. {
  473. SetNeedsDisplay ();
  474. SetParentSetNeedsDisplay ();
  475. return true;
  476. }
  477. if (!disabled)
  478. {
  479. _host.OnMenuOpened ();
  480. }
  481. }
  482. else
  483. {
  484. _host.SelectItem (_menuItemToSelect);
  485. }
  486. }
  487. else if (_host.IsMenuOpen)
  488. {
  489. _host.CloseAllMenus ();
  490. }
  491. else
  492. {
  493. _host.OpenMenu ();
  494. }
  495. //_openedByHotKey = true;
  496. return true;
  497. }
  498. /// <inheritdoc/>
  499. public override bool? OnInvokingKeyBindings (Key keyEvent)
  500. {
  501. // This is a bit of a hack. We want to handle the key bindings for menu bar but
  502. // InvokeKeyBindings doesn't pass any context so we can't tell which item it is for.
  503. // So before we call the base class we set SelectedItem appropriately.
  504. KeyCode key = keyEvent.KeyCode;
  505. if (KeyBindings.TryGet (key, out _))
  506. {
  507. _menuBarItemToActivate = -1;
  508. _menuItemToSelect = null;
  509. MenuItem [] children = _barItems.Children;
  510. if (children is null)
  511. {
  512. return base.OnInvokingKeyBindings (keyEvent);
  513. }
  514. // Search for shortcuts first. If there's a shortcut, we don't want to activate the menu item.
  515. foreach (MenuItem c in children)
  516. {
  517. if (key == c?.Shortcut)
  518. {
  519. _menuBarItemToActivate = -1;
  520. _menuItemToSelect = c;
  521. //keyEvent.Scope = KeyBindingScope.HotKey;
  522. return base.OnInvokingKeyBindings (keyEvent);
  523. }
  524. MenuBarItem subMenu = _barItems.SubMenu (c);
  525. if (FindShortcutInChildMenu (key, subMenu))
  526. {
  527. //keyEvent.Scope = KeyBindingScope.HotKey;
  528. return base.OnInvokingKeyBindings (keyEvent);
  529. }
  530. }
  531. // Search for hot keys next.
  532. for (var c = 0; c < children.Length; c++)
  533. {
  534. int hotKeyValue = children [c]?.HotKey.Value ?? default (int);
  535. var hotKey = (KeyCode)hotKeyValue;
  536. if (hotKey == KeyCode.Null)
  537. {
  538. continue;
  539. }
  540. bool matches = key == hotKey || key == (hotKey | KeyCode.AltMask);
  541. if (!_host.IsMenuOpen)
  542. {
  543. // If the menu is open, only match if Alt is not pressed.
  544. matches = key == hotKey;
  545. }
  546. if (matches)
  547. {
  548. _menuItemToSelect = children [c];
  549. _currentChild = c;
  550. return base.OnInvokingKeyBindings (keyEvent);
  551. }
  552. }
  553. }
  554. bool? handled = base.OnInvokingKeyBindings (keyEvent);
  555. if (handled is { } && (bool)handled)
  556. {
  557. return true;
  558. }
  559. // This supports the case where the menu bar is a context menu
  560. return _host.OnInvokingKeyBindings (keyEvent);
  561. }
  562. private bool FindShortcutInChildMenu (KeyCode key, MenuBarItem menuBarItem)
  563. {
  564. if (menuBarItem?.Children is null)
  565. {
  566. return false;
  567. }
  568. foreach (MenuItem menuItem in menuBarItem.Children)
  569. {
  570. if (key == menuItem?.Shortcut)
  571. {
  572. _menuBarItemToActivate = -1;
  573. _menuItemToSelect = menuItem;
  574. return true;
  575. }
  576. MenuBarItem subMenu = menuBarItem.SubMenu (menuItem);
  577. FindShortcutInChildMenu (key, subMenu);
  578. }
  579. return false;
  580. }
  581. private void Current_TerminalResized (object sender, SizeChangedEventArgs e)
  582. {
  583. if (_host.IsMenuOpen)
  584. {
  585. _host.CloseAllMenus ();
  586. }
  587. }
  588. /// <inheritdoc/>
  589. public override void OnVisibleChanged ()
  590. {
  591. base.OnVisibleChanged ();
  592. if (Visible)
  593. {
  594. Application.MouseEvent += Application_RootMouseEvent;
  595. }
  596. else
  597. {
  598. Application.MouseEvent -= Application_RootMouseEvent;
  599. }
  600. }
  601. private void Application_RootMouseEvent (object sender, MouseEvent a)
  602. {
  603. if (a.View is { } and (MenuBar or not Menu))
  604. {
  605. return;
  606. }
  607. if (!Visible)
  608. {
  609. throw new InvalidOperationException ("This shouldn't running on a invisible menu!");
  610. }
  611. View view = a.View ?? this;
  612. Point boundsPoint = view.ScreenToViewport (new (a.Position.X, a.Position.Y));
  613. var me = new MouseEvent
  614. {
  615. Position = boundsPoint,
  616. Flags = a.Flags,
  617. ScreenPosition = a.Position,
  618. View = view
  619. };
  620. if (view.NewMouseEvent (me) == true || a.Flags == MouseFlags.Button1Pressed || a.Flags == MouseFlags.Button1Released)
  621. {
  622. a.Handled = true;
  623. }
  624. }
  625. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  626. {
  627. if (item is null)
  628. {
  629. return GetNormalColor ();
  630. }
  631. if (index == _currentChild)
  632. {
  633. return GetFocusColor ();
  634. }
  635. return !item.IsEnabled () ? ColorScheme.Disabled : GetNormalColor ();
  636. }
  637. public override void OnDrawContent (Rectangle viewport)
  638. {
  639. if (_barItems.Children is null)
  640. {
  641. return;
  642. }
  643. Rectangle savedClip = Driver.Clip;
  644. Driver.Clip = new (0, 0, Driver.Cols, Driver.Rows);
  645. Driver.SetAttribute (GetNormalColor ());
  646. OnDrawAdornments ();
  647. OnRenderLineCanvas ();
  648. for (int i = Viewport.Y; i < _barItems.Children.Length; i++)
  649. {
  650. if (i < 0)
  651. {
  652. continue;
  653. }
  654. if (ViewportToScreen (Viewport).Y + i >= Driver.Rows)
  655. {
  656. break;
  657. }
  658. MenuItem item = _barItems.Children [i];
  659. Driver.SetAttribute (
  660. item is null ? GetNormalColor () :
  661. i == _currentChild ? GetFocusColor() : GetNormalColor ()
  662. );
  663. if (item is null && BorderStyle != LineStyle.None)
  664. {
  665. var s = ViewportToScreen (new Point (-1, i));
  666. Driver.Move (s.X, s.Y);
  667. Driver.AddRune (Glyphs.LeftTee);
  668. }
  669. else if (Frame.X < Driver.Cols)
  670. {
  671. Move (0, i);
  672. }
  673. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  674. for (int p = Viewport.X; p < Frame.Width - 2; p++)
  675. {
  676. // This - 2 is for the border
  677. if (p < 0)
  678. {
  679. continue;
  680. }
  681. if (ViewportToScreen (Viewport).X + p >= Driver.Cols)
  682. {
  683. break;
  684. }
  685. if (item is null)
  686. {
  687. Driver.AddRune (Glyphs.HLine);
  688. }
  689. else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { })
  690. {
  691. Driver.AddRune (Glyphs.LeftArrow);
  692. }
  693. // This `- 3` is left border + right border + one row in from right
  694. else if (p == Frame.Width - 3 && _barItems.SubMenu (_barItems.Children [i]) is { })
  695. {
  696. Driver.AddRune (Glyphs.RightArrow);
  697. }
  698. else
  699. {
  700. Driver.AddRune ((Rune)' ');
  701. }
  702. }
  703. if (item is null)
  704. {
  705. if (BorderStyle != LineStyle.None && SuperView?.Frame.Right - Frame.X > Frame.Width)
  706. {
  707. var s = ViewportToScreen (new Point (Frame.Width - 2, i));
  708. Driver.Move (s.X, s.Y);
  709. Driver.AddRune (Glyphs.RightTee);
  710. }
  711. continue;
  712. }
  713. string textToDraw = null;
  714. Rune nullCheckedChar = Glyphs.NullChecked;
  715. Rune checkChar = Glyphs.Selected;
  716. Rune uncheckedChar = Glyphs.UnSelected;
  717. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked))
  718. {
  719. checkChar = Glyphs.Checked;
  720. uncheckedChar = Glyphs.UnChecked;
  721. }
  722. // Support Checked even though CheckType wasn't set
  723. if (item.CheckType == MenuItemCheckStyle.Checked && item.Checked is null)
  724. {
  725. textToDraw = $"{nullCheckedChar} {item.Title}";
  726. }
  727. else if (item.Checked == true)
  728. {
  729. textToDraw = $"{checkChar} {item.Title}";
  730. }
  731. else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio))
  732. {
  733. textToDraw = $"{uncheckedChar} {item.Title}";
  734. }
  735. else
  736. {
  737. textToDraw = item.Title;
  738. }
  739. var screen = ViewportToScreen (new Point(0 , i));
  740. if (screen.X < Driver.Cols)
  741. {
  742. Driver.Move (screen.X + 1, screen.Y);
  743. if (!item.IsEnabled ())
  744. {
  745. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  746. }
  747. else if (i == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { })
  748. {
  749. var tf = new TextFormatter
  750. {
  751. AutoSize = true,
  752. Alignment = Alignment.Center, HotKeySpecifier = MenuBar.HotKeySpecifier, Text = textToDraw
  753. };
  754. // The -3 is left/right border + one space (not sure what for)
  755. tf.Draw (
  756. ViewportToScreen (new Rectangle(1, i, Frame.Width - 3, 1)),
  757. i == _currentChild ? GetFocusColor () : GetNormalColor (),
  758. i == _currentChild ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  759. SuperView?.ViewportToScreen (SuperView.Viewport) ?? Rectangle.Empty
  760. );
  761. }
  762. else
  763. {
  764. DrawHotString (
  765. textToDraw,
  766. i == _currentChild ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  767. i == _currentChild ? GetFocusColor () : GetNormalColor ()
  768. );
  769. }
  770. // The help string
  771. int l = item.ShortcutTag.GetColumns () == 0
  772. ? item.Help.GetColumns ()
  773. : item.Help.GetColumns () + item.ShortcutTag.GetColumns () + 2;
  774. int col = Frame.Width - l - 3;
  775. screen = ViewportToScreen (new Point (col, i));
  776. if (screen.X < Driver.Cols)
  777. {
  778. Driver.Move (screen.X, screen.Y);
  779. Driver.AddStr (item.Help);
  780. // The shortcut tag string
  781. if (!string.IsNullOrEmpty (item.ShortcutTag))
  782. {
  783. Driver.Move (screen.X + l - item.ShortcutTag.GetColumns (), screen.Y);
  784. Driver.AddStr (item.ShortcutTag);
  785. }
  786. }
  787. }
  788. }
  789. Driver.Clip = savedClip;
  790. // PositionCursor ();
  791. }
  792. private void Current_DrawContentComplete (object sender, DrawEventArgs e)
  793. {
  794. if (Visible)
  795. {
  796. OnDrawContent (Viewport);
  797. }
  798. }
  799. public override Point? PositionCursor ()
  800. {
  801. if (_host?.IsMenuOpen != false)
  802. {
  803. if (_barItems.IsTopLevel)
  804. {
  805. return _host?.PositionCursor ();
  806. }
  807. else
  808. {
  809. Move (2, 1 + _currentChild);
  810. return null; // Don't show the cursor
  811. }
  812. }
  813. return _host?.PositionCursor ();
  814. }
  815. public void Run (Action action)
  816. {
  817. if (action is null || _host is null)
  818. {
  819. return;
  820. }
  821. Application.UngrabMouse ();
  822. _host.CloseAllMenus ();
  823. Application.Refresh ();
  824. _host.Run (action);
  825. }
  826. public override bool OnLeave (View view) { return _host.OnLeave (view); }
  827. private void RunSelected ()
  828. {
  829. if (_barItems.IsTopLevel)
  830. {
  831. Run (_barItems.Action);
  832. }
  833. else
  834. {
  835. switch (_currentChild)
  836. {
  837. case > -1 when _barItems.Children [_currentChild].Action != null:
  838. Run (_barItems.Children [_currentChild].Action);
  839. break;
  840. case 0 when _host.UseSubMenusSingleFrame && _barItems.Children [_currentChild].Parent.Parent != null:
  841. _host.PreviousMenu (_barItems.Children [_currentChild].Parent.IsFromSubMenu, true);
  842. break;
  843. case > -1 when _barItems.SubMenu (_barItems.Children [_currentChild]) != null:
  844. CheckSubMenu ();
  845. break;
  846. }
  847. }
  848. }
  849. private void CloseAllMenus ()
  850. {
  851. Application.UngrabMouse ();
  852. _host.CloseAllMenus ();
  853. }
  854. private bool MoveDown ()
  855. {
  856. if (_barItems.IsTopLevel)
  857. {
  858. return true;
  859. }
  860. bool disabled;
  861. do
  862. {
  863. _currentChild++;
  864. if (_currentChild >= _barItems.Children.Length)
  865. {
  866. _currentChild = 0;
  867. }
  868. if (this != _host.openCurrentMenu && _barItems.Children [_currentChild]?.IsFromSubMenu == true && _host._selectedSub > -1)
  869. {
  870. _host.PreviousMenu (true);
  871. _host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild);
  872. _host.openCurrentMenu = this;
  873. }
  874. MenuItem item = _barItems.Children [_currentChild];
  875. if (item?.IsEnabled () != true)
  876. {
  877. disabled = true;
  878. }
  879. else
  880. {
  881. disabled = false;
  882. }
  883. if (!_host.UseSubMenusSingleFrame
  884. && _host.UseKeysUpDownAsKeysLeftRight
  885. && _barItems.SubMenu (_barItems.Children [_currentChild]) != null
  886. && !disabled
  887. && _host.IsMenuOpen)
  888. {
  889. if (!CheckSubMenu ())
  890. {
  891. return false;
  892. }
  893. break;
  894. }
  895. if (!_host.IsMenuOpen)
  896. {
  897. _host.OpenMenu (_host._selected);
  898. }
  899. }
  900. while (_barItems.Children [_currentChild] is null || disabled);
  901. SetNeedsDisplay ();
  902. SetParentSetNeedsDisplay ();
  903. if (!_host.UseSubMenusSingleFrame)
  904. {
  905. _host.OnMenuOpened ();
  906. }
  907. return true;
  908. }
  909. private bool MoveUp ()
  910. {
  911. if (_barItems.IsTopLevel || _currentChild == -1)
  912. {
  913. return true;
  914. }
  915. bool disabled;
  916. do
  917. {
  918. _currentChild--;
  919. if (_host.UseKeysUpDownAsKeysLeftRight && !_host.UseSubMenusSingleFrame)
  920. {
  921. if ((_currentChild == -1 || this != _host.openCurrentMenu)
  922. && _barItems.Children [_currentChild + 1].IsFromSubMenu
  923. && _host._selectedSub > -1)
  924. {
  925. _currentChild++;
  926. _host.PreviousMenu (true);
  927. if (_currentChild > 0)
  928. {
  929. _currentChild--;
  930. _host.openCurrentMenu = this;
  931. }
  932. break;
  933. }
  934. }
  935. if (_currentChild < 0)
  936. {
  937. _currentChild = _barItems.Children.Length - 1;
  938. }
  939. if (!_host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild, false))
  940. {
  941. _currentChild = 0;
  942. if (!_host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild) && !_host.CloseMenu (false))
  943. {
  944. return false;
  945. }
  946. break;
  947. }
  948. MenuItem item = _barItems.Children [_currentChild];
  949. disabled = item?.IsEnabled () != true;
  950. if (_host.UseSubMenusSingleFrame
  951. || !_host.UseKeysUpDownAsKeysLeftRight
  952. || _barItems.SubMenu (_barItems.Children [_currentChild]) == null
  953. || disabled
  954. || !_host.IsMenuOpen)
  955. {
  956. continue;
  957. }
  958. if (!CheckSubMenu ())
  959. {
  960. return false;
  961. }
  962. break;
  963. }
  964. while (_barItems.Children [_currentChild] is null || disabled);
  965. SetNeedsDisplay ();
  966. SetParentSetNeedsDisplay ();
  967. if (!_host.UseSubMenusSingleFrame)
  968. {
  969. _host.OnMenuOpened ();
  970. }
  971. return true;
  972. }
  973. private void SetParentSetNeedsDisplay ()
  974. {
  975. if (_host._openSubMenu is { })
  976. {
  977. foreach (Menu menu in _host._openSubMenu)
  978. {
  979. menu.SetNeedsDisplay ();
  980. }
  981. }
  982. _host?._openMenu?.SetNeedsDisplay ();
  983. _host?.SetNeedsDisplay ();
  984. }
  985. protected internal override bool OnMouseEvent (MouseEvent me)
  986. {
  987. if (!_host._handled && !_host.HandleGrabView (me, this))
  988. {
  989. return false;
  990. }
  991. _host._handled = false;
  992. bool disabled;
  993. if (me.Flags == MouseFlags.Button1Clicked)
  994. {
  995. disabled = false;
  996. if (me.Position.Y < 0)
  997. {
  998. return me.Handled = true;
  999. }
  1000. if (me.Position.Y >= _barItems.Children.Length)
  1001. {
  1002. return me.Handled = true;
  1003. }
  1004. MenuItem item = _barItems.Children [me.Position.Y];
  1005. if (item is null || !item.IsEnabled ())
  1006. {
  1007. disabled = true;
  1008. }
  1009. if (disabled)
  1010. {
  1011. return me.Handled = true;
  1012. }
  1013. _currentChild = me.Position.Y;
  1014. RunSelected ();
  1015. return me.Handled = true;
  1016. }
  1017. if (me.Flags != MouseFlags.Button1Pressed
  1018. && me.Flags != MouseFlags.Button1DoubleClicked
  1019. && me.Flags != MouseFlags.Button1TripleClicked
  1020. && me.Flags != MouseFlags.ReportMousePosition
  1021. && !me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  1022. {
  1023. return false;
  1024. }
  1025. {
  1026. disabled = false;
  1027. if (me.Position.Y < 0 || me.Position.Y >= _barItems.Children.Length)
  1028. {
  1029. return me.Handled = true;
  1030. }
  1031. MenuItem item = _barItems.Children [me.Position.Y];
  1032. if (item is null)
  1033. {
  1034. return me.Handled = true;
  1035. }
  1036. if (item?.IsEnabled () != true)
  1037. {
  1038. disabled = true;
  1039. }
  1040. if (!disabled)
  1041. {
  1042. _currentChild = me.Position.Y;
  1043. }
  1044. if (_host.UseSubMenusSingleFrame || !CheckSubMenu ())
  1045. {
  1046. SetNeedsDisplay ();
  1047. SetParentSetNeedsDisplay ();
  1048. return me.Handled = true;
  1049. }
  1050. _host.OnMenuOpened ();
  1051. return me.Handled = true;
  1052. }
  1053. }
  1054. internal bool CheckSubMenu ()
  1055. {
  1056. if (_currentChild == -1 || _barItems.Children [_currentChild] is null)
  1057. {
  1058. return true;
  1059. }
  1060. MenuBarItem subMenu = _barItems.SubMenu (_barItems.Children [_currentChild]);
  1061. if (subMenu is { })
  1062. {
  1063. int pos = -1;
  1064. if (_host._openSubMenu is { })
  1065. {
  1066. pos = _host._openSubMenu.FindIndex (o => o?._barItems == subMenu);
  1067. }
  1068. if (pos == -1
  1069. && this != _host.openCurrentMenu
  1070. && subMenu.Children != _host.openCurrentMenu._barItems.Children
  1071. && !_host.CloseMenu (false, true))
  1072. {
  1073. return false;
  1074. }
  1075. _host.Activate (_host._selected, pos, subMenu);
  1076. }
  1077. else if (_host._openSubMenu?.Count == 0 || _host._openSubMenu?.Last ()._barItems.IsSubMenuOf (_barItems.Children [_currentChild]) == false)
  1078. {
  1079. return _host.CloseMenu (false, true);
  1080. }
  1081. else
  1082. {
  1083. SetNeedsDisplay ();
  1084. SetParentSetNeedsDisplay ();
  1085. }
  1086. return true;
  1087. }
  1088. private int GetSubMenuIndex (MenuBarItem subMenu)
  1089. {
  1090. int pos = -1;
  1091. if (Subviews.Count == 0)
  1092. {
  1093. return pos;
  1094. }
  1095. Menu v = null;
  1096. foreach (View menu in Subviews)
  1097. {
  1098. if (((Menu)menu)._barItems == subMenu)
  1099. {
  1100. v = (Menu)menu;
  1101. }
  1102. }
  1103. if (v is { })
  1104. {
  1105. pos = Subviews.IndexOf (v);
  1106. }
  1107. return pos;
  1108. }
  1109. protected override void Dispose (bool disposing)
  1110. {
  1111. if (Application.Current is { })
  1112. {
  1113. Application.Current.DrawContentComplete -= Current_DrawContentComplete;
  1114. Application.Current.SizeChanging -= Current_TerminalResized;
  1115. }
  1116. Application.MouseEvent -= Application_RootMouseEvent;
  1117. base.Dispose (disposing);
  1118. }
  1119. }