ScrollBar.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. #nullable enable
  2. using System.ComponentModel;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Indicates the size of scrollable content and controls the position of the visible content, either vertically or
  6. /// horizontally.
  7. /// Two <see cref="Button"/>s are provided, one to scroll up or left and one to scroll down or right. Between the
  8. /// buttons is a <see cref="ScrollSlider"/> that can be dragged to
  9. /// control the position of the visible content. The ScrollSlier is sized to show the proportion of the scrollable
  10. /// content to the size of the <see cref="View.Viewport"/>.
  11. /// </summary>
  12. /// <remarks>
  13. /// <para>
  14. /// See the <see href="https://gui-cs.github.io/Terminal.GuiV2Docs/docs/scrolling.html">Scrolling Deep Dive</see>.
  15. /// </para>
  16. /// <para>
  17. /// By default, the built-in View scrollbars (<see cref="View.VerticalScrollBar"/>/
  18. /// <see cref="View.HorizontalScrollBar"/>) have both <see cref="View.Visible"/> and <see cref="AutoShow"/> set to
  19. /// <see langword="false"/>.
  20. /// To enable them, either set <see cref="AutoShow"/> set to <see langword="true"/> or explicitly set
  21. /// <see cref="View.Visible"/>
  22. /// to <see langword="true"/>.
  23. /// </para>
  24. /// <para>
  25. /// By default, this view cannot be focused and does not support keyboard input.
  26. /// </para>
  27. /// </remarks>
  28. public class ScrollBar : View, IOrientation, IDesignable
  29. {
  30. private readonly Button _decreaseButton;
  31. private readonly ScrollSlider _slider;
  32. private readonly Button _increaseButton;
  33. /// <inheritdoc/>
  34. public ScrollBar ()
  35. {
  36. // Set the default width and height based on the orientation - fill Viewport
  37. Width = Dim.Auto (
  38. DimAutoStyle.Content,
  39. Dim.Func (() => Orientation == Orientation.Vertical ? 1 : SuperView?.Viewport.Width ?? 0));
  40. Height = Dim.Auto (
  41. DimAutoStyle.Content,
  42. Dim.Func (() => Orientation == Orientation.Vertical ? SuperView?.Viewport.Height ?? 0 : 1));
  43. _decreaseButton = new ()
  44. {
  45. CanFocus = false,
  46. NoDecorations = true,
  47. NoPadding = true,
  48. ShadowStyle = ShadowStyle.None,
  49. WantContinuousButtonPressed = true
  50. };
  51. _decreaseButton.Accepting += OnDecreaseButtonOnAccept;
  52. _slider = new ()
  53. {
  54. SliderPadding = 2 // For the buttons
  55. };
  56. _slider.Scrolled += SliderOnScroll;
  57. _slider.PositionChanged += SliderOnPositionChanged;
  58. _increaseButton = new ()
  59. {
  60. CanFocus = false,
  61. NoDecorations = true,
  62. NoPadding = true,
  63. ShadowStyle = ShadowStyle.None,
  64. WantContinuousButtonPressed = true
  65. };
  66. _increaseButton.Accepting += OnIncreaseButtonOnAccept;
  67. Add (_decreaseButton, _slider, _increaseButton);
  68. CanFocus = false;
  69. _orientationHelper = new (this); // Do not use object initializer!
  70. _orientationHelper.Orientation = Orientation.Vertical;
  71. // This sets the width/height etc...
  72. OnOrientationChanged (Orientation);
  73. return;
  74. void OnDecreaseButtonOnAccept (object? s, CommandEventArgs e)
  75. {
  76. Position -= Increment;
  77. e.Cancel = true;
  78. }
  79. void OnIncreaseButtonOnAccept (object? s, CommandEventArgs e)
  80. {
  81. Position += Increment;
  82. e.Cancel = true;
  83. }
  84. }
  85. /// <inheritdoc/>
  86. protected override void OnFrameChanged (in Rectangle frame) { ShowHide (); }
  87. private void ShowHide ()
  88. {
  89. if (AutoShow)
  90. {
  91. Visible = VisibleContentSize < ScrollableContentSize;
  92. }
  93. _slider.VisibleContentSize = VisibleContentSize;
  94. _slider.Size = CalculateSliderSize ();
  95. _sliderPosition = CalculateSliderPositionFromContentPosition (_position);
  96. _slider.Position = _sliderPosition.Value;
  97. }
  98. private void PositionSubviews ()
  99. {
  100. if (Orientation == Orientation.Vertical)
  101. {
  102. _decreaseButton.Y = 0;
  103. _decreaseButton.X = 0;
  104. _decreaseButton.Width = Dim.Fill ();
  105. _decreaseButton.Height = 1;
  106. _decreaseButton.Title = Glyphs.UpArrow.ToString ();
  107. _slider.X = 0;
  108. _slider.Y = 1;
  109. _slider.Width = Dim.Fill ();
  110. _increaseButton.Y = Pos.AnchorEnd ();
  111. _increaseButton.X = 0;
  112. _increaseButton.Width = Dim.Fill ();
  113. _increaseButton.Height = 1;
  114. _increaseButton.Title = Glyphs.DownArrow.ToString ();
  115. }
  116. else
  117. {
  118. _decreaseButton.Y = 0;
  119. _decreaseButton.X = 0;
  120. _decreaseButton.Width = 1;
  121. _decreaseButton.Height = Dim.Fill ();
  122. _decreaseButton.Title = Glyphs.LeftArrow.ToString ();
  123. _slider.Y = 0;
  124. _slider.X = 1;
  125. _slider.Height = Dim.Fill ();
  126. _increaseButton.Y = 0;
  127. _increaseButton.X = Pos.AnchorEnd ();
  128. _increaseButton.Width = 1;
  129. _increaseButton.Height = Dim.Fill ();
  130. _increaseButton.Title = Glyphs.RightArrow.ToString ();
  131. }
  132. }
  133. #region IOrientation members
  134. private readonly OrientationHelper _orientationHelper;
  135. /// <inheritdoc/>
  136. public Orientation Orientation
  137. {
  138. get => _orientationHelper.Orientation;
  139. set => _orientationHelper.Orientation = value;
  140. }
  141. /// <inheritdoc/>
  142. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  143. /// <inheritdoc/>
  144. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  145. /// <inheritdoc/>
  146. public void OnOrientationChanged (Orientation newOrientation)
  147. {
  148. TextDirection = Orientation == Orientation.Vertical ? TextDirection.TopBottom_LeftRight : TextDirection.LeftRight_TopBottom;
  149. TextAlignment = Alignment.Center;
  150. VerticalTextAlignment = Alignment.Center;
  151. _slider.Orientation = newOrientation;
  152. PositionSubviews ();
  153. OrientationChanged?.Invoke (this, new (newOrientation));
  154. }
  155. #endregion
  156. /// <summary>
  157. /// Gets or sets the amount each mouse wheel event, or click on the increment/decrement buttons, will
  158. /// incremenet/decrement the <see cref="Position"/>.
  159. /// </summary>
  160. /// <remarks>
  161. /// The default is 1.
  162. /// </remarks>
  163. public int Increment { get; set; } = 1;
  164. // AutoShow should be false by default. Views should not be hidden by default.
  165. private bool _autoShow;
  166. /// <summary>
  167. /// Gets or sets whether <see cref="View.Visible"/> will be set to <see langword="true"/> if the dimension of the
  168. /// scroll bar is less than <see cref="ScrollableContentSize"/> and <see langword="false"/> if greater than or equal
  169. /// to.
  170. /// </summary>
  171. /// <remarks>
  172. /// The default is <see langword="false"/>.
  173. /// </remarks>
  174. public bool AutoShow
  175. {
  176. get => _autoShow;
  177. set
  178. {
  179. if (_autoShow != value)
  180. {
  181. _autoShow = value;
  182. if (!AutoShow)
  183. {
  184. Visible = true;
  185. }
  186. ShowHide ();
  187. SetNeedsLayout ();
  188. }
  189. }
  190. }
  191. private int? _visibleContentSize;
  192. /// <summary>
  193. /// Gets or sets the size of the visible viewport into the content being scrolled, bounded by
  194. /// <see cref="ScrollableContentSize"/>.
  195. /// </summary>
  196. /// <remarks>
  197. /// If not explicitly set, the visible content size will be appropriate dimension of the ScrollBar's Frame.
  198. /// </remarks>
  199. public int VisibleContentSize
  200. {
  201. get
  202. {
  203. if (_visibleContentSize.HasValue)
  204. {
  205. return _visibleContentSize.Value;
  206. }
  207. return Orientation == Orientation.Vertical ? Frame.Height : Frame.Width;
  208. }
  209. set
  210. {
  211. _visibleContentSize = value;
  212. _slider.Size = CalculateSliderSize ();
  213. ShowHide ();
  214. }
  215. }
  216. private int? _scrollableContentSize;
  217. /// <summary>
  218. /// Gets or sets the size of the content that can be scrolled. This is typically set to
  219. /// <see cref="View.GetContentSize()"/>.
  220. /// </summary>
  221. public int ScrollableContentSize
  222. {
  223. get
  224. {
  225. if (_scrollableContentSize.HasValue)
  226. {
  227. return _scrollableContentSize.Value;
  228. }
  229. return Orientation == Orientation.Vertical ? SuperView?.GetContentSize ().Height ?? 0 : SuperView?.GetContentSize ().Width ?? 0;
  230. }
  231. set
  232. {
  233. if (value == _scrollableContentSize || value < 0)
  234. {
  235. return;
  236. }
  237. _scrollableContentSize = value;
  238. _slider.Size = CalculateSliderSize ();
  239. ShowHide ();
  240. if (!Visible)
  241. {
  242. return;
  243. }
  244. OnSizeChanged (value);
  245. ScrollableContentSizeChanged?.Invoke (this, new (in value));
  246. SetNeedsLayout ();
  247. }
  248. }
  249. /// <summary>Called when <see cref="ScrollableContentSize"/> has changed. </summary>
  250. protected virtual void OnSizeChanged (int size) { }
  251. /// <summary>Raised when <see cref="ScrollableContentSize"/> has changed.</summary>
  252. public event EventHandler<EventArgs<int>>? ScrollableContentSizeChanged;
  253. #region Position
  254. private int _position;
  255. /// <summary>
  256. /// Gets or sets the position of the slider relative to <see cref="ScrollableContentSize"/>.
  257. /// </summary>
  258. /// <remarks>
  259. /// <para>
  260. /// The content position is clamped to 0 and <see cref="ScrollableContentSize"/> minus
  261. /// <see cref="VisibleContentSize"/>.
  262. /// </para>
  263. /// <para>
  264. /// Setting will result in the <see cref="PositionChanging"/> and <see cref="PositionChanged"/>
  265. /// events being raised.
  266. /// </para>
  267. /// </remarks>
  268. public int Position
  269. {
  270. get => _position;
  271. set
  272. {
  273. if (value == _position || !Visible)
  274. {
  275. return;
  276. }
  277. // Clamp the value between 0 and Size - VisibleContentSize
  278. int newContentPosition = Math.Clamp (value, 0, Math.Max (0, ScrollableContentSize - VisibleContentSize));
  279. NavigationDirection direction = newContentPosition >= _position ? NavigationDirection.Forward : NavigationDirection.Backward;
  280. if (OnPositionChanging (_position, newContentPosition))
  281. {
  282. return;
  283. }
  284. CancelEventArgs<int> args = new (ref _position, ref newContentPosition);
  285. PositionChanging?.Invoke (this, args);
  286. if (args.Cancel)
  287. {
  288. return;
  289. }
  290. int distance = newContentPosition - _position;
  291. if (_position == newContentPosition)
  292. {
  293. return;
  294. }
  295. _position = newContentPosition;
  296. _sliderPosition = CalculateSliderPositionFromContentPosition (_position, direction);
  297. if (_slider.Position != _sliderPosition)
  298. {
  299. _slider.Position = _sliderPosition.Value;
  300. }
  301. OnPositionChanged (_position);
  302. PositionChanged?.Invoke (this, new (in _position));
  303. OnScrolled (distance);
  304. Scrolled?.Invoke (this, new (in distance));
  305. SetNeedsLayout ();
  306. }
  307. }
  308. /// <summary>
  309. /// Called when <see cref="Position"/> is changing. Return true to cancel the change.
  310. /// </summary>
  311. protected virtual bool OnPositionChanging (int currentPos, int newPos) { return false; }
  312. /// <summary>
  313. /// Raised when the <see cref="Position"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to
  314. /// <see langword="true"/> to prevent the position from being changed.
  315. /// </summary>
  316. public event EventHandler<CancelEventArgs<int>>? PositionChanging;
  317. /// <summary>Called when <see cref="Position"/> has changed.</summary>
  318. protected virtual void OnPositionChanged (int position) { }
  319. /// <summary>Raised when the <see cref="Position"/> has changed.</summary>
  320. public event EventHandler<EventArgs<int>>? PositionChanged;
  321. /// <summary>Called when <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  322. protected virtual void OnScrolled (int distance) { }
  323. /// <summary>Raised when the <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  324. public event EventHandler<EventArgs<int>>? Scrolled;
  325. /// <summary>
  326. /// INTERNAL API (for unit tests) - Calculates the position within the <see cref="ScrollableContentSize"/> based on the
  327. /// slider position.
  328. /// </summary>
  329. /// <remarks>
  330. /// Clamps the sliderPosition, ensuring the returned content position is always less than
  331. /// <see cref="ScrollableContentSize"/> - <see cref="VisibleContentSize"/>.
  332. /// </remarks>
  333. /// <param name="sliderPosition"></param>
  334. /// <returns></returns>
  335. internal int CalculatePositionFromSliderPosition (int sliderPosition)
  336. {
  337. int scrollBarSize = Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width;
  338. return ScrollSlider.CalculateContentPosition (ScrollableContentSize, VisibleContentSize, sliderPosition, scrollBarSize - _slider.SliderPadding);
  339. }
  340. #endregion ContentPosition
  341. #region Slider Management
  342. private int? _sliderPosition;
  343. /// <summary>
  344. /// INTERNAL (for unit tests). Calculates the size of the slider based on the Orientation, VisibleContentSize, the
  345. /// actual Viewport, and Size.
  346. /// </summary>
  347. /// <returns></returns>
  348. internal int CalculateSliderSize ()
  349. {
  350. int maxSliderSize = (Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width) - 2;
  351. return ScrollSlider.CalculateSize (ScrollableContentSize, VisibleContentSize, maxSliderSize);
  352. }
  353. private void SliderOnPositionChanged (object? sender, EventArgs<int> e)
  354. {
  355. if (VisibleContentSize == 0)
  356. {
  357. return;
  358. }
  359. RaiseSliderPositionChangeEvents (_sliderPosition, e.CurrentValue);
  360. }
  361. private void SliderOnScroll (object? sender, EventArgs<int> e)
  362. {
  363. if (VisibleContentSize == 0)
  364. {
  365. return;
  366. }
  367. int calculatedSliderPos = CalculateSliderPositionFromContentPosition (
  368. _position,
  369. e.CurrentValue >= 0 ? NavigationDirection.Forward : NavigationDirection.Backward);
  370. if (calculatedSliderPos == _sliderPosition)
  371. {
  372. return;
  373. }
  374. int sliderScrolledAmount = e.CurrentValue;
  375. int calculatedPosition = CalculatePositionFromSliderPosition (calculatedSliderPos + sliderScrolledAmount);
  376. Position = calculatedPosition;
  377. }
  378. /// <summary>
  379. /// Gets or sets the position of the start of the Scroll slider, within the Viewport.
  380. /// </summary>
  381. public int GetSliderPosition () { return CalculateSliderPositionFromContentPosition (_position); }
  382. private void RaiseSliderPositionChangeEvents (int? currentSliderPosition, int newSliderPosition)
  383. {
  384. if (currentSliderPosition == newSliderPosition)
  385. {
  386. return;
  387. }
  388. _sliderPosition = newSliderPosition;
  389. OnSliderPositionChanged (newSliderPosition);
  390. SliderPositionChanged?.Invoke (this, new (in newSliderPosition));
  391. }
  392. /// <summary>Called when the slider position has changed.</summary>
  393. protected virtual void OnSliderPositionChanged (int position) { }
  394. /// <summary>Raised when the slider position has changed.</summary>
  395. public event EventHandler<EventArgs<int>>? SliderPositionChanged;
  396. /// <summary>
  397. /// INTERNAL API (for unit tests) - Calculates the position of the slider based on the content position.
  398. /// </summary>
  399. /// <param name="contentPosition"></param>
  400. /// <param name="direction"></param>
  401. /// <returns></returns>
  402. internal int CalculateSliderPositionFromContentPosition (int contentPosition, NavigationDirection direction = NavigationDirection.Forward)
  403. {
  404. int scrollBarSize = Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width;
  405. return ScrollSlider.CalculatePosition (ScrollableContentSize, VisibleContentSize, contentPosition, scrollBarSize - 2, direction);
  406. }
  407. #endregion Slider Management
  408. /// <inheritdoc/>
  409. protected override bool OnClearingViewport ()
  410. {
  411. if (Orientation == Orientation.Vertical)
  412. {
  413. FillRect (Viewport with { Y = Viewport.Y + 1, Height = Viewport.Height - 2 }, Glyphs.Stipple);
  414. }
  415. else
  416. {
  417. FillRect (Viewport with { X = Viewport.X + 1, Width = Viewport.Width - 2 }, Glyphs.Stipple);
  418. }
  419. SetNeedsDraw ();
  420. return true;
  421. }
  422. // TODO: Change this to work OnMouseEvent with continuouse press and grab so it's continous.
  423. /// <inheritdoc/>
  424. protected override bool OnMouseClick (MouseEventArgs args)
  425. {
  426. // Check if the mouse click is a single click
  427. if (!args.IsSingleClicked)
  428. {
  429. return false;
  430. }
  431. int sliderCenter;
  432. int distanceFromCenter;
  433. if (Orientation == Orientation.Vertical)
  434. {
  435. sliderCenter = 1 + _slider.Frame.Y + _slider.Frame.Height / 2;
  436. distanceFromCenter = args.Position.Y - sliderCenter;
  437. }
  438. else
  439. {
  440. sliderCenter = 1 + _slider.Frame.X + _slider.Frame.Width / 2;
  441. distanceFromCenter = args.Position.X - sliderCenter;
  442. }
  443. #if PROPORTIONAL_SCROLL_JUMP
  444. // TODO: This logic mostly works to provide a proportional jump. However, the math
  445. // TODO: falls apart in edge cases. Most other scroll bars (e.g. Windows) do not do proportional
  446. // TODO: Thus, this is disabled; we just jump a page each click.
  447. // Ratio of the distance to the viewport dimension
  448. double ratio = (double)Math.Abs (distanceFromCenter) / (VisibleContentSize);
  449. // Jump size based on the ratio and the total content size
  450. int jump = (int)(ratio * (Size - VisibleContentSize));
  451. #else
  452. int jump = VisibleContentSize;
  453. #endif
  454. // Adjust the content position based on the distance
  455. if (distanceFromCenter < 0)
  456. {
  457. Position = Math.Max (0, Position - jump);
  458. }
  459. else
  460. {
  461. Position = Math.Min (ScrollableContentSize - _slider.VisibleContentSize, Position + jump);
  462. }
  463. return true;
  464. }
  465. /// <inheritdoc/>
  466. protected override bool OnMouseEvent (MouseEventArgs mouseEvent)
  467. {
  468. if (SuperView is null)
  469. {
  470. return false;
  471. }
  472. if (!mouseEvent.IsWheel)
  473. {
  474. return false;
  475. }
  476. if (Orientation == Orientation.Vertical)
  477. {
  478. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledDown))
  479. {
  480. Position += Increment;
  481. }
  482. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledUp))
  483. {
  484. Position -= Increment;
  485. }
  486. }
  487. else
  488. {
  489. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledRight))
  490. {
  491. Position += Increment;
  492. }
  493. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledLeft))
  494. {
  495. Position -= Increment;
  496. }
  497. }
  498. return true;
  499. }
  500. /// <inheritdoc/>
  501. public bool EnableForDesign ()
  502. {
  503. OrientationChanged += (sender, args) =>
  504. {
  505. if (args.CurrentValue == Orientation.Vertical)
  506. {
  507. Width = 1;
  508. Height = Dim.Fill ();
  509. }
  510. else
  511. {
  512. Width = Dim.Fill ();
  513. Height = 1;
  514. }
  515. };
  516. Width = 1;
  517. Height = Dim.Fill ();
  518. ScrollableContentSize = 250;
  519. return true;
  520. }
  521. }