Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Crop overlay: a Filee stage with an aspect dial, a strip of files and a summary donut
KnifeLemon71335b790bab
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 20a2887f..00ae8d32 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -116,6 +116,29 @@ the drag donut shows files and flips on `FlipKeyPressed` / `FlipWheelTurned`: thcan't hold an event back; Explorer and Finder ignore Tab during a drag) and reports one flip per key press.The editor's Front / Back switch (`ToolbarPageViewModel.EditingBack`) edits either list with the same drag and drop.+## Crop overlay++The Crop tool (`tool-crop`) opens `Views/CropOverlayWindow` instead of running a job: the files one after another,+each cropped by hand and saved by `CropService` (the preset's output rule, the source's quality kept, animated or+multi-frame pictures refused, the EXIF thumbnail dropped), one history entry for the run.++- `CropOverlayViewModel` walks the queue (Enter saves and opens the next file, Skip, Esc closes), keeps a+ `CropQueueItem` per file for the strip of thumbnails (waiting, current, done, skipped, failed; a thumbnail is a+ small copy of the preview, made once) and, after the last file, shows the summary when something failed or was+ skipped. Every file starts free and whole, its portrait/landscape choice following the picture.+- `Controls/CropCanvas` is the stage: the picture inside `ImagePadding`, the part outside the frame frosted (a copy at+ most 40 px across, drawn large) under a veil of the page colour, the frame in the accent colour with round handles,+ a rule-of-thirds grid while dragging and a size chip that follows the frame. The preview is downscaled once by+ `CropService.LoadPreviewAsync`; nothing is decoded again while dragging. Programmatic changes (reset, a ratio, a+ new picture) ease in with tweens read against the clock, so a lost frame never leaves one half done; dragging and+ arrow-key nudges follow at once, and `PlayAnimations` (from `Motion.Enabled`) turns all of it off.+- `Controls/AspectDial` is a small donut of the ratios (free, original, 1:1, 4:3, 3:2, 16:9): each slice a+ `RingSegment` button that answers only inside its wedge (`DonutGeometry.Wedge`, rounded by the softness), the hub+ swaps portrait and landscape. `AspectGlyph` is the dial in miniature on the toolbar button that opens it, and+ `CropSummaryRing` the end summary's donut (a slice per file).+- `Controls/CropMath` holds the arithmetic (ratios and their portrait forms, nudging by whole pixels, the frame in+ pixels, where the size chip goes) and is unit tested.+## Settings and data`UserDataStore` owns `settings.json`, `presets.json`, `profiles.json` and `history.json`diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 95db3665..6913a402 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -174,6 +174,19 @@"crop.aspect_free": "Free","crop.aspect_original": "Original","crop.page_counter": "{0} of {1}",+ "crop.save_next": "Crop & Next",+ "crop.swap": "Swap portrait and landscape (X)",+ "crop.portrait": "Portrait",+ "crop.landscape": "Landscape",+ "crop.hint_keys": "Arrow keys move the frame, Shift × 10 · Esc closes",+ "crop.close_hint": "Close (Esc)",+ "crop.maximize": "Maximize",+ "crop.restore": "Restore",+ "crop.state_current": "Open now",+ "crop.state_waiting": "Waiting",+ "crop.state_done": "Cropped",+ "crop.state_skipped": "Skipped",+ "crop.state_failed": "Failed","preset.half_size": "Half size","preset.grayscale": "Grayscale",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex 2c372ed2..5369e493 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -165,6 +165,19 @@"crop.aspect_free": "Libre","crop.aspect_original": "Original","crop.page_counter": "{0} de {1}",+ "crop.save_next": "Recortar y seguir",+ "crop.swap": "Cambiar entre vertical y horizontal (X)",+ "crop.portrait": "Vertical",+ "crop.landscape": "Horizontal",+ "crop.hint_keys": "Las flechas mueven el marco, Mayús × 10 · Esc cierra",+ "crop.close_hint": "Cerrar (Esc)",+ "crop.maximize": "Maximizar",+ "crop.restore": "Restaurar",+ "crop.state_current": "Abierto ahora",+ "crop.state_waiting": "En espera",+ "crop.state_done": "Recortado",+ "crop.state_skipped": "Omitido",+ "crop.state_failed": "Error","preset.half_size": "Reducir 50 %","preset.grayscale": "Grises","preset.remove_background": "Quitar fondo",diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.jsonindex 1e8c28a6..f47a196f 100644--- a/src/Filee.App/Assets/i18n/hi.json+++ b/src/Filee.App/Assets/i18n/hi.json@@ -165,6 +165,19 @@"crop.aspect_free": "मुक्त","crop.aspect_original": "मूल","crop.page_counter": "{1} में से {0}",+ "crop.save_next": "क्रॉप करके अगला",+ "crop.swap": "खड़ा और आड़ा बदलें (X)",+ "crop.portrait": "खड़ा",+ "crop.landscape": "आड़ा",+ "crop.hint_keys": "ऐरो कुंजियाँ फ़्रेम खिसकाती हैं, Shift से 10 गुना · Esc से बंद करें",+ "crop.close_hint": "बंद करें (Esc)",+ "crop.maximize": "बड़ा करें",+ "crop.restore": "पहले जैसा करें",+ "crop.state_current": "अभी संपादन में",+ "crop.state_waiting": "प्रतीक्षा में",+ "crop.state_done": "क्रॉप हो गया",+ "crop.state_skipped": "छोड़ा गया",+ "crop.state_failed": "विफल","preset.half_size": "आधा आकार","preset.grayscale": "ग्रेस्केल","preset.remove_background": "बैकग्राउंड हटाएँ",diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.jsonindex fbacb1b2..99303d52 100644--- a/src/Filee.App/Assets/i18n/ja.json+++ b/src/Filee.App/Assets/i18n/ja.json@@ -165,6 +165,19 @@"crop.aspect_free": "自由","crop.aspect_original": "元の比率","crop.page_counter": "{0}/{1}",+ "crop.save_next": "トリミングして次へ",+ "crop.swap": "縦向きと横向きを切り替え (X)",+ "crop.portrait": "縦向き",+ "crop.landscape": "横向き",+ "crop.hint_keys": "矢印キーで枠を移動、Shift で 10 倍 · Esc で閉じる",+ "crop.close_hint": "閉じる (Esc)",+ "crop.maximize": "最大化",+ "crop.restore": "元のサイズに戻す",+ "crop.state_current": "表示中",+ "crop.state_waiting": "待機中",+ "crop.state_done": "トリミング済み",+ "crop.state_skipped": "スキップ",+ "crop.state_failed": "失敗","preset.half_size": "縮小 50%","preset.grayscale": "グレースケール","preset.remove_background": "背景を削除",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 90931517..35aedae3 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -174,6 +174,19 @@"crop.aspect_free": "자유","crop.aspect_original": "원본","crop.page_counter": "{0}/{1}",+ "crop.save_next": "자르고 다음으로",+ "crop.swap": "세로/가로 바꾸기 (X)",+ "crop.portrait": "세로",+ "crop.landscape": "가로",+ "crop.hint_keys": "화살표 키로 틀 이동, Shift는 10배 · Esc로 닫기",+ "crop.close_hint": "닫기 (Esc)",+ "crop.maximize": "최대화",+ "crop.restore": "이전 크기로",+ "crop.state_current": "편집 중",+ "crop.state_waiting": "대기 중",+ "crop.state_done": "자르기 완료",+ "crop.state_skipped": "건너뜀",+ "crop.state_failed": "실패","preset.half_size": "50% 축소","preset.grayscale": "흑백",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 81406635..b96ebb8b 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -174,6 +174,19 @@"crop.aspect_free": "Dowolne","crop.aspect_original": "Oryginalne","crop.page_counter": "{0} z {1}",+ "crop.save_next": "Kadruj i dalej",+ "crop.swap": "Zamień pion i poziom (X)",+ "crop.portrait": "Pionowo",+ "crop.landscape": "Poziomo",+ "crop.hint_keys": "Strzałki przesuwają ramkę, Shift × 10 · Esc zamyka",+ "crop.close_hint": "Zamknij (Esc)",+ "crop.maximize": "Maksymalizuj",+ "crop.restore": "Przywróć",+ "crop.state_current": "Otwarty teraz",+ "crop.state_waiting": "Czeka",+ "crop.state_done": "Wykadrowany",+ "crop.state_skipped": "Pominięty",+ "crop.state_failed": "Błąd","preset.half_size": "Połowa rozmiaru","preset.grayscale": "Skala szarości",diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.jsonindex d23e578f..99d4ea5f 100644--- a/src/Filee.App/Assets/i18n/ru.json+++ b/src/Filee.App/Assets/i18n/ru.json@@ -174,6 +174,19 @@"crop.aspect_free": "Произвольные","crop.aspect_original": "Исходные","crop.page_counter": "{0} из {1}",+ "crop.save_next": "Обрезать и дальше",+ "crop.swap": "Поменять книжную и альбомную (X)",+ "crop.portrait": "Книжная",+ "crop.landscape": "Альбомная",+ "crop.hint_keys": "Стрелки двигают рамку, Shift × 10 · Esc закрывает",+ "crop.close_hint": "Закрыть (Esc)",+ "crop.maximize": "Развернуть",+ "crop.restore": "Восстановить",+ "crop.state_current": "Открыт сейчас",+ "crop.state_waiting": "Ожидает",+ "crop.state_done": "Обрезан",+ "crop.state_skipped": "Пропущен",+ "crop.state_failed": "Ошибка","preset.half_size": "Вдвое меньше","preset.grayscale": "Оттенки серого",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex f9489345..3f676d8e 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -174,6 +174,19 @@"crop.aspect_free": "自由","crop.aspect_original": "原始比例","crop.page_counter": "{0}/{1}",+ "crop.save_next": "裁剪并下一张",+ "crop.swap": "切换纵向与横向 (X)",+ "crop.portrait": "纵向",+ "crop.landscape": "横向",+ "crop.hint_keys": "方向键移动裁剪框,Shift 为 10 倍 · Esc 关闭",+ "crop.close_hint": "关闭 (Esc)",+ "crop.maximize": "最大化",+ "crop.restore": "还原",+ "crop.state_current": "正在编辑",+ "crop.state_waiting": "等待中",+ "crop.state_done": "已裁剪",+ "crop.state_skipped": "已跳过",+ "crop.state_failed": "失败","preset.half_size": "缩小 50%","preset.grayscale": "灰度",diff --git a/src/Filee.App/Controls/AspectDial.cs b/src/Filee.App/Controls/AspectDial.csnew file mode 100644index 00000000..c58f5644--- /dev/null+++ b/src/Filee.App/Controls/AspectDial.cs@@ -0,0 +1,301 @@+// The crop overlay's aspect dial: a small donut whose slices are the ratios (free, the picture's own, 1:1, 4:3, 3:2,+// 16:9), each with a tiny outline of its shape, and a hub that swaps portrait and landscape. The slices are real+// buttons (focus, keyboard, screen readers) that only answer inside their wedge. AspectGlyph is the dial in miniature+// on the toolbar button that opens it.++using System.Globalization;+using Avalonia;+using Avalonia.Automation;+using Avalonia.Controls;+using Avalonia.Controls.Documents;+using Avalonia.Media;+using Avalonia.Rendering;++namespace Filee.App.Controls;++/// <summary>Lays out <see cref="RingSegment"/> children as a ring, clockwise from the top, and any other child in the hub.</summary>+public sealed class AspectDial : Panel+{+ public static readonly StyledProperty<double> OuterRadiusProperty =+ AvaloniaProperty.Register<AspectDial, double>(nameof(OuterRadius), 118);++ public static readonly StyledProperty<double> InnerRadiusProperty =+ AvaloniaProperty.Register<AspectDial, double>(nameof(InnerRadius), 52);++ /// <summary>The theme's softness: slices are rounded by half of it, as on the donut.</summary>+ public static readonly StyledProperty<CornerRadius> CornerRadiusProperty =+ AvaloniaProperty.Register<AspectDial, CornerRadius>(nameof(CornerRadius), new CornerRadius(16));++ public static readonly StyledProperty<string?> SelectedModeProperty =+ AvaloniaProperty.Register<AspectDial, string?>(nameof(SelectedMode));++ public static readonly StyledProperty<bool> IsPortraitProperty =+ AvaloniaProperty.Register<AspectDial, bool>(nameof(IsPortrait));++ /// <summary>Width / height of the picture: the outline on the "original" slice.</summary>+ public static readonly StyledProperty<double> OriginalRatioProperty =+ AvaloniaProperty.Register<AspectDial, double>(nameof(OriginalRatio));++ public double OuterRadius { get => GetValue(OuterRadiusProperty); set => SetValue(OuterRadiusProperty, value); }+ public double InnerRadius { get => GetValue(InnerRadiusProperty); set => SetValue(InnerRadiusProperty, value); }+ public CornerRadius CornerRadius { get => GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); }+ public string? SelectedMode { get => GetValue(SelectedModeProperty); set => SetValue(SelectedModeProperty, value); }+ public bool IsPortrait { get => GetValue(IsPortraitProperty); set => SetValue(IsPortraitProperty, value); }+ public double OriginalRatio { get => GetValue(OriginalRatioProperty); set => SetValue(OriginalRatioProperty, value); }++ /// <summary>Gap between slices, as on the donut.</summary>+ public const double Gap = 4;++ static AspectDial()+ {+ AffectsArrange<AspectDial>(OuterRadiusProperty, InnerRadiusProperty, CornerRadiusProperty, SelectedModeProperty,+ IsPortraitProperty, OriginalRatioProperty);+ AffectsMeasure<AspectDial>(OuterRadiusProperty);+ }++ public IEnumerable<RingSegment> Segments => Children.OfType<RingSegment>();++ /// <summary>A donut slice (<see cref="DonutGeometry.Wedge"/>) as a geometry to draw.</summary>+ internal static StreamGeometry WedgeGeometry(Point center, double inner, double outer, double mid, double span, double gap, double corner)+ {+ var outline = DonutGeometry.Wedge(center, inner, outer, mid, span, gap, corner);+ var geometry = new StreamGeometry();+ using var ctx = geometry.Open();+ ctx.BeginFigure(outline.Start, true);+ foreach (var step in outline.Steps)+ {+ if (step.IsArc)+ ctx.ArcTo(step.To, new Size(step.ArcRadius, step.ArcRadius), 0, step.IsLargeArc,+ step.Clockwise ? SweepDirection.Clockwise : SweepDirection.CounterClockwise);+ else+ ctx.LineTo(step.To);+ }+ ctx.EndFigure(true);+ return geometry;+ }++ /// <summary>Width and height of the dial, with room for a hovered slice moving out.</summary>+ public double Side => OuterRadius * 2 + RingSegment.PopOut * 2;++ protected override Size MeasureOverride(Size availableSize)+ {+ var side = Side;+ foreach (var child in Children)+ child.Measure(new Size(side, side));+ return new Size(side, side);+ }++ protected override Size ArrangeOverride(Size finalSize)+ {+ var segments = Segments.ToList();+ var center = new Point(finalSize.Width / 2, finalSize.Height / 2);+ for (var i = 0; i < segments.Count; i++)+ {+ var segment = segments[i];+ segment.Place(center, i, segments.Count, InnerRadius, OuterRadius, Math.Clamp(CornerRadius.TopLeft, 0, 28) * 0.5);+ segment.Show(SelectedMode == segment.Mode, IsPortrait, OriginalRatio);+ segment.Arrange(new Rect(finalSize));+ }++ var hub = (InnerRadius - Gap) * 2;+ foreach (var child in Children.Where(c => c is not RingSegment))+ child.Arrange(new Rect(center.X - hub / 2, center.Y - hub / 2, hub, hub));+ return finalSize;+ }+}++/// <summary>One ratio of the <see cref="AspectDial"/>: a wedge with the ratio's outline and name.</summary>+public sealed class RingSegment : Button, ICustomHitTest+{+ public static readonly StyledProperty<string> ModeProperty =+ AvaloniaProperty.Register<RingSegment, string>(nameof(Mode), "free");++ /// <summary>0 at rest, 1 hovered: the slice moves out a little and lights up (eased by a transition).</summary>+ public static readonly StyledProperty<double> PopProperty =+ AvaloniaProperty.Register<RingSegment, double>(nameof(Pop));++ public static readonly StyledProperty<IBrush?> AccentBrushProperty =+ AvaloniaProperty.Register<RingSegment, IBrush?>(nameof(AccentBrush), Brushes.MediumPurple);++ public static readonly StyledProperty<IBrush?> AccentSoftBrushProperty =+ AvaloniaProperty.Register<RingSegment, IBrush?>(nameof(AccentSoftBrush));++ public static readonly StyledProperty<IBrush?> OnAccentBrushProperty =+ AvaloniaProperty.Register<RingSegment, IBrush?>(nameof(OnAccentBrush), Brushes.White);++ public string Mode { get => GetValue(ModeProperty); set => SetValue(ModeProperty, value); }+ public double Pop { get => GetValue(PopProperty); set => SetValue(PopProperty, value); }+ public IBrush? AccentBrush { get => GetValue(AccentBrushProperty); set => SetValue(AccentBrushProperty, value); }+ public IBrush? AccentSoftBrush { get => GetValue(AccentSoftBrushProperty); set => SetValue(AccentSoftBrushProperty, value); }+ public IBrush? OnAccentBrush { get => GetValue(OnAccentBrushProperty); set => SetValue(OnAccentBrushProperty, value); }++ /// <summary>How far a hovered slice moves out.</summary>+ public const double PopOut = 5;++ private Point _center;+ private int _index;+ private int _count = 1;+ private double _inner;+ private double _outer;+ private double _corner;+ private Geometry? _wedge;+ private bool _portrait;+ private double _originalRatio;++ /// <summary>Whether this slice's ratio is the one in use.</summary>+ public bool IsSelected { get; private set; }++ /// <summary>The name drawn on the slice: the content, or the ratio's numbers ("3:4" in portrait).</summary>+ public string Label => Content as string ?? CropMath.Numbers(Mode, _portrait);++ static RingSegment()+ {+ AffectsRender<RingSegment>(PopProperty, AccentBrushProperty, AccentSoftBrushProperty, OnAccentBrushProperty,+ ModeProperty, BackgroundProperty, ForegroundProperty, BorderBrushProperty);+ FocusAdornerProperty.OverrideDefaultValue<RingSegment>(null);+ }++ public RingSegment()+ {+ ClipToBounds = false;+ Template = null; // drawn by Render: a button's template would cover the whole dial+ }++ internal void Place(Point center, int index, int count, double inner, double outer, double corner)+ {+ if (_center == center && _index == index && _count == count && _inner == inner && _outer == outer && _corner == corner && _wedge is not null)+ return;+ (_center, _index, _count, _inner, _outer, _corner) = (center, index, count, inner, outer, corner);+ _wedge = BuildWedge();+ InvalidateVisual();+ }++ internal void Show(bool selected, bool portrait, double originalRatio)+ {+ var label = Label;+ IsSelected = selected;+ _portrait = portrait;+ _originalRatio = originalRatio;+ PseudoClasses.Set(":selected", selected);+ if (label != Label || AutomationProperties.GetName(this) is null or "")+ AutomationProperties.SetName(this, Label);+ InvalidateVisual();+ }++ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)+ {+ base.OnPropertyChanged(change);+ if (change.Property == ContentProperty || change.Property == ModeProperty)+ AutomationProperties.SetName(this, Label);+ }++ private double Mid => DonutGeometry.MidAngle(_index, _count);++ private Geometry BuildWedge() =>+ AspectDial.WedgeGeometry(_center, _inner, _outer, Mid, DonutGeometry.Span(_count), AspectDial.Gap, _corner);++ /// <summary>Only the wedge answers the pointer, so neighbouring slices (sharing one square) each get their own.</summary>+ public bool HitTest(Point point) => _wedge?.FillContains(point) == true;++ public override void Render(DrawingContext context)+ {+ if (_wedge is null)+ return;+ var pop = Math.Clamp(Pop, -0.2, 1.3);+ var offset = DonutGeometry.PointAt(default, pop * PopOut, Mid);+ using var moved = context.PushTransform(Matrix.CreateTranslation(offset.X, offset.Y));++ var pen = BorderBrush is { } border ? new Pen(border, 1) : null;+ context.DrawGeometry(IsSelected ? AccentBrush : Background, pen, _wedge);+ if (!IsSelected && pop > 0.01 && AccentSoftBrush is { } soft)+ {+ using var lit = context.PushOpacity(Math.Clamp(pop, 0, 1));+ context.DrawGeometry(soft, null, _wedge);+ }+ if (IsFocused && PseudoClasses.Contains(":focus-visible") && AccentBrush is { } accent)+ context.DrawGeometry(null, new Pen(accent, 2.5), _wedge);++ var ink = IsSelected ? OnAccentBrush : Foreground;+ var labelCenter = DonutGeometry.PointAt(_center, (_inner + _outer) / 2, Mid);+ DrawShape(context, ink, new Point(labelCenter.X, labelCenter.Y - 9));++ var typeface = new Typeface(GetValue(TextElement.FontFamilyProperty), FontStyle.Normal, FontWeight.SemiBold);+ // As wide as the slice is a little outside its middle; a long word gets a smaller size before it would break.+ var width = 2 * ((_inner + _outer) / 2 + 6) * Math.Sin(Math.Min(Math.PI / 2, DonutGeometry.Span(_count) / 2)) - 12;+ FormattedText Text(double size) => new(Label, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, size, ink)+ {+ MaxTextWidth = width,+ MaxLineCount = 2,+ TextAlignment = TextAlignment.Center,+ Trimming = TextTrimming.CharacterEllipsis,+ };+ var text = Text(12);+ var longest = Label.Split(' ').Max(word => new FormattedText(word, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, 12, ink).Width);+ if (longest > width)+ text = Text(Math.Max(9.5, 12 * width / longest));+ context.DrawText(text, new Point(labelCenter.X - width / 2, labelCenter.Y + 2));+ }++ /// <summary>A small outline of the ratio over its name; free is a dashed square.</summary>+ private void DrawShape(DrawingContext context, IBrush? ink, Point center)+ {+ if (ink is null)+ return;+ var ratio = Mode == "original" ? _originalRatio : CropMath.Ratio(Mode, _portrait, 0, 0);+ const double box = 15;+ double w = box, h = box;+ if (ratio > 0)+ {+ if (ratio >= 1)+ h = box / ratio;+ else+ w = box * ratio;+ }+ var rect = new Rect(center.X - w / 2, center.Y - h / 2, w, h);+ var pen = new Pen(ink, 1.5) { DashStyle = ratio > 0 ? null : new DashStyle([2, 1.6], 0) };+ context.DrawRectangle(null, pen, new RoundedRect(rect, 2.5));+ }+}++/// <summary>The dial in miniature (the toolbar button): six slices, the one in use lit.</summary>+public sealed class AspectGlyph : Control+{+ public static readonly StyledProperty<int> SelectedIndexProperty =+ AvaloniaProperty.Register<AspectGlyph, int>(nameof(SelectedIndex));++ public static readonly StyledProperty<IBrush?> AccentBrushProperty =+ AvaloniaProperty.Register<AspectGlyph, IBrush?>(nameof(AccentBrush), Brushes.MediumPurple);++ public static readonly StyledProperty<IBrush?> RingBrushProperty =+ AvaloniaProperty.Register<AspectGlyph, IBrush?>(nameof(RingBrush), Brushes.Gray);++ public int SelectedIndex { get => GetValue(SelectedIndexProperty); set => SetValue(SelectedIndexProperty, value); }+ public IBrush? AccentBrush { get => GetValue(AccentBrushProperty); set => SetValue(AccentBrushProperty, value); }+ public IBrush? RingBrush { get => GetValue(RingBrushProperty); set => SetValue(RingBrushProperty, value); }++ static AspectGlyph()+ {+ AffectsRender<AspectGlyph>(SelectedIndexProperty, AccentBrushProperty, RingBrushProperty);+ }++ public override void Render(DrawingContext context)+ {+ var count = CropMath.AspectModes.Count;+ var center = new Point(Bounds.Width / 2, Bounds.Height / 2);+ var outer = Math.Min(Bounds.Width, Bounds.Height) / 2;+ var inner = outer * 0.48;+ for (var i = 0; i < count; i++)+ {+ var geometry = AspectDial.WedgeGeometry(center, inner, outer, DonutGeometry.MidAngle(i, count), DonutGeometry.Span(count), 1.6, 1);+ if (i == SelectedIndex)+ {+ context.DrawGeometry(AccentBrush, null, geometry);+ }+ else+ {+ using var faint = context.PushOpacity(0.45);+ context.DrawGeometry(RingBrush, null, geometry);+ }+ }+ }+}diff --git a/src/Filee.App/Controls/CropCanvas.cs b/src/Filee.App/Controls/CropCanvas.csindex 1ec71590..d3ffb8b2 100644--- a/src/Filee.App/Controls/CropCanvas.cs+++ b/src/Filee.App/Controls/CropCanvas.cs@@ -1,10 +1,17 @@-// Interactive image crop control: handles, rule-of-thirds grid and aspect ratio constraints.+// The crop overlay's stage: the picture on a dimmed backdrop with soft accent glows, the part outside the frame+// frosted (a tiny copy of the preview drawn large, so nothing is decoded again while dragging), the frame in the+// accent colour with round handles, a rule-of-thirds grid that fades in while dragging and a size chip that follows+// the frame. Programmatic changes (reset, ratio, a new picture) ease in; dragging follows the pointer directly.+using System.Diagnostics;+using System.Globalization;using Avalonia;using Avalonia.Controls;+using Avalonia.Controls.Documents;using Avalonia.Input;using Avalonia.Media;using Avalonia.Media.Imaging;+using Avalonia.Styling;namespace Filee.App.Controls;@@ -34,6 +41,35 @@ public sealed class CropCanvas : Controlpublic static readonly StyledProperty<double> AspectRatioProperty =AvaloniaProperty.Register<CropCanvas, double>(nameof(AspectRatio), 0);+ /// <summary>Room kept free around the picture for the floating chips and the toolbar.</summary>+ public static readonly StyledProperty<Thickness> ImagePaddingProperty =+ AvaloniaProperty.Register<CropCanvas, Thickness>(nameof(ImagePadding));++ /// <summary>"W × H px" in the chip under the frame; nothing when empty.</summary>+ public static readonly StyledProperty<string?> SizeTextProperty =+ AvaloniaProperty.Register<CropCanvas, string?>(nameof(SizeText));++ /// <summary>The picture's size in pixels: arrow keys move the frame by whole pixels of it.</summary>+ public static readonly StyledProperty<PixelSize> PixelSizeProperty =+ AvaloniaProperty.Register<CropCanvas, PixelSize>(nameof(PixelSize));++ public static readonly StyledProperty<IBrush?> AccentBrushProperty =+ AvaloniaProperty.Register<CropCanvas, IBrush?>(nameof(AccentBrush), Brushes.MediumPurple);++ /// <summary>The theme's page colour: the stage under the picture and the frosted veil outside the frame.</summary>+ public static readonly StyledProperty<IBrush?> StageBrushProperty =+ AvaloniaProperty.Register<CropCanvas, IBrush?>(nameof(StageBrush));++ public static readonly StyledProperty<IBrush?> ChipBackgroundProperty =+ AvaloniaProperty.Register<CropCanvas, IBrush?>(nameof(ChipBackground), Brushes.White);++ public static readonly StyledProperty<IBrush?> ChipForegroundProperty =+ AvaloniaProperty.Register<CropCanvas, IBrush?>(nameof(ChipForeground), Brushes.Black);++ /// <summary>False with reduced motion: every change shows at once.</summary>+ public static readonly StyledProperty<bool> PlayAnimationsProperty =+ AvaloniaProperty.Register<CropCanvas, bool>(nameof(PlayAnimations), true);+public Bitmap? SourceImage{get => GetValue(SourceImageProperty);@@ -52,13 +88,47 @@ public sealed class CropCanvas : Controlset => SetValue(AspectRatioProperty, value);}+ public Thickness ImagePadding { get => GetValue(ImagePaddingProperty); set => SetValue(ImagePaddingProperty, value); }+ public string? SizeText { get => GetValue(SizeTextProperty); set => SetValue(SizeTextProperty, value); }+ public PixelSize PixelSize { get => GetValue(PixelSizeProperty); set => SetValue(PixelSizeProperty, value); }+ public IBrush? AccentBrush { get => GetValue(AccentBrushProperty); set => SetValue(AccentBrushProperty, value); }+ public IBrush? StageBrush { get => GetValue(StageBrushProperty); set => SetValue(StageBrushProperty, value); }+ public IBrush? ChipBackground { get => GetValue(ChipBackgroundProperty); set => SetValue(ChipBackgroundProperty, value); }+ public IBrush? ChipForeground { get => GetValue(ChipForegroundProperty); set => SetValue(ChipForegroundProperty, value); }+ public bool PlayAnimations { get => GetValue(PlayAnimationsProperty); set => SetValue(PlayAnimationsProperty, value); }+public event Action<Rect>? CropRectChanged;private CropHandle _activeHandle = CropHandle.None;+ private CropHandle _hoverHandle = CropHandle.None;private Point _dragStartPoint;private Rect _dragStartCrop;private const double MinSizePx = 24.0;+ // ───── Motion: tweens evaluated against the clock at each render, so a lost frame never leaves one half done ─────++ private const double FrameSeconds = 0.34; // reset, ratio+ private const double AppearSeconds = 0.42; // a new picture+ private const double GridInSeconds = 0.14;+ private const double GridOutSeconds = 0.38;+ private const double HandleSeconds = 0.26;++ private Tween _frame = Tween.Done(1); // 0 → 1 from _frameFrom to NormalizedCropRect+ private Rect _frameFrom;+ private Tween _appear = Tween.Done(1);+ private Tween _grid = Tween.Done(0);+ private Tween _handlePop = Tween.Done(0); // the hovered or dragged handle grows a little+ private CropHandle _poppedHandle = CropHandle.None;+ private bool _animateNextRect;+ private bool _looping;++ // ───── Cached drawing resources ─────++ private Bitmap? _soft; // the tiny copy for the frosted outside+ private FormattedText? _chipText;+ private string? _chipTextFor;+ private IBrush? _chipTextBrush;+private static readonly Cursor ArrowCursor = new(StandardCursorType.Arrow);private static readonly Cursor SizeAllCursor = new(StandardCursorType.SizeAll);private static readonly Cursor SizeNorthSouthCursor = new(StandardCursorType.SizeNorthSouth);@@ -67,25 +137,27 @@ public sealed class CropCanvas : Controlprivate static readonly Cursor TopRightCursor = new(StandardCursorType.TopRightCorner);private static readonly Cursor CrossCursor = new(StandardCursorType.Cross);- private static readonly IBrush DimMaskBrush = new SolidColorBrush(Color.FromArgb(175, 0, 0, 0));- private static readonly IPen CropBorderPen = new Pen(Brushes.White, 1.5);- private static readonly IPen GridPen = new Pen(new SolidColorBrush(Color.FromArgb(80, 255, 255, 255)), 1);- private static readonly IPen HandlePen = new Pen(Brushes.White, 3.5);- private static readonly IPen HandleShadowPen = new Pen(new SolidColorBrush(Color.FromArgb(140, 0, 0, 0)), 5.0);+ private static readonly IPen FrameShadowPen = new Pen(new SolidColorBrush(Color.FromArgb(70, 0, 0, 0)), 4);+ private static readonly IPen GridPen = new Pen(new SolidColorBrush(Color.FromArgb(170, 255, 255, 255)), 1);+ private static readonly IPen GridShadowPen = new Pen(new SolidColorBrush(Color.FromArgb(60, 0, 0, 0)), 1);+ private static readonly IPen HandleRingPen = new Pen(Brushes.White, 2.5);+ private static readonly IBrush HandleShadowBrush = new SolidColorBrush(Color.FromArgb(60, 0, 0, 0));+ private static readonly BoxShadows PictureShadow = BoxShadows.Parse("0 10 30 0 #38000000");+ private static readonly BoxShadows ChipShadow = BoxShadows.Parse("0 2 8 0 #26000000");private static double SafeClamp(double val, double min, double max) =>min > max ? Math.Clamp(val, max, min) : Math.Clamp(val, min, max);static CropCanvas(){- AffectsRender<CropCanvas>(SourceImageProperty, NormalizedCropRectProperty, AspectRatioProperty);+ AffectsRender<CropCanvas>(SourceImageProperty, NormalizedCropRectProperty, AspectRatioProperty, ImagePaddingProperty,+ SizeTextProperty, AccentBrushProperty, StageBrushProperty, ChipBackgroundProperty, ChipForegroundProperty);+ FocusableProperty.OverrideDefaultValue<CropCanvas>(false);}public void ResetCrop(){- NormalizedCropRect = new Rect(0, 0, 1, 1);- CropRectChanged?.Invoke(NormalizedCropRect);- InvalidateVisual();+ SetRect(new Rect(0, 0, 1, 1), animate: true);}public void SetAspectRatio(double ratio)@@ -134,36 +206,46 @@ public sealed class CropCanvas : Controlvar x = SafeClamp(current.Center.X - w / 2.0, imgBounds.Left, Math.Max(imgBounds.Left, imgBounds.Right - w));var y = SafeClamp(current.Center.Y - h / 2.0, imgBounds.Top, Math.Max(imgBounds.Top, imgBounds.Bottom - h));- SetCropFromScreen(new Rect(x, y, w, h), imgBounds);+ SetCropFromScreen(new Rect(x, y, w, h), imgBounds, animate: true);}+ /// <summary>Moves the frame by whole pixels of the picture (arrow keys; the window passes 10 with Shift).</summary>+ public void Nudge(int dx, int dy)+ {+ var size = PixelSize;+ if (SourceImage is null || size.Width <= 0 || size.Height <= 0)+ return;+ SetRect(CropMath.Nudge(NormalizedCropRect, dx, dy, size.Width, size.Height), animate: false);+ }++ /// <summary>The picture's place: as large as fits inside <see cref="ImagePadding"/>, centred.</summary>public Rect CalculateImageBounds(){if (SourceImage is null || Bounds.Width <= 0 || Bounds.Height <= 0)return default;+ var area = new Rect(Bounds.Size).Deflate(ImagePadding);+ if (area.Width <= 0 || area.Height <= 0)+ area = new Rect(Bounds.Size);var imgSize = SourceImage.Size;- var scale = Math.Min(Bounds.Width / imgSize.Width, Bounds.Height / imgSize.Height);+ var scale = Math.Min(area.Width / imgSize.Width, area.Height / imgSize.Height);var w = imgSize.Width * scale;var h = imgSize.Height * scale;- var x = (Bounds.Width - w) / 2.0;- var y = (Bounds.Height - h) / 2.0;+ var x = area.X + (area.Width - w) / 2.0;+ var y = area.Y + (area.Height - h) / 2.0;return new Rect(x, y, w, h);}- public Rect GetScreenCropRect(Rect imgBounds)- {- var norm = NormalizedCropRect;- return new Rect(- imgBounds.X + norm.X * imgBounds.Width,- imgBounds.Y + norm.Y * imgBounds.Height,- Math.Max(MinSizePx, norm.Width * imgBounds.Width),- Math.Max(MinSizePx, norm.Height * imgBounds.Height)- );- }+ public Rect GetScreenCropRect(Rect imgBounds) => ToScreen(NormalizedCropRect, imgBounds);- private void SetCropFromScreen(Rect screenCrop, Rect imgBounds)+ private static Rect ToScreen(Rect norm, Rect imgBounds) => new(+ imgBounds.X + norm.X * imgBounds.Width,+ imgBounds.Y + norm.Y * imgBounds.Height,+ Math.Max(MinSizePx, norm.Width * imgBounds.Width),+ Math.Max(MinSizePx, norm.Height * imgBounds.Height));++ private void SetCropFromScreen(Rect screenCrop, Rect imgBounds, bool animate = false){if (imgBounds.Width <= 0 || imgBounds.Height <= 0)return;@@ -175,102 +257,363 @@ public sealed class CropCanvas : Controlvar w = SafeClamp(screenCrop.Width, MinSizePx, Math.Max(MinSizePx, maxW));var h = SafeClamp(screenCrop.Height, MinSizePx, Math.Max(MinSizePx, maxH));- NormalizedCropRect = new Rect(+ SetRect(new Rect((x - imgBounds.Left) / imgBounds.Width,(y - imgBounds.Top) / imgBounds.Height,w / imgBounds.Width,- h / imgBounds.Height- );- CropRectChanged?.Invoke(NormalizedCropRect);+ h / imgBounds.Height), animate);+ }++ private void SetRect(Rect normalized, bool animate)+ {+ _animateNextRect = animate;+ var same = NormalizedCropRect == normalized;+ NormalizedCropRect = normalized;+ _animateNextRect = false;+ if (same)+ CropRectChanged?.Invoke(normalized); // told again: the view model may have moved on (a new picture)InvalidateVisual();}+ /// <summary>Ends every running animation (tests capture the settled picture).</summary>+ internal void FinishAnimations()+ {+ _frame = Tween.Done(1);+ _appear = Tween.Done(1);+ _grid = Tween.Done(_grid.To);+ _handlePop = Tween.Done(_handlePop.To);+ InvalidateVisual();+ }++ /// <summary>The frame where it is drawn now (between two places while it eases).</summary>+ internal Rect ShownCropRect => Lerp(_frameFrom, NormalizedCropRect, EaseOutCubic(_frame.Value(Now())));++ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)+ {+ if (change.Property == NormalizedCropRectProperty)+ {+ var now = Now();+ var appearing = _appear.Value(now) < 1;+ if (_animateNextRect && PlayAnimations && !appearing && IsEffectivelyVisible)+ {+ // From where it is drawn now, even halfway through the last change.+ _frameFrom = Lerp(_frameFrom, change.GetOldValue<Rect>(), EaseOutCubic(_frame.Value(now)));+ _frame = Tween.Begin(0, 1, FrameSeconds);+ StartLoop();+ }+ else+ {+ _frameFrom = change.GetNewValue<Rect>();+ _frame = Tween.Done(1);+ }+ CropRectChanged?.Invoke(change.GetNewValue<Rect>());+ }+ else if (change.Property == SourceImageProperty)+ {+ _soft?.Dispose();+ _soft = Soften(change.GetNewValue<Bitmap?>());+ _frame = Tween.Done(1);+ _frameFrom = NormalizedCropRect;+ if (change.GetNewValue<Bitmap?>() is not null && PlayAnimations)+ {+ _appear = Tween.Begin(0, 1, AppearSeconds);+ StartLoop();+ }+ else+ {+ _appear = Tween.Done(1);+ }+ }+ else if (change.Property == PlayAnimationsProperty && !change.GetNewValue<bool>())+ {+ FinishAnimations();+ }+ base.OnPropertyChanged(change);+ }++ protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)+ {+ base.OnDetachedFromVisualTree(e);+ _soft?.Dispose();+ _soft = null;+ }++ protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)+ {+ base.OnAttachedToVisualTree(e);+ _soft ??= Soften(SourceImage);+ }++ /// <summary>A copy at most 40 px across: drawn as large as the picture it is a soft blur, at no cost per frame.</summary>+ private static Bitmap? Soften(Bitmap? source)+ {+ if (source is null)+ return null;+ try+ {+ var size = source.PixelSize;+ var scale = 40.0 / Math.Max(size.Width, size.Height);+ if (scale >= 1)+ return null;+ var target = new PixelSize(Math.Max(1, (int)Math.Round(size.Width * scale)), Math.Max(1, (int)Math.Round(size.Height * scale)));+ return source.CreateScaledBitmap(target, BitmapInterpolationMode.HighQuality);+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ return null; // the sharp picture under the veil is fine too+ }+ }++ // ───────────────────────── Drawing ─────────────────────────+public override void Render(DrawingContext context){base.Render(context);+ var now = Now();+ var bounds = new Rect(Bounds.Size);+ DrawStage(context, bounds);+var imgBounds = CalculateImageBounds();if (SourceImage is null || imgBounds.Width <= 0 || imgBounds.Height <= 0)return;- // 1. Render Source Image- context.DrawImage(SourceImage, new Rect(0, 0, SourceImage.Size.Width, SourceImage.Size.Height), imgBounds);+ // A new picture settles in: a little smaller and transparent at first.+ var appear = EaseOutCubic(_appear.Value(now));+ var scale = 0.965 + 0.035 * appear;+ var center = imgBounds.Center;+ using var appearing = context.PushTransform(+ Matrix.CreateTranslation(-center.X, -center.Y) * Matrix.CreateScale(scale, scale) * Matrix.CreateTranslation(center.X, center.Y));+ using var fading = context.PushOpacity(appear);- var crop = GetScreenCropRect(imgBounds);+ var source = new Rect(SourceImage.Size);+ context.DrawRectangle(StageBrush ?? Brushes.Gray, null, new RoundedRect(imgBounds), PictureShadow);- // 2. Draw Dim Mask around crop box- var topMask = new Rect(imgBounds.X, imgBounds.Y, imgBounds.Width, Math.Max(0, crop.Y - imgBounds.Y));- var bottomMask = new Rect(imgBounds.X, crop.Bottom, imgBounds.Width, Math.Max(0, imgBounds.Bottom - crop.Bottom));- var leftMask = new Rect(imgBounds.X, crop.Y, Math.Max(0, crop.X - imgBounds.X), crop.Height);- var rightMask = new Rect(crop.Right, crop.Y, Math.Max(0, imgBounds.Right - crop.Right), crop.Height);+ // Outside the frame: the frosted copy under a veil of the page colour (milky in light, dim in dark).+ using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality }))+ {+ if (_soft is { } soft)+ context.DrawImage(soft, new Rect(soft.Size), imgBounds);+ else+ context.DrawImage(SourceImage, source, imgBounds);+ }+ using (context.PushOpacity(IsDark ? 0.62 : 0.58))+ context.FillRectangle(StageBrush ?? Brushes.Gray, imgBounds);++ // Inside: the picture itself.+ var crop = ToScreen(ShownCropRect, imgBounds);+ using (context.PushClip(crop))+ using (context.PushRenderOptions(new RenderOptions { BitmapInterpolationMode = BitmapInterpolationMode.HighQuality }))+ context.DrawImage(SourceImage, source, imgBounds);++ DrawGrid(context, crop, _grid.Value(now));+ DrawFrame(context, crop, now);+ DrawSizeChip(context, crop, imgBounds, bounds);+ }- context.DrawRectangle(DimMaskBrush, null, topMask);- context.DrawRectangle(DimMaskBrush, null, bottomMask);- context.DrawRectangle(DimMaskBrush, null, leftMask);- context.DrawRectangle(DimMaskBrush, null, rightMask);+ private bool IsDark => ActualThemeVariant == ThemeVariant.Dark;- // 3. Draw Rule-of-Thirds Grid- if (crop.Width > 50 && crop.Height > 50)+ /// <summary>The backdrop: the page colour dimmed, with two soft glows of the accent colour.</summary>+ private void DrawStage(DrawingContext context, Rect bounds)+ {+ if (StageBrush is { } stage)+ context.FillRectangle(stage, bounds);+ context.FillRectangle(new SolidColorBrush(Colors.Black, IsDark ? 0.28 : 0.06), bounds);++ if (AccentBrush is ISolidColorBrush { Color: var accent }){- var x1 = crop.X + crop.Width / 3.0;- var x2 = crop.X + (crop.Width * 2.0) / 3.0;- var y1 = crop.Y + crop.Height / 3.0;- var y2 = crop.Y + (crop.Height * 2.0) / 3.0;-- context.DrawLine(GridPen, new Point(x1, crop.Y), new Point(x1, crop.Bottom));- context.DrawLine(GridPen, new Point(x2, crop.Y), new Point(x2, crop.Bottom));- context.DrawLine(GridPen, new Point(crop.X, y1), new Point(crop.Right, y1));- context.DrawLine(GridPen, new Point(crop.X, y2), new Point(crop.Right, y2));+ var strength = IsDark ? 0.16 : 0.22;+ Glow(context, accent, new Point(bounds.Width * 0.12, bounds.Height * 0.10), bounds.Width * 0.45, strength);+ Glow(context, accent, new Point(bounds.Width * 0.92, bounds.Height * 0.95), bounds.Width * 0.38, strength * 0.7);}+ }- // 4. Draw Crop Rectangle Border- context.DrawRectangle(null, CropBorderPen, crop);-- // 5. Corner brackets and edge bars- DrawCornerBracket(context, crop.TopLeft, 1, 1);- DrawCornerBracket(context, crop.TopRight, -1, 1);- DrawCornerBracket(context, crop.BottomLeft, 1, -1);- DrawCornerBracket(context, crop.BottomRight, -1, -1);+ private static void Glow(DrawingContext context, Color color, Point center, double radius, double strength)+ {+ var brush = new RadialGradientBrush+ {+ GradientStops =+ {+ new GradientStop(Color.FromArgb((byte)(255 * strength), color.R, color.G, color.B), 0),+ new GradientStop(Color.FromArgb((byte)(255 * strength * 0.35), color.R, color.G, color.B), 0.55),+ new GradientStop(Color.FromArgb(0, color.R, color.G, color.B), 1),+ },+ };+ context.DrawEllipse(brush, null, center, radius, radius);+ }- DrawEdgeBar(context, new Point(crop.Center.X, crop.Top), isHorizontal: true);- DrawEdgeBar(context, new Point(crop.Center.X, crop.Bottom), isHorizontal: true);- DrawEdgeBar(context, new Point(crop.Left, crop.Center.Y), isHorizontal: false);- DrawEdgeBar(context, new Point(crop.Right, crop.Center.Y), isHorizontal: false);+ private static void DrawGrid(DrawingContext context, Rect crop, double opacity)+ {+ if (opacity <= 0.01 || crop.Width < 50 || crop.Height < 50)+ return;+ using var fade = context.PushOpacity(opacity);+ for (var i = 1; i <= 2; i++)+ {+ var x = Math.Round(crop.X + crop.Width * i / 3.0) + 0.5;+ var y = Math.Round(crop.Y + crop.Height * i / 3.0) + 0.5;+ context.DrawLine(GridShadowPen, new Point(x + 1, crop.Top), new Point(x + 1, crop.Bottom));+ context.DrawLine(GridShadowPen, new Point(crop.Left, y + 1), new Point(crop.Right, y + 1));+ context.DrawLine(GridPen, new Point(x, crop.Top), new Point(x, crop.Bottom));+ context.DrawLine(GridPen, new Point(crop.Left, y), new Point(crop.Right, y));+ }}- private void DrawCornerBracket(DrawingContext context, Point corner, int dirX, int dirY)+ private void DrawFrame(DrawingContext context, Rect crop, long now){- const double length = 18;- var pHoriz = new Point(corner.X + dirX * length, corner.Y);- var pVert = new Point(corner.X, corner.Y + dirY * length);+ var accent = AccentBrush ?? Brushes.MediumPurple;+ context.DrawRectangle(null, FrameShadowPen, crop);+ context.DrawRectangle(null, new Pen(accent, 2), crop);++ var pop = EaseOutBack(_handlePop.Value(now));+ foreach (var handle in new[] { CropHandle.TopLeft, CropHandle.TopRight, CropHandle.BottomRight, CropHandle.BottomLeft })+ {+ var grow = handle == _poppedHandle ? pop : 0;+ DrawDot(context, accent, HandlePoint(crop, handle), 6.5 + 2.5 * grow);+ }- // Shadow behind bracket for clear visibility on bright/white photos- context.DrawLine(HandleShadowPen, new Point(corner.X - dirX * 0.5, corner.Y), pHoriz);- context.DrawLine(HandleShadowPen, new Point(corner.X, corner.Y - dirY * 0.5), pVert);+ // Pills on the edges, where the frame is long enough for them to stay apart from the corners.+ foreach (var handle in new[] { CropHandle.Top, CropHandle.Right, CropHandle.Bottom, CropHandle.Left })+ {+ var horizontal = handle is CropHandle.Top or CropHandle.Bottom;+ if ((horizontal ? crop.Width : crop.Height) < 90)+ continue;+ var grow = handle == _poppedHandle ? pop : 0;+ var length = 22 + 8 * grow;+ const double thickness = 7;+ var c = HandlePoint(crop, handle);+ var rect = horizontal+ ? new Rect(c.X - length / 2, c.Y - thickness / 2, length, thickness)+ : new Rect(c.X - thickness / 2, c.Y - length / 2, thickness, length);+ context.DrawRectangle(HandleShadowBrush, null, new RoundedRect(rect.Translate(new Vector(0, 1)).Inflate(1.5), thickness));+ context.DrawRectangle(accent, HandleRingPen, new RoundedRect(rect, thickness / 2));+ }+ }- // Crisp white bracket- context.DrawLine(HandlePen, corner, pHoriz);- context.DrawLine(HandlePen, corner, pVert);+ private static void DrawDot(DrawingContext context, IBrush accent, Point center, double radius)+ {+ context.DrawEllipse(HandleShadowBrush, null, center + new Vector(0, 1), radius + 2, radius + 2);+ context.DrawEllipse(accent, HandleRingPen, center, radius, radius);}- private void DrawEdgeBar(DrawingContext context, Point center, bool isHorizontal)+ private static Point HandlePoint(Rect crop, CropHandle handle) => handle switch+ {+ CropHandle.TopLeft => crop.TopLeft,+ CropHandle.TopRight => crop.TopRight,+ CropHandle.BottomRight => crop.BottomRight,+ CropHandle.BottomLeft => crop.BottomLeft,+ CropHandle.Top => new Point(crop.Center.X, crop.Top),+ CropHandle.Bottom => new Point(crop.Center.X, crop.Bottom),+ CropHandle.Left => new Point(crop.Left, crop.Center.Y),+ CropHandle.Right => new Point(crop.Right, crop.Center.Y),+ _ => crop.Center,+ };++ /// <summary>How far below the picture the size chip may go (the toolbar starts further down).</summary>+ private const double ChipReach = 40;++ private void DrawSizeChip(DrawingContext context, Rect crop, Rect imgBounds, Rect bounds){- const double halfLen = 10;- Point p1, p2;- if (isHorizontal)+ if (string.IsNullOrEmpty(SizeText))+ return;+ var foreground = ChipForeground ?? Brushes.Black;+ if (_chipText is null || _chipTextFor != SizeText || !ReferenceEquals(_chipTextBrush, foreground)){- p1 = new Point(center.X - halfLen, center.Y);- p2 = new Point(center.X + halfLen, center.Y);+ var typeface = new Typeface(GetValue(TextElement.FontFamilyProperty), FontStyle.Normal, FontWeight.SemiBold);+ _chipText = new FormattedText(SizeText, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, 11.5, foreground);+ _chipTextFor = SizeText;+ _chipTextBrush = foreground;}- else++ var chip = new Size(Math.Ceiling(_chipText.Width) + 20, Math.Ceiling(_chipText.Height) + 8);+ var area = new Rect(imgBounds.Left, imgBounds.Top, imgBounds.Width, imgBounds.Height + ChipReach)+ .Intersect(bounds.Deflate(6));+ var origin = CropMath.SizeChipOrigin(crop, chip, area);+ var pill = new RoundedRect(new Rect(origin, chip), chip.Height / 2);+ context.DrawRectangle(ChipBackground, null, pill, ChipShadow);+ context.DrawText(_chipText, new Point(origin.X + 10, origin.Y + 4));+ }++ // ───────────────────────── Motion ─────────────────────────++ private static long Now() => Stopwatch.GetTimestamp();++ private static double EaseOutCubic(double t) => 1 - Math.Pow(1 - Math.Clamp(t, 0, 1), 3);++ /// <summary>Overshoots a little before settling: the "squishy" grow of a handle.</summary>+ private static double EaseOutBack(double t)+ {+ t = Math.Clamp(t, 0, 1);+ const double s = 1.9;+ return 1 + (s + 1) * Math.Pow(t - 1, 3) + s * Math.Pow(t - 1, 2);+ }++ private static Rect Lerp(Rect a, Rect b, double t) => new(+ a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.Width + (b.Width - a.Width) * t, a.Height + (b.Height - a.Height) * t);++ private void SetGrid(bool visible)+ {+ var target = visible ? 1 : 0;+ if (_grid.To == target)+ return;+ _grid = PlayAnimations ? _grid.Retarget(target, visible ? GridInSeconds : GridOutSeconds, Now()) : Tween.Done(target);+ StartLoop();+ }++ private void PopHandle(CropHandle handle)+ {+ if (handle is CropHandle.None or CropHandle.Body or CropHandle.CreateNew)+ handle = CropHandle.None;+ if (handle == _poppedHandle)+ return;+ _poppedHandle = handle;+ _handlePop = handle == CropHandle.None || !PlayAnimations+ ? Tween.Done(handle == CropHandle.None ? 0 : 1)+ : Tween.Begin(0, 1, HandleSeconds);+ StartLoop();+ }++ private void StartLoop()+ {+ InvalidateVisual();+ if (_looping || TopLevel.GetTopLevel(this) is not { } top)+ return;+ _looping = true;+ top.RequestAnimationFrame(OnFrame);+ }++ private void OnFrame(TimeSpan _)+ {+ InvalidateVisual();+ var now = Now();+ if (_frame.IsRunning(now) || _appear.IsRunning(now) || _grid.IsRunning(now) || _handlePop.IsRunning(now)){- p1 = new Point(center.X, center.Y - halfLen);- p2 = new Point(center.X, center.Y + halfLen);+ if (TopLevel.GetTopLevel(this) is { } top)+ {+ top.RequestAnimationFrame(OnFrame);+ return;+ }}+ _looping = false;+ }++ /// <summary>A value easing from <see cref="From"/> to <see cref="To"/> over a time, read against the clock.</summary>+ private readonly record struct Tween(double From, double To, long Start, double Seconds)+ {+ public static Tween Done(double value) => new(value, value, 0, 0);++ public static Tween Begin(double from, double to, double seconds) => new(from, to, Now(), seconds);++ public double Progress(long now) => Seconds <= 0 ? 1 : Math.Clamp(Stopwatch.GetElapsedTime(Start, now).TotalSeconds / Seconds, 0, 1);++ public double Value(long now) => From + (To - From) * Progress(now);++ public bool IsRunning(long now) => Progress(now) < 1;- context.DrawLine(HandleShadowPen, p1, p2);- context.DrawLine(HandlePen, p1, p2);+ /// <summary>Heads for a new value from where it is now.</summary>+ public Tween Retarget(double to, double seconds, long now) => new(Value(now), to, now, seconds);}+ // ───────────────────────── Pointer ─────────────────────────+private CropHandle HitTestHandle(Point pt, Rect crop, Rect imgBounds){const double hitTol = 16.0;@@ -292,6 +635,14 @@ public sealed class CropCanvas : Controlprivate static double Distance(Point a, Point b) => Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));+ protected override void OnPointerExited(PointerEventArgs e)+ {+ base.OnPointerExited(e);+ _hoverHandle = CropHandle.None;+ if (_activeHandle == CropHandle.None)+ PopHandle(CropHandle.None);+ }+protected override void OnPointerMoved(PointerEventArgs e){base.OnPointerMoved(e);@@ -314,6 +665,8 @@ public sealed class CropCanvas : ControlCropHandle.CreateNew => CrossCursor,_ => ArrowCursor,};+ _hoverHandle = h;+ PopHandle(h);return;}@@ -537,6 +890,8 @@ public sealed class CropCanvas : Control_dragStartCrop = crop;e.Pointer.Capture(this);e.Handled = true;+ PopHandle(_activeHandle);+ SetGrid(true);}}@@ -548,6 +903,19 @@ public sealed class CropCanvas : Control_activeHandle = CropHandle.None;e.Pointer.Capture(null);e.Handled = true;+ SetGrid(false);+ PopHandle(_hoverHandle);+ }+ }++ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)+ {+ base.OnPointerCaptureLost(e);+ if (_activeHandle != CropHandle.None)+ {+ _activeHandle = CropHandle.None;+ SetGrid(false);+ PopHandle(CropHandle.None);}}diff --git a/src/Filee.App/Controls/CropMath.cs b/src/Filee.App/Controls/CropMath.csnew file mode 100644index 00000000..bddf6121--- /dev/null+++ b/src/Filee.App/Controls/CropMath.cs@@ -0,0 +1,82 @@+// The crop overlay's arithmetic without a window: the ratios of the aspect dial, keyboard nudges, the frame's size in+// pixels and where the size chip sits next to the frame.++using Avalonia;++namespace Filee.App.Controls;++public static class CropMath+{+ /// <summary>The aspect dial's choices, clockwise from the top.</summary>+ public static IReadOnlyList<string> AspectModes => Modes;++ private static readonly string[] Modes = ["free", "original", "1:1", "4:3", "3:2", "16:9"];++ /// <summary>Where the mode sits on the dial, -1 for none.</summary>+ public static int AspectIndex(string mode) => Array.IndexOf(Modes, mode);++ /// <summary>A fixed ratio with a portrait and a landscape form (not free, the picture's own or square).</summary>+ public static bool CanSwap(string mode) => mode is "4:3" or "3:2" or "16:9";++ /// <summary>Width / height of the mode, 0 for free. Portrait turns a swappable ratio around (4:3 → 3:4).</summary>+ public static double Ratio(string mode, bool portrait, int originalWidth, int originalHeight)+ {+ var ratio = mode switch+ {+ "original" => originalWidth > 0 && originalHeight > 0 ? (double)originalWidth / originalHeight : 0,+ "1:1" => 1.0,+ "4:3" => 4.0 / 3.0,+ "3:2" => 3.0 / 2.0,+ "16:9" => 16.0 / 9.0,+ _ => 0,+ };+ return portrait && CanSwap(mode) ? 1 / ratio : ratio;+ }++ /// <summary>The numbers shown for a mode: "4:3", or "3:4" in portrait. Free and original have none.</summary>+ public static string Numbers(string mode, bool portrait)+ {+ if (!CanSwap(mode) || !portrait)+ return mode;+ var parts = mode.Split(':');+ return $"{parts[1]}:{parts[0]}";+ }++ /// <summary>The frame in pixels of the picture (at least 1 × 1).</summary>+ public static PixelSize PixelSize(Rect normalized, int width, int height) =>+ new(Math.Max(1, (int)Math.Round(normalized.Width * width)), Math.Max(1, (int)Math.Round(normalized.Height * height)));++ /// <summary>+ /// Moves the frame by whole pixels of the picture (an arrow key: 1, with Shift 10). The frame lands on the pixel+ /// grid and stops at the picture's edges; its size stays.+ /// </summary>+ public static Rect Nudge(Rect normalized, int dx, int dy, int width, int height)+ {+ if (width <= 0 || height <= 0)+ return normalized;+ var size = PixelSize(normalized, width, height);+ var x = Math.Clamp((int)Math.Round(normalized.X * width) + dx, 0, Math.Max(0, width - size.Width));+ var y = Math.Clamp((int)Math.Round(normalized.Y * height) + dy, 0, Math.Max(0, height - size.Height));+ return new Rect((double)x / width, (double)y / height, normalized.Width, normalized.Height);+ }++ /// <summary>Space between the frame and the size chip.</summary>+ public const double ChipGap = 10;++ /// <summary>+ /// Top-left corner of the size chip: centred under the frame; inside its bottom edge when there's no room below+ /// <paramref name="area"/>; above the frame when the frame is too low for it as well. Never outside the area.+ /// </summary>+ public static Point SizeChipOrigin(Rect frame, Size chip, Rect area)+ {+ var x = Math.Clamp(frame.Center.X - chip.Width / 2, area.Left, Math.Max(area.Left, area.Right - chip.Width));+ double y;+ if (frame.Bottom + ChipGap + chip.Height <= area.Bottom)+ y = frame.Bottom + ChipGap;+ else if (frame.Height >= chip.Height + 3 * ChipGap)+ y = frame.Bottom - ChipGap * 1.6 - chip.Height; // clear of the handle on the bottom edge+ else+ y = frame.Top - ChipGap - chip.Height;+ return new Point(x, Math.Clamp(y, area.Top, Math.Max(area.Top, area.Bottom - chip.Height)));+ }+}diff --git a/src/Filee.App/Controls/CropSummaryRing.cs b/src/Filee.App/Controls/CropSummaryRing.csnew file mode 100644index 00000000..e3a809e0--- /dev/null+++ b/src/Filee.App/Controls/CropSummaryRing.cs@@ -0,0 +1,89 @@+// The crop overlay's end summary as a small donut: a slice per file (cropped in the accent colour, skipped muted,+// failed in the danger colour), grouped into three slices when there are too many files for a slice each, and the+// number cropped in the hub.++using System.Globalization;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Documents;+using Avalonia.Media;++namespace Filee.App.Controls;++public sealed class CropSummaryRing : Control+{+ public static readonly StyledProperty<int> DoneProperty = AvaloniaProperty.Register<CropSummaryRing, int>(nameof(Done));+ public static readonly StyledProperty<int> SkippedProperty = AvaloniaProperty.Register<CropSummaryRing, int>(nameof(Skipped));+ public static readonly StyledProperty<int> FailedProperty = AvaloniaProperty.Register<CropSummaryRing, int>(nameof(Failed));++ public static readonly StyledProperty<IBrush?> AccentBrushProperty =+ AvaloniaProperty.Register<CropSummaryRing, IBrush?>(nameof(AccentBrush), Brushes.MediumPurple);++ public static readonly StyledProperty<IBrush?> MutedBrushProperty =+ AvaloniaProperty.Register<CropSummaryRing, IBrush?>(nameof(MutedBrush), Brushes.Gray);++ public static readonly StyledProperty<IBrush?> DangerBrushProperty =+ AvaloniaProperty.Register<CropSummaryRing, IBrush?>(nameof(DangerBrush), Brushes.IndianRed);++ public static readonly StyledProperty<IBrush?> HubBrushProperty =+ AvaloniaProperty.Register<CropSummaryRing, IBrush?>(nameof(HubBrush), Brushes.White);++ public static readonly StyledProperty<IBrush?> ForegroundProperty =+ TextElement.ForegroundProperty.AddOwner<CropSummaryRing>();++ public int Done { get => GetValue(DoneProperty); set => SetValue(DoneProperty, value); }+ public int Skipped { get => GetValue(SkippedProperty); set => SetValue(SkippedProperty, value); }+ public int Failed { get => GetValue(FailedProperty); set => SetValue(FailedProperty, value); }+ public IBrush? AccentBrush { get => GetValue(AccentBrushProperty); set => SetValue(AccentBrushProperty, value); }+ public IBrush? MutedBrush { get => GetValue(MutedBrushProperty); set => SetValue(MutedBrushProperty, value); }+ public IBrush? DangerBrush { get => GetValue(DangerBrushProperty); set => SetValue(DangerBrushProperty, value); }+ public IBrush? HubBrush { get => GetValue(HubBrushProperty); set => SetValue(HubBrushProperty, value); }+ public IBrush? Foreground { get => GetValue(ForegroundProperty); set => SetValue(ForegroundProperty, value); }++ /// <summary>Up to this many files, each gets its own slice.</summary>+ private const int MaxSlices = 24;++ static CropSummaryRing()+ {+ AffectsRender<CropSummaryRing>(DoneProperty, SkippedProperty, FailedProperty, AccentBrushProperty, MutedBrushProperty,+ DangerBrushProperty, HubBrushProperty, ForegroundProperty);+ }++ public override void Render(DrawingContext context)+ {+ var center = new Point(Bounds.Width / 2, Bounds.Height / 2);+ var outer = Math.Min(Bounds.Width, Bounds.Height) / 2 - 1;+ var inner = outer * 0.62;+ var total = Done + Skipped + Failed;+ if (total <= 0 || outer <= 4)+ return;++ var groups = new[] { (Done, AccentBrush), (Skipped, MutedBrush), (Failed, DangerBrush) }.Where(g => g.Item1 > 0).ToList();+ var slices = total <= MaxSlices+ ? groups.SelectMany(g => Enumerable.Repeat((Share: 1.0, Brush: g.Item2), g.Item1)).ToList()+ : groups.Select(g => (Share: (double)g.Item1, Brush: g.Item2)).ToList();+ var sum = slices.Sum(s => s.Share);++ if (slices.Count == 1)+ {+ context.DrawEllipse(null, new Pen(slices[0].Brush, outer - inner), center, (outer + inner) / 2, (outer + inner) / 2);+ }+ else+ {+ var start = 0.0;+ foreach (var (share, brush) in slices)+ {+ var span = 2 * Math.PI * share / sum;+ var geometry = AspectDial.WedgeGeometry(center, inner, outer, start + span / 2, span, 3, 3);+ context.DrawGeometry(brush, null, geometry);+ start += span;+ }+ }++ context.DrawEllipse(HubBrush, null, center, inner - 5, inner - 5);+ var typeface = new Typeface(GetValue(TextElement.FontFamilyProperty), FontStyle.Normal, FontWeight.SemiBold);+ var text = new FormattedText($"{Done}/{total}", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface,+ Math.Max(12, inner * 0.42), Foreground);+ context.DrawText(text, new Point(center.X - text.Width / 2, center.Y - text.Height / 2));+ }+}diff --git a/src/Filee.App/ViewModels/CropOverlayViewModel.cs b/src/Filee.App/ViewModels/CropOverlayViewModel.csindex f2484717..eea322ff 100644--- a/src/Filee.App/ViewModels/CropOverlayViewModel.cs+++ b/src/Filee.App/ViewModels/CropOverlayViewModel.cs@@ -6,6 +6,7 @@ using Avalonia;using Avalonia.Media.Imaging;using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;+using Filee.App.Controls;using Filee.App.Services;using Filee.Core.Conversion;using Filee.Core.History;@@ -38,19 +39,38 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable[ObservableProperty] private string _counterText = "";[ObservableProperty] private bool _hasMultipleFiles;[ObservableProperty] private Bitmap? _previewImage;- [ObservableProperty] private int _originalWidth;- [ObservableProperty] private int _originalHeight;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(OriginalRatio))]+ [NotifyPropertyChangedFor(nameof(PixelSize))]+ private int _originalWidth;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(OriginalRatio))]+ [NotifyPropertyChangedFor(nameof(PixelSize))]+ private int _originalHeight;+[ObservableProperty] private string _dimensionsText = "";[ObservableProperty] private bool _isBusy;[ObservableProperty] private double _aspectRatio;+[ObservableProperty]+ [NotifyPropertyChangedFor(nameof(AspectLabel))]+ [NotifyPropertyChangedFor(nameof(AspectToolTip))]+ [NotifyPropertyChangedFor(nameof(SelectedAspectIndex))]+ [NotifyPropertyChangedFor(nameof(CanSwapOrientation))][NotifyPropertyChangedFor(nameof(IsAspectFree))]- [NotifyPropertyChangedFor(nameof(IsAspectOriginal))]- [NotifyPropertyChangedFor(nameof(IsAspectSquare))]- [NotifyPropertyChangedFor(nameof(IsAspect43))]- [NotifyPropertyChangedFor(nameof(IsAspect169))]private string _selectedAspect = "free";+ /// <summary>The fixed ratios (4:3, 3:2, 16:9) turned upright: 3:4, 2:3, 9:16.</summary>+ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(AspectLabel))]+ [NotifyPropertyChangedFor(nameof(AspectToolTip))]+ [NotifyPropertyChangedFor(nameof(OrientationText))]+ private bool _isPortrait;++ [ObservableProperty] private bool _isAspectDialOpen;+[ObservableProperty][NotifyPropertyChangedFor(nameof(HasStatusNotice))]private string _statusNotice = "";@@ -72,11 +92,46 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable/// <summary>"file: reason" for each file that failed or was skipped.</summary>public ObservableCollection<string> Problems { get; } = [];+ /// <summary>Every file of the run with how it went, for the strip of thumbnails.</summary>+ public ObservableCollection<CropQueueItem> Queue { get; } = [];++ /// <summary>Counts for the end summary's ring.</summary>+ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(HasDone))]+ private int _doneCount;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(HasSkipped))]+ private int _skippedCount;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(HasFailed))]+ private int _failedCount;++ public bool HasDone => DoneCount > 0;+ public bool HasSkipped => SkippedCount > 0;+ public bool HasFailed => FailedCount > 0;++ /// <summary>The primary button: "Crop & next" while more files follow, else "Crop & save".</summary>+ [ObservableProperty] private string _saveText = "";+public bool IsAspectFree => SelectedAspect == "free";- public bool IsAspectOriginal => SelectedAspect == "original";- public bool IsAspectSquare => SelectedAspect == "1:1";- public bool IsAspect43 => SelectedAspect == "4:3";- public bool IsAspect169 => SelectedAspect == "16:9";+ public bool CanSwapOrientation => CropMath.CanSwap(SelectedAspect);+ public int SelectedAspectIndex => Math.Max(0, CropMath.AspectIndex(SelectedAspect));+ public double OriginalRatio => OriginalWidth > 0 && OriginalHeight > 0 ? (double)OriginalWidth / OriginalHeight : 0;+ public PixelSize PixelSize => new(OriginalWidth, OriginalHeight);++ /// <summary>The ratio in use, as on the dial's button: "Free", "Original", "1:1", "3:4"…</summary>+ public string AspectLabel => SelectedAspect switch+ {+ "free" => _loc["crop.aspect_free"],+ "original" => _loc["crop.aspect_original"],+ _ => CropMath.Numbers(SelectedAspect, IsPortrait),+ };++ public string AspectToolTip => $"{_loc["crop.aspect_title"]} {AspectLabel}";++ public string OrientationText => _loc[IsPortrait ? "crop.portrait" : "crop.landscape"];public event Action? CloseRequested;public event Action? ResetRequested;@@ -92,6 +147,9 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable_store = store;_log = log;_hasMultipleFiles = files.Count > 1;+ for (var i = 0; i < files.Count; i++)+ Queue.Add(new CropQueueItem(loc, Path.GetFileName(files[i]), i));+ loc.LanguageChanged += OnLanguageChanged;_ = LoadFileAsync(0);}@@ -109,6 +167,8 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposablevar path = _files[index];CurrentFileName = Path.GetFileName(path);CounterText = _loc.Format("crop.page_counter", index + 1, _files.Count);+ SaveText = _loc[index < _files.Count - 1 ? "crop.save_next" : "crop.save"];+ Queue[index].State = CropItemState.Current;try{@@ -122,10 +182,13 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposablevar old = PreviewImage;PreviewImage = bitmap;old?.Dispose();+ Queue[index].SetThumbnail(bitmap);OriginalWidth = origW;OriginalHeight = origH;SelectedAspect = "free";+ IsPortrait = origH > origW;+ IsAspectDialOpen = false;AspectRatio = 0;AspectRatioChanged?.Invoke(0);CurrentCropRect = new Rect(0.05, 0.05, 0.9, 0.9);@@ -159,9 +222,8 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposablepublic void UpdateDimensions(Rect norm){CurrentCropRect = norm;- var pixelW = Math.Max(1, (int)Math.Round(norm.Width * OriginalWidth));- var pixelH = Math.Max(1, (int)Math.Round(norm.Height * OriginalHeight));- DimensionsText = $"{pixelW} × {pixelH} px";+ var size = CropMath.PixelSize(norm, OriginalWidth, OriginalHeight);+ DimensionsText = $"{size.Width} × {size.Height} px";}[RelayCommand]@@ -171,7 +233,9 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposablereturn;IsBusy = true;+ IsAspectDialOpen = false;var path = _files[CurrentIndex];+ var item = Queue[CurrentIndex];_processedSources.Add(path);var x = (int)Math.Round(CurrentCropRect.X * OriginalWidth);@@ -183,11 +247,19 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable{var result = await CropService.CropFileAsync(path, x, y, w, h, _preset, _store, _loc, _log);if (result.Status == CropStatus.Success && result.OutputPath is not null)+ {_outputs.Add(result.OutputPath);+ item.State = CropItemState.Done;+ }else if (result.Status == CropStatus.SkippedExists)+ {AddProblem(path, "toast.skipped"); // as in the job queue: skipped counts as done, not as a failure+ item.State = CropItemState.Skipped;+ }else+ {AddFailure(path, result.ErrorKey ?? "error.conversion_failed", result.ErrorDetail);+ }}catch (Exception ex){@@ -220,6 +292,7 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposableif (IsBusy || IsFinished || _closed)return;+ Queue[CurrentIndex].State = CropItemState.Skipped;if (CurrentIndex < _files.Count - 1)await LoadFileAsync(CurrentIndex + 1);else@@ -230,6 +303,7 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposablepublic void Reset(){SelectedAspect = "free";+ IsPortrait = OriginalHeight > OriginalWidth;AspectRatio = 0;AspectRatioChanged?.Invoke(0);ResetRequested?.Invoke();@@ -243,27 +317,51 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposableCloseRequested?.Invoke();}+ /// <summary>Locks the frame to a ratio of the dial ("free", "original", "1:1", "4:3", "3:2", "16:9") and closes the dial.</summary>[RelayCommand]public void SetAspect(string mode)+ {+ IsAspectDialOpen = false;+ ApplyAspect(mode);+ }++ /// <summary>Turns a fixed ratio between landscape and portrait (4:3 ↔ 3:4); the dial stays open.</summary>+ [RelayCommand]+ public void SwapOrientation()+ {+ if (!CanSwapOrientation || IsFinished)+ return;+ IsPortrait = !IsPortrait;+ ApplyAspect(SelectedAspect);+ }++ /// <summary>The next (or previous) ratio of the dial, round and round.</summary>+ public void CycleAspect(int step)+ {+ var modes = CropMath.AspectModes;+ var next = ((SelectedAspectIndex + step) % modes.Count + modes.Count) % modes.Count;+ ApplyAspect(modes[next]);+ }++ [RelayCommand]+ public void ToggleAspectDial()+ {+ if (IsEditing && !IsBusy)+ IsAspectDialOpen = !IsAspectDialOpen;+ }++ private void ApplyAspect(string mode){SelectedAspect = mode;- double ratio = mode switch- {- "free" => 0,- "original" => OriginalHeight > 0 ? (double)OriginalWidth / OriginalHeight : 0,- "1:1" => 1.0,- "4:3" => 4.0 / 3.0,- "16:9" => 16.0 / 9.0,- _ => 0,- };- AspectRatio = ratio;- AspectRatioChanged?.Invoke(ratio);+ AspectRatio = CropMath.Ratio(mode, IsPortrait, OriginalWidth, OriginalHeight);+ AspectRatioChanged?.Invoke(AspectRatio);}private void AddFailure(string path, string errorKey, string? detail){_failures.Add(new HistoryFailure { Source = path, ErrorKey = errorKey, ErrorDetail = detail });AddProblem(path, errorKey);+ Queue[CurrentIndex].State = CropItemState.Failed;}private void AddProblem(string path, string key)@@ -285,8 +383,12 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposableSummary = _failures.Count > 0? _loc.Format("toast.done_errors", _failures.Count, _processedSources.Count): _loc["toast.done"];+ DoneCount = Queue.Count(q => q.State == CropItemState.Done);+ SkippedCount = Queue.Count(q => q.State == CropItemState.Skipped);+ FailedCount = Queue.Count(q => q.State == CropItemState.Failed);StatusNotice = "";HasMultipleFiles = false;+ IsAspectDialOpen = false;var old = PreviewImage;PreviewImage = null;old?.Dispose();@@ -325,10 +427,111 @@ public sealed partial class CropOverlayViewModel : ObservableObject, IDisposable});}+ private void OnLanguageChanged(object? sender, EventArgs e)+ {+ if (!IsFinished && CurrentIndex < _files.Count)+ {+ CounterText = _loc.Format("crop.page_counter", CurrentIndex + 1, _files.Count);+ SaveText = _loc[CurrentIndex < _files.Count - 1 ? "crop.save_next" : "crop.save"];+ }+ OnPropertyChanged(nameof(AspectLabel));+ OnPropertyChanged(nameof(AspectToolTip));+ OnPropertyChanged(nameof(OrientationText));+ foreach (var item in Queue)+ item.RefreshTexts();+ }+public void Dispose(){Shutdown();+ _loc.LanguageChanged -= OnLanguageChanged;PreviewImage?.Dispose();PreviewImage = null;+ foreach (var item in Queue)+ item.Dispose();+ }+}++public enum CropItemState+{+ Waiting,+ Current,+ Done,+ Skipped,+ Failed,+}++/// <summary>One file of the crop overlay's strip: a small thumbnail once it has been opened, and how it went.</summary>+public sealed partial class CropQueueItem(ILocalizer loc, string name, int index) : ObservableObject, IDisposable+{+ /// <summary>Longest side of a thumbnail in the strip (at twice its size on screen, for high-DPI displays).</summary>+ private const int ThumbnailSide = 72;++ public string Name { get; } = name;+ public string Number { get; } = (index + 1).ToString(System.Globalization.CultureInfo.CurrentCulture);++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(IsCurrent))]+ [NotifyPropertyChangedFor(nameof(IsDone))]+ [NotifyPropertyChangedFor(nameof(IsSkipped))]+ [NotifyPropertyChangedFor(nameof(IsFailed))]+ [NotifyPropertyChangedFor(nameof(HasBadge))]+ [NotifyPropertyChangedFor(nameof(StateText))]+ [NotifyPropertyChangedFor(nameof(AccessibleName))]+ private CropItemState _state;++ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(HasThumbnail))]+ private Bitmap? _thumbnail;++ public bool IsCurrent => State == CropItemState.Current;+ public bool IsDone => State == CropItemState.Done;+ public bool IsSkipped => State == CropItemState.Skipped;+ public bool IsFailed => State == CropItemState.Failed;+ public bool HasBadge => IsDone || IsSkipped || IsFailed;+ public bool HasThumbnail => Thumbnail is not null;++ public string StateText => loc[State switch+ {+ CropItemState.Current => "crop.state_current",+ CropItemState.Done => "crop.state_done",+ CropItemState.Skipped => "crop.state_skipped",+ CropItemState.Failed => "crop.state_failed",+ _ => "crop.state_waiting",+ }];++ /// <summary>"photo.jpg: Cropped", for the tooltip and screen readers.</summary>+ public string AccessibleName => $"{Name}: {StateText}";++ /// <summary>Keeps a small copy of the preview (made once, from the already downscaled preview).</summary>+ internal void SetThumbnail(Bitmap preview)+ {+ if (Thumbnail is not null)+ return;+ try+ {+ var size = preview.PixelSize;+ var scale = Math.Min(1.0, (double)ThumbnailSide / Math.Max(size.Width, size.Height));+ Thumbnail = preview.CreateScaledBitmap(+ new PixelSize(Math.Max(1, (int)Math.Round(size.Width * scale)), Math.Max(1, (int)Math.Round(size.Height * scale))),+ BitmapInterpolationMode.HighQuality);+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ Thumbnail = null; // the strip shows the file's number instead+ }+ }++ internal void RefreshTexts()+ {+ OnPropertyChanged(nameof(StateText));+ OnPropertyChanged(nameof(AccessibleName));+ }++ public void Dispose()+ {+ var thumbnail = Thumbnail;+ Thumbnail = null;+ thumbnail?.Dispose();}}diff --git a/src/Filee.App/Views/CropOverlayWindow.axaml b/src/Filee.App/Views/CropOverlayWindow.axamlindex 08712329..22276d7d 100644--- a/src/Filee.App/Views/CropOverlayWindow.axaml+++ b/src/Filee.App/Views/CropOverlayWindow.axaml@@ -1,3 +1,7 @@+<!-- The interactive crop overlay: a frameless soft-rounded stage with the picture large on the dimmed theme backdrop.+ Floating on it: the file chip (top left), the strip of files (top, several files), size and close (top right),+ and the toolbar pill at the bottom with the aspect dial, Reset, Skip and "Crop & save" / "Crop & next".+ After the last file with problems, a summary card with a small donut of how the files went. --><Window xmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:vm="using:Filee.App.ViewModels"@@ -6,122 +10,375 @@x:DataType="vm:CropOverlayViewModel"Title="{DynamicResource preset.crop}"Icon="avares://Filee/Assets/Icons/filee.ico"- Width="960" Height="680" MinWidth="680" MinHeight="500"+ Width="1040" Height="720" MinWidth="680" MinHeight="500"WindowDecorations="None"Background="Transparent"TransparencyLevelHint="Transparent"Topmost="True"CanResize="True">-++ <Window.Resources>+ <StreamGeometry x:Key="Crop.Swap">M7 3.5h8.5A4.5 4.5 0 0 1 20 8v2.2h2.2l-3.7 4.3-3.7-4.3H17V8a1.5 1.5 0 0 0-1.5-1.5H7z M17 20.5H8.5A4.5 4.5 0 0 1 4 16v-2.2H1.8l3.7-4.3 3.7 4.3H7V16a1.5 1.5 0 0 0 1.5 1.5H17z</StreamGeometry>+ <StreamGeometry x:Key="Crop.Maximize">M4 7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3z M7 6.2a.8.8 0 0 0-.8.8v10c0 .44.36.8.8.8h10a.8.8 0 0 0 .8-.8V7a.8.8 0 0 0-.8-.8z</StreamGeometry>+ <StreamGeometry x:Key="Crop.Grip">M18 10a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3z M18 16a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3z M12 16a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3z</StreamGeometry>+ </Window.Resources>+<Window.Styles>- <Style Selector="Button.aspect">- <Setter Property="Padding" Value="10,5" />- <Setter Property="CornerRadius" Value="6" />- <Setter Property="FontSize" Value="12" />+ <!-- The frame of the window; none when maximized -->+ <Style Selector="Border#Shell">+ <Setter Property="Margin" Value="12" />+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusLarge}" />+ </Style>+ <Style Selector="Window.maximized Border#Shell">+ <Setter Property="Margin" Value="0" />+ <Setter Property="CornerRadius" Value="0" />+ <Setter Property="BorderThickness" Value="0" />+ </Style>++ <!-- Floating pieces on the stage -->+ <Style Selector="Border.float">+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="BoxShadow" Value="{DynamicResource CardShadow}" />+ </Style>++ <!-- Toolbar buttons: quiet, round, a soft tint on hover -->+ <Style Selector="Button.tool">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Padding" Value="12,8" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Cursor" Value="Hand" />+ </Style>+ <Style Selector="Button.tool:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />+ </Style>+ <Style Selector="Button.tool.open /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />+ </Style>+ <Style Selector="Button.round">+ <Setter Property="Padding" Value="9" />+ <Setter Property="Width" Value="34" />+ <Setter Property="Height" Value="34" />+ </Style>+ <Style Selector="Button.primary">+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Padding" Value="16,8" />+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>++ <!-- Keycaps: the shortcut beside a button's name -->+ <Style Selector="Border.key"><Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ <Setter Property="CornerRadius" Value="5" />+ <Setter Property="Padding" Value="5,0" />+ <Setter Property="MinWidth" Value="18" />+ <Setter Property="Height" Value="18" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="Border.key > TextBlock">+ <Setter Property="FontSize" Value="10.5" />+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />+ <Setter Property="HorizontalAlignment" Value="Center" />+ <Setter Property="VerticalAlignment" Value="Center" />+ </Style>+ <Style Selector="Border.key.onaccent">+ <Setter Property="Background" Value="#2EFFFFFF" />+ </Style>+ <Style Selector="Border.key.onaccent > TextBlock">+ <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />+ </Style>++ <!-- The aspect dial: slices like the donut's, growing out of the toolbar button -->+ <Style Selector="c|RingSegment">+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" /><Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />- <Setter Property="BorderThickness" Value="1" /><Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="AccentBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="AccentSoftBrush" Value="{DynamicResource AccentSoftBrush}" />+ <Setter Property="OnAccentBrush" Value="{DynamicResource OnAccentBrush}" /><Setter Property="Cursor" Value="Hand" />+ <Setter Property="Transitions">+ <Transitions>+ <DoubleTransition Property="Pop" Duration="0:0:0.24" Easing="{StaticResource SoftEase}" />+ </Transitions>+ </Setter></Style>- <Style Selector="Button.aspect:pointerover">- <Setter Property="Opacity" Value="0.85" />+ <Style Selector="c|RingSegment:pointerover">+ <Setter Property="Pop" Value="1" /></Style>- <Style Selector="Button.aspect.active">- <Setter Property="Background" Value="{DynamicResource AccentBrush}" />- <Setter Property="Foreground" Value="{DynamicResource OnAccentBrush}" />- <Setter Property="FontWeight" Value="SemiBold" />- <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Style Selector="c|RingSegment:pressed">+ <Setter Property="Pop" Value="-0.2" />+ </Style>+ <Style Selector="c|AspectDial">+ <Setter Property="Opacity" Value="0" />+ <Setter Property="IsHitTestVisible" Value="False" />+ <Setter Property="RenderTransformOrigin" Value="50%,100%" />+ <Setter Property="RenderTransform" Value="scale(0.55)" />+ <Setter Property="Transitions">+ <Transitions>+ <DoubleTransition Property="Opacity" Duration="0:0:0.16" />+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.34" Easing="{StaticResource SoftEase}" />+ </Transitions>+ </Setter>+ </Style>+ <Style Selector="c|AspectDial.open">+ <Setter Property="Opacity" Value="1" />+ <Setter Property="IsHitTestVisible" Value="True" />+ <Setter Property="RenderTransform" Value="scale(1)" />+ </Style>+ <Style Selector="Button.hub">+ <Setter Property="HorizontalAlignment" Value="Stretch" />+ <Setter Property="VerticalAlignment" Value="Stretch" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="Padding" Value="4" />+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="HorizontalContentAlignment" Value="Center" />+ <Setter Property="VerticalContentAlignment" Value="Center" /></Style>- <Style Selector="Button.aspect.active:pointerover">- <Setter Property="Background" Value="{DynamicResource AccentBrush}" />+ <Style Selector="Button.hub:pointerover /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />+ </Style>+ <Style Selector="Button.hub:disabled /template/ ContentPresenter#PART_ContentPresenter">+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />+ </Style>+ <Style Selector="Button.hub:disabled">+ <Setter Property="Opacity" Value="0.55" />+ </Style>++ <!-- The strip of files -->+ <Style Selector="Border.tile">+ <Setter Property="Width" Value="38" />+ <Setter Property="Height" Value="28" />+ <Setter Property="Margin" Value="3,0" />+ <Setter Property="CornerRadius" Value="7" />+ <Setter Property="ClipToBounds" Value="True" />+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="RenderTransform" Value="scale(0.86)" /><Setter Property="Opacity" Value="0.9" />+ <Setter Property="Transitions">+ <Transitions>+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.32" Easing="{StaticResource SoftEase}" />+ <DoubleTransition Property="Opacity" Duration="0:0:0.2" />+ </Transitions>+ </Setter>+ </Style>+ <Style Selector="Border.tile.current">+ <Setter Property="RenderTransform" Value="scale(1.08)" />+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />+ <Setter Property="BorderThickness" Value="2" />+ <Setter Property="Opacity" Value="1" />+ </Style>+ <Style Selector="Border.tile.skipped, Border.tile.failed">+ <Setter Property="Opacity" Value="0.55" />+ </Style>+ <Style Selector="Border.badge-dot">+ <Setter Property="Width" Value="13" />+ <Setter Property="Height" Value="13" />+ <Setter Property="CornerRadius" Value="999" />+ <Setter Property="HorizontalAlignment" Value="Right" />+ <Setter Property="VerticalAlignment" Value="Bottom" />+ <Setter Property="Margin" Value="0,0,1,1" />+ <Setter Property="BorderBrush" Value="{DynamicResource SurfaceBrush}" />+ <Setter Property="BorderThickness" Value="1.5" />+ </Style>++ <!-- Reduced motion: everything here appears at once -->+ <Style Selector="Window.reduced-motion c|AspectDial, Window.reduced-motion Border.tile">+ <Setter Property="Transitions" Value="{x:Null}" /></Style></Window.Styles>- <!-- Overlay card with soft rounded corners and theme styling -->- <Border Margin="16" CornerRadius="{DynamicResource SoftRadius}"- Background="{DynamicResource SurfaceBrush}"+ <Border x:Name="Shell" ClipToBounds="True"+ Background="{DynamicResource PageBrush}"BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1"- ClipToBounds="True"BoxShadow="{DynamicResource CardShadow}">- <DockPanel>- <!-- Top header bar -->- <Border DockPanel.Dock="Top" Height="48" Padding="16,0" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="0,0,0,1"- Background="{DynamicResource SurfaceAltBrush}">- <DockPanel VerticalAlignment="Center">- <Button DockPanel.Dock="Right" Classes="icon" Command="{Binding CancelCommand}"- ToolTip.Tip="{DynamicResource common.cancel}" Margin="4,0,0,0">- <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" Foreground="{DynamicResource TextSecondaryBrush}" />- </Button>-- <StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">- <PathIcon Width="16" Height="16" Data="{StaticResource Icon.Crop}" Foreground="{DynamicResource AccentBrush}" />- <TextBlock Text="{DynamicResource preset.crop}" FontWeight="SemiBold" FontSize="14" Foreground="{DynamicResource TextPrimaryBrush}" />- <TextBlock Text="—" Foreground="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding IsEditing}" />- <TextBlock Text="{Binding CurrentFileName}" IsVisible="{Binding IsEditing}" FontSize="13" Foreground="{DynamicResource TextSecondaryBrush}" TextTrimming="CharacterEllipsis" MaxWidth="360" />-- <Border IsVisible="{Binding HasMultipleFiles}" Background="{DynamicResource AccentSoftBrush}" CornerRadius="10" Padding="8,2">- <TextBlock Text="{Binding CounterText}" FontSize="11" Foreground="{DynamicResource TextPrimaryBrush}" />- </Border>-- <Border IsVisible="{Binding HasStatusNotice}" Background="{DynamicResource SurfaceBrush}"- BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" CornerRadius="10" Padding="8,2">- <TextBlock Text="{Binding StatusNotice}" FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}"- TextTrimming="CharacterEllipsis" MaxWidth="320" />- </Border>- </StackPanel>- </DockPanel>- </Border>+ <Grid x:Name="Stage">+ <!-- The picture, the frame and the backdrop -->+ <c:CropCanvas x:Name="Canvas"+ SourceImage="{Binding PreviewImage}"+ SizeText="{Binding DimensionsText}"+ PixelSize="{Binding PixelSize}"+ ImagePadding="36,70,36,118"+ AccentBrush="{DynamicResource AccentBrush}"+ StageBrush="{DynamicResource PageBrush}"+ ChipBackground="{DynamicResource SurfaceBrush}"+ ChipForeground="{DynamicResource TextPrimaryBrush}" />++ <!-- Top: the file, the strip of files, size and close -->+ <Grid ColumnDefinitions="Auto,*,Auto" VerticalAlignment="Top" Margin="14,14,14,0">+ <StackPanel Spacing="8" HorizontalAlignment="Left">+ <Border Classes="float" Padding="5,5,12,5" IsVisible="{Binding IsEditing}" HorizontalAlignment="Left">+ <StackPanel Orientation="Horizontal" Spacing="9">+ <Border Width="26" Height="26" CornerRadius="999" Background="{DynamicResource AccentSoftBrush}">+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Crop}" Foreground="{DynamicResource AccentBrush}" />+ </Border>+ <TextBlock Text="{Binding CurrentFileName}" FontSize="13" FontWeight="SemiBold" VerticalAlignment="Center"+ TextTrimming="CharacterEllipsis" MaxWidth="260" Foreground="{DynamicResource TextPrimaryBrush}" />+ <Border IsVisible="{Binding HasMultipleFiles}" Background="{DynamicResource SurfaceAltBrush}" CornerRadius="999"+ Padding="8,2" VerticalAlignment="Center">+ <TextBlock Text="{Binding CounterText}" FontSize="11.5" Foreground="{DynamicResource TextSecondaryBrush}" />+ </Border>+ </StackPanel>+ </Border>++ <!-- The last file that failed or was skipped -->+ <Border Classes="float" Padding="10,6,12,6" IsVisible="{Binding HasStatusNotice}" HorizontalAlignment="Left"+ CornerRadius="{DynamicResource SoftRadius}" MaxWidth="420">+ <StackPanel Orientation="Horizontal" Spacing="8">+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Alert}" Foreground="{DynamicResource WarningBrush}" VerticalAlignment="Center" />+ <TextBlock Text="{Binding StatusNotice}" FontSize="12" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"+ Foreground="{DynamicResource TextSecondaryBrush}" MaxWidth="380" />+ </StackPanel>+ </Border>+ </StackPanel>- <!-- Bottom toolbar -->- <Border DockPanel.Dock="Bottom" Padding="16,12" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="0,1,0,0"- Background="{DynamicResource SurfaceAltBrush}">- <DockPanel>- <!-- Action Buttons on the Right -->- <Button DockPanel.Dock="Right" Content="{DynamicResource common.close}" Command="{Binding CancelCommand}"- IsVisible="{Binding IsFinished}" IsDefault="{Binding IsFinished}" Classes="accent" FontWeight="SemiBold" Padding="14,6" CornerRadius="6" />- <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="8" VerticalAlignment="Center" IsVisible="{Binding IsEditing}">- <Button Content="{DynamicResource crop.reset}" Command="{Binding ResetCommand}"- Classes="aspect" />- <Button Content="{DynamicResource crop.skip}" Command="{Binding SkipCommand}"- IsVisible="{Binding HasMultipleFiles}" Classes="aspect" />- <Button Content="{DynamicResource common.cancel}" Command="{Binding CancelCommand}"- IsCancel="True" Classes="aspect" />- <Button Content="{DynamicResource crop.save}" Command="{Binding CropAndSaveCommand}"- IsDefault="{Binding IsEditing}" Classes="accent" FontWeight="SemiBold" Padding="14,6" CornerRadius="6" />+ <!-- Several files: a thumbnail each, the current one lifted, done / skipped / failed marked -->+ <Border Grid.Column="1" Classes="float" Padding="6" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="16,0"+ IsVisible="{Binding HasMultipleFiles}">+ <ScrollViewer x:Name="StripScroller" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled" MaxWidth="440">+ <ItemsControl x:Name="Strip" ItemsSource="{Binding Queue}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Orientation="Horizontal" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ <ItemsControl.ItemTemplate>+ <DataTemplate x:DataType="vm:CropQueueItem">+ <Panel ToolTip.Tip="{Binding AccessibleName}" AutomationProperties.Name="{Binding AccessibleName}">+ <Border Classes="tile" Classes.current="{Binding IsCurrent}" Classes.skipped="{Binding IsSkipped}"+ Classes.failed="{Binding IsFailed}">+ <Panel>+ <TextBlock Text="{Binding Number}" FontSize="10.5" HorizontalAlignment="Center" VerticalAlignment="Center"+ Foreground="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding !HasThumbnail}" />+ <Image Source="{Binding Thumbnail}" Stretch="UniformToFill" />+ </Panel>+ </Border>+ <Border Classes="badge-dot" Background="{DynamicResource AccentBrush}" IsVisible="{Binding IsDone}">+ <PathIcon Width="7" Height="7" Data="{StaticResource Icon.Check}" Foreground="{DynamicResource OnAccentBrush}" />+ </Border>+ <Border Classes="badge-dot" Background="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding IsSkipped}">+ <Border Width="6" Height="1.5" Background="{DynamicResource SurfaceBrush}" />+ </Border>+ <Border Classes="badge-dot" Background="{DynamicResource DangerBrush}" IsVisible="{Binding IsFailed}">+ <TextBlock Text="!" FontSize="9" FontWeight="Bold" Foreground="{DynamicResource SurfaceBrush}"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ </Panel>+ </DataTemplate>+ </ItemsControl.ItemTemplate>+ </ItemsControl>+ </ScrollViewer>+ </Border>++ <Border Grid.Column="2" Classes="float" Padding="3" VerticalAlignment="Top">+ <StackPanel Orientation="Horizontal" Spacing="2">+ <Button x:Name="MaximizeButton" Classes="tool round" Click="OnMaximize"+ ToolTip.Tip="{DynamicResource crop.maximize}" AutomationProperties.Name="{DynamicResource crop.maximize}">+ <PathIcon Width="13" Height="13" Data="{StaticResource Crop.Maximize}" Foreground="{DynamicResource TextSecondaryBrush}" />+ </Button>+ <Button Classes="tool round" Command="{Binding CancelCommand}"+ ToolTip.Tip="{DynamicResource crop.close_hint}" AutomationProperties.Name="{DynamicResource common.close}">+ <PathIcon Width="11" Height="11" Data="{StaticResource Icon.Close}" Foreground="{DynamicResource TextSecondaryBrush}" />+ </Button></StackPanel>+ </Border>+ </Grid>++ <!-- Bottom: the toolbar pill and the keys -->+ <StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="16,0,16,12" Spacing="7" IsVisible="{Binding IsEditing}">+ <Border Classes="float" Padding="5">+ <StackPanel Orientation="Horizontal" Spacing="3">+ <Button x:Name="DialButton" Classes="tool" Classes.open="{Binding IsAspectDialOpen}" Padding="8,6,12,6"+ Command="{Binding ToggleAspectDialCommand}"+ ToolTip.Tip="{Binding AspectToolTip}" AutomationProperties.Name="{Binding AspectToolTip}">+ <StackPanel Orientation="Horizontal" Spacing="8">+ <c:AspectGlyph Width="22" Height="22" SelectedIndex="{Binding SelectedAspectIndex}"+ AccentBrush="{DynamicResource AccentBrush}" RingBrush="{DynamicResource TextSecondaryBrush}" />+ <TextBlock Text="{Binding AspectLabel}" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="13" MinWidth="30" />+ <Border Classes="key"><TextBlock Text="A" /></Border>+ </StackPanel>+ </Button>- <!-- Aspect ratio selector on the Left -->- <StackPanel Orientation="Horizontal" Spacing="6" VerticalAlignment="Center" IsVisible="{Binding IsEditing}">- <TextBlock Text="{DynamicResource crop.aspect_title}" VerticalAlignment="Center" FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,2,0" />- <Button Classes="aspect" Classes.active="{Binding IsAspectFree}" Content="{DynamicResource crop.aspect_free}" Command="{Binding SetAspectCommand}" CommandParameter="free" />- <Button Classes="aspect" Classes.active="{Binding IsAspectSquare}" Content="1:1" Command="{Binding SetAspectCommand}" CommandParameter="1:1" />- <Button Classes="aspect" Classes.active="{Binding IsAspect43}" Content="4:3" Command="{Binding SetAspectCommand}" CommandParameter="4:3" />- <Button Classes="aspect" Classes.active="{Binding IsAspect169}" Content="16:9" Command="{Binding SetAspectCommand}" CommandParameter="16:9" />- <Button Classes="aspect" Classes.active="{Binding IsAspectOriginal}" Content="{DynamicResource crop.aspect_original}" Command="{Binding SetAspectCommand}" CommandParameter="original" />-- <Border Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1" CornerRadius="6" Padding="8,4" Margin="6,0,0,0">- <TextBlock Text="{Binding DimensionsText}" FontSize="11" FontFamily="Consolas, monospace" Foreground="{DynamicResource TextSecondaryBrush}" />- </Border>+ <Border Width="1" Height="22" Margin="3,0" Background="{DynamicResource SubtleBorderBrush}" VerticalAlignment="Center" />++ <Button Classes="tool" Command="{Binding ResetCommand}" AutomationProperties.Name="{DynamicResource crop.reset}">+ <StackPanel Orientation="Horizontal" Spacing="7">+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Refresh}" Foreground="{DynamicResource TextSecondaryBrush}" />+ <TextBlock Text="{DynamicResource crop.reset}" FontSize="13" VerticalAlignment="Center" />+ <Border Classes="key"><TextBlock Text="R" /></Border>+ </StackPanel>+ </Button>+ <Button Classes="tool" Command="{Binding SkipCommand}" IsVisible="{Binding HasMultipleFiles}"+ AutomationProperties.Name="{DynamicResource crop.skip}">+ <StackPanel Orientation="Horizontal" Spacing="5">+ <TextBlock Text="{DynamicResource crop.skip}" FontSize="13" VerticalAlignment="Center" />+ <PathIcon Width="11" Height="11" Data="{StaticResource Icon.ChevronRight}" Foreground="{DynamicResource TextSecondaryBrush}" />+ </StackPanel>+ </Button>++ <Button x:Name="PrimaryButton" Classes="accent primary" Margin="4,0,0,0" Command="{Binding CropAndSaveCommand}"+ AutomationProperties.Name="{Binding SaveText}">+ <StackPanel Orientation="Horizontal" Spacing="9">+ <TextBlock Text="{Binding SaveText}" FontSize="13" VerticalAlignment="Center" />+ <Border Classes="key onaccent"><TextBlock Text="Enter" /></Border>+ </StackPanel>+ </Button></StackPanel>- </DockPanel>+ </Border>+ <TextBlock Text="{DynamicResource crop.hint_keys}" FontSize="11" HorizontalAlignment="Center" TextAlignment="Center"+ TextWrapping="Wrap" MaxWidth="560" Opacity="0.8" Foreground="{DynamicResource TextSecondaryBrush}" />+ </StackPanel>++ <!-- Drag the bottom-right corner to resize -->+ <Border x:Name="ResizeGrip" Width="22" Height="22" Background="Transparent" HorizontalAlignment="Right" VerticalAlignment="Bottom"+ Margin="0,0,4,4" Cursor="BottomRightCorner">+ <PathIcon Width="14" Height="14" Data="{StaticResource Crop.Grip}" Foreground="{DynamicResource TextSecondaryBrush}" Opacity="0.6" /></Border>- <!-- Center image viewport and interactive crop canvas -->- <Grid Background="{DynamicResource PageBrush}">- <c:CropCanvas x:Name="Canvas"- SourceImage="{Binding PreviewImage}"- HorizontalAlignment="Stretch"- VerticalAlignment="Stretch" IsVisible="{Binding IsEditing}" />-- <!-- After the last file, when files failed or were skipped -->- <Border IsVisible="{Binding IsFinished}" HorizontalAlignment="Center" VerticalAlignment="Center" MaxWidth="560" Margin="24"- Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="1"- CornerRadius="{DynamicResource SoftRadius}" Padding="20,16">- <StackPanel Spacing="10">- <TextBlock Text="{Binding Summary}" FontWeight="SemiBold" FontSize="14" Foreground="{DynamicResource TextPrimaryBrush}" />- <ScrollViewer MaxHeight="320">+ <!-- After the last file, when files failed or were skipped -->+ <Border Classes="card" IsVisible="{Binding IsFinished}" HorizontalAlignment="Center" VerticalAlignment="Center"+ MaxWidth="540" Margin="24" Padding="26,24">+ <StackPanel Spacing="14">+ <c:CropSummaryRing Width="112" Height="112" HorizontalAlignment="Center"+ Done="{Binding DoneCount}" Skipped="{Binding SkippedCount}" Failed="{Binding FailedCount}"+ AccentBrush="{DynamicResource AccentBrush}" MutedBrush="{DynamicResource TextSecondaryBrush}"+ DangerBrush="{DynamicResource DangerBrush}" HubBrush="{DynamicResource SurfaceBrush}"+ Foreground="{DynamicResource TextPrimaryBrush}" />+ <TextBlock Text="{Binding Summary}" FontWeight="SemiBold" FontSize="16" TextAlignment="Center" TextWrapping="Wrap"+ Foreground="{DynamicResource TextPrimaryBrush}" />+ <WrapPanel HorizontalAlignment="Center">+ <StackPanel Orientation="Horizontal" Spacing="6" Margin="8,2" IsVisible="{Binding HasDone}">+ <Ellipse Width="9" Height="9" Fill="{DynamicResource AccentBrush}" VerticalAlignment="Center" />+ <TextBlock FontSize="12.5" Foreground="{DynamicResource TextSecondaryBrush}">+ <Run Text="{DynamicResource crop.state_done}" /><Run Text=" " /><Run Text="{Binding DoneCount}" FontWeight="SemiBold" />+ </TextBlock>+ </StackPanel>+ <StackPanel Orientation="Horizontal" Spacing="6" Margin="8,2" IsVisible="{Binding HasSkipped}">+ <Ellipse Width="9" Height="9" Fill="{DynamicResource TextSecondaryBrush}" VerticalAlignment="Center" />+ <TextBlock FontSize="12.5" Foreground="{DynamicResource TextSecondaryBrush}">+ <Run Text="{DynamicResource crop.state_skipped}" /><Run Text=" " /><Run Text="{Binding SkippedCount}" FontWeight="SemiBold" />+ </TextBlock>+ </StackPanel>+ <StackPanel Orientation="Horizontal" Spacing="6" Margin="8,2" IsVisible="{Binding HasFailed}">+ <Ellipse Width="9" Height="9" Fill="{DynamicResource DangerBrush}" VerticalAlignment="Center" />+ <TextBlock FontSize="12.5" Foreground="{DynamicResource TextSecondaryBrush}">+ <Run Text="{DynamicResource crop.state_failed}" /><Run Text=" " /><Run Text="{Binding FailedCount}" FontWeight="SemiBold" />+ </TextBlock>+ </StackPanel>+ </WrapPanel>+ <Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="{DynamicResource SoftRadiusSmall}" Padding="14,10">+ <ScrollViewer MaxHeight="220"><ItemsControl ItemsSource="{Binding Problems}"><ItemsControl.ItemTemplate><DataTemplate x:DataType="x:String">@@ -130,14 +387,39 @@</ItemsControl.ItemTemplate></ItemsControl></ScrollViewer>- </StackPanel>- </Border>+ </Border>+ <Button x:Name="CloseButton" Classes="accent primary" HorizontalAlignment="Center" MinWidth="120"+ HorizontalContentAlignment="Center" Content="{DynamicResource common.close}" Command="{Binding CancelCommand}" />+ </StackPanel>+ </Border>- <!-- Loading spinner / busy indicator -->- <Border IsVisible="{Binding IsBusy}" Background="#44000000" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">- <ProgressBar IsIndeterminate="True" Width="80" Height="4" HorizontalAlignment="Center" VerticalAlignment="Center" />- </Border>- </Grid>- </DockPanel>+ <!-- Loading a picture or saving a crop -->+ <Border Classes="float" IsVisible="{Binding IsBusy}" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="18,14">+ <ProgressBar Classes="soft" IsIndeterminate="True" Width="96" />+ </Border>++ <!-- The aspect dial over everything; a click beside it closes it -->+ <Border x:Name="DialScrim" Background="Transparent" IsVisible="{Binding IsAspectDialOpen}" PointerPressed="OnScrimPressed" />+ <c:AspectDial x:Name="Dial" HorizontalAlignment="Left" VerticalAlignment="Top" IsVisible="False"+ Classes.open="{Binding IsAspectDialOpen}"+ CornerRadius="{DynamicResource SoftRadius}"+ SelectedMode="{Binding SelectedAspect}" IsPortrait="{Binding IsPortrait}" OriginalRatio="{Binding OriginalRatio}">+ <c:RingSegment Mode="free" Content="{DynamicResource crop.aspect_free}" Command="{Binding SetAspectCommand}" CommandParameter="free" />+ <c:RingSegment Mode="original" Content="{DynamicResource crop.aspect_original}" Command="{Binding SetAspectCommand}" CommandParameter="original" />+ <c:RingSegment Mode="1:1" Command="{Binding SetAspectCommand}" CommandParameter="1:1" />+ <c:RingSegment Mode="4:3" Command="{Binding SetAspectCommand}" CommandParameter="4:3" />+ <c:RingSegment Mode="3:2" Command="{Binding SetAspectCommand}" CommandParameter="3:2" />+ <c:RingSegment Mode="16:9" Command="{Binding SetAspectCommand}" CommandParameter="16:9" />+ <Button Classes="hub" Command="{Binding SwapOrientationCommand}" IsEnabled="{Binding CanSwapOrientation}"+ ToolTip.Tip="{DynamicResource crop.swap}" AutomationProperties.Name="{DynamicResource crop.swap}">+ <StackPanel Spacing="3" HorizontalAlignment="Center">+ <PathIcon Width="16" Height="16" Data="{StaticResource Crop.Swap}" Foreground="{DynamicResource AccentBrush}" />+ <TextBlock Text="{Binding OrientationText}" FontSize="11" FontWeight="SemiBold" TextAlignment="Center" TextWrapping="Wrap"+ MaxWidth="80" Foreground="{DynamicResource TextPrimaryBrush}" />+ <Border Classes="key" HorizontalAlignment="Center"><TextBlock Text="X" /></Border>+ </StackPanel>+ </Button>+ </c:AspectDial>+ </Grid></Border></Window>diff --git a/src/Filee.App/Views/CropOverlayWindow.axaml.cs b/src/Filee.App/Views/CropOverlayWindow.axaml.csindex 082d9e79..7edd238d 100644--- a/src/Filee.App/Views/CropOverlayWindow.axaml.cs+++ b/src/Filee.App/Views/CropOverlayWindow.axaml.cs@@ -1,18 +1,42 @@+using System.ComponentModel;using Avalonia;using Avalonia.Controls;using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.Threading;+using Filee.App.Controls;+using Filee.App.Services;using Filee.App.ViewModels;namespace Filee.App.Views;+/// <summary>+/// The crop overlay's window: placement, keys (Enter saves, Esc closes, R resets, A opens the aspect dial, X swaps+/// portrait and landscape, arrows move the frame, Shift × 10), the aspect dial over the toolbar and moving, sizing and+/// maximizing the frameless window.+/// </summary>public partial class CropOverlayWindow : Window{+ private CropOverlayViewModel? _vm;+ private bool _dialByKeyboard;+public CropOverlayWindow(){InitializeComponent();+ Motion.Track(this);+ Canvas.PlayAnimations = Motion.Enabled;+ Motion.Changed += OnMotionChanged;DataContextChanged += OnDataContextChanged;+ AddHandler(KeyDownEvent, OnKeyDownFirst, RoutingStrategies.Tunnel);+ ResizeGrip.PointerPressed += OnGripPressed;+ Stage.SizeChanged += (_, _) => PlaceDial();+ Closed += (_, _) => Motion.Changed -= OnMotionChanged;}+ /// <summary>+ /// Opens near <paramref name="near"/> (the screen of the donut), else on the primary screen, centred in its working+ /// area and no larger than most of it.+ /// </summary>public void PositionOnScreen(PixelPoint? near = null){var screen = (near.HasValue ? Screens.ScreenFromPoint(near.Value) : null)@@ -23,6 +47,8 @@ public partial class CropOverlayWindow : Window{var scaling = screen.Scaling;var area = screen.WorkingArea;+ Width = Math.Max(MinWidth, Math.Min(Width, area.Width / scaling * 0.94));+ Height = Math.Max(MinHeight, Math.Min(Height, area.Height / scaling * 0.92));var winW = (int)(Width * scaling);var winH = (int)(Height * scaling);var x = area.X + Math.Max(0, (area.Width - winW) / 2);@@ -31,43 +57,192 @@ public partial class CropOverlayWindow : Window}}+ /// <summary>Settles every animation and transition (tests capture the end state).</summary>+ internal void SettleForCapture()+ {+ Classes.Set("reduced-motion", true);+ Canvas.PlayAnimations = false;+ Canvas.FinishAnimations();+ }++ internal CropCanvas CropCanvas => Canvas;+ internal AspectDial AspectDial => Dial;+private void OnDataContextChanged(object? sender, EventArgs e){- if (DataContext is CropOverlayViewModel vm)+ if (DataContext is CropOverlayViewModel vm && !ReferenceEquals(vm, _vm)){+ _vm = vm;vm.CloseRequested += Close;vm.ResetRequested += () => Canvas.ResetCrop();vm.AspectRatioChanged += ratio => Canvas.SetAspectRatio(ratio);+ vm.PropertyChanged += OnViewModelChanged;Canvas.CropRectChanged += rect => vm.UpdateDimensions(rect);Closed += (_, _) => vm.Dispose();}}- protected override void OnKeyDown(KeyEventArgs e)+ private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e){- base.OnKeyDown(e);- if (e.Key == Key.Escape)+ if (_vm is null)+ return;+ if (e.PropertyName == nameof(CropOverlayViewModel.IsAspectDialOpen))+ ShowDial(_vm.IsAspectDialOpen);+ else if (e.PropertyName == nameof(CropOverlayViewModel.CurrentIndex))+ Dispatcher.UIThread.Post(() => Strip.ContainerFromIndex(_vm.CurrentIndex)?.BringIntoView(), DispatcherPriority.Background);+ }++ private void OnMotionChanged(object? sender, EventArgs e) => Canvas.PlayAnimations = Motion.Enabled;++ // ───────────────────────── The aspect dial ─────────────────────────++ private void ShowDial(bool open)+ {+ if (open){- Close();- e.Handled = true;+ PlaceDial();+ Dial.IsVisible = true;+ var byKeyboard = _dialByKeyboard;+ Dispatcher.UIThread.Post(() =>+ {+ var selected = Dial.Segments.FirstOrDefault(s => s.IsSelected) ?? Dial.Segments.FirstOrDefault();+ selected?.Focus(byKeyboard ? NavigationMethod.Tab : NavigationMethod.Pointer);+ }, DispatcherPriority.Input);+ return;}- else if (e.Key == Key.R && e.KeyModifiers == KeyModifiers.None)++ _dialByKeyboard = false;+ if (Dial.IsKeyboardFocusWithin)+ DialButton.Focus();+ // Hidden once it has shrunk away, so Tab doesn't reach its slices.+ if (Motion.Enabled && !Classes.Contains("reduced-motion"))+ DispatcherTimer.RunOnce(() => Dial.IsVisible = _vm?.IsAspectDialOpen == true, TimeSpan.FromMilliseconds(220));+ else+ Dial.IsVisible = false;+ }++ /// <summary>Centres the dial over its toolbar button, a little above it, inside the window.</summary>+ private void PlaceDial()+ {+ if (!DialButton.IsEffectivelyVisible || DialButton.TranslatePoint(new Point(DialButton.Bounds.Width / 2, 0), Stage) is not { } anchor)+ return;+ var side = Dial.Side; // measured only once visible+ var x = Math.Clamp(anchor.X - side / 2, 8, Math.Max(8, Stage.Bounds.Width - side - 8));+ var y = Math.Max(8, anchor.Y - side - 4);+ Dial.Margin = new Thickness(x, y, 0, 0);+ }++ private void OnScrimPressed(object? sender, PointerPressedEventArgs e)+ {+ if (_vm is not null)+ _vm.IsAspectDialOpen = false;+ e.Handled = true;+ }++ /// <summary>Arrow keys on the open dial go round its slices.</summary>+ private void MoveDialFocus(int step)+ {+ var segments = Dial.Segments.ToList();+ if (segments.Count == 0)+ return;+ var index = segments.FindIndex(s => s.IsFocused);+ if (index < 0)+ index = Math.Max(0, segments.FindIndex(s => s.IsSelected));+ else+ index = ((index + step) % segments.Count + segments.Count) % segments.Count;+ segments[index].Focus(NavigationMethod.Tab);+ }++ // ───────────────────────── Keys ─────────────────────────++ /// <summary>Before any focused control: Enter always saves (not "click the focused button").</summary>+ private void OnKeyDownFirst(object? sender, KeyEventArgs e)+ {+ if (_vm is not { } vm)+ return;+ var dialOpen = vm.IsAspectDialOpen;+ var plain = e.KeyModifiers == KeyModifiers.None;+ switch (e.Key){- if (DataContext is CropOverlayViewModel vm)- {+ case Key.Escape:+ if (dialOpen)+ vm.IsAspectDialOpen = false;+ else+ vm.Cancel();+ e.Handled = true;+ break;+ case Key.Enter when !dialOpen:+ if (vm.IsFinished)+ vm.Cancel();+ else+ _ = vm.CropAndSaveAsync();+ e.Handled = true;+ break;+ case Key.R when plain && vm.IsEditing:+ vm.IsAspectDialOpen = false;vm.Reset();e.Handled = true;- }+ break;+ case Key.A when plain && vm.IsEditing:+ _dialByKeyboard = true;+ vm.ToggleAspectDial();+ e.Handled = true;+ break;+ case Key.X when plain && vm.IsEditing:+ vm.SwapOrientation();+ e.Handled = true;+ break;+ case Key.Left or Key.Right or Key.Up or Key.Down when dialOpen:+ MoveDialFocus(e.Key is Key.Left or Key.Up ? -1 : 1);+ e.Handled = true;+ break;+ case Key.Left or Key.Right or Key.Up or Key.Down when vm.IsEditing && !vm.IsBusy+ && (e.KeyModifiers & ~KeyModifiers.Shift) == KeyModifiers.None:+ var step = e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? 10 : 1;+ Canvas.Nudge(e.Key switch { Key.Left => -step, Key.Right => step, _ => 0 },+ e.Key switch { Key.Up => -step, Key.Down => step, _ => 0 });+ e.Handled = true;+ break;}}+ // ───────────────────────── Moving and sizing the window ─────────────────────────++ /// <summary>The stage beside the picture moves the window; a double click maximizes it.</summary>protected override void OnPointerPressed(PointerPressedEventArgs e){base.OnPointerPressed(e);- var pt = e.GetPosition(this);- if (pt.Y < 50 && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)- {+ if (e.Handled || !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)+ return;+ if (e.ClickCount == 2)+ ToggleMaximized();+ else if (WindowState == WindowState.Normal)BeginMoveDrag(e);+ }++ private void OnGripPressed(object? sender, PointerPressedEventArgs e)+ {+ if (WindowState == WindowState.Normal && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)+ BeginResizeDrag(WindowEdge.SouthEast, e);+ e.Handled = true;+ }++ private void OnMaximize(object? sender, RoutedEventArgs e) => ToggleMaximized();++ private void ToggleMaximized() =>+ WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;++ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)+ {+ base.OnPropertyChanged(change);+ if (change.Property == WindowStateProperty)+ {+ var maximized = WindowState == WindowState.Maximized;+ Classes.Set("maximized", maximized);+ ResizeGrip.IsVisible = !maximized;+ var key = maximized ? "crop.restore" : "crop.maximize";+ MaximizeButton.Bind(ToolTip.TipProperty, MaximizeButton.GetResourceObservable(key));+ MaximizeButton.Bind(Avalonia.Automation.AutomationProperties.NameProperty, MaximizeButton.GetResourceObservable(key));}}}diff --git a/tests/Filee.App.Tests/CropMathTests.cs b/tests/Filee.App.Tests/CropMathTests.csnew file mode 100644index 00000000..d2ed1772--- /dev/null+++ b/tests/Filee.App.Tests/CropMathTests.cs@@ -0,0 +1,83 @@+// The crop overlay's arithmetic: ratios and their portrait forms, keyboard nudges, the frame in pixels and where the+// size chip goes.++using Avalonia;+using Filee.App.Controls;++namespace Filee.App.Tests;++public class CropMathTests+{+ [Theory]+ [InlineData("free", false, 0.0)]+ [InlineData("1:1", true, 1.0)]+ [InlineData("4:3", false, 4.0 / 3.0)]+ [InlineData("4:3", true, 3.0 / 4.0)]+ [InlineData("3:2", true, 2.0 / 3.0)]+ [InlineData("16:9", false, 16.0 / 9.0)]+ [InlineData("16:9", true, 9.0 / 16.0)]+ [InlineData("original", true, 1.6)] // the picture's own ratio isn't turned around+ public void Ratios_and_their_portrait_forms(string mode, bool portrait, double expected)+ {+ Assert.Equal(expected, CropMath.Ratio(mode, portrait, 1600, 1000), 6);+ }++ [Fact]+ public void Only_fixed_ratios_that_arent_square_swap()+ {+ Assert.Equal(["4:3", "3:2", "16:9"], CropMath.AspectModes.Where(CropMath.CanSwap));+ Assert.Equal("9:16", CropMath.Numbers("16:9", portrait: true));+ Assert.Equal("16:9", CropMath.Numbers("16:9", portrait: false));+ Assert.Equal("1:1", CropMath.Numbers("1:1", portrait: true));+ Assert.Equal(0, CropMath.Ratio("original", false, 0, 0));+ Assert.Equal(3, CropMath.AspectIndex("4:3"));+ Assert.Equal(-1, CropMath.AspectIndex("5:4"));+ }++ [Fact]+ public void Nudging_moves_by_whole_pixels_and_stops_at_the_edges()+ {+ var frame = new Rect(0.25, 0.25, 0.5, 0.5); // 400, 250, 800 × 500 of 1600 × 1000+ Assert.Equal(new Rect(401 / 1600.0, 250 / 1000.0, 0.5, 0.5), CropMath.Nudge(frame, 1, 0, 1600, 1000));+ Assert.Equal(new Rect(400 / 1600.0, 240 / 1000.0, 0.5, 0.5), CropMath.Nudge(frame, 0, -10, 1600, 1000));+ Assert.Equal(new Rect(0, 250 / 1000.0, 0.5, 0.5), CropMath.Nudge(frame, -1000, 0, 1600, 1000));+ Assert.Equal(new Rect(800 / 1600.0, 500 / 1000.0, 0.5, 0.5), CropMath.Nudge(frame, 5000, 5000, 1600, 1000));++ // Off the pixel grid (a frame dragged on screen), the first nudge lands on it.+ var loose = new Rect(100.4 / 1600, 0, 0.5, 0.5);+ Assert.Equal(101 / 1600.0, CropMath.Nudge(loose, 1, 0, 1600, 1000).X, 9);++ // A frame as large as the picture doesn't move; an unknown picture leaves it alone.+ Assert.Equal(new Rect(0, 0, 1, 1), CropMath.Nudge(new Rect(0, 0, 1, 1), 3, 3, 1600, 1000));+ Assert.Equal(frame, CropMath.Nudge(frame, 3, 3, 0, 0));+ }++ [Fact]+ public void The_frame_in_pixels_is_rounded_and_never_empty()+ {+ Assert.Equal(new PixelSize(800, 333), CropMath.PixelSize(new Rect(0, 0, 0.5, 0.333), 1600, 1000));+ Assert.Equal(new PixelSize(1, 1), CropMath.PixelSize(new Rect(0, 0, 0.0001, 0), 1600, 1000));+ }++ [Fact]+ public void The_size_chip_sits_under_the_frame_inside_it_or_above_it()+ {+ var area = new Rect(0, 0, 800, 600);+ var chip = new Size(100, 24);++ // Room below: centred under the frame.+ Assert.Equal(new Point(150, 310), CropMath.SizeChipOrigin(new Rect(100, 100, 200, 200), chip, area));++ // The frame reaches the bottom: inside along its bottom edge, clear of the edge's handle.+ var low = CropMath.SizeChipOrigin(new Rect(100, 300, 200, 300), chip, area);+ Assert.Equal(150, low.X);+ Assert.True(low.Y + chip.Height < 600 - CropMath.ChipGap && low.Y > 300);++ // A thin frame at the bottom: above it.+ Assert.Equal(new Point(150, 576 - CropMath.ChipGap - 24), CropMath.SizeChipOrigin(new Rect(100, 576, 200, 24), chip, area));++ // Near a side: kept inside the area.+ Assert.Equal(0, CropMath.SizeChipOrigin(new Rect(0, 100, 40, 40), chip, area).X);+ Assert.Equal(700, CropMath.SizeChipOrigin(new Rect(760, 100, 40, 40), chip, area).X);+ }+}diff --git a/tests/Filee.App.Tests/CropOverlayTests.cs b/tests/Filee.App.Tests/CropOverlayTests.csnew file mode 100644index 00000000..f63ba3c5--- /dev/null+++ b/tests/Filee.App.Tests/CropOverlayTests.cs@@ -0,0 +1,291 @@+// The crop overlay's window: the stage with the frame and its size chip, the aspect dial, the strip of several files,+// the end summary (screenshots in light and dark, short and long languages), and its keys and ratio choices.++using System.IO;+using Avalonia;+using Avalonia.Headless;+using Avalonia.Headless.XUnit;+using Avalonia.Input;+using Avalonia.Threading;+using Filee.App.Controls;+using Filee.App.Services;+using Filee.App.ViewModels;+using Filee.App.Views;+using Filee.Core.Localization;+using Filee.Core.Presets;+using Filee.Core.Settings;+using ImageMagick;+using ImageMagick.Drawing;+using static Filee.App.Tests.RenderTests;++namespace Filee.App.Tests;++public class CropOverlayTests+{+ public static TheoryData<string, bool> Looks => new()+ {+ { "en", false }, { "en", true }, { "ko", false }, { "ko", true }, { "ru", false }, { "hi", true },+ };++ [AvaloniaTheory]+ [MemberData(nameof(Looks))]+ public void One_picture_shows_the_frame_its_size_and_the_aspect_dial(string language, bool dark)+ {+ WithOverlay(language, dark, ["harbour.jpg"], (window, vm, suffix) =>+ {+ Assert.False(vm.HasMultipleFiles);+ Assert.Equal(AppHost.Get<ILocalizer>()["crop.save"], vm.SaveText);++ vm.SetAspect("4:3");+ window.CropCanvas.NormalizedCropRect = new Rect(0.30, 0.18, 0.5, 0.6);+ Settle(window);+ Assert.Equal("800 × 600 px", vm.DimensionsText);+ Save(window, $"crop-single-{suffix}.png");++ vm.ToggleAspectDial();+ Settle(window);+ Assert.True(window.AspectDial.IsVisible);+ Assert.Equal("4:3", window.AspectDial.Segments.Single(s => s.IsSelected).Mode);+ Save(window, $"crop-dial-{suffix}.png");+ });+ }++ [AvaloniaTheory]+ [MemberData(nameof(Looks))]+ public void Several_files_show_a_strip_with_how_each_went(string language, bool dark)+ {+ WithOverlay(language, dark, ["one.jpg", "two.jpg", "spinner.gif", "four.jpg", "five.jpg"], (window, vm, suffix) =>+ {+ Assert.True(vm.HasMultipleFiles);+ Assert.Equal(AppHost.Get<ILocalizer>()["crop.save_next"], vm.SaveText);++ _ = vm.CropAndSaveAsync();+ WaitFor(() => vm.CurrentIndex == 1 && !vm.IsBusy);+ _ = vm.SkipAsync();+ // The animated GIF can't be cropped: it fails on its own and the fourth file opens.+ WaitFor(() => vm.CurrentIndex == 3 && !vm.IsBusy && vm.PreviewImage is not null);++ Assert.Equal(+ [CropItemState.Done, CropItemState.Skipped, CropItemState.Failed, CropItemState.Current, CropItemState.Waiting],+ vm.Queue.Select(q => q.State));+ Assert.All(vm.Queue.Take(2).Append(vm.Queue[3]), q => Assert.NotNull(q.Thumbnail));+ Assert.Null(vm.Queue[4].Thumbnail);+ Assert.True(vm.HasStatusNotice);++ window.CropCanvas.NormalizedCropRect = new Rect(0.12, 0.2, 0.6, 0.55);+ Settle(window);+ Save(window, $"crop-multi-{suffix}.png");++ // Several problems: the summary stays until closed, with a slice per file.+ _ = vm.CropAndSaveAsync();+ WaitFor(() => vm.CurrentIndex == 4 && !vm.IsBusy);+ _ = vm.CropAndSaveAsync();+ WaitFor(() => vm.IsFinished);+ Assert.Equal((3, 1, 1), (vm.DoneCount, vm.SkippedCount, vm.FailedCount));+ Settle(window);+ Save(window, $"crop-summary-{suffix}.png");+ });+ }++ [AvaloniaFact]+ public void Dragging_shows_the_grid_and_the_size_chip_follows_the_frame()+ {+ WithOverlay("en", false, ["harbour.jpg"], (window, vm, _suffix) =>+ {+ var canvas = window.CropCanvas;+ var image = canvas.CalculateImageBounds();+ var origin = canvas.TranslatePoint(default, window)!.Value;+ var corner = canvas.GetScreenCropRect(image).BottomRight + (Vector)origin;+ window.MouseDown(corner, MouseButton.Left);+ window.MouseMove(corner - new Vector(image.Width * 0.3, image.Height * 0.25));+ Pump();+ canvas.FinishAnimations();+ var size = CropMath.PixelSize(canvas.NormalizedCropRect, 1600, 1000);+ Assert.InRange(size.Width, 1100, 1140);+ Assert.Equal($"{size.Width} × {size.Height} px", vm.DimensionsText);+ Save(window, "crop-drag-en.png");+ window.MouseUp(corner, MouseButton.Left);+ });+ }++ [AvaloniaFact]+ public void Keys_nudge_the_frame_open_the_dial_reset_and_close()+ {+ WithOverlay("en", false, ["harbour.jpg"], (window, vm, _suffix) =>+ {+ var canvas = window.CropCanvas;+ canvas.NormalizedCropRect = new Rect(0.25, 0.25, 0.5, 0.5); // 400, 250, 800 × 500+ Press(window, Key.Right);+ Press(window, Key.Right);+ Press(window, Key.Down, RawInputModifiers.Shift);+ Assert.Equal(new Rect(402 / 1600.0, 260 / 1000.0, 0.5, 0.5), canvas.NormalizedCropRect);+ Assert.Equal(canvas.NormalizedCropRect, vm.CurrentCropRect);++ // Stops at the picture's edge.+ for (var i = 0; i < 50; i++)+ Press(window, Key.Left, RawInputModifiers.Shift);+ Assert.Equal(0, canvas.NormalizedCropRect.X);++ // A opens the dial: arrows then go round its slices instead of moving the frame, Esc closes only the dial.+ Press(window, Key.A);+ Assert.True(vm.IsAspectDialOpen);+ Pump();+ var before = canvas.NormalizedCropRect;+ Press(window, Key.Right);+ Assert.Equal(before, canvas.NormalizedCropRect);+ Press(window, Key.Escape);+ Assert.False(vm.IsAspectDialOpen);+ Assert.True(window.IsVisible);++ // X swaps a fixed ratio; R resets the ratio and the frame.+ vm.SetAspect("16:9");+ Press(window, Key.X);+ Assert.True(vm.IsPortrait);+ Assert.Equal(9.0 / 16.0, canvas.AspectRatio, 6);+ Press(window, Key.R);+ Assert.Equal("free", vm.SelectedAspect);+ Assert.False(vm.IsPortrait);+ Assert.Equal(0, canvas.AspectRatio);+ Assert.Equal(new Rect(0, 0, 1, 1), canvas.NormalizedCropRect);++ var closed = false;+ window.Closed += (_, _) => closed = true;+ Press(window, Key.Escape);+ Assert.True(closed);+ });+ }++ [AvaloniaFact]+ public void Fixed_ratios_follow_the_pictures_orientation_and_swap()+ {+ WithOverlay("en", false, ["tall.jpg"], (window, vm, _suffix) =>+ {+ Assert.True(vm.IsPortrait); // a portrait picture starts with the portrait forms+ vm.SetAspect("4:3");+ Assert.Equal(3.0 / 4.0, vm.AspectRatio, 6);+ Assert.Equal("3:4", vm.AspectLabel);+ Assert.True(vm.CanSwapOrientation);++ vm.SwapOrientation();+ Assert.False(vm.IsPortrait);+ Assert.Equal(4.0 / 3.0, window.CropCanvas.AspectRatio, 6);+ Assert.Equal("4:3", vm.AspectLabel);+ var frame = window.CropCanvas.NormalizedCropRect;+ Assert.Equal(4.0 / 3.0, frame.Width * 1000 / (frame.Height * 1600), 2);++ // Square, free and the picture's own ratio have no second form.+ vm.SetAspect("1:1");+ Assert.False(vm.CanSwapOrientation);+ vm.SwapOrientation();+ Assert.Equal(1.0, vm.AspectRatio);+ vm.SetAspect("original");+ Assert.Equal(1000.0 / 1600.0, vm.AspectRatio, 6);+ Assert.Equal("Original", vm.AspectLabel);+ });+ }++ [AvaloniaFact]+ public void The_next_file_starts_free_and_full_in_view_and_canvas_alike()+ {+ WithOverlay("en", false, ["harbour.jpg", "tall.jpg"], (window, vm, _suffix) =>+ {+ vm.SetAspect("16:9");+ vm.SwapOrientation();+ _ = vm.CropAndSaveAsync();+ WaitFor(() => vm.CurrentIndex == 1 && !vm.IsBusy && vm.PreviewImage is not null);+ Pump();++ Assert.Equal("free", vm.SelectedAspect);+ Assert.Equal(0, vm.AspectRatio);+ Assert.Equal(0, window.CropCanvas.AspectRatio);+ Assert.True(vm.IsPortrait); // the second picture is upright+ Assert.Equal(new Rect(0, 0, 1, 1), window.CropCanvas.NormalizedCropRect);+ Assert.Equal(new Rect(0, 0, 1, 1), vm.CurrentCropRect);+ Assert.Equal("1000 × 1600 px", vm.DimensionsText);+ Assert.Equal(AppHost.Get<ILocalizer>()["crop.save"], vm.SaveText);+ });+ }++ // ───────────────────────── Helpers ─────────────────────────++ private static void WithOverlay(string language, bool dark, string[] names, Action<CropOverlayWindow, CropOverlayViewModel, string> act)+ {+ TestServices.EnsureInitialized(language);+ var theme = AppHost.Get<ThemeService>();+ if (dark)+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);+ var folder = Directory.CreateTempSubdirectory("filee-crop-overlay-").FullName;+ CropOverlayWindow? window = null;+ try+ {+ var files = names.Select(name => Picture(folder, name)).ToList();+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-crop");+ var vm = new CropOverlayViewModel(files, preset, AppHost.Get<ILocalizer>(), AppHost.Get<UserDataStore>());+ window = new CropOverlayWindow { DataContext = vm, Width = 1040, Height = 720 };+ window.Show();+ WaitFor(() => vm.PreviewImage is not null && !vm.IsBusy);+ Pump();+ window.CropCanvas.FinishAnimations();+ act(window, vm, $"{language}-{(dark ? "dark" : "light")}");+ }+ finally+ {+ if (window?.IsVisible == true)+ window.Close();+ if (dark)+ theme.Apply(new ThemeSettings(), language);+ try { Directory.Delete(folder, true); } catch (IOException) { }+ }+ }++ /// <summary>A landscape (1600 × 1000), an upright picture ("tall", 1000 × 1600) or a two-frame GIF ("…gif").</summary>+ private static string Picture(string folder, string name)+ {+ var path = Path.Combine(folder, name);+ if (name.EndsWith(".gif", StringComparison.Ordinal))+ {+ using var frames = new MagickImageCollection();+ frames.Add(new MagickImage(MagickColors.Coral, 40, 40));+ frames.Add(new MagickImage(MagickColors.Teal, 40, 40));+ frames.Write(path, MagickFormat.Gif);+ return path;+ }+ var tall = name.StartsWith("tall", StringComparison.Ordinal);+ var hue = name.Sum(c => c) % 5;+ string[] skies = ["#8EC5FC-#F8D2A6", "#A1C4FD-#C2E9FB", "#FBC2EB-#A6C1EE", "#84FAB0-#8FD3F4", "#FFECD2-#FCB69F"];+ using var image = new MagickImage($"gradient:{skies[hue]}", tall ? 1000u : 1600u, tall ? 1600u : 1000u);+ var w = (double)image.Width;+ var h = (double)image.Height;+ new Drawables()+ .FillColor(new MagickColor("#FFF2C2")).Circle(w * 0.68, h * 0.36, w * 0.68, h * 0.36 + Math.Min(w, h) * 0.1)+ .FillColor(new MagickColor("#4F7CAC")).Rectangle(0, h * 0.64, w, h)+ .FillColor(new MagickColor("#6C9A5B")).Polygon(new PointD(0, h * 0.7), new PointD(w * 0.24, h * 0.47), new PointD(w * 0.48, h * 0.69), new PointD(0, h * 0.76))+ .FillColor(new MagickColor("#3F6E4A")).Polygon(new PointD(w * 0.38, h * 0.7), new PointD(w * 0.62, h * 0.52), new PointD(w, h * 0.7), new PointD(w, h * 0.76), new PointD(w * 0.38, h * 0.76))+ .Draw(image);+ image.Write(path, MagickFormat.Jpeg);+ return path;+ }++ private static void Settle(CropOverlayWindow window)+ {+ Pump();+ window.SettleForCapture();+ Pump();+ }++ private static void Press(CropOverlayWindow window, Key key, RawInputModifiers modifiers = RawInputModifiers.None)+ {+ window.KeyPress(key, modifiers, PhysicalKey.None, null);+ Dispatcher.UIThread.RunJobs();+ }++ private static void WaitFor(Func<bool> condition)+ {+ for (var i = 0; i < 500 && !condition(); i++)+ {+ Dispatcher.UIThread.RunJobs();+ Thread.Sleep(10);+ }+ Assert.True(condition());+ }+}diff --git a/tests/Filee.App.Tests/WhatsNewMedia.cs b/tests/Filee.App.Tests/WhatsNewMedia.csindex c976507b..b0404b3f 100644--- a/tests/Filee.App.Tests/WhatsNewMedia.cs+++ b/tests/Filee.App.Tests/WhatsNewMedia.cs@@ -245,6 +245,7 @@ public class WhatsNewMedia};window.Show();WaitFor(() => vm.PreviewImage is not null && !vm.IsBusy);+ window.SettleForCapture(); // each frame of the clip is drawn where it endsPump();var canvas = window.GetVisualDescendants().OfType<CropCanvas>().Single();try