TabView.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 TabRowView _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 TabRowView (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. // Default keybindings for this view
  69. KeyBindings.Add (Key.CursorLeft, Command.Left);
  70. KeyBindings.Add (Key.CursorRight, Command.Right);
  71. KeyBindings.Add (Key.Home, Command.LeftStart);
  72. KeyBindings.Add (Key.End, Command.RightEnd);
  73. KeyBindings.Add (Key.PageDown, Command.PageDown);
  74. KeyBindings.Add (Key.PageUp, Command.PageUp);
  75. }
  76. /// <summary>
  77. /// The maximum number of characters to render in a Tab header. This prevents one long tab from pushing out all
  78. /// the others.
  79. /// </summary>
  80. public uint MaxTabTextWidth { get; set; } = DefaultMaxTabTextWidth;
  81. // This is needed to hold initial value because it may change during the setter process
  82. private bool _selectedTabHasFocus;
  83. /// <summary>The currently selected member of <see cref="Tabs"/> chosen by the user.</summary>
  84. /// <value></value>
  85. public Tab? SelectedTab
  86. {
  87. get => _selectedTab;
  88. set
  89. {
  90. if (value == _selectedTab)
  91. {
  92. return;
  93. }
  94. Tab? old = _selectedTab;
  95. _selectedTabHasFocus = old is { } && (old.HasFocus || !_containerView.CanFocus);
  96. if (_selectedTab is { })
  97. {
  98. if (_selectedTab.View is { })
  99. {
  100. _selectedTab.View.CanFocusChanged -= ContainerViewCanFocus!;
  101. // remove old content
  102. _containerView.Remove (_selectedTab.View);
  103. }
  104. }
  105. _selectedTab = value;
  106. // add new content
  107. if (_selectedTab?.View != null)
  108. {
  109. _selectedTab.View.CanFocusChanged += ContainerViewCanFocus!;
  110. _containerView.Add (_selectedTab.View);
  111. }
  112. ContainerViewCanFocus (null!, null!);
  113. EnsureSelectedTabIsVisible ();
  114. if (old != _selectedTab)
  115. {
  116. if (_selectedTabHasFocus || !_containerView.CanFocus)
  117. {
  118. SelectedTab?.SetFocus ();
  119. }
  120. OnSelectedTabChanged (old!, _selectedTab!);
  121. }
  122. SetNeedsLayout ();
  123. }
  124. }
  125. private void ContainerViewCanFocus (object sender, EventArgs eventArgs)
  126. {
  127. _containerView.CanFocus = _containerView.Subviews.Count (v => v.CanFocus) > 0;
  128. }
  129. private TabStyle _style = new ();
  130. /// <summary>Render choices for how to display tabs. After making changes, call <see cref="ApplyStyleChanges()"/>.</summary>
  131. /// <value></value>
  132. public TabStyle Style
  133. {
  134. get => _style;
  135. set
  136. {
  137. if (_style == value)
  138. {
  139. return;
  140. }
  141. _style = value;
  142. SetNeedsLayout ();
  143. }
  144. }
  145. /// <summary>All tabs currently hosted by the control.</summary>
  146. /// <value></value>
  147. public IReadOnlyCollection<Tab> Tabs => _tabs.AsReadOnly ();
  148. /// <summary>When there are too many tabs to render, this indicates the first tab to render on the screen.</summary>
  149. /// <value></value>
  150. public int TabScrollOffset
  151. {
  152. get => _tabScrollOffset;
  153. set
  154. {
  155. _tabScrollOffset = EnsureValidScrollOffsets (value);
  156. SetNeedsLayout ();
  157. }
  158. }
  159. /// <summary>Adds the given <paramref name="tab"/> to <see cref="Tabs"/>.</summary>
  160. /// <param name="tab"></param>
  161. /// <param name="andSelect">True to make the newly added Tab the <see cref="SelectedTab"/>.</param>
  162. public void AddTab (Tab tab, bool andSelect)
  163. {
  164. if (_tabs.Contains (tab))
  165. {
  166. return;
  167. }
  168. _tabs.Add (tab);
  169. _tabsBar.Add (tab);
  170. if (SelectedTab is null || andSelect)
  171. {
  172. SelectedTab = tab;
  173. EnsureSelectedTabIsVisible ();
  174. tab.View?.SetFocus ();
  175. }
  176. SetNeedsLayout ();
  177. }
  178. /// <summary>
  179. /// Updates the control to use the latest state settings in <see cref="Style"/>. This can change the size of the
  180. /// client area of the tab (for rendering the selected tab's content). This method includes a call to
  181. /// <see cref="View.SetNeedsDraw()"/>.
  182. /// </summary>
  183. public void ApplyStyleChanges ()
  184. {
  185. _containerView.BorderStyle = Style.ShowBorder ? LineStyle.Single : LineStyle.None;
  186. _containerView.Width = Dim.Fill ();
  187. if (Style.TabsOnBottom)
  188. {
  189. // Tabs are along the bottom so just dodge the border
  190. if (Style.ShowBorder)
  191. {
  192. _containerView.Border!.Thickness = new Thickness (1, 1, 1, 0);
  193. }
  194. _containerView.Y = 0;
  195. int tabHeight = GetTabHeight (false);
  196. // Fill client area leaving space at bottom for tabs
  197. _containerView.Height = Dim.Fill (tabHeight);
  198. _tabsBar.Height = tabHeight;
  199. _tabsBar.Y = Pos.Bottom (_containerView);
  200. }
  201. else
  202. {
  203. // Tabs are along the top
  204. if (Style.ShowBorder)
  205. {
  206. _containerView.Border!.Thickness = new Thickness (1, 0, 1, 1);
  207. }
  208. _tabsBar.Y = 0;
  209. int tabHeight = GetTabHeight (true);
  210. //move content down to make space for tabs
  211. _containerView.Y = Pos.Bottom (_tabsBar);
  212. // Fill client area leaving space at bottom for border
  213. _containerView.Height = Dim.Fill ();
  214. // The top tab should be 2 or 3 rows high and on the top
  215. _tabsBar.Height = tabHeight;
  216. // Should be able to just use 0 but switching between top/bottom tabs repeatedly breaks in ValidatePosDim if just using the absolute value 0
  217. }
  218. SetNeedsLayout ();
  219. }
  220. /// <inheritdoc />
  221. protected override void OnViewportChanged (DrawEventArgs e)
  222. {
  223. _tabLocations = CalculateViewport (Viewport).ToArray ();
  224. base.OnViewportChanged (e);
  225. }
  226. /// <summary>Updates <see cref="TabScrollOffset"/> to ensure that <see cref="SelectedTab"/> is visible.</summary>
  227. public void EnsureSelectedTabIsVisible ()
  228. {
  229. if (!IsInitialized || SelectedTab is null)
  230. {
  231. return;
  232. }
  233. // if current viewport does not include the selected tab
  234. if (!CalculateViewport (Viewport).Any (t => Equals (SelectedTab, t)))
  235. {
  236. // Set scroll offset so the first tab rendered is the
  237. TabScrollOffset = Math.Max (0, Tabs.IndexOf (SelectedTab));
  238. }
  239. }
  240. /// <summary>Updates <see cref="TabScrollOffset"/> to be a valid index of <see cref="Tabs"/>.</summary>
  241. /// <param name="value">The value to validate.</param>
  242. /// <remarks>Changes will not be immediately visible in the display until you call <see cref="View.SetNeedsDraw()"/>.</remarks>
  243. /// <returns>The valid <see cref="TabScrollOffset"/> for the given value.</returns>
  244. public int EnsureValidScrollOffsets (int value) { return Math.Max (Math.Min (value, Tabs.Count - 1), 0); }
  245. /// <inheritdoc />
  246. protected override void OnHasFocusChanged (bool newHasFocus, View? previousFocusedView, View? focusedView)
  247. {
  248. if (SelectedTab is { HasFocus: false } && !_containerView.CanFocus && focusedView == this)
  249. {
  250. SelectedTab?.SetFocus ();
  251. return;
  252. }
  253. base.OnHasFocusChanged (newHasFocus, previousFocusedView, focusedView);
  254. }
  255. /// <summary>
  256. /// Removes the given <paramref name="tab"/> from <see cref="Tabs"/>. Caller is responsible for disposing the
  257. /// tab's hosted <see cref="Tab.View"/> if appropriate.
  258. /// </summary>
  259. /// <param name="tab"></param>
  260. public void RemoveTab (Tab? tab)
  261. {
  262. if (tab is null || !_tabs.Contains (tab))
  263. {
  264. return;
  265. }
  266. // what tab was selected before closing
  267. int idx = _tabs.IndexOf (tab);
  268. _tabs.Remove (tab);
  269. // if the currently selected tab is no longer a member of Tabs
  270. if (SelectedTab is null || !Tabs.Contains (SelectedTab))
  271. {
  272. // select the tab closest to the one that disappeared
  273. int toSelect = Math.Max (idx - 1, 0);
  274. if (toSelect < Tabs.Count)
  275. {
  276. SelectedTab = Tabs.ElementAt (toSelect);
  277. }
  278. else
  279. {
  280. SelectedTab = Tabs.LastOrDefault ();
  281. }
  282. }
  283. EnsureSelectedTabIsVisible ();
  284. SetNeedsLayout ();
  285. }
  286. /// <summary>Event for when <see cref="SelectedTab"/> changes.</summary>
  287. public event EventHandler<TabChangedEventArgs>? SelectedTabChanged;
  288. /// <summary>
  289. /// Changes the <see cref="SelectedTab"/> by the given <paramref name="amount"/>. Positive for right, negative for
  290. /// left. If no tab is currently selected then the first tab will become selected.
  291. /// </summary>
  292. /// <param name="amount"></param>
  293. public bool SwitchTabBy (int amount)
  294. {
  295. if (Tabs.Count == 0)
  296. {
  297. return false;
  298. }
  299. // if there is only one tab anyway or nothing is selected
  300. if (Tabs.Count == 1 || SelectedTab is null)
  301. {
  302. SelectedTab = Tabs.ElementAt (0);
  303. return SelectedTab is { };
  304. }
  305. int currentIdx = Tabs.IndexOf (SelectedTab);
  306. // Currently selected tab has vanished!
  307. if (currentIdx == -1)
  308. {
  309. SelectedTab = Tabs.ElementAt (0);
  310. return true;
  311. }
  312. int newIdx = Math.Max (0, Math.Min (currentIdx + amount, Tabs.Count - 1));
  313. if (newIdx == currentIdx)
  314. {
  315. return false;
  316. }
  317. SelectedTab = _tabs [newIdx];
  318. EnsureSelectedTabIsVisible ();
  319. return true;
  320. }
  321. /// <summary>
  322. /// Event fired when a <see cref="Tab"/> is clicked. Can be used to cancel navigation, show context menu (e.g. on
  323. /// right click) etc.
  324. /// </summary>
  325. public event EventHandler<TabMouseEventArgs>? TabClicked;
  326. /// <summary>Disposes the control and all <see cref="Tabs"/>.</summary>
  327. /// <param name="disposing"></param>
  328. protected override void Dispose (bool disposing)
  329. {
  330. base.Dispose (disposing);
  331. // The selected tab will automatically be disposed but
  332. // any tabs not visible will need to be manually disposed
  333. foreach (Tab tab in Tabs)
  334. {
  335. if (!Equals (SelectedTab, tab))
  336. {
  337. tab.View?.Dispose ();
  338. }
  339. }
  340. }
  341. /// <summary>Raises the <see cref="SelectedTabChanged"/> event.</summary>
  342. protected virtual void OnSelectedTabChanged (Tab oldTab, Tab newTab)
  343. {
  344. SelectedTabChanged?.Invoke (this, new TabChangedEventArgs (oldTab, newTab));
  345. }
  346. /// <summary>Returns which tabs to render at each x location.</summary>
  347. /// <returns></returns>
  348. internal IEnumerable<Tab> CalculateViewport (Rectangle bounds)
  349. {
  350. UnSetCurrentTabs ();
  351. var i = 1;
  352. View? prevTab = null;
  353. // Starting at the first or scrolled to tab
  354. foreach (Tab tab in Tabs.Skip (TabScrollOffset))
  355. {
  356. if (prevTab is { })
  357. {
  358. tab.X = Pos.Right (prevTab) - 1;
  359. }
  360. else
  361. {
  362. tab.X = 0;
  363. }
  364. tab.Y = 0;
  365. // while there is space for the tab
  366. int tabTextWidth = tab.DisplayText.EnumerateRunes ().Sum (c => c.GetColumns ());
  367. // The maximum number of characters to use for the tab name as specified
  368. // by the user (MaxTabTextWidth). But not more than the width of the view
  369. // or we won't even be able to render a single tab!
  370. long maxWidth = Math.Max (0, Math.Min (bounds.Width - 3, MaxTabTextWidth));
  371. tab.Width = 2;
  372. tab.Height = Style.ShowTopLine ? 3 : 2;
  373. // if tab view is width <= 3 don't render any tabs
  374. if (maxWidth == 0)
  375. {
  376. tab.Visible = true;
  377. tab.MouseClick += Tab_MouseClick!;
  378. tab.Border!.MouseClick += Tab_MouseClick!;
  379. yield return tab;
  380. break;
  381. }
  382. if (tabTextWidth > maxWidth)
  383. {
  384. tab.Text = tab.DisplayText.Substring (0, (int)maxWidth);
  385. tabTextWidth = (int)maxWidth;
  386. }
  387. else
  388. {
  389. tab.Text = tab.DisplayText;
  390. }
  391. tab.Width = Math.Max (tabTextWidth + 2, 1);
  392. tab.Height = Style.ShowTopLine ? 3 : 2;
  393. // if there is not enough space for this tab
  394. if (i + tabTextWidth >= bounds.Width)
  395. {
  396. tab.Visible = false;
  397. break;
  398. }
  399. // there is enough space!
  400. tab.Visible = true;
  401. tab.MouseClick += Tab_MouseClick!;
  402. tab.Border!.MouseClick += Tab_MouseClick!;
  403. yield return tab;
  404. prevTab = tab;
  405. i += tabTextWidth + 1;
  406. }
  407. if (_selectedTabHasFocus)
  408. {
  409. SelectedTab?.SetFocus ();
  410. }
  411. }
  412. /// <summary>
  413. /// Returns the number of rows occupied by rendering the tabs, this depends on <see cref="TabStyle.ShowTopLine"/>
  414. /// and can be 0 (e.g. if <see cref="TabStyle.TabsOnBottom"/> and you ask for <paramref name="top"/>).
  415. /// </summary>
  416. /// <param name="top">True to measure the space required at the top of the control, false to measure space at the bottom.</param>
  417. /// .
  418. /// <returns></returns>
  419. private int GetTabHeight (bool top)
  420. {
  421. if (top && Style.TabsOnBottom)
  422. {
  423. return 0;
  424. }
  425. if (!top && !Style.TabsOnBottom)
  426. {
  427. return 0;
  428. }
  429. return Style.ShowTopLine ? 3 : 2;
  430. }
  431. internal void Tab_MouseClick (object sender, MouseEventArgs e)
  432. {
  433. e.Handled = _tabsBar.NewMouseEvent (e) == true;
  434. }
  435. private void UnSetCurrentTabs ()
  436. {
  437. if (_tabLocations is null)
  438. {
  439. // Ensures unset any visible tab prior to TabScrollOffset
  440. for (int i = 0; i < TabScrollOffset; i++)
  441. {
  442. Tab tab = Tabs.ElementAt (i);
  443. if (tab.Visible)
  444. {
  445. tab.MouseClick -= Tab_MouseClick!;
  446. tab.Border!.MouseClick -= Tab_MouseClick!;
  447. tab.Visible = false;
  448. }
  449. }
  450. }
  451. else if (_tabLocations is { })
  452. {
  453. foreach (Tab tabToRender in _tabLocations)
  454. {
  455. tabToRender.MouseClick -= Tab_MouseClick!;
  456. tabToRender.Border!.MouseClick -= Tab_MouseClick!;
  457. tabToRender.Visible = false;
  458. }
  459. _tabLocations = null;
  460. }
  461. }
  462. /// <summary>Raises the <see cref="TabClicked"/> event.</summary>
  463. /// <param name="tabMouseEventArgs"></param>
  464. internal virtual void OnTabClicked (TabMouseEventArgs tabMouseEventArgs) { TabClicked?.Invoke (this, tabMouseEventArgs); }
  465. }