TabView.cs 17 KB

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