ScrollBar.cs 20 KB

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