ScrollBar.cs 21 KB

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