Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

fix(crop): stop perspective corners on the picture's edge, keep plain rectangles unresampled

SeoJCalive44c683067882
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index c981eb91..aa837b22 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -262,9 +262,9 @@
"crop.state_done": "자르기 완료",
"crop.state_skipped": "건너뜀",
"crop.state_failed": "실패",
- "crop.perspective": "원근",
- "crop.perspective_tip": "원근: 모서리를 하나씩 옮겨 비스듬한 사진을 반듯하게 펴기",
- "crop.perspective_pdf": "원근은 그림에만 쓸 수 있고 PDF 쪽에는 쓸 수 없어요",
+ "crop.perspective": "원근 보정",
+ "crop.perspective_tip": "원근 보정: 모서리를 하나씩 옮겨 비스듬한 이미지를 반듯하게 펴기",
+ "crop.perspective_pdf": "원근 보정은 이미지에만 쓸 수 있고 PDF 페이지에는 쓸 수 없어요",
"crop.hint_keys_perspective": "Tab으로 모서리 고르기, 화살표 키로 이동, Shift는 10배 · Esc로 닫기",
"crop.corner_top_left": "왼쪽 위 모서리",
"crop.corner_top_right": "오른쪽 위 모서리",
diff --git a/src/Filee.App/Controls/CropCanvas.cs b/src/Filee.App/Controls/CropCanvas.cs
index 056d639f..aa44f251 100644
--- a/src/Filee.App/Controls/CropCanvas.cs
+++ b/src/Filee.App/Controls/CropCanvas.cs
@@ -1,7 +1,9 @@
// 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.
+// the frame. Programmatic changes (reset, ratio, a new picture) ease in; dragging follows the pointer directly. In the
+// perspective mode the frame gives way to four corners that move on their own (by pointer or keyboard), joined by the
+// outline of the quadrilateral to straighten, with the size chip showing the straightened size.
using System.Diagnostics;
using System.Globalization;
diff --git a/src/Filee.App/Controls/CropMath.cs b/src/Filee.App/Controls/CropMath.cs
index 5c271bcc..a4a01ff8 100644
--- a/src/Filee.App/Controls/CropMath.cs
+++ b/src/Filee.App/Controls/CropMath.cs
@@ -1,5 +1,7 @@
// The crop overlay's arithmetic without a window: the ratios of the aspect dial, keyboard nudges, the frame's size in
-// pixels, where the size chip sits next to the frame and where the aspect dial opens.
+// pixels, where the size chip sits next to the frame and where the aspect dial opens. For the perspective mode it holds
+// the four corners (CropQuad), which shapes they may form and how they move, the straightened output size and whether
+// the corners still form a plain rectangle.
using Avalonia;
@@ -55,10 +57,13 @@ public static class CropMath
return true;
}
- /// <summary>Moves one corner only when the resulting quadrilateral is valid.</summary>
+ /// <summary>
+ /// Moves one corner, stopping it on the picture's edge when the target lies outside, and only when the resulting
+ /// quadrilateral is valid.
+ /// </summary>
public static CropQuad MoveCorner(CropQuad q, int corner, Point target, int width, int height)
{
- var moved = q.With(corner, target);
+ var moved = q.With(corner, new Point(Math.Clamp(target.X, 0, 1), Math.Clamp(target.Y, 0, 1)));
return IsValidQuad(moved, width, height) ? moved : q;
}
@@ -83,6 +88,26 @@ public static class CropMath
Math.Max(1, (int)Math.Round(Math.Max(Length(q.TopLeft, q.BottomLeft), Length(q.TopRight, q.BottomRight)))));
}
+ /// <summary>
+ /// The quadrilateral as a rectangle in original pixels when it already is one: sides along the picture's edges and
+ /// every corner on a whole pixel, as the corners are until they're dragged off the grid. Saving it is then a plain
+ /// crop, with no resampling.
+ /// </summary>
+ public static PixelRect? AxisAlignedRect(CropQuad q, int width, int height)
+ {
+ static int? Whole(double v) => Math.Abs(v - Math.Round(v)) < 1e-6 ? (int)Math.Round(v) : null;
+ var left = Whole(q.TopLeft.X * width);
+ var top = Whole(q.TopLeft.Y * height);
+ var right = Whole(q.BottomRight.X * width);
+ var bottom = Whole(q.BottomRight.Y * height);
+ if (left is not { } l || top is not { } t || right is not { } r || bottom is not { } b
+ || Whole(q.TopRight.X * width) != r || Whole(q.TopRight.Y * height) != t
+ || Whole(q.BottomLeft.X * width) != l || Whole(q.BottomLeft.Y * height) != b
+ || r <= l || b <= t)
+ return null;
+ return new PixelRect(l, t, r - l, b - t);
+ }
+
/// <summary>The aspect dial's choices, clockwise from the top.</summary>
public static IReadOnlyList<string> AspectModes => Modes;
diff --git a/src/Filee.App/Services/CropService.cs b/src/Filee.App/Services/CropService.cs
index 5cba4fee..661267d5 100644
--- a/src/Filee.App/Services/CropService.cs
+++ b/src/Filee.App/Services/CropService.cs
@@ -150,7 +150,16 @@ public static class CropService
image.AutoOrient();
if (corners is { } quad)
- Straighten(image, quad);
+ {
+ // Corners still on a whole-pixel rectangle need no resampling, which would only soften the picture.
+ if (CropMath.AxisAlignedRect(quad, (int)image.Width, (int)image.Height) is { } rect)
+ {
+ image.Crop(new MagickGeometry(rect.X, rect.Y, (uint)rect.Width, (uint)rect.Height));
+ image.ResetPage();
+ }
+ else
+ Straighten(image, quad);
+ }
else
{
var clampedX = Math.Clamp(x, 0, Math.Max(0, (int)image.Width - 1));
diff --git a/src/Filee.App/Views/CropOverlayWindow.axaml b/src/Filee.App/Views/CropOverlayWindow.axaml
index 533ab671..89dcdfa7 100644
--- a/src/Filee.App/Views/CropOverlayWindow.axaml
+++ b/src/Filee.App/Views/CropOverlayWindow.axaml
@@ -66,10 +66,12 @@
<Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
</Style>
- <Style Selector="Button.tool:disabled /template/ ContentPresenter#PART_ContentPresenter, ToggleButton.tool:disabled /template/ ContentPresenter#PART_ContentPresenter">
+ <!-- Only the ratio button (off in the perspective mode) and the perspective toggle (off for a PDF) fade; the other
+ tool buttons keep their usual look while disabled, and the ratio boxes the usual look of a disabled number box. -->
+ <Style Selector="Button#DialButton:disabled /template/ ContentPresenter#PART_ContentPresenter, ToggleButton#PerspectiveButton:disabled /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
</Style>
- <Style Selector="Button.tool:disabled, ToggleButton.tool:disabled">
+ <Style Selector="Button#DialButton:disabled, ToggleButton#PerspectiveButton:disabled">
<Setter Property="Opacity" Value="0.45" />
</Style>
<Style Selector="Button.corner">
diff --git a/tests/Filee.App.Tests/CropMathTests.cs b/tests/Filee.App.Tests/CropMathTests.cs
index ffec1021..1fdfc73a 100644
--- a/tests/Filee.App.Tests/CropMathTests.cs
+++ b/tests/Filee.App.Tests/CropMathTests.cs
@@ -1,5 +1,6 @@
// The crop overlay's arithmetic: ratios and their portrait forms, keyboard nudges, snapping to the centre, the frame
-// in pixels and where the size chip goes.
+// in pixels and where the size chip goes, and for the perspective mode the corners' allowed shapes and moves, the
+// straightened size and when the corners are still a plain rectangle.
using Avalonia;
using Filee.App.Controls;
@@ -9,7 +10,7 @@ namespace Filee.App.Tests;
public class CropMathTests
{
[Fact]
- public void A_corner_moves_only_to_a_convex_untwisted_shape_inside_the_picture()
+ public void A_corner_moves_only_to_a_convex_untwisted_shape()
{
var square = new CropQuad(new Point(0.2, 0.2), new Point(0.8, 0.2),
new Point(0.8, 0.8), new Point(0.2, 0.8));
@@ -19,8 +20,6 @@ public class CropMathTests
new Point(0.6, 0.6), // concave
new Point(0.5, 0.5), // three collinear points
new Point(0.9, 0.2), // passes the neighbouring corner
- new Point(-0.1, 0.2),
- new Point(0.2, 1.1),
};
static Point Rotate(Point p) => new(1 - p.Y, p.X);
@@ -61,6 +60,36 @@ public class CropMathTests
Assert.Equal(fractional, CropMath.MoveCorner(CropQuad.Full, 0, fractional.TopLeft, 1, 1));
}
+ [Fact]
+ public void A_corner_pushed_past_the_edge_stops_on_it()
+ {
+ var nearEdge = new CropQuad(new Point(5 / 1600.0, 0.2), new Point(0.8, 0.2),
+ new Point(0.8, 0.8), new Point(0.2, 0.8));
+ Assert.Equal(nearEdge.With(0, new Point(0, 0.2)),
+ CropMath.MoveCorner(nearEdge, 0, new Point(-50 / 1600.0, 0.2), 1600, 1000));
+ Assert.Equal(nearEdge.With(0, new Point(0, 0)),
+ CropMath.MoveCorner(nearEdge, 0, new Point(-0.3, -0.4), 1600, 1000));
+ Assert.Equal(nearEdge.With(2, new Point(1, 1)),
+ CropMath.MoveCorner(nearEdge, 2, new Point(1.2, 1.5), 1600, 1000));
+
+ var threeFromEdge = nearEdge.With(0, new Point(3 / 1600.0, 0.2));
+ Assert.Equal(nearEdge.With(0, new Point(0, 0.2)), CropMath.NudgeCorner(threeFromEdge, 0, -10, 0, 1600, 1000));
+
+ // Stopped on the edge, the corner would cross the bottom side: still refused.
+ var leaning = new CropQuad(new Point(0.2, 0.2), new Point(0.8, 0.2), new Point(0.8, 0.8), new Point(0, 0.8));
+ Assert.Equal(leaning, CropMath.MoveCorner(leaning, 0, new Point(-1, 0.9), 1600, 1000));
+ }
+
+ [Fact]
+ public void Corners_on_a_whole_pixel_rectangle_are_a_plain_crop()
+ {
+ Assert.Equal(new PixelRect(0, 0, 1600, 1000), CropMath.AxisAlignedRect(CropQuad.Full, 1600, 1000));
+ var nudged = CropMath.NudgeCorner(CropMath.NudgeCorner(CropQuad.Full, 0, 7, 0, 1600, 1000), 3, 7, 0, 1600, 1000);
+ Assert.Equal(new PixelRect(7, 0, 1593, 1000), CropMath.AxisAlignedRect(nudged, 1600, 1000));
+ Assert.Null(CropMath.AxisAlignedRect(CropQuad.Full.With(0, new Point(7 / 1600.0, 0)), 1600, 1000));
+ Assert.Null(CropMath.AxisAlignedRect(CropQuad.Full.With(0, new Point(0.5 / 1600, 0)).With(3, new Point(0.5 / 1600, 1)), 1600, 1000));
+ }
+
[Fact]
public void Perspective_size_is_the_longer_of_each_pair_of_sides()
{
diff --git a/tests/Filee.App.Tests/CropOverlayTests.cs b/tests/Filee.App.Tests/CropOverlayTests.cs
index 8c0a14bf..9801bfa6 100644
--- a/tests/Filee.App.Tests/CropOverlayTests.cs
+++ b/tests/Filee.App.Tests/CropOverlayTests.cs
@@ -653,6 +653,51 @@ public class CropOverlayTests
});
}
+ [AvaloniaFact]
+ public async Task A_corner_dragged_or_nudged_past_the_edge_stops_on_it()
+ {
+ await WithOverlayAsync("en", false, ["harbour.jpg"], (window, vm, _) =>
+ {
+ ClickPerspective(window);
+ var canvas = window.CropCanvas;
+ var start = new CropQuad(new Point(5 / 1600.0, 0.2), new Point(0.6, 0.2), new Point(0.6, 0.8), new Point(0.2, 0.8));
+
+ canvas.NormalizedCorners = start;
+ Pump();
+ var image = canvas.CalculateImageBounds();
+ var from = canvas.TranslatePoint(canvas.CornerScreenPoint(0), window)!.Value;
+ Drag(window, from, from + new Vector(-55 / 1600.0 * image.Width, 0));
+ Assert.Equal(0, canvas.NormalizedCorners.TopLeft.X);
+ Assert.Equal(0.2, canvas.NormalizedCorners.TopLeft.Y, 3);
+
+ canvas.NormalizedCorners = start.With(0, new Point(3 / 1600.0, 0.2));
+ CornerButtons(window)[0].Focus(NavigationMethod.Tab);
+ Pump();
+ Press(window, Key.Left, RawInputModifiers.Shift);
+ Assert.Equal(start.With(0, new Point(0, 0.2)), canvas.NormalizedCorners);
+ return Task.CompletedTask;
+ });
+ }
+
+ [AvaloniaFact]
+ public async Task Only_the_ratio_and_perspective_buttons_fade_while_disabled()
+ {
+ await WithOverlayAsync("en", false, ["harbour.jpg", "tall.jpg"], (window, vm, _) =>
+ {
+ ClickPerspective(window);
+ var dial = window.FindControl<Button>("DialButton")!;
+ Assert.False(dial.IsEffectivelyEnabled);
+ Assert.Equal(0.45, dial.Opacity, 3);
+
+ var skip = window.GetVisualDescendants().OfType<Button>().Single(b => b.Command == vm.SkipCommand);
+ skip.IsEnabled = false;
+ Pump();
+ Assert.False(skip.IsEffectivelyEnabled);
+ Assert.Equal(1, skip.Opacity);
+ return Task.CompletedTask;
+ });
+ }
+
[AvaloniaFact]
public async Task Tab_picks_a_corner_and_arrows_move_it()
{
diff --git a/tests/Filee.App.Tests/CropServiceTests.cs b/tests/Filee.App.Tests/CropServiceTests.cs
index 510d58ea..9aca86c7 100644
--- a/tests/Filee.App.Tests/CropServiceTests.cs
+++ b/tests/Filee.App.Tests/CropServiceTests.cs
@@ -1,4 +1,5 @@
-// Tests for CropService and the crop overlay: output resolving, conflict policies, quality, failures and skips.
+// Tests for CropService and the crop overlay: output resolving, conflict policies, quality, failures and skips, and the
+// perspective crop (straightening, orientation, a plain rectangle saved without resampling).
using System.IO;
using Avalonia;
@@ -98,6 +99,36 @@ public class CropServiceTests
}
}
+ [AvaloniaFact]
+ public async Task A_perspective_crop_of_a_plain_rectangle_is_not_resampled()
+ {
+ TestServices.EnsureInitialized("en");
+ var folder = Directory.CreateTempSubdirectory("filee-perspective-rectangle-").FullName;
+ try
+ {
+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "tool-crop");
+ var plain = Tilted(Directory.CreateDirectory(Path.Combine(folder, "plain")).FullName, "tilted.png");
+ var quad = Tilted(Directory.CreateDirectory(Path.Combine(folder, "quad")).FullName, "tilted.png");
+ var rectangle = new CropQuad(new Point(100.0 / 800, 60.0 / 600), new Point(500.0 / 800, 60.0 / 600),
+ new Point(500.0 / 800, 420.0 / 600), new Point(100.0 / 800, 420.0 / 600));
+ var expected = await CropService.CropFileAsync(plain, 100, 60, 400, 360, preset,
+ AppHost.Get<UserDataStore>(), AppHost.Get<ILocalizer>());
+ var actual = await CropService.CropFileAsync(quad, 0, 0, 800, 600, preset,
+ AppHost.Get<UserDataStore>(), AppHost.Get<ILocalizer>(), corners: rectangle);
+ Assert.Equal(CropStatus.Success, expected.Status);
+ Assert.Equal(CropStatus.Success, actual.Status);
+ using var want = new MagickImage(expected.OutputPath!);
+ using var got = new MagickImage(actual.OutputPath!);
+ Assert.Equal(400u, got.Width);
+ Assert.Equal(360u, got.Height);
+ Assert.Equal(0, got.Compare(want, ErrorMetric.Absolute));
+ }
+ finally
+ {
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+
[AvaloniaFact]
public async Task A_perspective_crop_follows_the_pictures_orientation()
{