ScrollSlider.cs 14 KB

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