ScrollBar.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #nullable enable
  2. using System.ComponentModel;
  3. using System.Drawing;
  4. namespace Terminal.Gui;
  5. /// <summary>
  6. /// Indicates the size of scrollable content and provides a visible element, referred to as the "ScrollSlider" that
  7. /// that is sized to
  8. /// show the proportion of the scrollable content to the size of the <see cref="View.Viewport"/>. The ScrollSlider
  9. /// can be dragged with the mouse. A Scroll can be oriented either vertically or horizontally and is used within a
  10. /// <see cref="ScrollBar"/>.
  11. /// </summary>
  12. /// <remarks>
  13. /// <para>
  14. /// By default, this view cannot be focused and does not support keyboard.
  15. /// </para>
  16. /// </remarks>
  17. public class ScrollBar : View, IOrientation, IDesignable
  18. {
  19. private readonly Button _decreaseButton;
  20. internal readonly ScrollSlider _slider;
  21. private readonly Button _increaseButton;
  22. /// <inheritdoc/>
  23. public ScrollBar ()
  24. {
  25. _decreaseButton = new ()
  26. {
  27. CanFocus = false,
  28. NoDecorations = true,
  29. NoPadding = true,
  30. ShadowStyle = ShadowStyle.None,
  31. WantContinuousButtonPressed = true
  32. };
  33. _decreaseButton.Accepting += OnDecreaseButtonOnAccept;
  34. _slider = new ()
  35. {
  36. SliderPadding = 2, // For the buttons
  37. };
  38. _slider.Scrolled += SliderOnScroll;
  39. _slider.PositionChanged += SliderOnPositionChanged;
  40. _increaseButton = new ()
  41. {
  42. CanFocus = false,
  43. NoDecorations = true,
  44. NoPadding = true,
  45. ShadowStyle = ShadowStyle.None,
  46. WantContinuousButtonPressed = true
  47. };
  48. _increaseButton.Accepting += OnIncreaseButtonOnAccept;
  49. base.Add (_decreaseButton, _slider, _increaseButton);
  50. CanFocus = false;
  51. _orientationHelper = new (this); // Do not use object initializer!
  52. _orientationHelper.Orientation = Orientation.Vertical;
  53. //_orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  54. //_orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  55. // This sets the width/height etc...
  56. OnOrientationChanged (Orientation);
  57. void OnDecreaseButtonOnAccept (object? s, CommandEventArgs e)
  58. {
  59. Position -= Increment;
  60. e.Cancel = true;
  61. }
  62. void OnIncreaseButtonOnAccept (object? s, CommandEventArgs e)
  63. {
  64. Position += Increment;
  65. e.Cancel = true;
  66. }
  67. }
  68. /// <inheritdoc/>
  69. protected override void OnFrameChanged (in Rectangle frame)
  70. {
  71. if (Orientation == Orientation.Vertical)
  72. {
  73. _slider.VisibleContentSize = Viewport.Height;
  74. }
  75. else
  76. {
  77. _slider.VisibleContentSize = Viewport.Width;
  78. }
  79. _slider.Size = CalculateSliderSize ();
  80. ShowHide ();
  81. }
  82. private void ShowHide ()
  83. {
  84. if (!AutoHide)
  85. {
  86. return;
  87. }
  88. if (Orientation == Orientation.Vertical)
  89. {
  90. Visible = Frame.Height < ScrollableContentSize;
  91. }
  92. else
  93. {
  94. Visible = Frame.Width < ScrollableContentSize;
  95. }
  96. _slider.Size = CalculateSliderSize ();
  97. _sliderPosition = CalculateSliderPositionFromContentPosition (_position, NavigationDirection.Forward);
  98. _slider.Position = _sliderPosition.Value;
  99. }
  100. /// <inheritdoc/>
  101. protected override void OnSubviewLayout (LayoutEventArgs args)
  102. {
  103. }
  104. private void PositionSubviews ()
  105. {
  106. if (Orientation == Orientation.Vertical)
  107. {
  108. _decreaseButton.Y = 0;
  109. _decreaseButton.X = 0;
  110. _decreaseButton.Width = Dim.Fill ();
  111. _decreaseButton.Height = 1;
  112. _decreaseButton.Title = Glyphs.UpArrow.ToString ();
  113. _slider.X = 0;
  114. _slider.Y = 1;
  115. _slider.Width = Dim.Fill ();
  116. _increaseButton.Y = Pos.AnchorEnd ();
  117. _increaseButton.X = 0;
  118. _increaseButton.Width = Dim.Fill ();
  119. _increaseButton.Height = 1;
  120. _increaseButton.Title = Glyphs.DownArrow.ToString ();
  121. }
  122. else
  123. {
  124. _decreaseButton.Y = 0;
  125. _decreaseButton.X = 0;
  126. _decreaseButton.Width = 1;
  127. _decreaseButton.Height = Dim.Fill ();
  128. _decreaseButton.Title = Glyphs.LeftArrow.ToString ();
  129. _slider.Y = 0;
  130. _slider.X = 1;
  131. _slider.Height = Dim.Fill ();
  132. _increaseButton.Y = 0;
  133. _increaseButton.X = Pos.AnchorEnd ();
  134. _increaseButton.Width = 1;
  135. _increaseButton.Height = Dim.Fill ();
  136. _increaseButton.Title = Glyphs.RightArrow.ToString ();
  137. }
  138. }
  139. #region IOrientation members
  140. private readonly OrientationHelper _orientationHelper;
  141. /// <inheritdoc/>
  142. public Orientation Orientation
  143. {
  144. get => _orientationHelper.Orientation;
  145. set => _orientationHelper.Orientation = value;
  146. }
  147. /// <inheritdoc/>
  148. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  149. /// <inheritdoc/>
  150. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  151. /// <inheritdoc/>
  152. public void OnOrientationChanged (Orientation newOrientation)
  153. {
  154. TextDirection = Orientation == Orientation.Vertical ? TextDirection.TopBottom_LeftRight : TextDirection.LeftRight_TopBottom;
  155. TextAlignment = Alignment.Center;
  156. VerticalTextAlignment = Alignment.Center;
  157. X = 0;
  158. Y = 0;
  159. if (Orientation == Orientation.Vertical)
  160. {
  161. Width = 1;
  162. Height = Dim.Fill ();
  163. }
  164. else
  165. {
  166. Width = Dim.Fill ();
  167. Height = 1;
  168. }
  169. _slider.Orientation = newOrientation;
  170. PositionSubviews ();
  171. OrientationChanged?.Invoke (this, new (newOrientation));
  172. }
  173. #endregion
  174. /// <summary>
  175. /// Gets or sets the amount each mouse wheel event will incremenet/decrement the <see cref="Position"/>.
  176. /// </summary>
  177. /// <remarks>
  178. /// The default is 1.
  179. /// </remarks>
  180. public int Increment { get; set; } = 1;
  181. private bool _autoHide = true;
  182. /// <summary>
  183. /// Gets or sets whether <see cref="View.Visible"/> will be set to <see langword="false"/> if the dimension of the
  184. /// scroll bar is greater than or equal to <see cref="ScrollableContentSize"/>.
  185. /// </summary>
  186. public bool AutoHide
  187. {
  188. get => _autoHide;
  189. set
  190. {
  191. if (_autoHide != value)
  192. {
  193. _autoHide = value;
  194. if (!AutoHide)
  195. {
  196. Visible = true;
  197. }
  198. SetNeedsLayout ();
  199. }
  200. }
  201. }
  202. public bool KeepContentInAllViewport
  203. {
  204. //get => _scroll.KeepContentInAllViewport;
  205. //set => _scroll.KeepContentInAllViewport = value;
  206. get;
  207. set;
  208. }
  209. /// <summary>
  210. /// Gets or sets whether the Scroll will show the percentage the slider
  211. /// takes up within the <see cref="ScrollableContentSize"/>.
  212. /// </summary>
  213. public bool ShowPercent
  214. {
  215. get => _slider.ShowPercent;
  216. set => _slider.ShowPercent = value;
  217. }
  218. private int? _visibleContentSize;
  219. /// <summary>
  220. /// Gets or sets the size of the visible viewport into the content being scrolled, bounded by <see cref="ScrollableContentSize"/>.
  221. /// </summary>
  222. /// <remarks>
  223. /// If not explicitly set, will be the appropriate dimension of the Scroll's Frame.
  224. /// </remarks>
  225. public int VisibleContentSize
  226. {
  227. get
  228. {
  229. if (_visibleContentSize.HasValue)
  230. {
  231. return _visibleContentSize.Value;
  232. }
  233. return Orientation == Orientation.Vertical ? Frame.Height : Frame.Width;
  234. }
  235. set
  236. {
  237. _visibleContentSize = value;
  238. _slider.Size = CalculateSliderSize ();
  239. }
  240. }
  241. private int _scrollableContentSize;
  242. /// <summary>
  243. /// Gets or sets the size of the content that can be scrolled. This is typically set to <see cref="View.GetContentSize()"/>.
  244. /// </summary>
  245. public int ScrollableContentSize
  246. {
  247. get => _scrollableContentSize;
  248. set
  249. {
  250. if (value == _scrollableContentSize || value < 0)
  251. {
  252. return;
  253. }
  254. _scrollableContentSize = value;
  255. _slider.Size = CalculateSliderSize ();
  256. OnSizeChanged (_scrollableContentSize);
  257. ScrollableContentSizeChanged?.Invoke (this, new (in _scrollableContentSize));
  258. SetNeedsLayout ();
  259. }
  260. }
  261. /// <summary>Called when <see cref="ScrollableContentSize"/> has changed. </summary>
  262. protected virtual void OnSizeChanged (int size) { }
  263. /// <summary>Raised when <see cref="ScrollableContentSize"/> has changed.</summary>
  264. public event EventHandler<EventArgs<int>>? ScrollableContentSizeChanged;
  265. #region Position
  266. private int _position;
  267. /// <summary>
  268. /// Gets or sets the position of the slider relative to <see cref="ScrollableContentSize"/>.
  269. /// </summary>
  270. /// <remarks>
  271. /// <para>
  272. /// The content position is clamped to 0 and <see cref="ScrollableContentSize"/> minus <see cref="VisibleContentSize"/>.
  273. /// </para>
  274. /// <para>
  275. /// Setting will result in the <see cref="PositionChanging"/> and <see cref="PositionChanged"/>
  276. /// events being raised.
  277. /// </para>
  278. /// </remarks>
  279. public int Position
  280. {
  281. get => _position;
  282. set
  283. {
  284. if (value == _position)
  285. {
  286. return;
  287. }
  288. // Clamp the value between 0 and Size - VisibleContentSize
  289. int newContentPosition = (int)Math.Clamp (value, 0, Math.Max (0, ScrollableContentSize - VisibleContentSize));
  290. NavigationDirection direction = newContentPosition >= _position ? NavigationDirection.Forward : NavigationDirection.Backward;
  291. if (OnPositionChanging (_position, newContentPosition))
  292. {
  293. return;
  294. }
  295. CancelEventArgs<int> args = new (ref _position, ref newContentPosition);
  296. PositionChanging?.Invoke (this, args);
  297. if (args.Cancel)
  298. {
  299. return;
  300. }
  301. int distance = newContentPosition - _position;
  302. _position = newContentPosition;
  303. _sliderPosition = CalculateSliderPositionFromContentPosition (_position, direction);
  304. if (_slider.Position != _sliderPosition)
  305. {
  306. _slider.Position = _sliderPosition.Value;
  307. }
  308. OnPositionChanged (_position);
  309. PositionChanged?.Invoke (this, new (in _position));
  310. OnScrolled (distance);
  311. Scrolled?.Invoke (this, new (in distance));
  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 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 actual Viewport, and Size.
  350. /// </summary>
  351. /// <returns></returns>
  352. internal int CalculateSliderSize ()
  353. {
  354. int maxSliderSize = (Orientation == Orientation.Vertical ? Viewport.Height : Viewport.Width) - 2;
  355. return ScrollSlider.CalculateSize (ScrollableContentSize, VisibleContentSize, maxSliderSize);
  356. }
  357. private void SliderOnPositionChanged (object? sender, EventArgs<int> e)
  358. {
  359. if (VisibleContentSize == 0)
  360. {
  361. return;
  362. }
  363. RaiseSliderPositionChangeEvents (_sliderPosition, e.CurrentValue);
  364. }
  365. private void SliderOnScroll (object? sender, EventArgs<int> e)
  366. {
  367. if (VisibleContentSize == 0)
  368. {
  369. return;
  370. }
  371. int calculatedSliderPos = CalculateSliderPositionFromContentPosition (_position, 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 () => 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. // BUGBUG: This logic mostly works to provide a proportional jump. However, the math
  447. // BUGBUG: falls apart in edge cases. Most other scroll bars (e.g. Windows) do not do proportional
  448. // BUGBUG: Thus, this is disabled and 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. }