ScrollBar.cs 21 KB

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