Menu.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  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 (a.X, a.Y);
  613. var me = new MouseEvent
  614. {
  615. X = boundsPoint.X,
  616. Y = boundsPoint.Y,
  617. Flags = a.Flags,
  618. ScreenPosition = new (a.X, a.Y),
  619. View = view
  620. };
  621. if (view.NewMouseEvent (me) == true || a.Flags == MouseFlags.Button1Pressed || a.Flags == MouseFlags.Button1Released)
  622. {
  623. a.Handled = true;
  624. }
  625. }
  626. internal Attribute DetermineColorSchemeFor (MenuItem item, int index)
  627. {
  628. if (item is null)
  629. {
  630. return GetNormalColor ();
  631. }
  632. if (index == _currentChild)
  633. {
  634. return GetFocusColor ();
  635. }
  636. return !item.IsEnabled () ? ColorScheme.Disabled : GetNormalColor ();
  637. }
  638. public override void OnDrawContent (Rectangle viewport)
  639. {
  640. if (_barItems.Children is null)
  641. {
  642. return;
  643. }
  644. Rectangle savedClip = Driver.Clip;
  645. Driver.Clip = new (0, 0, Driver.Cols, Driver.Rows);
  646. Driver.SetAttribute (GetNormalColor ());
  647. OnDrawAdornments ();
  648. OnRenderLineCanvas ();
  649. for (int i = Viewport.Y; i < _barItems.Children.Length; i++)
  650. {
  651. if (i < 0)
  652. {
  653. continue;
  654. }
  655. if (ViewportToScreen (Viewport).Y + i >= Driver.Rows)
  656. {
  657. break;
  658. }
  659. MenuItem item = _barItems.Children [i];
  660. Driver.SetAttribute (
  661. item is null ? GetNormalColor () :
  662. i == _currentChild ? GetFocusColor() : GetNormalColor ()
  663. );
  664. if (item is null && BorderStyle != LineStyle.None)
  665. {
  666. var s = ViewportToScreen (new (-1, i, 0, 0));
  667. Driver.Move (s.X, s.Y);
  668. Driver.AddRune (Glyphs.LeftTee);
  669. }
  670. else if (Frame.X < Driver.Cols)
  671. {
  672. Move (0, i);
  673. }
  674. Driver.SetAttribute (DetermineColorSchemeFor (item, i));
  675. for (int p = Viewport.X; p < Frame.Width - 2; p++)
  676. {
  677. // This - 2 is for the border
  678. if (p < 0)
  679. {
  680. continue;
  681. }
  682. if (ViewportToScreen (Viewport).X + p >= Driver.Cols)
  683. {
  684. break;
  685. }
  686. if (item is null)
  687. {
  688. Driver.AddRune (Glyphs.HLine);
  689. }
  690. else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { })
  691. {
  692. Driver.AddRune (Glyphs.LeftArrow);
  693. }
  694. // This `- 3` is left border + right border + one row in from right
  695. else if (p == Frame.Width - 3 && _barItems.SubMenu (_barItems.Children [i]) is { })
  696. {
  697. Driver.AddRune (Glyphs.RightArrow);
  698. }
  699. else
  700. {
  701. Driver.AddRune ((Rune)' ');
  702. }
  703. }
  704. if (item is null)
  705. {
  706. if (BorderStyle != LineStyle.None && SuperView?.Frame.Right - Frame.X > Frame.Width)
  707. {
  708. var s = ViewportToScreen (new (Frame.Width - 2, i, 0, 0));
  709. Driver.Move (s.X, s.Y);
  710. Driver.AddRune (Glyphs.RightTee);
  711. }
  712. continue;
  713. }
  714. string textToDraw = null;
  715. Rune nullCheckedChar = Glyphs.NullChecked;
  716. Rune checkChar = Glyphs.Selected;
  717. Rune uncheckedChar = Glyphs.UnSelected;
  718. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked))
  719. {
  720. checkChar = Glyphs.Checked;
  721. uncheckedChar = Glyphs.UnChecked;
  722. }
  723. // Support Checked even though CheckType wasn't set
  724. if (item.CheckType == MenuItemCheckStyle.Checked && item.Checked is null)
  725. {
  726. textToDraw = $"{nullCheckedChar} {item.Title}";
  727. }
  728. else if (item.Checked == true)
  729. {
  730. textToDraw = $"{checkChar} {item.Title}";
  731. }
  732. else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio))
  733. {
  734. textToDraw = $"{uncheckedChar} {item.Title}";
  735. }
  736. else
  737. {
  738. textToDraw = item.Title;
  739. }
  740. Rectangle screen = ViewportToScreen (new (new (0 , i), Size.Empty));
  741. if (screen.X < Driver.Cols)
  742. {
  743. Driver.Move (screen.X + 1, screen.Y);
  744. if (!item.IsEnabled ())
  745. {
  746. DrawHotString (textToDraw, ColorScheme.Disabled, ColorScheme.Disabled);
  747. }
  748. else if (i == 0 && _host.UseSubMenusSingleFrame && item.Parent.Parent is { })
  749. {
  750. var tf = new TextFormatter
  751. {
  752. AutoSize = true,
  753. Alignment = TextAlignment.Centered, HotKeySpecifier = MenuBar.HotKeySpecifier, Text = textToDraw
  754. };
  755. // The -3 is left/right border + one space (not sure what for)
  756. tf.Draw (
  757. ViewportToScreen (new (1, i, Frame.Width - 3, 1)),
  758. i == _currentChild ? GetFocusColor () : GetNormalColor (),
  759. i == _currentChild ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  760. SuperView?.ViewportToScreen (SuperView.Viewport) ?? Rectangle.Empty
  761. );
  762. }
  763. else
  764. {
  765. DrawHotString (
  766. textToDraw,
  767. i == _currentChild ? ColorScheme.HotFocus : ColorScheme.HotNormal,
  768. i == _currentChild ? GetFocusColor () : GetNormalColor ()
  769. );
  770. }
  771. // The help string
  772. int l = item.ShortcutTag.GetColumns () == 0
  773. ? item.Help.GetColumns ()
  774. : item.Help.GetColumns () + item.ShortcutTag.GetColumns () + 2;
  775. int col = Frame.Width - l - 3;
  776. screen = ViewportToScreen (new (new (col, i), Size.Empty));
  777. if (screen.X < Driver.Cols)
  778. {
  779. Driver.Move (screen.X, screen.Y);
  780. Driver.AddStr (item.Help);
  781. // The shortcut tag string
  782. if (!string.IsNullOrEmpty (item.ShortcutTag))
  783. {
  784. Driver.Move (screen.X + l - item.ShortcutTag.GetColumns (), screen.Y);
  785. Driver.AddStr (item.ShortcutTag);
  786. }
  787. }
  788. }
  789. }
  790. Driver.Clip = savedClip;
  791. // PositionCursor ();
  792. }
  793. private void Current_DrawContentComplete (object sender, DrawEventArgs e)
  794. {
  795. if (Visible)
  796. {
  797. OnDrawContent (Viewport);
  798. }
  799. }
  800. public override Point? PositionCursor ()
  801. {
  802. if (_host?.IsMenuOpen != false)
  803. {
  804. if (_barItems.IsTopLevel)
  805. {
  806. return _host?.PositionCursor ();
  807. }
  808. else
  809. {
  810. Move (2, 1 + _currentChild);
  811. return null;//new (2, 1 + _currentChild);
  812. }
  813. }
  814. return _host?.PositionCursor ();
  815. }
  816. public void Run (Action action)
  817. {
  818. if (action is null || _host is null)
  819. {
  820. return;
  821. }
  822. Application.UngrabMouse ();
  823. _host.CloseAllMenus ();
  824. Application.Refresh ();
  825. _host.Run (action);
  826. }
  827. public override bool OnLeave (View view) { return _host.OnLeave (view); }
  828. private void RunSelected ()
  829. {
  830. if (_barItems.IsTopLevel)
  831. {
  832. Run (_barItems.Action);
  833. }
  834. else
  835. {
  836. switch (_currentChild)
  837. {
  838. case > -1 when _barItems.Children [_currentChild].Action != null:
  839. Run (_barItems.Children [_currentChild].Action);
  840. break;
  841. case 0 when _host.UseSubMenusSingleFrame && _barItems.Children [_currentChild].Parent.Parent != null:
  842. _host.PreviousMenu (_barItems.Children [_currentChild].Parent.IsFromSubMenu, true);
  843. break;
  844. case > -1 when _barItems.SubMenu (_barItems.Children [_currentChild]) != null:
  845. CheckSubMenu ();
  846. break;
  847. }
  848. }
  849. }
  850. private void CloseAllMenus ()
  851. {
  852. Application.UngrabMouse ();
  853. _host.CloseAllMenus ();
  854. }
  855. private bool MoveDown ()
  856. {
  857. if (_barItems.IsTopLevel)
  858. {
  859. return true;
  860. }
  861. bool disabled;
  862. do
  863. {
  864. _currentChild++;
  865. if (_currentChild >= _barItems.Children.Length)
  866. {
  867. _currentChild = 0;
  868. }
  869. if (this != _host.openCurrentMenu && _barItems.Children [_currentChild]?.IsFromSubMenu == true && _host._selectedSub > -1)
  870. {
  871. _host.PreviousMenu (true);
  872. _host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild);
  873. _host.openCurrentMenu = this;
  874. }
  875. MenuItem item = _barItems.Children [_currentChild];
  876. if (item?.IsEnabled () != true)
  877. {
  878. disabled = true;
  879. }
  880. else
  881. {
  882. disabled = false;
  883. }
  884. if (!_host.UseSubMenusSingleFrame
  885. && _host.UseKeysUpDownAsKeysLeftRight
  886. && _barItems.SubMenu (_barItems.Children [_currentChild]) != null
  887. && !disabled
  888. && _host.IsMenuOpen)
  889. {
  890. if (!CheckSubMenu ())
  891. {
  892. return false;
  893. }
  894. break;
  895. }
  896. if (!_host.IsMenuOpen)
  897. {
  898. _host.OpenMenu (_host._selected);
  899. }
  900. }
  901. while (_barItems.Children [_currentChild] is null || disabled);
  902. SetNeedsDisplay ();
  903. SetParentSetNeedsDisplay ();
  904. if (!_host.UseSubMenusSingleFrame)
  905. {
  906. _host.OnMenuOpened ();
  907. }
  908. return true;
  909. }
  910. private bool MoveUp ()
  911. {
  912. if (_barItems.IsTopLevel || _currentChild == -1)
  913. {
  914. return true;
  915. }
  916. bool disabled;
  917. do
  918. {
  919. _currentChild--;
  920. if (_host.UseKeysUpDownAsKeysLeftRight && !_host.UseSubMenusSingleFrame)
  921. {
  922. if ((_currentChild == -1 || this != _host.openCurrentMenu)
  923. && _barItems.Children [_currentChild + 1].IsFromSubMenu
  924. && _host._selectedSub > -1)
  925. {
  926. _currentChild++;
  927. _host.PreviousMenu (true);
  928. if (_currentChild > 0)
  929. {
  930. _currentChild--;
  931. _host.openCurrentMenu = this;
  932. }
  933. break;
  934. }
  935. }
  936. if (_currentChild < 0)
  937. {
  938. _currentChild = _barItems.Children.Length - 1;
  939. }
  940. if (!_host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild, false))
  941. {
  942. _currentChild = 0;
  943. if (!_host.SelectEnabledItem (_barItems.Children, _currentChild, out _currentChild) && !_host.CloseMenu (false))
  944. {
  945. return false;
  946. }
  947. break;
  948. }
  949. MenuItem item = _barItems.Children [_currentChild];
  950. disabled = item?.IsEnabled () != true;
  951. if (_host.UseSubMenusSingleFrame
  952. || !_host.UseKeysUpDownAsKeysLeftRight
  953. || _barItems.SubMenu (_barItems.Children [_currentChild]) == null
  954. || disabled
  955. || !_host.IsMenuOpen)
  956. {
  957. continue;
  958. }
  959. if (!CheckSubMenu ())
  960. {
  961. return false;
  962. }
  963. break;
  964. }
  965. while (_barItems.Children [_currentChild] is null || disabled);
  966. SetNeedsDisplay ();
  967. SetParentSetNeedsDisplay ();
  968. if (!_host.UseSubMenusSingleFrame)
  969. {
  970. _host.OnMenuOpened ();
  971. }
  972. return true;
  973. }
  974. private void SetParentSetNeedsDisplay ()
  975. {
  976. if (_host._openSubMenu is { })
  977. {
  978. foreach (Menu menu in _host._openSubMenu)
  979. {
  980. menu.SetNeedsDisplay ();
  981. }
  982. }
  983. _host?._openMenu?.SetNeedsDisplay ();
  984. _host?.SetNeedsDisplay ();
  985. }
  986. protected internal override bool OnMouseEvent (MouseEvent me)
  987. {
  988. if (!_host._handled && !_host.HandleGrabView (me, this))
  989. {
  990. return false;
  991. }
  992. _host._handled = false;
  993. bool disabled;
  994. if (me.Flags == MouseFlags.Button1Clicked)
  995. {
  996. disabled = false;
  997. if (me.Y < 0)
  998. {
  999. return me.Handled = true;
  1000. }
  1001. if (me.Y >= _barItems.Children.Length)
  1002. {
  1003. return me.Handled = true;
  1004. }
  1005. MenuItem item = _barItems.Children [me.Y];
  1006. if (item is null || !item.IsEnabled ())
  1007. {
  1008. disabled = true;
  1009. }
  1010. if (disabled)
  1011. {
  1012. return me.Handled = true;
  1013. }
  1014. _currentChild = me.Y;
  1015. RunSelected ();
  1016. return me.Handled = true;
  1017. }
  1018. if (me.Flags != MouseFlags.Button1Pressed
  1019. && me.Flags != MouseFlags.Button1DoubleClicked
  1020. && me.Flags != MouseFlags.Button1TripleClicked
  1021. && me.Flags != MouseFlags.ReportMousePosition
  1022. && !me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  1023. {
  1024. return false;
  1025. }
  1026. {
  1027. disabled = false;
  1028. if (me.Y < 0 || me.Y >= _barItems.Children.Length)
  1029. {
  1030. return me.Handled = true;
  1031. }
  1032. MenuItem item = _barItems.Children [me.Y];
  1033. if (item is null)
  1034. {
  1035. return me.Handled = true;
  1036. }
  1037. if (item?.IsEnabled () != true)
  1038. {
  1039. disabled = true;
  1040. }
  1041. if (!disabled)
  1042. {
  1043. _currentChild = me.Y;
  1044. }
  1045. if (_host.UseSubMenusSingleFrame || !CheckSubMenu ())
  1046. {
  1047. SetNeedsDisplay ();
  1048. SetParentSetNeedsDisplay ();
  1049. return me.Handled = true;
  1050. }
  1051. _host.OnMenuOpened ();
  1052. return me.Handled = true;
  1053. }
  1054. }
  1055. internal bool CheckSubMenu ()
  1056. {
  1057. if (_currentChild == -1 || _barItems.Children [_currentChild] is null)
  1058. {
  1059. return true;
  1060. }
  1061. MenuBarItem subMenu = _barItems.SubMenu (_barItems.Children [_currentChild]);
  1062. if (subMenu is { })
  1063. {
  1064. int pos = -1;
  1065. if (_host._openSubMenu is { })
  1066. {
  1067. pos = _host._openSubMenu.FindIndex (o => o?._barItems == subMenu);
  1068. }
  1069. if (pos == -1
  1070. && this != _host.openCurrentMenu
  1071. && subMenu.Children != _host.openCurrentMenu._barItems.Children
  1072. && !_host.CloseMenu (false, true))
  1073. {
  1074. return false;
  1075. }
  1076. _host.Activate (_host._selected, pos, subMenu);
  1077. }
  1078. else if (_host._openSubMenu?.Count == 0 || _host._openSubMenu?.Last ()._barItems.IsSubMenuOf (_barItems.Children [_currentChild]) == false)
  1079. {
  1080. return _host.CloseMenu (false, true);
  1081. }
  1082. else
  1083. {
  1084. SetNeedsDisplay ();
  1085. SetParentSetNeedsDisplay ();
  1086. }
  1087. return true;
  1088. }
  1089. private int GetSubMenuIndex (MenuBarItem subMenu)
  1090. {
  1091. int pos = -1;
  1092. if (Subviews.Count == 0)
  1093. {
  1094. return pos;
  1095. }
  1096. Menu v = null;
  1097. foreach (View menu in Subviews)
  1098. {
  1099. if (((Menu)menu)._barItems == subMenu)
  1100. {
  1101. v = (Menu)menu;
  1102. }
  1103. }
  1104. if (v is { })
  1105. {
  1106. pos = Subviews.IndexOf (v);
  1107. }
  1108. return pos;
  1109. }
  1110. /// <inheritdoc/>
  1111. public override bool OnEnter (View view)
  1112. {
  1113. Application.Driver.SetCursorVisibility (CursorVisibility.Invisible);
  1114. return base.OnEnter (view);
  1115. }
  1116. protected override void Dispose (bool disposing)
  1117. {
  1118. if (Application.Current is { })
  1119. {
  1120. Application.Current.DrawContentComplete -= Current_DrawContentComplete;
  1121. Application.Current.SizeChanging -= Current_TerminalResized;
  1122. }
  1123. Application.MouseEvent -= Application_RootMouseEvent;
  1124. base.Dispose (disposing);
  1125. }
  1126. }