ScrollSlider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #nullable enable
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. namespace Terminal.Gui;
  6. /// <summary>
  7. /// The ScrollSlider can be dragged with the mouse, constrained by the size of the Viewport of it's superview. The
  8. /// ScrollSlider can be
  9. /// oriented either vertically or horizontally.
  10. /// </summary>
  11. /// <remarks>
  12. /// <para>
  13. /// If <see cref="View.Text"/> is set, it will be displayed centered within the slider. Set
  14. /// <see cref="ShowPercent"/> to automatically have the Text
  15. /// be show what percent the slider is to the Superview's Viewport size.
  16. /// </para>
  17. /// <para>
  18. /// Used to represent the proportion of the visible content to the Viewport in a <see cref="Scrolled"/>.
  19. /// </para>
  20. /// </remarks>
  21. public class ScrollSlider : View, IOrientation, IDesignable
  22. {
  23. /// <summary>
  24. /// Initializes a new instance.
  25. /// </summary>
  26. public ScrollSlider ()
  27. {
  28. Id = "scrollSlider";
  29. WantMousePositionReports = true;
  30. _orientationHelper = new (this); // Do not use object initializer!
  31. _orientationHelper.Orientation = Orientation.Vertical;
  32. _orientationHelper.OrientationChanging += (sender, e) => OrientationChanging?.Invoke (this, e);
  33. _orientationHelper.OrientationChanged += (sender, e) => OrientationChanged?.Invoke (this, e);
  34. OnOrientationChanged (Orientation);
  35. HighlightStyle = HighlightStyle.Hover;
  36. }
  37. #region IOrientation members
  38. private readonly OrientationHelper _orientationHelper;
  39. /// <inheritdoc/>
  40. public Orientation Orientation
  41. {
  42. get => _orientationHelper.Orientation;
  43. set => _orientationHelper.Orientation = value;
  44. }
  45. /// <inheritdoc/>
  46. public event EventHandler<CancelEventArgs<Orientation>>? OrientationChanging;
  47. /// <inheritdoc/>
  48. public event EventHandler<EventArgs<Orientation>>? OrientationChanged;
  49. /// <inheritdoc/>
  50. public void OnOrientationChanged (Orientation newOrientation)
  51. {
  52. TextDirection = Orientation == Orientation.Vertical ? TextDirection.TopBottom_LeftRight : TextDirection.LeftRight_TopBottom;
  53. TextAlignment = Alignment.Center;
  54. VerticalTextAlignment = Alignment.Center;
  55. // Reset Position to 0 when changing orientation
  56. X = 0;
  57. Y = 0;
  58. Position = 0;
  59. // Reset opposite dim to Dim.Fill ()
  60. if (Orientation == Orientation.Vertical)
  61. {
  62. Height = Width;
  63. Width = Dim.Fill ();
  64. }
  65. else
  66. {
  67. Width = Height;
  68. Height = Dim.Fill ();
  69. }
  70. SetNeedsLayout ();
  71. }
  72. #endregion
  73. /// <inheritdoc/>
  74. protected override bool OnClearingViewport ()
  75. {
  76. if (Orientation == Orientation.Vertical)
  77. {
  78. FillRect (Viewport with { Height = Size }, Glyphs.ContinuousMeterSegment);
  79. }
  80. else
  81. {
  82. FillRect (Viewport with { Width = Size }, Glyphs.ContinuousMeterSegment);
  83. }
  84. return true;
  85. }
  86. private int? _size;
  87. /// <summary>
  88. /// Gets or sets the size of the ScrollSlider. This is a helper that gets or sets Width or Height depending
  89. /// on <see cref="Orientation"/>. The size will be clamped between 1 and the dimension of
  90. /// the <see cref="View.SuperView"/>'s Viewport.
  91. /// </summary>
  92. /// <remarks>
  93. /// <para>
  94. /// The dimension of the ScrollSlider that is perpendicular to the <see cref="Orientation"/> will be set to
  95. /// <see cref="Dim.Fill()"/>
  96. /// </para>
  97. /// </remarks>
  98. public int Size
  99. {
  100. get => _size ?? 1;
  101. set
  102. {
  103. if (value == _size)
  104. {
  105. return;
  106. }
  107. _size = Math.Clamp (value, 1, VisibleContentSize);
  108. if (Orientation == Orientation.Vertical)
  109. {
  110. Height = _size;
  111. }
  112. else
  113. {
  114. Width = _size;
  115. }
  116. SetNeedsLayout ();
  117. }
  118. }
  119. private int? _visibleContentSize;
  120. /// <summary>
  121. /// Gets or sets the size of the viewport into the content being scrolled. If not explicitly set, will be the
  122. /// greater of 1 and the dimension of the <see cref="View.SuperView"/>.
  123. /// </summary>
  124. public int VisibleContentSize
  125. {
  126. get
  127. {
  128. if (_visibleContentSize.HasValue)
  129. {
  130. return _visibleContentSize.Value;
  131. }
  132. return Math.Max (1, Orientation == Orientation.Vertical ? SuperView?.Viewport.Height ?? 2048 : SuperView?.Viewport.Width ?? 2048);
  133. }
  134. set
  135. {
  136. if (value == _visibleContentSize)
  137. {
  138. return;
  139. }
  140. _visibleContentSize = int.Max (1, value);
  141. if (_position >= _visibleContentSize - _size)
  142. {
  143. Position = _position;
  144. }
  145. SetNeedsLayout ();
  146. }
  147. }
  148. private int _position;
  149. /// <summary>
  150. /// Gets or sets the position of the ScrollSlider relative to the size of the ScrollSlider's Frame.
  151. /// The position will be constrained such that the ScrollSlider will not go outside the Viewport of
  152. /// the <see cref="View.SuperView"/>.
  153. /// </summary>
  154. public int Position
  155. {
  156. get => _position;
  157. set
  158. {
  159. int clampedPosition = ClampPosition (value);
  160. if (_position == clampedPosition)
  161. {
  162. return;
  163. }
  164. RaisePositionChangeEvents (clampedPosition);
  165. SetNeedsLayout ();
  166. }
  167. }
  168. /// <summary>
  169. /// Moves the scroll slider to the specified position. Does not clamp.
  170. /// </summary>
  171. /// <param name="position"></param>
  172. internal void MoveToPosition (int position)
  173. {
  174. if (Orientation == Orientation.Vertical)
  175. {
  176. Y = _position + SliderPadding / 2;
  177. }
  178. else
  179. {
  180. X = _position + SliderPadding / 2;
  181. }
  182. }
  183. /// <summary>
  184. /// INTERNAL API (for unit tests) - Clamps the position such that the right side of the slider
  185. /// never goes past the edge of the Viewport.
  186. /// </summary>
  187. /// <param name="newPosition"></param>
  188. /// <returns></returns>
  189. internal int ClampPosition (int newPosition)
  190. {
  191. return Math.Clamp (newPosition, 0, Math.Max (SliderPadding / 2, VisibleContentSize - SliderPadding - Size));
  192. }
  193. private void RaisePositionChangeEvents (int newPosition)
  194. {
  195. if (OnPositionChanging (_position, newPosition))
  196. {
  197. return;
  198. }
  199. CancelEventArgs<int> args = new (ref _position, ref newPosition);
  200. PositionChanging?.Invoke (this, args);
  201. if (args.Cancel)
  202. {
  203. return;
  204. }
  205. int distance = newPosition - _position;
  206. _position = ClampPosition (newPosition);
  207. MoveToPosition (_position);
  208. OnPositionChanged (_position);
  209. PositionChanged?.Invoke (this, new (in _position));
  210. OnScrolled (distance);
  211. Scrolled?.Invoke (this, new (in distance));
  212. RaiseSelecting (new (Command.Select, null, null, distance));
  213. }
  214. /// <summary>
  215. /// Called when <see cref="Position"/> is changing. Return true to cancel the change.
  216. /// </summary>
  217. protected virtual bool OnPositionChanging (int currentPos, int newPos) { return false; }
  218. /// <summary>
  219. /// Raised when the <see cref="Position"/> is changing. Set <see cref="CancelEventArgs.Cancel"/> to
  220. /// <see langword="true"/> to prevent the position from being changed.
  221. /// </summary>
  222. public event EventHandler<CancelEventArgs<int>>? PositionChanging;
  223. /// <summary>Called when <see cref="Position"/> has changed.</summary>
  224. protected virtual void OnPositionChanged (int position) { }
  225. /// <summary>Raised when the <see cref="Position"/> has changed.</summary>
  226. public event EventHandler<EventArgs<int>>? PositionChanged;
  227. /// <summary>Called when <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  228. protected virtual void OnScrolled (int distance) { }
  229. /// <summary>Raised when the <see cref="Position"/> has changed. Indicates how much to scroll.</summary>
  230. public event EventHandler<EventArgs<int>>? Scrolled;
  231. /// <inheritdoc/>
  232. public override Attribute GetNormalColor () { return base.GetHotNormalColor (); }
  233. ///// <inheritdoc/>
  234. private int _lastLocation = -1;
  235. /// <summary>
  236. /// Gets or sets the amount to pad the start and end of the scroll slider. The default is 0.
  237. /// </summary>
  238. /// <remarks>
  239. /// When the scroll slider is used by <see cref="ScrollBar"/>, which has increment and decrement buttons, the
  240. /// SliderPadding should be set to the size of the buttons (typically 2).
  241. /// </remarks>
  242. public int SliderPadding { get; set; }
  243. /// <inheritdoc/>
  244. protected override bool OnMouseEvent (MouseEventArgs mouseEvent)
  245. {
  246. if (SuperView is null)
  247. {
  248. return false;
  249. }
  250. if (mouseEvent.IsSingleDoubleOrTripleClicked)
  251. {
  252. return true;
  253. }
  254. int location = (Orientation == Orientation.Vertical ? mouseEvent.Position.Y : mouseEvent.Position.X);
  255. int offsetFromLastLocation = _lastLocation > -1 ? location - _lastLocation : 0;
  256. int superViewDimension = VisibleContentSize;
  257. if (mouseEvent.IsPressed || mouseEvent.IsReleased)
  258. {
  259. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Pressed) && _lastLocation == -1)
  260. {
  261. if (Application.MouseGrabView != this)
  262. {
  263. Application.GrabMouse (this);
  264. _lastLocation = location;
  265. }
  266. }
  267. else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition))
  268. {
  269. int currentLocation;
  270. if (Orientation == Orientation.Vertical)
  271. {
  272. currentLocation = Frame.Y;
  273. }
  274. else
  275. {
  276. currentLocation = Frame.X;
  277. }
  278. currentLocation -= SliderPadding / 2;
  279. int newLocation = currentLocation + offsetFromLastLocation;
  280. Position = newLocation;
  281. }
  282. else if (mouseEvent.Flags == MouseFlags.Button1Released)
  283. {
  284. _lastLocation = -1;
  285. if (Application.MouseGrabView == this)
  286. {
  287. Application.UngrabMouse ();
  288. }
  289. }
  290. return true;
  291. }
  292. return false;
  293. }
  294. /// <summary>
  295. /// Gets the slider size.
  296. /// </summary>
  297. /// <param name="scrollableContentSize">The size of the content.</param>
  298. /// <param name="visibleContentSize">The size of the visible content.</param>
  299. /// <param name="sliderBounds">The bounds of the area the slider moves in (e.g. the size of the <see cref="ScrollBar"/> minus 2).</param>
  300. public static int CalculateSize (
  301. int scrollableContentSize,
  302. int visibleContentSize,
  303. int sliderBounds
  304. )
  305. {
  306. if (scrollableContentSize <= 0 || sliderBounds <= 0)
  307. {
  308. return 1; // Slider must be at least 1
  309. }
  310. if (visibleContentSize <= 0 || scrollableContentSize <= visibleContentSize)
  311. {
  312. return sliderBounds;
  313. }
  314. double sliderSizeD = ((double)visibleContentSize / scrollableContentSize) * sliderBounds;
  315. int sliderSize = (int)Math.Floor (sliderSizeD);
  316. return Math.Clamp (sliderSize, 1, sliderBounds);
  317. }
  318. /// <summary>
  319. /// Calculates the slider position.
  320. /// </summary>
  321. /// <param name="scrollableContentSize">The size of the content.</param>
  322. /// <param name="visibleContentSize">The size of the visible content.</param>
  323. /// <param name="contentPosition">The position in the content (between 0 and <paramref name="scrollableContentSize"/>).</param>
  324. /// <param name="sliderBounds">The bounds of the area the slider moves in (e.g. the size of the <see cref="ScrollBar"/> minus 2).</param>
  325. /// <param name="direction">The direction the slider is moving.</param>
  326. internal static int CalculatePosition (
  327. int scrollableContentSize,
  328. int visibleContentSize,
  329. int contentPosition,
  330. int sliderBounds,
  331. NavigationDirection direction
  332. )
  333. {
  334. if (scrollableContentSize - visibleContentSize <= 0 || sliderBounds <= 0)
  335. {
  336. return 0;
  337. }
  338. int calculatedSliderSize = CalculateSize (scrollableContentSize, visibleContentSize, sliderBounds);
  339. double newSliderPosition = ((double)contentPosition / (scrollableContentSize - visibleContentSize)) * (sliderBounds - calculatedSliderSize);
  340. return Math.Clamp ((int)Math.Round (newSliderPosition), 0, sliderBounds - calculatedSliderSize);
  341. }
  342. /// <summary>
  343. /// Calculates the content position.
  344. /// </summary>
  345. /// <param name="scrollableContentSize">The size of the content.</param>
  346. /// <param name="visibleContentSize">The size of the visible content.</param>
  347. /// <param name="sliderPosition">The position of the slider.</param>
  348. /// <param name="sliderBounds">The bounds of the area the slider moves in (e.g. the size of the <see cref="ScrollBar"/> minus 2).</param>
  349. internal static int CalculateContentPosition (
  350. int scrollableContentSize,
  351. int visibleContentSize,
  352. int sliderPosition,
  353. int sliderBounds
  354. )
  355. {
  356. int sliderSize = CalculateSize (scrollableContentSize, visibleContentSize, sliderBounds);
  357. double pos = ((double)(sliderPosition) / (sliderBounds - sliderSize)) * (scrollableContentSize - visibleContentSize);
  358. if (pos is double.NaN)
  359. {
  360. return 0;
  361. }
  362. double rounded = Math.Ceiling (pos);
  363. return (int)Math.Clamp (rounded, 0, Math.Max (0, scrollableContentSize - sliderSize));
  364. }
  365. /// <inheritdoc/>
  366. public bool EnableForDesign ()
  367. {
  368. Size = 5;
  369. return true;
  370. }
  371. }