2
0

TabView.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. #nullable enable
  2. namespace Terminal.Gui;
  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. return IsInitialized && SelectedTab is { } && (HasFocus || (bool)_containerView?.HasFocus) && (_selectedTabHasFocus || !_containerView.CanFocus);
  202. }
  203. private void ContainerViewCanFocus (object sender, EventArgs eventArgs)
  204. {
  205. _containerView.CanFocus = _containerView.SubViews.Count (v => v.CanFocus) > 0;
  206. }
  207. private TabStyle _style = new ();
  208. /// <summary>Render choices for how to display tabs. After making changes, call <see cref="ApplyStyleChanges()"/>.</summary>
  209. /// <value></value>
  210. public TabStyle Style
  211. {
  212. get => _style;
  213. set
  214. {
  215. if (_style == value)
  216. {
  217. return;
  218. }
  219. _style = value;
  220. SetNeedsLayout ();
  221. }
  222. }
  223. /// <summary>All tabs currently hosted by the control.</summary>
  224. /// <value></value>
  225. public IReadOnlyCollection<Tab> Tabs => _tabs.AsReadOnly ();
  226. /// <summary>When there are too many tabs to render, this indicates the first tab to render on the screen.</summary>
  227. /// <value></value>
  228. public int TabScrollOffset
  229. {
  230. get => _tabScrollOffset;
  231. set
  232. {
  233. _tabScrollOffset = EnsureValidScrollOffsets (value);
  234. SetNeedsLayout ();
  235. }
  236. }
  237. /// <summary>Adds the given <paramref name="tab"/> to <see cref="Tabs"/>.</summary>
  238. /// <param name="tab"></param>
  239. /// <param name="andSelect">True to make the newly added Tab the <see cref="SelectedTab"/>.</param>
  240. public void AddTab (Tab tab, bool andSelect)
  241. {
  242. if (_tabs.Contains (tab))
  243. {
  244. return;
  245. }
  246. _tabs.Add (tab);
  247. _tabsBar.Add (tab);
  248. if (SelectedTab is null || andSelect)
  249. {
  250. SelectedTab = tab;
  251. EnsureSelectedTabIsVisible ();
  252. tab.View?.SetFocus ();
  253. }
  254. SetNeedsLayout ();
  255. }
  256. /// <summary>
  257. /// Updates the control to use the latest state settings in <see cref="Style"/>. This can change the size of the
  258. /// client area of the tab (for rendering the selected tab's content). This method includes a call to
  259. /// <see cref="View.SetNeedsDraw()"/>.
  260. /// </summary>
  261. public void ApplyStyleChanges ()
  262. {
  263. _containerView.BorderStyle = Style.ShowBorder ? LineStyle.Single : LineStyle.None;
  264. _containerView.Width = Dim.Fill ();
  265. if (Style.TabsOnBottom)
  266. {
  267. // Tabs are along the bottom so just dodge the border
  268. if (Style.ShowBorder)
  269. {
  270. _containerView.Border!.Thickness = new Thickness (1, 1, 1, 0);
  271. }
  272. _containerView.Y = 0;
  273. int tabHeight = GetTabHeight (false);
  274. // Fill client area leaving space at bottom for tabs
  275. _containerView.Height = Dim.Fill (tabHeight);
  276. _tabsBar.Height = tabHeight;
  277. _tabsBar.Y = Pos.Bottom (_containerView);
  278. }
  279. else
  280. {
  281. // Tabs are along the top
  282. if (Style.ShowBorder)
  283. {
  284. _containerView.Border!.Thickness = new Thickness (1, 0, 1, 1);
  285. }
  286. _tabsBar.Y = 0;
  287. int tabHeight = GetTabHeight (true);
  288. //move content down to make space for tabs
  289. _containerView.Y = Pos.Bottom (_tabsBar);
  290. // Fill client area leaving space at bottom for border
  291. _containerView.Height = Dim.Fill ();
  292. // The top tab should be 2 or 3 rows high and on the top
  293. _tabsBar.Height = tabHeight;
  294. // Should be able to just use 0 but switching between top/bottom tabs repeatedly breaks in ValidatePosDim if just using the absolute value 0
  295. }
  296. SetNeedsLayout ();
  297. }
  298. /// <inheritdoc />
  299. protected override void OnViewportChanged (DrawEventArgs e)
  300. {
  301. _tabLocations = CalculateViewport (Viewport).ToArray ();
  302. base.OnViewportChanged (e);
  303. }
  304. /// <summary>Updates <see cref="TabScrollOffset"/> to ensure that <see cref="SelectedTab"/> is visible.</summary>
  305. public void EnsureSelectedTabIsVisible ()
  306. {
  307. if (!IsInitialized || SelectedTab is null)
  308. {
  309. return;
  310. }
  311. // if current viewport does not include the selected tab
  312. if (!CalculateViewport (Viewport).Any (t => Equals (SelectedTab, t)))
  313. {
  314. // Set scroll offset so the first tab rendered is the
  315. TabScrollOffset = Math.Max (0, Tabs.IndexOf (SelectedTab));
  316. }
  317. }
  318. /// <summary>Updates <see cref="TabScrollOffset"/> to be a valid index of <see cref="Tabs"/>.</summary>
  319. /// <param name="value">The value to validate.</param>
  320. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>.</remarks>
  321. /// <returns>The valid <see cref="TabScrollOffset"/> for the given value.</returns>
  322. public int EnsureValidScrollOffsets (int value) { return Math.Max (Math.Min (value, Tabs.Count - 1), 0); }
  323. /// <inheritdoc />
  324. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  325. {
  326. if (SelectedTab is { HasFocus: false } && !_containerView.CanFocus && focusedView == this)
  327. {
  328. SelectedTab?.SetFocus ();
  329. return;
  330. }
  331. base.OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  332. }
  333. /// <summary>
  334. /// Removes the given <paramref name="tab"/> from <see cref="Tabs"/>. Caller is responsible for disposing the
  335. /// tab's hosted <see cref="Tab.View"/> if appropriate.
  336. /// </summary>
  337. /// <param name="tab"></param>
  338. public void RemoveTab (Tab? tab)
  339. {
  340. if (tab is null || !_tabs.Contains (tab))
  341. {
  342. return;
  343. }
  344. // what tab was selected before closing
  345. int idx = _tabs.IndexOf (tab);
  346. _tabs.Remove (tab);
  347. // if the currently selected tab is no longer a member of Tabs
  348. if (SelectedTab is null || !Tabs.Contains (SelectedTab))
  349. {
  350. // select the tab closest to the one that disappeared
  351. int toSelect = Math.Max (idx - 1, 0);
  352. if (toSelect < Tabs.Count)
  353. {
  354. SelectedTab = Tabs.ElementAt (toSelect);
  355. }
  356. else
  357. {
  358. SelectedTab = Tabs.LastOrDefault ();
  359. }
  360. }
  361. EnsureSelectedTabIsVisible ();
  362. SetNeedsLayout ();
  363. }
  364. /// <summary>Event for when <see cref="SelectedTab"/> changes.</summary>
  365. public event EventHandler<TabChangedEventArgs>? SelectedTabChanged;
  366. /// <summary>
  367. /// Changes the <see cref="SelectedTab"/> by the given <paramref name="amount"/>. Positive for right, negative for
  368. /// left. If no tab is currently selected then the first tab will become selected.
  369. /// </summary>
  370. /// <param name="amount"></param>
  371. public bool SwitchTabBy (int amount)
  372. {
  373. if (Tabs.Count == 0)
  374. {
  375. return false;
  376. }
  377. // if there is only one tab anyway or nothing is selected
  378. if (Tabs.Count == 1 || SelectedTab is null)
  379. {
  380. SelectedTab = Tabs.ElementAt (0);
  381. return SelectedTab is { };
  382. }
  383. int currentIdx = Tabs.IndexOf (SelectedTab);
  384. // Currently selected tab has vanished!
  385. if (currentIdx == -1)
  386. {
  387. SelectedTab = Tabs.ElementAt (0);
  388. return true;
  389. }
  390. int newIdx = Math.Max (0, Math.Min (currentIdx + amount, Tabs.Count - 1));
  391. if (newIdx == currentIdx)
  392. {
  393. return false;
  394. }
  395. SelectedTab = _tabs [newIdx];
  396. EnsureSelectedTabIsVisible ();
  397. return true;
  398. }
  399. /// <summary>
  400. /// Event fired when a <see cref="Tab"/> is clicked. Can be used to cancel navigation, show context menu (e.g. on
  401. /// right click) etc.
  402. /// </summary>
  403. public event EventHandler<TabMouseEventArgs>? TabClicked;
  404. /// <summary>Disposes the control and all <see cref="Tabs"/>.</summary>
  405. /// <param name="disposing"></param>
  406. protected override void Dispose (bool disposing)
  407. {
  408. base.Dispose (disposing);
  409. // The selected tab will automatically be disposed but
  410. // any tabs not visible will need to be manually disposed
  411. foreach (Tab tab in Tabs)
  412. {
  413. if (!Equals (SelectedTab, tab))
  414. {
  415. tab.View?.Dispose ();
  416. }
  417. }
  418. }
  419. /// <summary>Raises the <see cref="SelectedTabChanged"/> event.</summary>
  420. protected virtual void OnSelectedTabChanged (Tab oldTab, Tab newTab)
  421. {
  422. SelectedTabChanged?.Invoke (this, new TabChangedEventArgs (oldTab, newTab));
  423. }
  424. /// <summary>Returns which tabs to render at each x location.</summary>
  425. /// <returns></returns>
  426. internal IEnumerable<Tab> CalculateViewport (Rectangle bounds)
  427. {
  428. UnSetCurrentTabs ();
  429. var i = 1;
  430. View? prevTab = null;
  431. // Starting at the first or scrolled to tab
  432. foreach (Tab tab in Tabs.Skip (TabScrollOffset))
  433. {
  434. if (prevTab is { })
  435. {
  436. tab.X = Pos.Right (prevTab) - 1;
  437. }
  438. else
  439. {
  440. tab.X = 0;
  441. }
  442. tab.Y = 0;
  443. // while there is space for the tab
  444. int tabTextWidth = tab.DisplayText.EnumerateRunes ().Sum (c => c.GetColumns ());
  445. // The maximum number of characters to use for the tab name as specified
  446. // by the user (MaxTabTextWidth). But not more than the width of the view
  447. // or we won't even be able to render a single tab!
  448. long maxWidth = Math.Max (0, Math.Min (bounds.Width - 3, MaxTabTextWidth));
  449. tab.Width = 2;
  450. tab.Height = Style.ShowTopLine ? 3 : 2;
  451. // if tab view is width <= 3 don't render any tabs
  452. if (maxWidth == 0)
  453. {
  454. tab.Visible = true;
  455. tab.MouseClick += Tab_MouseClick!;
  456. tab.Border!.MouseClick += Tab_MouseClick!;
  457. yield return tab;
  458. break;
  459. }
  460. if (tabTextWidth > maxWidth)
  461. {
  462. tab.Text = tab.DisplayText.Substring (0, (int)maxWidth);
  463. tabTextWidth = (int)maxWidth;
  464. }
  465. else
  466. {
  467. tab.Text = tab.DisplayText;
  468. }
  469. tab.Width = Math.Max (tabTextWidth + 2, 1);
  470. tab.Height = Style.ShowTopLine ? 3 : 2;
  471. // if there is not enough space for this tab
  472. if (i + tabTextWidth >= bounds.Width)
  473. {
  474. tab.Visible = false;
  475. break;
  476. }
  477. // there is enough space!
  478. tab.Visible = true;
  479. tab.MouseClick += Tab_MouseClick!;
  480. tab.Border!.MouseClick += Tab_MouseClick!;
  481. yield return tab;
  482. prevTab = tab;
  483. i += tabTextWidth + 1;
  484. }
  485. if (TabCanSetFocus ())
  486. {
  487. SelectedTab?.SetFocus ();
  488. }
  489. else if (HasFocus)
  490. {
  491. SelectedTab?.View?.SetFocus ();
  492. }
  493. }
  494. /// <summary>
  495. /// Returns the number of rows occupied by rendering the tabs, this depends on <see cref="TabStyle.ShowTopLine"/>
  496. /// and can be 0 (e.g. if <see cref="TabStyle.TabsOnBottom"/> and you ask for <paramref name="top"/>).
  497. /// </summary>
  498. /// <param name="top">True to measure the space required at the top of the control, false to measure space at the bottom.</param>
  499. /// .
  500. /// <returns></returns>
  501. private int GetTabHeight (bool top)
  502. {
  503. if (top && Style.TabsOnBottom)
  504. {
  505. return 0;
  506. }
  507. if (!top && !Style.TabsOnBottom)
  508. {
  509. return 0;
  510. }
  511. return Style.ShowTopLine ? 3 : 2;
  512. }
  513. internal void Tab_MouseClick (object sender, MouseEventArgs e)
  514. {
  515. e.Handled = _tabsBar.NewMouseEvent (e) == true;
  516. }
  517. private void UnSetCurrentTabs ()
  518. {
  519. if (_tabLocations is null)
  520. {
  521. // Ensures unset any visible tab prior to TabScrollOffset
  522. for (int i = 0; i < TabScrollOffset; i++)
  523. {
  524. Tab tab = Tabs.ElementAt (i);
  525. if (tab.Visible)
  526. {
  527. tab.MouseClick -= Tab_MouseClick!;
  528. tab.Border!.MouseClick -= Tab_MouseClick!;
  529. tab.Visible = false;
  530. }
  531. }
  532. }
  533. else if (_tabLocations is { })
  534. {
  535. foreach (Tab tabToRender in _tabLocations)
  536. {
  537. tabToRender.MouseClick -= Tab_MouseClick!;
  538. tabToRender.Border!.MouseClick -= Tab_MouseClick!;
  539. tabToRender.Visible = false;
  540. }
  541. _tabLocations = null;
  542. }
  543. }
  544. /// <summary>Raises the <see cref="TabClicked"/> event.</summary>
  545. /// <param name="tabMouseEventArgs"></param>
  546. internal virtual void OnTabClicked (TabMouseEventArgs tabMouseEventArgs) { TabClicked?.Invoke (this, tabMouseEventArgs); }
  547. }