ScrollBar.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. #pragma warning disable CS0067 // The event is never used
  142. /// <inheritdoc/>
  143. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  144. /// <inheritdoc/>
  145. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  146. #pragma warning restore CS0067 // The event is never used
  147. /// <inheritdoc/>
  148. public void OnOrientationChanged (Orientation newOrientation)
  149. {
  150. TextDirection = Orientation == Orientation.Vertical ? TextDirection.TopBottom_LeftRight : TextDirection.LeftRight_TopBottom;
  151. TextAlignment = Alignment.Center;
  152. VerticalTextAlignment = Alignment.Center;
  153. _slider.Orientation = newOrientation;
  154. PositionSubviews ();
  155. OrientationChanged?.Invoke (this, new (newOrientation));
  156. }
  157. #endregion
  158. /// <summary>
  159. /// Gets or sets the amount each mouse wheel event, or click on the increment/decrement buttons, will
  160. /// incremenet/decrement the <see cref="Position"/>.
  161. /// </summary>
  162. /// <remarks>
  163. /// The default is 1.
  164. /// </remarks>
  165. public int Increment { get; set; } = 1;
  166. // AutoShow should be false by default. Views should not be hidden by default.
  167. private bool _autoShow;
  168. /// <summary>
  169. /// Gets or sets whether <see cref="View.Visible"/> will be set to <see langword="true"/> if the dimension of the
  170. /// scroll bar is less than <see cref="ScrollableContentSize"/> and <see langword="false"/> if greater than or equal
  171. /// to.
  172. /// </summary>
  173. /// <remarks>
  174. /// The default is <see langword="false"/>.
  175. /// </remarks>
  176. public bool AutoShow
  177. {
  178. get => _autoShow;
  179. set
  180. {
  181. if (_autoShow != value)
  182. {
  183. _autoShow = value;
  184. if (!AutoShow)
  185. {
  186. Visible = true;
  187. }
  188. ShowHide ();
  189. SetNeedsLayout ();
  190. }
  191. }
  192. }
  193. private int? _visibleContentSize;
  194. /// <summary>
  195. /// Gets or sets the size of the visible viewport into the content being scrolled, bounded by
  196. /// <see cref="ScrollableContentSize"/>.
  197. /// </summary>
  198. /// <remarks>
  199. /// If not explicitly set, the visible content size will be appropriate dimension of the ScrollBar's Frame.
  200. /// </remarks>
  201. public int VisibleContentSize
  202. {
  203. get
  204. {
  205. if (_visibleContentSize.HasValue)
  206. {
  207. return _visibleContentSize.Value;
  208. }
  209. return Orientation == Orientation.Vertical ? Frame.Height : Frame.Width;
  210. }
  211. set
  212. {
  213. _visibleContentSize = value;
  214. _slider.Size = CalculateSliderSize ();
  215. ShowHide ();
  216. }
  217. }
  218. private int? _scrollableContentSize;
  219. /// <summary>
  220. /// Gets or sets the size of the content that can be scrolled. This is typically set to
  221. /// <see cref="View.GetContentSize()"/>.
  222. /// </summary>
  223. public int ScrollableContentSize
  224. {
  225. get
  226. {
  227. if (_scrollableContentSize.HasValue)
  228. {
  229. return _scrollableContentSize.Value;
  230. }
  231. return Orientation == Orientation.Vertical ? SuperView?.GetContentSize ().Height ?? 0 : SuperView?.GetContentSize ().Width ?? 0;
  232. }
  233. set
  234. {
  235. if (value == _scrollableContentSize || value < 0)
  236. {
  237. return;
  238. }
  239. _scrollableContentSize = value;
  240. _slider.Size = CalculateSliderSize ();
  241. ShowHide ();
  242. if (!Visible)
  243. {
  244. return;
  245. }
  246. OnSizeChanged (value);
  247. ScrollableContentSizeChanged?.Invoke (this, new (in value));
  248. SetNeedsLayout ();
  249. }
  250. }
  251. /// <summary>Called when <see cref="ScrollableContentSize"/> has changed. </summary>
  252. protected virtual void OnSizeChanged (int size) { }
  253. /// <summary>Raised when <see cref="ScrollableContentSize"/> has changed.</summary>
  254. public event EventHandler<EventArgs<int>>? ScrollableContentSizeChanged;
  255. #region Position
  256. private int _position;
  257. /// <summary>
  258. /// Gets or sets the position of the slider relative to <see cref="ScrollableContentSize"/>.
  259. /// </summary>
  260. /// <remarks>
  261. /// <para>
  262. /// The content position is clamped to 0 and <see cref="ScrollableContentSize"/> minus
  263. /// <see cref="VisibleContentSize"/>.
  264. /// </para>
  265. /// <para>
  266. /// Setting will result in the <see cref="PositionChanging"/> and <see cref="PositionChanged"/>
  267. /// events being raised.
  268. /// </para>
  269. /// </remarks>
  270. public int Position
  271. {
  272. get => _position;
  273. set
  274. {
  275. if (value == _position || !Visible)
  276. {
  277. return;
  278. }
  279. // Clamp the value between 0 and Size - VisibleContentSize
  280. int newContentPosition = Math.Clamp (value, 0, Math.Max (0, ScrollableContentSize - VisibleContentSize));
  281. NavigationDirection direction = newContentPosition >= _position ? NavigationDirection.Forward : NavigationDirection.Backward;
  282. if (OnPositionChanging (_position, newContentPosition))
  283. {
  284. return;
  285. }
  286. CancelEventArgs<int> args = new (ref _position, ref newContentPosition);
  287. PositionChanging?.Invoke (this, args);
  288. if (args.Cancel)
  289. {
  290. return;
  291. }
  292. int distance = newContentPosition - _position;
  293. if (_position == newContentPosition)
  294. {
  295. return;
  296. }
  297. _position = newContentPosition;
  298. _sliderPosition = CalculateSliderPositionFromContentPosition (_position, direction);
  299. if (_slider.Position != _sliderPosition)
  300. {
  301. _slider.Position = _sliderPosition.Value;
  302. }
  303. OnPositionChanged (_position);
  304. PositionChanged?.Invoke (this, new (in _position));
  305. OnScrolled (distance);
  306. Scrolled?.Invoke (this, new (in distance));
  307. SetNeedsLayout ();
  308. }
  309. }
  310. /// <summary>
  311. /// Called when <see cref="Position"/> is changing. Return true to cancel the change.
  312. /// </summary>
  313. protected virtual bool OnPositionChanging (int currentPos, int newPos) { return false; }
  314. /// <summary>
  315. /// Raised when the <see cref="Position"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to
  316. /// <see langword="true"/> to prevent the position from being changed.
  317. /// </summary>
  318. public event EventHandler<CancelEventArgs<int>>? PositionChanging;
  319. /// <summary>Called when <see cref="Position"/> has changed.</summary>
  320. protected virtual void OnPositionChanged (int position) { }
  321. /// <summary>Raised when the <see cref="Position"/> has changed.</summary>
  322. public event EventHandler<EventArgs<int>>? PositionChanged;
  323. /// <summary>Called when <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  324. protected virtual void OnScrolled (int distance) { }
  325. /// <summary>Raised when the <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  326. public event EventHandler<EventArgs<int>>? Scrolled;
  327. /// <summary>
  328. /// INTERNAL API (for unit tests) - Calculates the position within the <see cref="ScrollableContentSize"/> based on the
  329. /// slider position.
  330. /// </summary>
  331. /// <remarks>
  332. /// Clamps the sliderPosition, ensuring the returned content position is always less than
  333. /// <see cref="ScrollableContentSize"/> - <see cref="VisibleContentSize"/>.
  334. /// </remarks>
  335. /// <param name="sliderPosition"></param>
  336. /// <returns></returns>
  337. internal int CalculatePositionFromSliderPosition (int sliderPosition)
  338. {
  339. int scrollBarSize = Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width;
  340. return ScrollSlider.CalculateContentPosition (ScrollableContentSize, VisibleContentSize, sliderPosition, scrollBarSize - _slider.SliderPadding);
  341. }
  342. #endregion ContentPosition
  343. #region Slider Management
  344. private int? _sliderPosition;
  345. /// <summary>
  346. /// INTERNAL (for unit tests). Calculates the size of the slider based on the Orientation, VisibleContentSize, the
  347. /// actual Viewport, and Size.
  348. /// </summary>
  349. /// <returns></returns>
  350. internal int CalculateSliderSize ()
  351. {
  352. int maxSliderSize = (Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width) - 2;
  353. return ScrollSlider.CalculateSize (ScrollableContentSize, VisibleContentSize, maxSliderSize);
  354. }
  355. private void SliderOnPositionChanged (object? sender, EventArgs<int> e)
  356. {
  357. if (VisibleContentSize == 0)
  358. {
  359. return;
  360. }
  361. RaiseSliderPositionChangeEvents (_sliderPosition, e.CurrentValue);
  362. }
  363. private void SliderOnScroll (object? sender, EventArgs<int> e)
  364. {
  365. if (VisibleContentSize == 0)
  366. {
  367. return;
  368. }
  369. int calculatedSliderPos = CalculateSliderPositionFromContentPosition (
  370. _position,
  371. e.CurrentValue >= 0 ? NavigationDirection.Forward : NavigationDirection.Backward);
  372. if (calculatedSliderPos == _sliderPosition)
  373. {
  374. return;
  375. }
  376. int sliderScrolledAmount = e.CurrentValue;
  377. int calculatedPosition = CalculatePositionFromSliderPosition (calculatedSliderPos + sliderScrolledAmount);
  378. Position = calculatedPosition;
  379. }
  380. /// <summary>
  381. /// Gets or sets the position of the start of the Scroll slider, within the Viewport.
  382. /// </summary>
  383. public int GetSliderPosition () { return CalculateSliderPositionFromContentPosition (_position); }
  384. private void RaiseSliderPositionChangeEvents (int? currentSliderPosition, int newSliderPosition)
  385. {
  386. if (currentSliderPosition == newSliderPosition)
  387. {
  388. return;
  389. }
  390. _sliderPosition = newSliderPosition;
  391. OnSliderPositionChanged (newSliderPosition);
  392. SliderPositionChanged?.Invoke (this, new (in newSliderPosition));
  393. }
  394. /// <summary>Called when the slider position has changed.</summary>
  395. protected virtual void OnSliderPositionChanged (int position) { }
  396. /// <summary>Raised when the slider position has changed.</summary>
  397. public event EventHandler<EventArgs<int>>? SliderPositionChanged;
  398. /// <summary>
  399. /// INTERNAL API (for unit tests) - Calculates the position of the slider based on the content position.
  400. /// </summary>
  401. /// <param name="contentPosition"></param>
  402. /// <param name="direction"></param>
  403. /// <returns></returns>
  404. internal int CalculateSliderPositionFromContentPosition (int contentPosition, NavigationDirection direction = NavigationDirection.Forward)
  405. {
  406. int scrollBarSize = Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width;
  407. return ScrollSlider.CalculatePosition (ScrollableContentSize, VisibleContentSize, contentPosition, scrollBarSize - 2, direction);
  408. }
  409. #endregion Slider Management
  410. /// <inheritdoc/>
  411. protected override bool OnClearingViewport ()
  412. {
  413. if (Orientation == Orientation.Vertical)
  414. {
  415. FillRect (Viewport with { Y = Viewport.Y + 1, Height = Viewport.Height - 2 }, Glyphs.Stipple);
  416. }
  417. else
  418. {
  419. FillRect (Viewport with { X = Viewport.X + 1, Width = Viewport.Width - 2 }, Glyphs.Stipple);
  420. }
  421. SetNeedsDraw ();
  422. return true;
  423. }
  424. // TODO: Change this to work OnMouseEvent with continuouse press and grab so it's continous.
  425. /// <inheritdoc/>
  426. protected override bool OnMouseClick (MouseEventArgs args)
  427. {
  428. // Check if the mouse click is a single click
  429. if (!args.IsSingleClicked)
  430. {
  431. return false;
  432. }
  433. int sliderCenter;
  434. int distanceFromCenter;
  435. if (Orientation == Orientation.Vertical)
  436. {
  437. sliderCenter = 1 + _slider.Frame.Y + _slider.Frame.Height / 2;
  438. distanceFromCenter = args.Position.Y - sliderCenter;
  439. }
  440. else
  441. {
  442. sliderCenter = 1 + _slider.Frame.X + _slider.Frame.Width / 2;
  443. distanceFromCenter = args.Position.X - sliderCenter;
  444. }
  445. #if PROPORTIONAL_SCROLL_JUMP
  446. // TODO: This logic mostly works to provide a proportional jump. However, the math
  447. // TODO: falls apart in edge cases. Most other scroll bars (e.g. Windows) do not do proportional
  448. // TODO: Thus, this is disabled; we just jump a page each click.
  449. // Ratio of the distance to the viewport dimension
  450. double ratio = (double)Math.Abs (distanceFromCenter) / (VisibleContentSize);
  451. // Jump size based on the ratio and the total content size
  452. int jump = (int)(ratio * (Size - VisibleContentSize));
  453. #else
  454. int jump = VisibleContentSize;
  455. #endif
  456. // Adjust the content position based on the distance
  457. if (distanceFromCenter < 0)
  458. {
  459. Position = Math.Max (0, Position - jump);
  460. }
  461. else
  462. {
  463. Position = Math.Min (ScrollableContentSize - _slider.VisibleContentSize, Position + jump);
  464. }
  465. return true;
  466. }
  467. /// <inheritdoc/>
  468. protected override bool OnMouseEvent (MouseEventArgs mouseEvent)
  469. {
  470. if (SuperView is null)
  471. {
  472. return false;
  473. }
  474. if (!mouseEvent.IsWheel)
  475. {
  476. return false;
  477. }
  478. if (Orientation == Orientation.Vertical)
  479. {
  480. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledDown))
  481. {
  482. Position += Increment;
  483. }
  484. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledUp))
  485. {
  486. Position -= Increment;
  487. }
  488. }
  489. else
  490. {
  491. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledRight))
  492. {
  493. Position += Increment;
  494. }
  495. if (mouseEvent.Flags.HasFlag (MouseFlags.WheeledLeft))
  496. {
  497. Position -= Increment;
  498. }
  499. }
  500. return true;
  501. }
  502. /// <inheritdoc/>
  503. public bool EnableForDesign ()
  504. {
  505. OrientationChanged += (sender, args) =>
  506. {
  507. if (args.CurrentValue == Orientation.Vertical)
  508. {
  509. Width = 1;
  510. Height = Dim.Fill ();
  511. }
  512. else
  513. {
  514. Width = Dim.Fill ();
  515. Height = 1;
  516. }
  517. };
  518. Width = 1;
  519. Height = Dim.Fill ();
  520. ScrollableContentSize = 250;
  521. return true;
  522. }
  523. }