ScrollBar.cs 20 KB

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