TabView.cs 18 KB

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