ScrollBar.cs 20 KB

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