TabView.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #nullable enable
  2. namespace Terminal.Gui.Views;
  3. /// <summary>Control that hosts multiple sub views, presenting a single one at once.</summary>
  4. public class TabView : View
  5. {
  6. /// <summary>The default <see cref="MaxTabTextWidth"/> to set on new <see cref="TabView"/> controls.</summary>
  7. public const uint DefaultMaxTabTextWidth = 30;
  8. /// <summary>
  9. /// This sub view is the main client area of the current tab. It hosts the <see cref="Tab.View"/> of the tab, the
  10. /// <see cref="SelectedTab"/>.
  11. /// </summary>
  12. private readonly View _containerView;
  13. private readonly List<Tab> _tabs = new ();
  14. /// <summary>This sub view is the 2 or 3 line control that represents the actual tabs themselves.</summary>
  15. private readonly TabRow _tabsBar;
  16. private Tab? _selectedTab;
  17. internal Tab []? _tabLocations;
  18. private int _tabScrollOffset;
  19. /// <summary>Initializes a <see cref="TabView"/> class.</summary>
  20. public TabView ()
  21. {
  22. CanFocus = true;
  23. TabStop = TabBehavior.TabStop; // Because TabView has focusable subviews, it must be a TabGroup
  24. _tabsBar = new TabRow (this);
  25. _containerView = new ();
  26. ApplyStyleChanges ();
  27. base.Add (_tabsBar);
  28. base.Add (_containerView);
  29. // Things this view knows how to do
  30. AddCommand (Command.Left, () => SwitchTabBy (-1));
  31. AddCommand (Command.Right, () => SwitchTabBy (1));
  32. AddCommand (
  33. Command.LeftStart,
  34. () =>
  35. {
  36. TabScrollOffset = 0;
  37. SelectedTab = Tabs.FirstOrDefault ()!;
  38. return true;
  39. }
  40. );
  41. AddCommand (
  42. Command.RightEnd,
  43. () =>
  44. {
  45. TabScrollOffset = Tabs.Count - 1;
  46. SelectedTab = Tabs.LastOrDefault ()!;
  47. return true;
  48. }
  49. );
  50. AddCommand (
  51. Command.PageDown,
  52. () =>
  53. {
  54. TabScrollOffset += _tabLocations!.Length;
  55. SelectedTab = Tabs.ElementAt (TabScrollOffset);
  56. return true;
  57. }
  58. );
  59. AddCommand (
  60. Command.PageUp,
  61. () =>
  62. {
  63. TabScrollOffset -= _tabLocations!.Length;
  64. SelectedTab = Tabs.ElementAt (TabScrollOffset);
  65. return true;
  66. }
  67. );
  68. AddCommand (
  69. Command.Up,
  70. () =>
  71. {
  72. if (_style.TabsOnBottom)
  73. {
  74. if (_tabsBar is { HasFocus: true } && _containerView.CanFocus)
  75. {
  76. _containerView.SetFocus ();
  77. return true;
  78. }
  79. }
  80. else
  81. {
  82. if (_containerView is { HasFocus: true })
  83. {
  84. var mostFocused = _containerView.MostFocused;
  85. if (mostFocused is { })
  86. {
  87. for (int? i = mostFocused.SuperView?.SubViews.IndexOf (mostFocused) - 1; i > -1; i--)
  88. {
  89. var view = mostFocused.SuperView?.SubViews.ElementAt ((int)i);
  90. if (view is { CanFocus: true, Enabled: true, Visible: true })
  91. {
  92. // Let toplevel handle it
  93. return false;
  94. }
  95. }
  96. }
  97. SelectedTab?.SetFocus ();
  98. return true;
  99. }
  100. }
  101. return false;
  102. }
  103. );
  104. AddCommand (
  105. Command.Down,
  106. () =>
  107. {
  108. if (_style.TabsOnBottom)
  109. {
  110. if (_containerView is { HasFocus: true })
  111. {
  112. var mostFocused = _containerView.MostFocused;
  113. if (mostFocused is { })
  114. {
  115. for (int? i = mostFocused.SuperView?.SubViews.IndexOf (mostFocused) + 1; i < mostFocused.SuperView?.SubViews.Count; i++)
  116. {
  117. var view = mostFocused.SuperView?.SubViews.ElementAt ((int)i);
  118. if (view is { CanFocus: true, Enabled: true, Visible: true })
  119. {
  120. // Let toplevel handle it
  121. return false;
  122. }
  123. }
  124. }
  125. SelectedTab?.SetFocus ();
  126. return true;
  127. }
  128. }
  129. else
  130. {
  131. if (_tabsBar is { HasFocus: true } && _containerView.CanFocus)
  132. {
  133. _containerView.SetFocus ();
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. );
  140. // Default keybindings for this view
  141. KeyBindings.Add (Key.CursorLeft, Command.Left);
  142. KeyBindings.Add (Key.CursorRight, Command.Right);
  143. KeyBindings.Add (Key.Home, Command.LeftStart);
  144. KeyBindings.Add (Key.End, Command.RightEnd);
  145. KeyBindings.Add (Key.PageDown, Command.PageDown);
  146. KeyBindings.Add (Key.PageUp, Command.PageUp);
  147. KeyBindings.Add (Key.CursorUp, Command.Up);
  148. KeyBindings.Add (Key.CursorDown, Command.Down);
  149. }
  150. /// <summary>
  151. /// The maximum number of characters to render in a Tab header. This prevents one long tab from pushing out all
  152. /// the others.
  153. /// </summary>
  154. public uint MaxTabTextWidth { get; set; } = DefaultMaxTabTextWidth;
  155. // This is needed to hold initial value because it may change during the setter process
  156. private bool _selectedTabHasFocus;
  157. /// <summary>The currently selected member of <see cref="Tabs"/> chosen by the user.</summary>
  158. /// <value></value>
  159. public Tab? SelectedTab
  160. {
  161. get => _selectedTab;
  162. set
  163. {
  164. if (value == _selectedTab)
  165. {
  166. return;
  167. }
  168. Tab? old = _selectedTab;
  169. _selectedTabHasFocus = old is { } && (old.HasFocus || !_containerView.CanFocus);
  170. if (_selectedTab is { })
  171. {
  172. if (_selectedTab.View is { })
  173. {
  174. _selectedTab.View.CanFocusChanged -= ContainerViewCanFocus!;
  175. // remove old content
  176. _containerView.Remove (_selectedTab.View);
  177. }
  178. }
  179. _selectedTab = value;
  180. // add new content
  181. if (_selectedTab?.View != null)
  182. {
  183. _selectedTab.View.CanFocusChanged += ContainerViewCanFocus!;
  184. _containerView.Add (_selectedTab.View);
  185. }
  186. ContainerViewCanFocus (null!, null!);
  187. EnsureSelectedTabIsVisible ();
  188. if (old != _selectedTab)
  189. {
  190. if (TabCanSetFocus ())
  191. {
  192. SelectedTab?.SetFocus ();
  193. }
  194. OnSelectedTabChanged (old!, _selectedTab!);
  195. }
  196. SetNeedsLayout ();
  197. }
  198. }
  199. private bool TabCanSetFocus ()
  200. {
  201. #pragma warning disable CS8629 // Nullable value type may be null.
  202. return IsInitialized && SelectedTab is { } && (HasFocus || (bool)_containerView?.HasFocus) && (_selectedTabHasFocus || !_containerView.CanFocus);
  203. #pragma warning restore CS8629 // Nullable value type may be null.
  204. }
  205. private void ContainerViewCanFocus (object sender, EventArgs eventArgs)
  206. {
  207. _containerView.CanFocus = _containerView.SubViews.Count (v => v.CanFocus) > 0;
  208. }
  209. private TabStyle _style = new ();
  210. /// <summary>Render choices for how to display tabs. After making changes, call <see cref="ApplyStyleChanges()"/>.</summary>
  211. /// <value></value>
  212. public TabStyle Style
  213. {
  214. get => _style;
  215. set
  216. {
  217. if (_style == value)
  218. {
  219. return;
  220. }
  221. _style = value;
  222. SetNeedsLayout ();
  223. }
  224. }
  225. /// <summary>All tabs currently hosted by the control.</summary>
  226. /// <value></value>
  227. public IReadOnlyCollection<Tab> Tabs => _tabs.AsReadOnly ();
  228. /// <summary>When there are too many tabs to render, this indicates the first tab to render on the screen.</summary>
  229. /// <value></value>
  230. public int TabScrollOffset
  231. {
  232. get => _tabScrollOffset;
  233. set
  234. {
  235. _tabScrollOffset = EnsureValidScrollOffsets (value);
  236. SetNeedsLayout ();
  237. }
  238. }
  239. /// <summary>Adds the given <paramref name="tab"/> to <see cref="Tabs"/>.</summary>
  240. /// <param name="tab"></param>
  241. /// <param name="andSelect">True to make the newly added Tab the <see cref="SelectedTab"/>.</param>
  242. public void AddTab (Tab tab, bool andSelect)
  243. {
  244. if (_tabs.Contains (tab))
  245. {
  246. return;
  247. }
  248. _tabs.Add (tab);
  249. _tabsBar.Add (tab);
  250. if (SelectedTab is null || andSelect)
  251. {
  252. SelectedTab = tab;
  253. EnsureSelectedTabIsVisible ();
  254. tab.View?.SetFocus ();
  255. }
  256. SetNeedsLayout ();
  257. }
  258. /// <summary>
  259. /// Updates the control to use the latest state settings in <see cref="Style"/>. This can change the size of the
  260. /// client area of the tab (for rendering the selected tab's content). This method includes a call to
  261. /// <see cref="View.SetNeedsDraw()"/>.
  262. /// </summary>
  263. public void ApplyStyleChanges ()
  264. {
  265. _containerView.BorderStyle = Style.ShowBorder ? LineStyle.Single : LineStyle.None;
  266. _containerView.Width = Dim.Fill ();
  267. if (Style.TabsOnBottom)
  268. {
  269. // Tabs are along the bottom so just dodge the border
  270. if (Style.ShowBorder)
  271. {
  272. _containerView.Border!.Thickness = new Thickness (1, 1, 1, 0);
  273. }
  274. _containerView.Y = 0;
  275. int tabHeight = GetTabHeight (false);
  276. // Fill client area leaving space at bottom for tabs
  277. _containerView.Height = Dim.Fill (tabHeight);
  278. _tabsBar.Height = tabHeight;
  279. _tabsBar.Y = Pos.Bottom (_containerView);
  280. }
  281. else
  282. {
  283. // Tabs are along the top
  284. if (Style.ShowBorder)
  285. {
  286. _containerView.Border!.Thickness = new Thickness (1, 0, 1, 1);
  287. }
  288. _tabsBar.Y = 0;
  289. int tabHeight = GetTabHeight (true);
  290. //move content down to make space for tabs
  291. _containerView.Y = Pos.Bottom (_tabsBar);
  292. // Fill client area leaving space at bottom for border
  293. _containerView.Height = Dim.Fill ();
  294. // The top tab should be 2 or 3 rows high and on the top
  295. _tabsBar.Height = tabHeight;
  296. // Should be able to just use 0 but switching between top/bottom tabs repeatedly breaks in ValidatePosDim if just using the absolute value 0
  297. }
  298. SetNeedsLayout ();
  299. }
  300. /// <inheritdoc />
  301. protected override void OnViewportChanged (DrawEventArgs e)
  302. {
  303. _tabLocations = CalculateViewport (Viewport).ToArray ();
  304. base.OnViewportChanged (e);
  305. }
  306. /// <summary>Updates <see cref="TabScrollOffset"/> to ensure that <see cref="SelectedTab"/> is visible.</summary>
  307. public void EnsureSelectedTabIsVisible ()
  308. {
  309. if (!IsInitialized || SelectedTab is null)
  310. {
  311. return;
  312. }
  313. // if current viewport does not include the selected tab
  314. if (!CalculateViewport (Viewport).Any (t => Equals (SelectedTab, t)))
  315. {
  316. // Set scroll offset so the first tab rendered is the
  317. TabScrollOffset = Math.Max (0, Tabs.IndexOf (SelectedTab));
  318. }
  319. }
  320. /// <summary>Updates <see cref="TabScrollOffset"/> to be a valid index of <see cref="Tabs"/>.</summary>
  321. /// <param name="value">The value to validate.</param>
  322. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>.</remarks>
  323. /// <returns>The valid <see cref="TabScrollOffset"/> for the given value.</returns>
  324. public int EnsureValidScrollOffsets (int value) { return Math.Max (Math.Min (value, Tabs.Count - 1), 0); }
  325. /// <inheritdoc />
  326. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  327. {
  328. if (SelectedTab is { HasFocus: false } && !_containerView.CanFocus && focusedView == this)
  329. {
  330. SelectedTab?.SetFocus ();
  331. return;
  332. }
  333. base.OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  334. }
  335. /// <summary>
  336. /// Removes the given <paramref name="tab"/> from <see cref="Tabs"/>. Caller is responsible for disposing the
  337. /// tab's hosted <see cref="Tab.View"/> if appropriate.
  338. /// </summary>
  339. /// <param name="tab"></param>
  340. public void RemoveTab (Tab? tab)
  341. {
  342. if (tab is null || !_tabs.Contains (tab))
  343. {
  344. return;
  345. }
  346. // what tab was selected before closing
  347. int idx = _tabs.IndexOf (tab);
  348. _tabs.Remove (tab);
  349. // if the currently selected tab is no longer a member of Tabs
  350. if (SelectedTab is null || !Tabs.Contains (SelectedTab))
  351. {
  352. // select the tab closest to the one that disappeared
  353. int toSelect = Math.Max (idx - 1, 0);
  354. if (toSelect < Tabs.Count)
  355. {
  356. SelectedTab = Tabs.ElementAt (toSelect);
  357. }
  358. else
  359. {
  360. SelectedTab = Tabs.LastOrDefault ();
  361. }
  362. }
  363. EnsureSelectedTabIsVisible ();
  364. SetNeedsLayout ();
  365. }
  366. /// <summary>Event for when <see cref="SelectedTab"/> changes.</summary>
  367. public event EventHandler<TabChangedEventArgs>? SelectedTabChanged;
  368. /// <summary>
  369. /// Changes the <see cref="SelectedTab"/> by the given <paramref name="amount"/>. Positive for right, negative for
  370. /// left. If no tab is currently selected then the first tab will become selected.
  371. /// </summary>
  372. /// <param name="amount"></param>
  373. public bool SwitchTabBy (int amount)
  374. {
  375. if (Tabs.Count == 0)
  376. {
  377. return false;
  378. }
  379. // if there is only one tab anyway or nothing is selected
  380. if (Tabs.Count == 1 || SelectedTab is null)
  381. {
  382. SelectedTab = Tabs.ElementAt (0);
  383. return SelectedTab is { };
  384. }
  385. int currentIdx = Tabs.IndexOf (SelectedTab);
  386. // Currently selected tab has vanished!
  387. if (currentIdx == -1)
  388. {
  389. SelectedTab = Tabs.ElementAt (0);
  390. return true;
  391. }
  392. int newIdx = Math.Max (0, Math.Min (currentIdx + amount, Tabs.Count - 1));
  393. if (newIdx == currentIdx)
  394. {
  395. return false;
  396. }
  397. SelectedTab = _tabs [newIdx];
  398. EnsureSelectedTabIsVisible ();
  399. return true;
  400. }
  401. /// <summary>
  402. /// Event fired when a <see cref="Tab"/> is clicked. Can be used to cancel navigation, show context menu (e.g. on
  403. /// right click) etc.
  404. /// </summary>
  405. public event EventHandler<TabMouseEventArgs>? TabClicked;
  406. /// <summary>Disposes the control and all <see cref="Tabs"/>.</summary>
  407. /// <param name="disposing"></param>
  408. protected override void Dispose (bool disposing)
  409. {
  410. base.Dispose (disposing);
  411. // The selected tab will automatically be disposed but
  412. // any tabs not visible will need to be manually disposed
  413. foreach (Tab tab in Tabs)
  414. {
  415. if (!Equals (SelectedTab, tab))
  416. {
  417. tab.View?.Dispose ();
  418. }
  419. }
  420. }
  421. /// <summary>Raises the <see cref="SelectedTabChanged"/> event.</summary>
  422. protected virtual void OnSelectedTabChanged (Tab oldTab, Tab newTab)
  423. {
  424. SelectedTabChanged?.Invoke (this, new TabChangedEventArgs (oldTab, newTab));
  425. }
  426. /// <summary>Returns which tabs to render at each x location.</summary>
  427. /// <returns></returns>
  428. internal IEnumerable<Tab> CalculateViewport (Rectangle bounds)
  429. {
  430. UnSetCurrentTabs ();
  431. var i = 1;
  432. View? prevTab = null;
  433. // Starting at the first or scrolled to tab
  434. foreach (Tab tab in Tabs.Skip (TabScrollOffset))
  435. {
  436. if (prevTab is { })
  437. {
  438. tab.X = Pos.Right (prevTab) - 1;
  439. }
  440. else
  441. {
  442. tab.X = 0;
  443. }
  444. tab.Y = 0;
  445. // while there is space for the tab
  446. int tabTextWidth = tab.DisplayText.EnumerateRunes ().Sum (c => c.GetColumns ());
  447. // The maximum number of characters to use for the tab name as specified
  448. // by the user (MaxTabTextWidth). But not more than the width of the view
  449. // or we won't even be able to render a single tab!
  450. long maxWidth = Math.Max (0, Math.Min (bounds.Width - 3, MaxTabTextWidth));
  451. tab.Width = 2;
  452. tab.Height = Style.ShowTopLine ? 3 : 2;
  453. // if tab view is width <= 3 don't render any tabs
  454. if (maxWidth == 0)
  455. {
  456. tab.Visible = true;
  457. tab.MouseClick += Tab_MouseClick!;
  458. tab.Border!.MouseClick += Tab_MouseClick!;
  459. yield return tab;
  460. break;
  461. }
  462. if (tabTextWidth > maxWidth)
  463. {
  464. tab.Text = tab.DisplayText.Substring (0, (int)maxWidth);
  465. tabTextWidth = (int)maxWidth;
  466. }
  467. else
  468. {
  469. tab.Text = tab.DisplayText;
  470. }
  471. tab.Width = Math.Max (tabTextWidth + 2, 1);
  472. tab.Height = Style.ShowTopLine ? 3 : 2;
  473. // if there is not enough space for this tab
  474. if (i + tabTextWidth >= bounds.Width)
  475. {
  476. tab.Visible = false;
  477. break;
  478. }
  479. // there is enough space!
  480. tab.Visible = true;
  481. tab.MouseClick += Tab_MouseClick!;
  482. tab.Border!.MouseClick += Tab_MouseClick!;
  483. yield return tab;
  484. prevTab = tab;
  485. i += tabTextWidth + 1;
  486. }
  487. if (TabCanSetFocus ())
  488. {
  489. SelectedTab?.SetFocus ();
  490. }
  491. else if (HasFocus)
  492. {
  493. SelectedTab?.View?.SetFocus ();
  494. }
  495. }
  496. /// <summary>
  497. /// Returns the number of rows occupied by rendering the tabs, this depends on <see cref="TabStyle.ShowTopLine"/>
  498. /// and can be 0 (e.g. if <see cref="TabStyle.TabsOnBottom"/> and you ask for <paramref name="top"/>).
  499. /// </summary>
  500. /// <param name="top">True to measure the space required at the top of the control, false to measure space at the bottom.</param>
  501. /// .
  502. /// <returns></returns>
  503. private int GetTabHeight (bool top)
  504. {
  505. if (top && Style.TabsOnBottom)
  506. {
  507. return 0;
  508. }
  509. if (!top && !Style.TabsOnBottom)
  510. {
  511. return 0;
  512. }
  513. return Style.ShowTopLine ? 3 : 2;
  514. }
  515. internal void Tab_MouseClick (object sender, MouseEventArgs e)
  516. {
  517. e.Handled = _tabsBar.NewMouseEvent (e) == true;
  518. }
  519. private void UnSetCurrentTabs ()
  520. {
  521. if (_tabLocations is null)
  522. {
  523. // Ensures unset any visible tab prior to TabScrollOffset
  524. for (int i = 0; i < TabScrollOffset; i++)
  525. {
  526. Tab tab = Tabs.ElementAt (i);
  527. if (tab.Visible)
  528. {
  529. tab.MouseClick -= Tab_MouseClick!;
  530. tab.Border!.MouseClick -= Tab_MouseClick!;
  531. tab.Visible = false;
  532. }
  533. }
  534. }
  535. else if (_tabLocations is { })
  536. {
  537. foreach (Tab tabToRender in _tabLocations)
  538. {
  539. tabToRender.MouseClick -= Tab_MouseClick!;
  540. tabToRender.Border!.MouseClick -= Tab_MouseClick!;
  541. tabToRender.Visible = false;
  542. }
  543. _tabLocations = null;
  544. }
  545. }
  546. /// <summary>Raises the <see cref="TabClicked"/> event.</summary>
  547. /// <param name="tabMouseEventArgs"></param>
  548. internal virtual void OnTabClicked (TabMouseEventArgs tabMouseEventArgs) { TabClicked?.Invoke (this, tabMouseEventArgs); }
  549. }