Menu.cs 41 KB

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