ScrollBar.cs 20 KB

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