ScrollBar.cs 20 KB

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