DraggableProgressBar.axaml.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Primitives;
  4. using Avalonia.Controls.Shapes;
  5. using Avalonia.Data;
  6. using Avalonia.Input;
  7. using Avalonia.Interactivity;
  8. using Avalonia.LogicalTree;
  9. using Avalonia.Media;
  10. using Avalonia.Threading;
  11. using PicView.Avalonia.Navigation;
  12. using PicView.Avalonia.UI;
  13. using PicView.Avalonia.ViewModels;
  14. using PicView.Avalonia.WindowBehavior;
  15. using R3;
  16. namespace PicView.Avalonia.CustomControls;
  17. public class DraggableProgressBar : TemplatedControl
  18. {
  19. // Define the Maximum property
  20. public static readonly StyledProperty<int> MaximumProperty =
  21. AvaloniaProperty.Register<DraggableProgressBar, int>(nameof(Maximum), 100);
  22. // Define the CurrentIndex property with two-way binding
  23. public static readonly StyledProperty<int> CurrentIndexProperty =
  24. AvaloniaProperty.Register<DraggableProgressBar, int>(nameof(CurrentIndex),
  25. defaultBindingMode: BindingMode.TwoWay);
  26. // Define a property for the thumb's fill color
  27. public static readonly StyledProperty<IBrush?> ThumbFillProperty =
  28. AvaloniaProperty.Register<DraggableProgressBar, IBrush?>(nameof(ThumbFill));
  29. // Define the DragSensitivity property
  30. public static readonly StyledProperty<double> DragSensitivityProperty =
  31. AvaloniaProperty.Register<DraggableProgressBar, double>(nameof(DragSensitivity), 1.0);
  32. private int _dragStartIndex;
  33. private Point _dragStartPoint;
  34. private Ellipse? _thumb;
  35. private Border? _track;
  36. private readonly CompositeDisposable _disposables = new();
  37. private bool _shouldUpdate;
  38. static DraggableProgressBar()
  39. {
  40. // This allows the control to react to property changes
  41. AffectsRender<DraggableProgressBar>(CurrentIndexProperty, MaximumProperty);
  42. AffectsMeasure<DraggableProgressBar>(CurrentIndexProperty, MaximumProperty);
  43. }
  44. public DraggableProgressBar()
  45. {
  46. Loaded += OnLoaded;
  47. LostFocus += OnLostFocus;
  48. }
  49. private void OnLostFocus(object? sender, RoutedEventArgs e)
  50. {
  51. IsDragging = false;
  52. }
  53. private void OnLoaded(object? sender, RoutedEventArgs e)
  54. {
  55. ToolTip.SetPlacement(this, PlacementMode.Top);
  56. ToolTip.SetVerticalOffset(this, -3);
  57. // Observe the CurrentIndexProperty for changes,
  58. // wait for a 25ms pause in changes (debounce), and then emit the last value.
  59. CurrentIndexProperty.Changed.ToObservable()
  60. .Debounce(TimeSpan.FromMilliseconds(25))
  61. .Skip(1) // Skip first loading, when it is just setup
  62. .SubscribeAwait(async (x, cancel) =>
  63. {
  64. // Check if the new value exists and is different from the old one.
  65. if (x.NewValue.HasValue && x.OldValue.HasValue && x.NewValue.Value != x.OldValue.Value)
  66. {
  67. if (IsDragging)
  68. {
  69. var isReverse = x.NewValue.Value < x.OldValue.Value;
  70. // Use lightweight image changing (without changing size) while dragging:
  71. await NavigationManager.ImageIterator.IterateToIndexSlim(x.NewValue.Value, isReverse, cancel);
  72. _shouldUpdate = true;
  73. }
  74. else
  75. {
  76. await NavigationManager.ImageIterator.IterateToIndex(x.NewValue.Value, cancel);
  77. _shouldUpdate = false;
  78. }
  79. }
  80. })
  81. .AddTo(_disposables);
  82. UpdateThumbPosition();
  83. }
  84. public bool IsDragging { get; private set; }
  85. public int Maximum
  86. {
  87. get => GetValue(MaximumProperty);
  88. set => SetValue(MaximumProperty, value);
  89. }
  90. public int CurrentIndex
  91. {
  92. get => GetValue(CurrentIndexProperty);
  93. set => SetValue(CurrentIndexProperty, value);
  94. }
  95. public IBrush? ThumbFill
  96. {
  97. get => GetValue(ThumbFillProperty);
  98. set => SetValue(ThumbFillProperty, value);
  99. }
  100. public double DragSensitivity
  101. {
  102. get => GetValue(DragSensitivityProperty);
  103. set => SetValue(DragSensitivityProperty, value);
  104. }
  105. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  106. {
  107. base.OnApplyTemplate(e);
  108. _track = e.NameScope.Find<Border>("PART_Track");
  109. _thumb = e.NameScope.Find<Ellipse>("PART_Thumb");
  110. if (!Settings.Theme.Dark)
  111. {
  112. _track.Background = UIHelper.GetBrush("SecondaryBackgroundColor");
  113. _thumb.Fill = UIHelper.GetBrush("TertiaryBackgroundColor");
  114. }
  115. }
  116. // Recalculate thumb position when CurrentIndex or Maximum changes
  117. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  118. {
  119. base.OnPropertyChanged(change);
  120. if ((change.Property != CurrentIndexProperty && change.Property != MaximumProperty) || IsDragging)
  121. {
  122. return;
  123. }
  124. if (_track is not null && _thumb is not null)
  125. {
  126. UpdateThumbPosition();
  127. }
  128. }
  129. public void UpdateThumbPosition()
  130. {
  131. if (_thumb == null)
  132. {
  133. return;
  134. }
  135. var position = IndexToPosition(CurrentIndex);
  136. if (_thumb.RenderTransform is TranslateTransform transform)
  137. {
  138. transform.X = position;
  139. }
  140. else
  141. {
  142. _thumb.RenderTransform = new TranslateTransform(position, 0);
  143. }
  144. }
  145. protected override void OnPointerPressed(PointerPressedEventArgs e)
  146. {
  147. base.OnPointerPressed(e);
  148. if (_track == null || _thumb == null)
  149. {
  150. return;
  151. }
  152. var properties = e.GetCurrentPoint(_track).Properties;
  153. if (!properties.IsLeftButtonPressed)
  154. {
  155. return;
  156. }
  157. var clickPosition = e.GetPosition(_track);
  158. // Get the thumb's current visual bounds relative to the track
  159. var thumbBounds = _thumb.Bounds;
  160. if (_thumb.RenderTransform is TranslateTransform transform)
  161. {
  162. thumbBounds = thumbBounds.WithX(transform.X);
  163. }
  164. // Expand bounds horizontally by 2x
  165. var expandedBounds = new Rect(
  166. thumbBounds.X - thumbBounds.Width / 2,
  167. thumbBounds.Y,
  168. thumbBounds.Width * 2,
  169. thumbBounds.Height
  170. );
  171. // Check if the click was inside the expanded thumb area
  172. if (!expandedBounds.Contains(clickPosition))
  173. {
  174. // Click was on the track (outside expanded thumb), so jump to position
  175. IsDragging = false;
  176. Task.Run(async () =>
  177. {
  178. await Dispatcher.UIThread.InvokeAsync(() =>
  179. {
  180. UpdateIndexFromPosition(clickPosition.X);
  181. }, DispatcherPriority.Send);
  182. await WindowResizing.SetSizeAsync(DataContext as MainViewModel);
  183. });
  184. }
  185. // Click was on (or near) the thumb, so start dragging
  186. IsDragging = true;
  187. _dragStartPoint = e.GetPosition(this);
  188. _dragStartIndex = CurrentIndex;
  189. e.Pointer.Capture(_thumb);
  190. }
  191. /// <summary>
  192. /// Show Position on hover, or handle dragging
  193. /// </summary>
  194. /// <param name="e"></param>
  195. protected override void OnPointerMoved(PointerEventArgs e)
  196. {
  197. base.OnPointerMoved(e);
  198. if (_track == null || _thumb == null)
  199. {
  200. return;
  201. }
  202. var trackWidth = GetTrackWidth();
  203. if (!IsDragging)
  204. {
  205. // Show index position on hover
  206. var pos = e.GetPosition(_track);
  207. if (GetThumbBounds().Contains(pos))
  208. {
  209. ToolTip.SetIsOpen(this, false);
  210. return;
  211. }
  212. var pointerOverIndex = Math.Max(PositionToIndex(pos.X) + 1, 1);
  213. ToolTip.SetTip(this, $"{pointerOverIndex}/{Maximum}");
  214. ToolTip.SetIsOpen(this, true);
  215. return;
  216. }
  217. // Dragging
  218. var currentPosition = e.GetPosition(this);
  219. var deltaX = currentPosition.X - _dragStartPoint.X;
  220. var pixelsPerIndex = trackWidth / Math.Max(1, Maximum - 1);
  221. var sensitiveDragPerIndex = pixelsPerIndex * DragSensitivity;
  222. if (Math.Abs(sensitiveDragPerIndex) < 0.001)
  223. {
  224. return;
  225. }
  226. var indexChange = deltaX / sensitiveDragPerIndex;
  227. var newIndex = _dragStartIndex + indexChange;
  228. UpdateIndexFromPosition(IndexToPosition((int)Math.Round(newIndex)));
  229. }
  230. protected override void OnPointerReleased(PointerReleasedEventArgs e)
  231. {
  232. base.OnPointerReleased(e);
  233. if (_shouldUpdate)
  234. {
  235. var vm = DataContext as MainViewModel;
  236. // Update from lightweight image loading to properly instantiate everything and update size
  237. _ = NavigationManager.ImageIterator.SlimUpdate(CurrentIndex, vm.PicViewer.ImageSource.CurrentValue);
  238. IsDragging = false;
  239. e.Pointer.Capture(null);
  240. return;
  241. }
  242. if (!IsDragging)
  243. {
  244. return;
  245. }
  246. IsDragging = false;
  247. e.Pointer.Capture(null);
  248. }
  249. private void UpdateIndexFromPosition(double x)
  250. {
  251. var newIndex = PositionToIndex(x);
  252. if (CurrentIndex == newIndex)
  253. {
  254. return;
  255. }
  256. CurrentIndex = newIndex;
  257. UpdateThumbPosition();
  258. }
  259. // Ensure the thumb is in the correct position when the control is resized
  260. protected override Size ArrangeOverride(Size finalSize)
  261. {
  262. var arrangedSize = base.ArrangeOverride(finalSize);
  263. UpdateThumbPosition();
  264. return arrangedSize;
  265. }
  266. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  267. {
  268. base.OnDetachedFromLogicalTree(e);
  269. _disposables.Dispose();
  270. Loaded -= OnLoaded;
  271. LostFocus -= OnLostFocus;
  272. }
  273. #region Helpers
  274. private double GetTrackWidth() =>
  275. _track is { } t && _thumb is { } th ? Math.Max(0, t.Bounds.Width - th.Bounds.Width) : 0;
  276. private Rect GetThumbBounds()
  277. {
  278. if (_thumb is null)
  279. {
  280. return default;
  281. }
  282. var bounds = _thumb.Bounds;
  283. if (_thumb.RenderTransform is TranslateTransform transform)
  284. {
  285. bounds = bounds.WithX(transform.X);
  286. }
  287. return bounds;
  288. }
  289. private int PositionToIndex(double x)
  290. {
  291. var trackWidth = GetTrackWidth();
  292. if (trackWidth <= 0 || Maximum <= 1)
  293. {
  294. return 0;
  295. }
  296. var clampedX = Math.Clamp(x - _thumb!.Width / 2, 0, trackWidth);
  297. var percentage = clampedX / trackWidth;
  298. return (int)Math.Round(percentage * (Maximum - 1));
  299. }
  300. private double IndexToPosition(int index)
  301. {
  302. var trackWidth = GetTrackWidth();
  303. if (trackWidth <= 0 || Maximum <= 1)
  304. {
  305. return 0;
  306. }
  307. var clampedIndex = Math.Clamp(index, 0, Maximum - 1);
  308. return (double)clampedIndex / (Maximum - 1) * trackWidth;
  309. }
  310. #endregion
  311. }