Menu.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. #nullable enable
  2. namespace Terminal.Gui;
  3. /// <summary>
  4. /// An internal class used to represent a menu pop-up menu. Created and managed by <see cref="MenuBar"/> and
  5. /// <see cref="ContextMenu"/>.
  6. /// </summary>
  7. internal sealed class Menu : View
  8. {
  9. public Menu ()
  10. {
  11. if (Application.Top is { })
  12. {
  13. Application.Top.DrawComplete += Top_DrawComplete;
  14. Application.Top.SizeChanging += Current_TerminalResized;
  15. }
  16. Application.MouseEvent += Application_RootMouseEvent;
  17. Application.UnGrabbedMouse += Application_UnGrabbedMouse;
  18. // Things this view knows how to do
  19. AddCommand (Command.Up, () => MoveUp ());
  20. AddCommand (Command.Down, () => MoveDown ());
  21. AddCommand (
  22. Command.Left,
  23. () =>
  24. {
  25. _host!.PreviousMenu (true);
  26. return true;
  27. }
  28. );
  29. AddCommand (
  30. Command.Cancel,
  31. () =>
  32. {
  33. CloseAllMenus ();
  34. return true;
  35. }
  36. );
  37. AddCommand (
  38. Command.Accept,
  39. () =>
  40. {
  41. RunSelected ();
  42. return true;
  43. }
  44. );
  45. AddCommand (
  46. Command.Select,
  47. ctx =>
  48. {
  49. if (ctx is not CommandContext<KeyBinding> keyCommandContext)
  50. {
  51. return false;
  52. }
  53. return _host?.SelectItem ((keyCommandContext.Binding.Data as MenuItem)!);
  54. });
  55. AddCommand (
  56. Command.Toggle,
  57. ctx =>
  58. {
  59. if (ctx is not CommandContext<KeyBinding> keyCommandContext)
  60. {
  61. return false;
  62. }
  63. return ExpandCollapse ((keyCommandContext.Binding.Data as MenuItem)!);
  64. });
  65. AddCommand (
  66. Command.HotKey,
  67. ctx =>
  68. {
  69. if (ctx is not CommandContext<KeyBinding> keyCommandContext)
  70. {
  71. return false;
  72. }
  73. return _host?.SelectItem ((keyCommandContext.Binding.Data as MenuItem)!);
  74. });
  75. // Default key bindings for this view
  76. KeyBindings.Add (Key.CursorUp, Command.Up);
  77. KeyBindings.Add (Key.CursorDown, Command.Down);
  78. KeyBindings.Add (Key.CursorLeft, Command.Left);
  79. KeyBindings.Add (Key.CursorRight, Command.Right);
  80. KeyBindings.Add (Key.Esc, Command.Cancel);
  81. }
  82. internal int _currentChild;
  83. internal View? _previousSubFocused;
  84. private readonly MenuBarItem? _barItems;
  85. private readonly MenuBar _host;
  86. public override void BeginInit ()
  87. {
  88. base.BeginInit ();
  89. Rectangle frame = MakeFrame (Frame.X, Frame.Y, _barItems!.Children!, Parent);
  90. if (Frame.X != frame.X)
  91. {
  92. X = frame.X;
  93. }
  94. if (Frame.Y != frame.Y)
  95. {
  96. Y = frame.Y;
  97. }
  98. Width = frame.Width;
  99. Height = frame.Height;
  100. if (_barItems.Children is { })
  101. {
  102. foreach (MenuItem? menuItem in _barItems.Children)
  103. {
  104. if (menuItem is { })
  105. {
  106. menuItem._menuBar = Host;
  107. if (menuItem.ShortcutKey != Key.Empty)
  108. {
  109. KeyBinding keyBinding = new ([Command.Select], this, data: menuItem);
  110. // Remove an existent ShortcutKey
  111. menuItem._menuBar.HotKeyBindings.Remove (menuItem.ShortcutKey!);
  112. menuItem._menuBar.HotKeyBindings.Add (menuItem.ShortcutKey!, keyBinding);
  113. }
  114. }
  115. }
  116. }
  117. if (_barItems is { IsTopLevel: true })
  118. {
  119. // This is a standalone MenuItem on a MenuBar
  120. ColorScheme = _host.ColorScheme;
  121. CanFocus = true;
  122. }
  123. else
  124. {
  125. _currentChild = -1;
  126. for (var i = 0; i < _barItems.Children?.Length; i++)
  127. {
  128. if (_barItems.Children [i]?.IsEnabled () == true)
  129. {
  130. _currentChild = i;
  131. break;
  132. }
  133. }
  134. ColorScheme = _host.ColorScheme;
  135. CanFocus = true;
  136. WantMousePositionReports = _host.WantMousePositionReports;
  137. }
  138. BorderStyle = _host.MenusBorderStyle;
  139. AddCommand (
  140. Command.Right,
  141. () =>
  142. {
  143. _host.NextMenu (
  144. !_barItems.IsTopLevel
  145. || (_barItems.Children is { Length: > 0 }
  146. && _currentChild > -1
  147. && _currentChild < _barItems.Children.Length
  148. && _barItems.Children [_currentChild]!.IsFromSubMenu),
  149. _barItems.Children is { Length: > 0 }
  150. && _currentChild > -1
  151. && _host.UseSubMenusSingleFrame
  152. && _barItems.SubMenu (
  153. _barItems.Children [_currentChild]!
  154. )
  155. != null!
  156. );
  157. return true;
  158. }
  159. );
  160. AddKeyBindingsHotKey (_barItems);
  161. }
  162. public override Point? PositionCursor ()
  163. {
  164. if (_host.IsMenuOpen)
  165. {
  166. if (_barItems!.IsTopLevel)
  167. {
  168. return _host.PositionCursor ();
  169. }
  170. Move (2, 1 + _currentChild);
  171. return null; // Don't show the cursor
  172. }
  173. return _host.PositionCursor ();
  174. }
  175. public void Run (Action? action)
  176. {
  177. if (action is null)
  178. {
  179. return;
  180. }
  181. Application.UngrabMouse ();
  182. _host.CloseAllMenus ();
  183. Application.LayoutAndDraw (true);
  184. _host.Run (action);
  185. }
  186. protected override void Dispose (bool disposing)
  187. {
  188. RemoveKeyBindingsHotKey (_barItems);
  189. if (Application.Top is { })
  190. {
  191. Application.Top.DrawComplete -= Top_DrawComplete;
  192. Application.Top.SizeChanging -= Current_TerminalResized;
  193. }
  194. Application.MouseEvent -= Application_RootMouseEvent;
  195. Application.UnGrabbedMouse -= Application_UnGrabbedMouse;
  196. base.Dispose (disposing);
  197. }
  198. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? view)
  199. {
  200. if (!newHasFocus)
  201. {
  202. _host.LostFocus (previousFocusedView!);
  203. }
  204. }
  205. /// <inheritdoc/>
  206. protected override bool OnKeyDownNotHandled (Key keyEvent)
  207. {
  208. // We didn't handle the key, pass it on to host
  209. bool? handled = null;
  210. return _host.InvokeCommandsBoundToHotKey (keyEvent, ref handled) == true;
  211. }
  212. protected override bool OnMouseEvent (MouseEventArgs me)
  213. {
  214. if (!_host._handled && !_host.HandleGrabView (me, this))
  215. {
  216. return false;
  217. }
  218. _host._handled = false;
  219. bool disabled;
  220. if (me.Flags == MouseFlags.Button1Clicked)
  221. {
  222. disabled = false;
  223. if (me.Position.Y < 0)
  224. {
  225. return me.Handled = true;
  226. }
  227. if (me.Position.Y >= _barItems!.Children!.Length)
  228. {
  229. return me.Handled = true;
  230. }
  231. MenuItem item = _barItems.Children [me.Position.Y]!;
  232. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  233. if (item is null || !item.IsEnabled ())
  234. {
  235. disabled = true;
  236. }
  237. if (disabled)
  238. {
  239. return me.Handled = true;
  240. }
  241. _currentChild = me.Position.Y;
  242. RunSelected ();
  243. return me.Handled = true;
  244. }
  245. if (me.Flags != MouseFlags.Button1Pressed
  246. && me.Flags != MouseFlags.Button1DoubleClicked
  247. && me.Flags != MouseFlags.Button1TripleClicked
  248. && me.Flags != MouseFlags.ReportMousePosition
  249. && !me.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  250. {
  251. return false;
  252. }
  253. {
  254. disabled = false;
  255. if (me.Position.Y < 0 || me.Position.Y >= _barItems!.Children!.Length)
  256. {
  257. return me.Handled = true;
  258. }
  259. MenuItem item = _barItems.Children [me.Position.Y]!;
  260. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  261. if (item is null)
  262. {
  263. return me.Handled = true;
  264. }
  265. if (item.IsEnabled () != true)
  266. {
  267. disabled = true;
  268. }
  269. if (!disabled)
  270. {
  271. _currentChild = me.Position.Y;
  272. }
  273. if (_host.UseSubMenusSingleFrame || !CheckSubMenu ())
  274. {
  275. SetNeedsDraw ();
  276. SetParentSetNeedsDisplay ();
  277. return me.Handled = true;
  278. }
  279. _host.OnMenuOpened ();
  280. return me.Handled = true;
  281. }
  282. }
  283. /// <inheritdoc/>
  284. protected override void OnVisibleChanged ()
  285. {
  286. base.OnVisibleChanged ();
  287. if (Visible)
  288. {
  289. Application.MouseEvent += Application_RootMouseEvent;
  290. }
  291. else
  292. {
  293. Application.MouseEvent -= Application_RootMouseEvent;
  294. }
  295. }
  296. internal required MenuBarItem? BarItems
  297. {
  298. get => _barItems!;
  299. init
  300. {
  301. ArgumentNullException.ThrowIfNull (value);
  302. _barItems = value;
  303. // Debugging aid so ToString() is helpful
  304. Text = _barItems.Title;
  305. }
  306. }
  307. internal bool CheckSubMenu ()
  308. {
  309. if (_currentChild == -1 || _barItems?.Children? [_currentChild] is null)
  310. {
  311. return true;
  312. }
  313. MenuBarItem? subMenu = _barItems.SubMenu (_barItems.Children [_currentChild]!);
  314. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  315. if (subMenu is { })
  316. {
  317. int pos = -1;
  318. if (_host._openSubMenu is { })
  319. {
  320. pos = _host._openSubMenu.FindIndex (o => o._barItems == subMenu);
  321. }
  322. if (pos == -1
  323. && this != _host.OpenCurrentMenu
  324. && subMenu.Children != _host.OpenCurrentMenu!._barItems!.Children
  325. && !_host.CloseMenu (false, true))
  326. {
  327. return false;
  328. }
  329. _host.Activate (_host._selected, pos, subMenu);
  330. }
  331. else if (_host._openSubMenu?.Count == 0 || _host._openSubMenu?.Last ()._barItems!.IsSubMenuOf (_barItems.Children [_currentChild]!) == false)
  332. {
  333. return _host.CloseMenu (false, true);
  334. }
  335. else
  336. {
  337. SetNeedsDraw ();
  338. SetParentSetNeedsDisplay ();
  339. }
  340. return true;
  341. }
  342. internal Attribute DetermineColorSchemeFor (MenuItem? item, int index)
  343. {
  344. if (item is null)
  345. {
  346. return GetNormalColor ();
  347. }
  348. if (index == _currentChild)
  349. {
  350. return GetFocusColor ();
  351. }
  352. return !item.IsEnabled () ? ColorScheme!.Disabled : GetNormalColor ();
  353. }
  354. internal required MenuBar Host
  355. {
  356. get => _host;
  357. init
  358. {
  359. ArgumentNullException.ThrowIfNull (value);
  360. _host = value;
  361. }
  362. }
  363. internal static Rectangle MakeFrame (int x, int y, MenuItem? []? items, Menu? parent = null)
  364. {
  365. if (items is null || items.Length == 0)
  366. {
  367. return Rectangle.Empty;
  368. }
  369. int minX = x;
  370. int minY = y;
  371. const int borderOffset = 2; // This 2 is for the space around
  372. int maxW = (items.Max (z => z?.Width) ?? 0) + borderOffset;
  373. int maxH = items.Length + borderOffset;
  374. if (parent is { } && x + maxW > Driver.Cols)
  375. {
  376. minX = Math.Max (parent.Frame.Right - parent.Frame.Width - maxW, 0);
  377. }
  378. if (y + maxH > Driver.Rows)
  379. {
  380. minY = Math.Max (Driver.Rows - maxH, 0);
  381. }
  382. return new (minX, minY, maxW, maxH);
  383. }
  384. internal Menu? Parent { get; init; }
  385. private void AddKeyBindingsHotKey (MenuBarItem? menuBarItem)
  386. {
  387. if (menuBarItem is null || menuBarItem.Children is null)
  388. {
  389. return;
  390. }
  391. IEnumerable<MenuItem> menuItems = menuBarItem.Children.Where (m => m is { })!;
  392. foreach (MenuItem menuItem in menuItems)
  393. {
  394. KeyBinding keyBinding = new ([Command.Toggle], this, data: menuItem);
  395. if (menuItem.HotKey != Key.Empty)
  396. {
  397. HotKeyBindings.Remove (menuItem.HotKey!);
  398. HotKeyBindings.Add (menuItem.HotKey!, keyBinding);
  399. HotKeyBindings.Remove (menuItem.HotKey!.WithAlt);
  400. HotKeyBindings.Add (menuItem.HotKey.WithAlt, keyBinding);
  401. }
  402. }
  403. }
  404. private void Application_RootMouseEvent (object? sender, MouseEventArgs a)
  405. {
  406. if (a.View is { } and (MenuBar or not Menu))
  407. {
  408. return;
  409. }
  410. if (!Visible)
  411. {
  412. throw new InvalidOperationException ("This shouldn't running on a invisible menu!");
  413. }
  414. View view = a.View ?? this;
  415. Point boundsPoint = view.ScreenToViewport (new (a.Position.X, a.Position.Y));
  416. var me = new MouseEventArgs
  417. {
  418. Position = boundsPoint,
  419. Flags = a.Flags,
  420. ScreenPosition = a.Position,
  421. View = view
  422. };
  423. if (view.NewMouseEvent (me) == true || a.Flags == MouseFlags.Button1Pressed || a.Flags == MouseFlags.Button1Released)
  424. {
  425. a.Handled = true;
  426. }
  427. }
  428. private void Application_UnGrabbedMouse (object? sender, ViewEventArgs a)
  429. {
  430. if (_host.IsMenuOpen)
  431. {
  432. _host.CloseAllMenus ();
  433. }
  434. }
  435. private void CloseAllMenus ()
  436. {
  437. Application.UngrabMouse ();
  438. _host.CloseAllMenus ();
  439. }
  440. private void Current_TerminalResized (object? sender, SizeChangedEventArgs e)
  441. {
  442. if (_host.IsMenuOpen)
  443. {
  444. _host.CloseAllMenus ();
  445. }
  446. }
  447. /// <summary>Called when a key bound to Command.ToggleExpandCollapse is pressed. This means a hot key was pressed.</summary>
  448. /// <returns></returns>
  449. private bool ExpandCollapse (MenuItem? menuItem)
  450. {
  451. if (!IsInitialized || !Visible)
  452. {
  453. return true;
  454. }
  455. for (var c = 0; c < _barItems!.Children!.Length; c++)
  456. {
  457. if (_barItems.Children [c] == menuItem)
  458. {
  459. _currentChild = c;
  460. break;
  461. }
  462. }
  463. if (menuItem is { })
  464. {
  465. var m = menuItem as MenuBarItem;
  466. if (m?.Children?.Length > 0)
  467. {
  468. MenuItem? item = _barItems.Children [_currentChild];
  469. if (item is null)
  470. {
  471. return true;
  472. }
  473. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  474. bool disabled = item is null || !item.IsEnabled ();
  475. if (!disabled && (_host.UseSubMenusSingleFrame || !CheckSubMenu ()))
  476. {
  477. SetNeedsDraw ();
  478. SetParentSetNeedsDisplay ();
  479. return true;
  480. }
  481. if (!disabled)
  482. {
  483. _host.OnMenuOpened ();
  484. }
  485. }
  486. else
  487. {
  488. _host.SelectItem (menuItem);
  489. }
  490. }
  491. else if (_host.IsMenuOpen)
  492. {
  493. _host.CloseAllMenus ();
  494. }
  495. else
  496. {
  497. _host.OpenMenu ();
  498. }
  499. return true;
  500. }
  501. private bool MoveDown ()
  502. {
  503. if (_barItems!.IsTopLevel)
  504. {
  505. return true;
  506. }
  507. bool disabled;
  508. do
  509. {
  510. _currentChild++;
  511. if (_currentChild >= _barItems?.Children?.Length)
  512. {
  513. _currentChild = 0;
  514. }
  515. if (this != _host.OpenCurrentMenu && _barItems?.Children? [_currentChild]?.IsFromSubMenu == true && _host._selectedSub > -1)
  516. {
  517. _host.PreviousMenu (true);
  518. _host.SelectEnabledItem (_barItems.Children!, _currentChild, out _currentChild);
  519. _host.OpenCurrentMenu = this;
  520. }
  521. MenuItem? item = _barItems?.Children? [_currentChild];
  522. if (item?.IsEnabled () != true)
  523. {
  524. disabled = true;
  525. }
  526. else
  527. {
  528. disabled = false;
  529. }
  530. if (_host is { UseSubMenusSingleFrame: false, UseKeysUpDownAsKeysLeftRight: true }
  531. && _barItems?.SubMenu (_barItems?.Children? [_currentChild]!) != null
  532. && !disabled
  533. && _host.IsMenuOpen)
  534. {
  535. if (!CheckSubMenu ())
  536. {
  537. return false;
  538. }
  539. break;
  540. }
  541. if (!_host.IsMenuOpen)
  542. {
  543. _host.OpenMenu (_host._selected);
  544. }
  545. }
  546. while (_barItems?.Children? [_currentChild] is null || disabled);
  547. SetNeedsDraw ();
  548. SetParentSetNeedsDisplay ();
  549. if (!_host.UseSubMenusSingleFrame)
  550. {
  551. _host.OnMenuOpened ();
  552. }
  553. return true;
  554. }
  555. private bool MoveUp ()
  556. {
  557. if (_barItems!.IsTopLevel || _currentChild == -1)
  558. {
  559. return true;
  560. }
  561. bool disabled;
  562. do
  563. {
  564. _currentChild--;
  565. if (_host.UseKeysUpDownAsKeysLeftRight && !_host.UseSubMenusSingleFrame)
  566. {
  567. if ((_currentChild == -1 || this != _host.OpenCurrentMenu)
  568. && _barItems.Children! [_currentChild + 1]!.IsFromSubMenu
  569. && _host._selectedSub > -1)
  570. {
  571. _currentChild++;
  572. _host.PreviousMenu (true);
  573. if (_currentChild > 0)
  574. {
  575. _currentChild--;
  576. _host.OpenCurrentMenu = this;
  577. }
  578. break;
  579. }
  580. }
  581. if (_currentChild < 0)
  582. {
  583. _currentChild = _barItems.Children!.Length - 1;
  584. }
  585. if (!_host.SelectEnabledItem (_barItems.Children!, _currentChild, out _currentChild, false))
  586. {
  587. _currentChild = 0;
  588. if (!_host.SelectEnabledItem (_barItems.Children!, _currentChild, out _currentChild) && !_host.CloseMenu ())
  589. {
  590. return false;
  591. }
  592. break;
  593. }
  594. MenuItem item = _barItems.Children! [_currentChild]!;
  595. disabled = item.IsEnabled () != true;
  596. if (_host.UseSubMenusSingleFrame
  597. || !_host.UseKeysUpDownAsKeysLeftRight
  598. || _barItems.SubMenu (_barItems.Children [_currentChild]!) == null!
  599. || disabled
  600. || !_host.IsMenuOpen)
  601. {
  602. continue;
  603. }
  604. if (!CheckSubMenu ())
  605. {
  606. return false;
  607. }
  608. break;
  609. }
  610. while (_barItems.Children [_currentChild] is null || disabled);
  611. SetNeedsDraw ();
  612. SetParentSetNeedsDisplay ();
  613. if (!_host.UseSubMenusSingleFrame)
  614. {
  615. _host.OnMenuOpened ();
  616. }
  617. return true;
  618. }
  619. private void RemoveKeyBindingsHotKey (MenuBarItem? menuBarItem)
  620. {
  621. if (menuBarItem is null || menuBarItem.Children is null)
  622. {
  623. return;
  624. }
  625. IEnumerable<MenuItem> menuItems = menuBarItem.Children.Where (m => m is { })!;
  626. foreach (MenuItem menuItem in menuItems)
  627. {
  628. if (menuItem.HotKey != Key.Empty)
  629. {
  630. KeyBindings.Remove (menuItem.HotKey!);
  631. KeyBindings.Remove (menuItem.HotKey!.WithAlt);
  632. }
  633. }
  634. }
  635. private void RunSelected ()
  636. {
  637. if (_barItems!.IsTopLevel)
  638. {
  639. Run (_barItems.Action);
  640. }
  641. else
  642. {
  643. switch (_currentChild)
  644. {
  645. case > -1 when _barItems.Children! [_currentChild]!.Action != null!:
  646. Run (_barItems.Children [_currentChild]?.Action);
  647. break;
  648. case 0 when _host.UseSubMenusSingleFrame && _barItems.Children [_currentChild]?.Parent!.Parent != null:
  649. _host.PreviousMenu (_barItems.Children [_currentChild]!.Parent!.IsFromSubMenu, true);
  650. break;
  651. case > -1 when _barItems.SubMenu (_barItems.Children [_currentChild]) != null!:
  652. CheckSubMenu ();
  653. break;
  654. }
  655. }
  656. }
  657. private void SetParentSetNeedsDisplay ()
  658. {
  659. if (_host._openSubMenu is { })
  660. {
  661. foreach (Menu menu in _host._openSubMenu)
  662. {
  663. menu.SetNeedsDraw ();
  664. }
  665. }
  666. _host._openMenu?.SetNeedsDraw ();
  667. _host.SetNeedsDraw ();
  668. }
  669. // By doing this we draw last, over everything else.
  670. private void Top_DrawComplete (object? sender, DrawEventArgs e)
  671. {
  672. if (!Visible)
  673. {
  674. return;
  675. }
  676. if (_barItems!.Children is null)
  677. {
  678. return;
  679. }
  680. DrawAdornments ();
  681. RenderLineCanvas ();
  682. // BUGBUG: Views should not change the clip. Doing so is an indcation of poor design or a bug in the framework.
  683. Region? savedClip = SetClipToScreen ();
  684. SetAttribute (GetNormalColor ());
  685. for (int i = Viewport.Y; i < _barItems!.Children.Length; i++)
  686. {
  687. if (i < 0)
  688. {
  689. continue;
  690. }
  691. if (ViewportToScreen (Viewport).Y + i >= Driver.Rows)
  692. {
  693. break;
  694. }
  695. MenuItem? item = _barItems.Children [i];
  696. SetAttribute (
  697. // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
  698. item is null ? GetNormalColor () :
  699. i == _currentChild ? GetFocusColor () : GetNormalColor ()
  700. );
  701. if (item is null && BorderStyle != LineStyle.None)
  702. {
  703. Point s = ViewportToScreen (new Point (-1, i));
  704. Driver.Move (s.X, s.Y);
  705. Driver.AddRune (Glyphs.LeftTee);
  706. }
  707. else if (Frame.X < Driver.Cols)
  708. {
  709. Move (0, i);
  710. }
  711. SetAttribute (DetermineColorSchemeFor (item, i));
  712. for (int p = Viewport.X; p < Frame.Width - 2; p++)
  713. {
  714. // This - 2 is for the border
  715. if (p < 0)
  716. {
  717. continue;
  718. }
  719. if (ViewportToScreen (Viewport).X + p >= Driver.Cols)
  720. {
  721. break;
  722. }
  723. if (item is null)
  724. {
  725. Driver.AddRune (Glyphs.HLine);
  726. }
  727. else if (i == 0 && p == 0 && _host.UseSubMenusSingleFrame && item.Parent!.Parent is { })
  728. {
  729. Driver.AddRune (Glyphs.LeftArrow);
  730. }
  731. // This `- 3` is left border + right border + one row in from right
  732. else if (p == Frame.Width - 3 && _barItems?.SubMenu (_barItems.Children [i]!) is { })
  733. {
  734. Driver.AddRune (Glyphs.RightArrow);
  735. }
  736. else
  737. {
  738. Driver.AddRune ((Rune)' ');
  739. }
  740. }
  741. if (item is null)
  742. {
  743. if (BorderStyle != LineStyle.None && SuperView?.Frame.Right - Frame.X > Frame.Width)
  744. {
  745. Point s = ViewportToScreen (new Point (Frame.Width - 2, i));
  746. Driver.Move (s.X, s.Y);
  747. Driver.AddRune (Glyphs.RightTee);
  748. }
  749. continue;
  750. }
  751. string? textToDraw;
  752. Rune nullCheckedChar = Glyphs.CheckStateNone;
  753. Rune checkChar = Glyphs.Selected;
  754. Rune uncheckedChar = Glyphs.UnSelected;
  755. if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked))
  756. {
  757. checkChar = Glyphs.CheckStateChecked;
  758. uncheckedChar = Glyphs.CheckStateUnChecked;
  759. }
  760. // Support Checked even though CheckType wasn't set
  761. if (item is { CheckType: MenuItemCheckStyle.Checked, Checked: null })
  762. {
  763. textToDraw = $"{nullCheckedChar} {item.Title}";
  764. }
  765. else if (item.Checked == true)
  766. {
  767. textToDraw = $"{checkChar} {item.Title}";
  768. }
  769. else if (item.CheckType.HasFlag (MenuItemCheckStyle.Checked) || item.CheckType.HasFlag (MenuItemCheckStyle.Radio))
  770. {
  771. textToDraw = $"{uncheckedChar} {item.Title}";
  772. }
  773. else
  774. {
  775. textToDraw = item.Title;
  776. }
  777. Point screen = ViewportToScreen (new Point (0, i));
  778. if (screen.X < Driver.Cols)
  779. {
  780. Driver.Move (screen.X + 1, screen.Y);
  781. if (!item.IsEnabled ())
  782. {
  783. DrawHotString (textToDraw, ColorScheme!.Disabled, ColorScheme.Disabled);
  784. }
  785. else if (i == 0 && _host.UseSubMenusSingleFrame && item.Parent!.Parent is { })
  786. {
  787. var tf = new TextFormatter
  788. {
  789. ConstrainToWidth = Frame.Width - 3,
  790. ConstrainToHeight = 1,
  791. Alignment = Alignment.Center, HotKeySpecifier = MenuBar.HotKeySpecifier, Text = textToDraw
  792. };
  793. // The -3 is left/right border + one space (not sure what for)
  794. tf.Draw (
  795. ViewportToScreen (new Rectangle (1, i, Frame.Width - 3, 1)),
  796. i == _currentChild ? GetFocusColor () : GetNormalColor (),
  797. i == _currentChild ? ColorScheme!.HotFocus : ColorScheme!.HotNormal,
  798. SuperView?.ViewportToScreen (SuperView.Viewport) ?? Rectangle.Empty
  799. );
  800. }
  801. else
  802. {
  803. DrawHotString (
  804. textToDraw,
  805. i == _currentChild ? ColorScheme!.HotFocus : ColorScheme!.HotNormal,
  806. i == _currentChild ? GetFocusColor () : GetNormalColor ()
  807. );
  808. }
  809. // The help string
  810. int l = item.ShortcutTag.GetColumns () == 0
  811. ? item.Help.GetColumns ()
  812. : item.Help.GetColumns () + item.ShortcutTag.GetColumns () + 2;
  813. int col = Frame.Width - l - 3;
  814. screen = ViewportToScreen (new Point (col, i));
  815. if (screen.X < Driver.Cols)
  816. {
  817. Driver.Move (screen.X, screen.Y);
  818. Driver.AddStr (item.Help);
  819. // The shortcut tag string
  820. if (!string.IsNullOrEmpty (item.ShortcutTag))
  821. {
  822. Driver.Move (screen.X + l - item.ShortcutTag.GetColumns (), screen.Y);
  823. Driver.AddStr (item.ShortcutTag);
  824. }
  825. }
  826. }
  827. }
  828. SetClip (savedClip);
  829. }
  830. }