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.

Merge main into feat/hide-areas: Edit pictures (schema 51) and Pixelate / blur (52) side by side

KnifeLemon25ecfdeaab8a
diff --cc src/Filee.App/Services/PresetAvailability.cs
index 6184fcb5,1763d469..ed826112
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@@ -120,10 -120,10 +120,14 @@@ public sealed class PresetAvailabilit
}
// Any picture among the files: the others are left out when the window opens.
+ if (preset.IsImageEditTool)
+ return formats.Any(f => ImageEditTool.CanEdit(f.Id))
+ ? new(PresetUse.Usable, null)
+ : new(PresetUse.Unusable, _loc["error.images_only"]);
+ if (preset.IsHideTool)
+ return formats.Any(f => HideService.CanOpen(f.Id))
+ ? new(PresetUse.Usable, null)
+ : new(PresetUse.Unusable, _loc["error.images_only"]);
if (preset.IsTool)
{
diff --cc src/Filee.App/Services/WindowService.cs
index 98dec687,f9acdb40..6c289ae6
--- a/src/Filee.App/Services/WindowService.cs
+++ b/src/Filee.App/Services/WindowService.cs
@@@ -36,10 -36,10 +36,12 @@@ public sealed class WindowService(ILoca
private CropOverlayWindow? _cropOverlay;
private ClipWindow? _clipWindow;
+ private HideWindow? _hideWindow;
+ private ImageEditWindow? _imageEdit;
internal ClipWindow? ClipWindow => _clipWindow;
+ internal HideWindow? HideWindow => _hideWindow;
+ internal ImageEditWindow? ImageEdit => _imageEdit;
private readonly HashSet<SpreadsheetPrintStudioWindow> _spreadsheetStudios = [];
internal IReadOnlyCollection<SpreadsheetPrintStudioWindow> SpreadsheetStudios => _spreadsheetStudios;
@@@ -123,15 -123,15 +125,17 @@@
public MainWindow? Main => _main;
/// <summary>
- /// Opens the window of a tool preset (crop, cut a clip, pixelate / blur, the spreadsheet print studio: one per
- /// workbook, the PDF page editor) on the files. A tool this version doesn't know opens nothing.
- /// Opens the window of a tool preset (crop, cut a clip, edit pictures, the spreadsheet print studio: one per workbook,
- /// the PDF page editor) on the files. A tool this version doesn't know opens nothing.
++ /// Opens the window of a tool preset (crop, cut a clip, edit pictures, pixelate / blur, the spreadsheet print studio:
++ /// one per workbook, the PDF page editor) on the files. A tool this version doesn't know opens nothing.
/// </summary>
public void ShowTool(IReadOnlyList<string> files, Preset preset, PixelPoint? near = null)
{
if (preset.IsClipTool)
ShowClipWindow(files, preset, near);
+ else if (preset.IsHideTool)
+ ShowHideWindow(files, preset, near);
+ else if (preset.IsImageEditTool)
+ ShowImageEditWindow(files, preset);
// Before the crop: the print studio and the PDF page tools have no Tool of their own, which reads as a crop
// ("Crop PDF" is one and opens the crop overlay).
else if (preset.Id == "tool-sheet-studio")
@@@ -177,38 -177,59 +181,91 @@@
win.Activate();
}
+ /// <summary>
+ /// Opens the "Edit pictures" window on the pictures among the files. Its Convert starts ordinary conversions, shown
+ /// in the toast.
+ /// </summary>
+ public void ShowImageEditWindow(IReadOnlyList<string> files, Preset preset)
+ {
+ var pictures = files.Where(f => FormatRegistry.Detect(f) is { } format && ImageEditTool.CanEdit(format.Id)).ToList();
+ if (pictures.Count == 0)
+ return;
+ _imageEdit?.Close();
+ var store = services.GetRequiredService<UserDataStore>();
+ var catalog = services.GetRequiredService<ConverterCatalog>();
+ var conversions = services.GetRequiredService<ConversionService>();
+ var log = services.GetService<ILogger<ImageEditViewModel>>();
+ var planner = catalog.CreatePlanner();
+ var formats = pictures.Select(path => FormatRegistry.Detect(path)?.Id ?? "").ToList();
+ var vm = new ImageEditViewModel(pictures, preset, loc, store,
+ (path, chosen) => ImageEditTool.TargetFor(FormatRegistry.Detect(path)?.Id ?? "", chosen, planner),
+ (paths, conversion) => conversions.Start(paths, conversion), PictureSize, log, ImageEditTool.TargetsFrom(formats, planner));
+ var win = new ImageEditWindow { DataContext = vm };
+ PrepareWindow(win);
+ win.Closed += (_, _) =>
+ {
+ if (_imageEdit == win)
+ _imageEdit = null;
+ };
+ _imageEdit = win;
+ win.Show();
+ win.Activate();
+ }
+
+ /// <summary>
+ /// Opens the "Pixelate / blur" window on the pictures among the files. Each picture is written by an ordinary
+ /// conversion, shown in the toast.
+ /// </summary>
+ public void ShowHideWindow(IReadOnlyList<string> files, Preset preset, PixelPoint? near = null)
+ {
+ var pictures = files.Where(f => FormatRegistry.Detect(f) is { } format && HideService.CanOpen(format.Id)).ToList();
+ if (pictures.Count == 0)
+ return;
+ _hideWindow?.Close();
+ var store = services.GetRequiredService<UserDataStore>();
+ var catalog = services.GetRequiredService<ConverterCatalog>();
+ var conversions = services.GetRequiredService<ConversionService>();
+ var log = services.GetService<ILogger<HideWindowViewModel>>();
+ var planner = catalog.CreatePlanner();
+ var vm = new HideWindowViewModel(pictures, preset, loc, store,
+ path => HideTool.TargetFor(FormatRegistry.Detect(path)?.Id ?? "", planner),
+ (path, conversion) => conversions.Start([path], conversion), log);
+ var win = new HideWindow { DataContext = vm };
+ PrepareWindow(win);
+ win.PositionOnScreen(near);
+ win.Closed += (_, _) =>
+ {
+ if (_hideWindow == win)
+ _hideWindow = null;
+ trimmer.Request();
+ };
+ _hideWindow = win;
+ win.Show();
+ win.Activate();
+ }
+
+ /// <summary>
+ /// The pixel size of a picture as it is seen, read from its headers: turned as its EXIF orientation says, and the
+ /// largest of an icon's sizes (the one converted). Null when ImageMagick can't read it.
+ /// </summary>
+ internal static (int Width, int Height)? PictureSize(string path)
+ {
+ try
+ {
+ var info = ImageMagick.MagickImageInfo.ReadCollection(path).MaxBy(frame => (long)frame.Width * frame.Height);
+ if (info is null)
+ return null;
+ return info.Orientation is ImageMagick.OrientationType.LeftTop or ImageMagick.OrientationType.RightTop
+ or ImageMagick.OrientationType.RightBottom or ImageMagick.OrientationType.LeftBottom
+ ? ((int)info.Height, (int)info.Width)
+ : ((int)info.Width, (int)info.Height);
+ }
+ catch (Exception ex) when (ex is ImageMagick.MagickException or IOException or UnauthorizedAccessException)
+ {
+ return null;
+ }
+ }
+
/// <summary>Opens the interactive crop overlay for the files.</summary>
public void ShowCropOverlay(IReadOnlyList<string> files, Preset preset, PixelPoint? near = null)
{
diff --cc src/Filee.Core/Presets/BuiltInData.cs
index 6bb3f5ca,230fa63d..ef437e67
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@@ -49,7 -49,7 +49,8 @@@ public static class BuiltInDat
Id = "tool-crop", NameKey = "preset.crop", TargetFormat = SameAsSource,
Kind = PresetKind.Tool, Output = { FileNamePattern = "{name}_cropped" },
},
+ .. ImageEditPresets(),
+ .. HidePresets(),
new()
{
Id = "tool-sheet-studio", NameKey = "preset.sheet_studio", TargetFormat = "pdf",
@@@ -194,19 -194,19 +195,32 @@@
},
];
+ /// <summary>
+ /// "Edit pictures" (#584, added in settings schema 51): size, format, turn and colour chosen in a window each time, on
+ /// the front of the images donut after "Half size".
+ /// </summary>
+ public static List<Preset> ImageEditPresets() =>
+ [
+ new()
+ {
+ Id = "tool-image-edit", NameKey = "preset.image_edit", TargetFormat = SameAsSource,
+ Kind = PresetKind.Tool, Tool = Preset.ImageEditTool, Output = { FileNamePattern = "{name}_edited" },
+ },
+ ];
+
+ /// <summary>
+ /// "Pixelate / blur" (added in settings schema 52): parts of a picture (names, faces, numbers) covered before it is
- /// shared. On the front of the images donut after "Half size".
++ /// shared. On the front of the images donut after "Edit pictures".
+ /// </summary>
+ public static List<Preset> HidePresets() =>
+ [
+ new()
+ {
+ Id = "tool-hide", NameKey = "preset.hide", TargetFormat = SameAsSource,
+ Kind = PresetKind.Tool, Tool = Preset.HideTool, Output = { FileNamePattern = "{name}_hidden" },
+ },
+ ];
+
/// <summary>
/// "Trim transparent borders" (issue #332, added in settings schema 33): a copy cropped to the visible pixels, in the
/// same format. On the images donut's back face after "Remove background".
@@@ -542,7 -542,7 +556,7 @@@
Id = "images", NameKey = "profile.images",
Extensions = ExtensionsOf(FormatCategory.Image),
PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size",
- "tool-hide"],
- "tool-image-edit"],
++ "tool-image-edit", "tool-hide"],
// Full (ToolbarProfile.MaxSlices): "Extract Live Photo video" stays in the library, on no donut.
BackPresetIds = ["tool-crop", "rotate", "flip", "remove-background", "trim-transparent", "grayscale", "to-avif", "to-gif", "merge-pdf",
"compress-image", "remove-metadata", "zip-all"],
diff --cc src/Filee.Core/Presets/Preset.cs
index 0d6306cd,78446690..7d92bdf1
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@@ -194,15 -207,17 +207,21 @@@ public sealed class Prese
/// <summary><see cref="Tool"/> of "Cut a clip": a part of a video, chosen on a timeline.</summary>
public const string ClipTool = "clip";
+ /// <summary>
+ /// <see cref="Tool"/> of "Edit pictures": the size, format, turn and colour of pictures, chosen in a small window each
+ /// time (#584).
+ /// </summary>
+ public const string ImageEditTool = "image-edit";
+
+ /// <summary>
+ /// <see cref="Tool"/> of "Pixelate / blur": parts of a picture covered before it is shared (names, faces, numbers).
+ /// </summary>
+ public const string HideTool = "hide";
+
/// <summary>
/// <see cref="PresetKind.Tool"/>: which window it opens, <see cref="CropTool"/> (or null, as saved before there were
- /// other tools), <see cref="ClipTool"/> or <see cref="HideTool"/>. A tool this version doesn't know (from a newer
- /// Filee) opens nothing. Ignored for other kinds.
- /// other tools), <see cref="ClipTool"/> or <see cref="ImageEditTool"/>. A tool this version doesn't know (from a newer
- /// Filee) opens nothing.
- /// Ignored for other kinds.
++ /// other tools), <see cref="ClipTool"/>, <see cref="ImageEditTool"/> or <see cref="HideTool"/>. A tool this version
++ /// doesn't know (from a newer Filee) opens nothing. Ignored for other kinds.
/// </summary>
public string? Tool { get; set; }
@@@ -214,10 -229,10 +233,14 @@@
[JsonIgnore]
public bool IsClipTool => IsTool && Tool == ClipTool;
+ /// <summary>True for "Edit pictures".</summary>
+ [JsonIgnore]
+ public bool IsImageEditTool => IsTool && Tool == ImageEditTool;
+
+ /// <summary>True for "Pixelate / blur".</summary>
+ [JsonIgnore]
+ public bool IsHideTool => IsTool && Tool == HideTool;
+
/// <summary>
/// True if converting a <paramref name="sourceFormat"/> file cuts a clip of it (<see cref="MediaOptions.Clip"/>,
/// set by the clip window on the conversion it starts): the file is a video. Other files convert as usual.
@@@ -363,16 -375,9 +406,16 @@@ public sealed class ImageOption
[JsonIgnore]
public bool TurnsOrMirrors => Rotation != ImageRotation.None || Flip != ImageFlip.None;
+ /// <summary>
+ /// Turns, mirrors or covers parts of the image (<see cref="HidesAreas"/>): done once, in the first step of a route whose
+ /// engine applies image options (<see cref="Conversion.IImageTransformer"/>); a file is never passed on as it is.
+ /// </summary>
+ [JsonIgnore]
+ public bool ReworksPixels => TurnsOrMirrors || HidesAreas;
+
/// <summary>Whether the preset edits picture content, size, or playback speed.</summary>
[JsonIgnore]
- public bool EditsPicture => Resize != ResizeMode.None || Grayscale || TrimTransparent || RemoveBackground || MaxCompression || ChangesSpeed;
+ public bool EditsPicture => Resize != ResizeMode.None || Grayscale || TrimTransparent || RemoveBackground || MaxCompression || ChangesSpeed || CustomSize is not null || MinShortEdge is not null;
/// <summary>Scale in percent when <see cref="Resize"/> is <see cref="ResizeMode.Percent"/>.</summary>
public int ResizePercent { get; set; } = 50;
@@@ -509,7 -516,9 +578,10 @@@
{
var copy = (ImageOptions)MemberwiseClone();
copy.IcoSizes = [.. IcoSizes];
+ copy.HiddenAreas = HiddenAreas?.Select(area => area.Clone()).ToList();
+ copy.CustomSize = CustomSize is { } size
+ ? new CustomImageSize { Width = size.Width, Height = size.Height, LockAspect = size.LockAspect }
+ : null;
return copy;
}
}
diff --cc src/Filee.Core/Settings/UserDataStore.cs
index cb89f91d,aaf4be19..e47cd2ca
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@@ -906,14 -906,13 +906,21 @@@ internal static class SettingsMigration
// v50: Dahua DVR recordings (.dav) learn the video donut; custom claims stay put.
if (from < 50)
changed |= LearnExtensions(profiles, out _, ["dav"]);
- // v52 (51 is kept for "Edit pictures"): "Pixelate / blur", after "Crop" as in a new library, and on the images
- // donut after "Half size" (after "Edit pictures" when that follows it) when the front has room, else at the
- // end of the back face when that has room. A front without "Half size" was laid out by the user and is
- // left alone (the tool is in the library); one who put the tool somewhere on the donut keeps it there.
+ // v51: "Edit pictures" (size, format, turn and colour chosen each time, #584), after "Crop" as in a new library,
+ // and on the front of the images donut after "Half size" when that is there, the user hasn't put the tool
+ // elsewhere on the donut and the face has room.
+ // Present already but saved since by a Filee before 45 (2.0): that one dropped the tool's name, which made it
+ // a crop, so it is put back. 2.1 keeps the name (the slice is greyed out there, as a tool it doesn't know).
+ if (from < 51)
+ changed |= AddImageEditTool(presets, profiles);
++ // v52: "Pixelate / blur", after "Edit pictures" (else "Crop") as in a new library, and on the images donut after
++ // "Half size" (after "Edit pictures" when that follows it) when the front has room, else at the end of the
++ // back face when that has room. A front without "Half size" was laid out by the user and is left alone (the
++ // tool is in the library); one who put the tool somewhere on the donut keeps it there.
+ // Present already but saved since by a Filee before 45 (2.0): that one dropped the tool's name, which made it
+ // a crop, so it is put back. 2.1 keeps the name (the slice is greyed out there, as a tool it doesn't know).
+ if (from < 52)
+ changed |= AddHideTool(presets, profiles);
return changed;
}
@@@ -1040,52 -1039,40 +1047,88 @@@
return changed;
}
+ private static bool AddImageEditTool(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ var edit = BuiltInData.ImageEditPresets().Single();
+ if (presets.FirstOrDefault(p => p.Id == edit.Id) is { } existing)
+ {
+ if (!existing.IsImageEditTool)
+ {
+ existing.Kind = PresetKind.Tool;
+ existing.Tool = Preset.ImageEditTool;
+ existing.SubPresetIds = [];
+ if (existing.TargetFormat == Preset.GroupTarget)
+ existing.TargetFormat = edit.TargetFormat;
+ changed = true;
+ }
+ }
+ else
+ {
+ var at = presets.FindIndex(p => p.Id == "tool-crop");
+ presets.Insert(at < 0 ? presets.Count : at + 1, edit);
+ changed = true;
+ }
+ // Next to "Half size", the resize it does more of: a front without it was laid out by the user and stays so.
+ if (profiles.FirstOrDefault(p => p.Id == "images") is { } images
+ && images.PresetIds.IndexOf("half-size") is >= 0 and var half
+ && !images.PresetIds.Contains(edit.Id) && images.BackPresetIds?.Contains(edit.Id) != true
+ && images.PresetIds.Count < ToolbarProfile.MaxSlices)
+ {
+ images.PresetIds.Insert(half + 1, edit.Id);
+ changed = true;
+ }
+ return changed;
+ }
+
+ private static bool AddHideTool(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ var hide = BuiltInData.HidePresets().Single();
+ if (presets.FirstOrDefault(p => p.Id == hide.Id) is { } existing)
+ {
+ if (!existing.IsHideTool)
+ {
+ existing.Kind = PresetKind.Tool;
+ existing.Tool = Preset.HideTool;
+ existing.SubPresetIds = [];
+ if (existing.TargetFormat == Preset.GroupTarget)
+ existing.TargetFormat = hide.TargetFormat;
+ changed = true;
+ }
+ }
+ else
+ {
- var at = presets.FindIndex(p => p.Id == "tool-crop");
++ var at = presets.FindIndex(p => p.Id == "tool-image-edit") is >= 0 and var edit
++ ? edit
++ : presets.FindIndex(p => p.Id == "tool-crop");
+ presets.Insert(at < 0 ? presets.Count : at + 1, hide);
+ changed = true;
+ }
+ if (profiles.FirstOrDefault(p => p.Id == "images") is not { } images
+ || images.PresetIds.Contains(hide.Id) || images.BackPresetIds?.Contains(hide.Id) == true)
+ return changed;
+ var front = images.PresetIds;
+ // Next to the other everyday edits: "Half size", and "Edit pictures" when it follows it. A front without "Half
+ // size" was laid out by the user and stays so, with the back face.
+ var after = front.IndexOf("half-size");
+ if (after < 0)
+ return changed;
+ if (after + 1 < front.Count && front[after + 1] == "tool-image-edit")
+ after++;
+ if (front.Count < ToolbarProfile.MaxSlices)
+ {
+ front.Insert(after + 1, hide.Id);
+ return true;
+ }
+ if (images.BackPresetIds is { } back && back.Count < ToolbarProfile.MaxSlices)
+ {
+ InsertBefore(back, hide.Id, "zip-all");
+ return true;
+ }
+ return changed;
+ }
+
private static bool AddGeo(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
diff --cc tests/Filee.App.Tests/RenderTests.cs
index 4411c3bf,add49dde..80e48183
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@@ -918,7 -918,7 +918,7 @@@ public class RenderTest
window.DonutControl.SetExternalHighlight(1);
Pump();
- Assert.Equal(11, vm.Items.Count); // with "Trace to SVG", "Line art to SVG" and "Pixelate / blur"
- Assert.Equal(11, vm.Items.Count); // with "Trace to SVG", "Line art to SVG" and "Edit pictures"
++ Assert.Equal(12, vm.Items.Count); // with "Trace to SVG", "Line art to SVG", "Edit pictures" and "Pixelate / blur"
Assert.Equal(title, vm.CenterTitle);
Save(window, $"donut-images-{language}.png");
window.Close();
diff --cc tests/Filee.App.Tests/ToolbarPaletteViewTests.cs
index 997af4b6,d0a42a45..ea46098f
--- a/tests/Filee.App.Tests/ToolbarPaletteViewTests.cs
+++ b/tests/Filee.App.Tests/ToolbarPaletteViewTests.cs
@@@ -491,13 -491,13 +491,16 @@@ public class ToolbarPaletteViewTest
RenderTests.Pump();
Assert.Equal(PaletteTab.All, view.Selected);
view.ClickTab(PaletteTab.Edit);
- Assert.Equal(["pdf-edit", "rotate", "flip", "test-group", "tool-crop", "tool-hide"], view.Chips);
- Assert.Equal(["pdf-edit", "rotate", "flip", "test-group", "tool-crop", "tool-image-edit"], view.Chips);
++ Assert.Equal(["pdf-edit", "rotate", "flip", "test-group", "tool-crop", "tool-image-edit", "tool-hide"], view.Chips);
DoubleTap(view.Chip("tool-crop"));
RenderTests.Pump();
Assert.Equal(["tool-crop"], jpg.PresetIds);
+ DoubleTap(view.Chip("tool-image-edit"));
+ RenderTests.Pump();
+ Assert.Equal(["tool-crop", "tool-image-edit"], jpg.PresetIds);
+ DoubleTap(view.Chip("tool-hide"));
+ RenderTests.Pump();
- Assert.Equal(["tool-crop", "tool-hide"], jpg.PresetIds);
++ Assert.Equal(["tool-crop", "tool-image-edit", "tool-hide"], jpg.PresetIds);
Assert.DoesNotContain(PaletteTab.Edit, view.TabIds);
Assert.Equal(PaletteTab.All, view.Selected);
Assert.Equal(["pdf-edit", "rotate", "flip", "test-group", "extract-motion", "test-motion"], view.Chips);
diff --cc tests/Filee.Core.Tests/BackFaceTests.cs
index d27e522d,46234db2..294fe7ce
--- a/tests/Filee.Core.Tests/BackFaceTests.cs
+++ b/tests/Filee.Core.Tests/BackFaceTests.cs
@@@ -95,7 -95,7 +95,7 @@@ public class BackFaceTest
public void The_fronts_stay_as_they_were_before_back_faces()
{
Assert.Equal(["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size",
- "tool-hide"], BuiltIn("images").PresetIds);
- "tool-image-edit"], BuiltIn("images").PresetIds);
++ "tool-image-edit", "tool-hide"], BuiltIn("images").PresetIds);
Assert.Equal(BuiltInData.PdfDonut, BuiltIn("pdf").PresetIds);
Assert.Equal(["to-pdf", "to-hwpx", "to-hwp", "to-docx", "to-odt", "to-txt", "to-html", "to-epub", "to-png", "merge-pdf"],
BuiltIn("office").PresetIds);
diff --cc tests/Filee.Core.Tests/HideToolTests.cs
index d07f9451,00000000..a545559b
mode 100644,000000..100644
--- a/tests/Filee.Core.Tests/HideToolTests.cs
+++ b/tests/Filee.Core.Tests/HideToolTests.cs
@@@ -1,404 -1,0 +1,409 @@@
+// "Pixelate / blur": where a part lies in pixels, how large the squares or the blur are and which square a pixel is in,
+// the conversion the tool becomes, how it is saved (and read by an older Filee), the job queue covering the parts once
+// and never handing the picture over uncovered, and the tool arriving in libraries from before it (settings schema 52).
+
+using System.Text.Json;
+using Filee.Core.Conversion;
+using Filee.Core.History;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class HideToolTests
+{
+ private static Preset Tool() => BuiltInData.CreatePresets().Single(p => p.Id == "tool-hide");
+
+ private static HiddenArea Area(double x, double y, double w, double h) => new() { X = x, Y = y, Width = w, Height = h };
+
+ // ───────────────────────── The arithmetic ─────────────────────────
+
+ [Theory]
+ [InlineData(1, 1920, 1080, 21.6)] // a desktop screenshot: 2 % of 1080, a little over a line of text
+ [InlineData(5, 1920, 1080, 43.2)] // the default: 4 %
+ [InlineData(10, 1920, 1080, 70.2)] // 6.5 %
+ [InlineData(5, 1080, 2400, 43.2)] // a phone screenshot: its shorter side counts, as tall as a line of its text
+ [InlineData(5, 6000, 4000, 160)] // a photo
+ [InlineData(1, 120, 80, 8)] // never under 8 px
+ [InlineData(0, 1920, 1080, 21.6)] // a hand-edited strength: within 1 … 10
+ [InlineData(99, 1920, 1080, 70.2)]
+ public void Squares_and_blur_grow_with_the_strength_and_the_pictures_shorter_side(int strength, int width, int height, double expected) =>
+ Assert.Equal(expected, HideTool.EffectSize(strength, width, height), 6);
+
+ [Fact]
+ public void Even_the_weakest_strength_covers_a_desktop_screenshots_line_of_text()
+ {
+ // Text on a 1080p screen is about 13 px tall: a square at least that tall leaves no letter to compare.
+ Assert.True(HideTool.EffectSize(HideTool.MinStrength, 1920, 1080) >= 13);
+ Assert.True(HideTool.EffectSize(HideTool.MinStrength, 3840, 2160) >= 26); // the same screen at 200 %
+ }
+
+ [Fact]
+ public void A_part_in_pixels_takes_every_pixel_it_touches()
+ {
+ // 0.1 × 1000 = 100 exactly; 0.1234 × 1000 = 123.4 → from 123; to 0.3234 × 1000 = 323.4 → up to 324.
+ Assert.Equal((100, 50, 200, 100), HideTool.PixelBounds(Area(0.1, 0.1, 0.2, 0.2), 1000, 500));
+ Assert.Equal((123, 61, 201, 101), HideTool.PixelBounds(Area(0.1234, 0.1234, 0.2, 0.2), 1000, 500));
+ // At least one pixel, even for a sliver.
+ Assert.Equal((500, 250, 1, 1), HideTool.PixelBounds(Area(0.5, 0.5, 0.0001, 0.0001), 1000, 500));
+ }
+
+ [Fact]
+ public void A_part_is_kept_inside_the_picture_and_nothing_is_made_of_one_outside_it()
+ {
+ Assert.Equal((900, 0, 100, 100), HideTool.PixelBounds(Area(0.9, -0.5, 0.5, 0.7), 1000, 500));
+ // Drawn from right to left (a negative width): the same part.
+ Assert.Equal((100, 50, 200, 100), HideTool.PixelBounds(Area(0.3, 0.3, -0.2, -0.2), 1000, 500));
+ Assert.Null(HideTool.PixelBounds(Area(1.2, 0.2, 0.3, 0.3), 1000, 500));
+ Assert.Null(HideTool.PixelBounds(Area(0.2, 0.2, 0, 0.3), 1000, 500));
+ Assert.Null(HideTool.PixelBounds(Area(double.NaN, 0.2, 0.1, 0.1), 1000, 500));
+ Assert.Null(HideTool.PixelBounds(Area(0.2, 0.2, 0.1, 0.1), 0, 500));
+ }
+
+ [Theory]
+ [InlineData(10)]
+ [InlineData(2.5)]
+ [InlineData(7.3)]
+ [InlineData(43.2)]
+ public void Every_pixel_falls_in_exactly_one_square_starting_where_the_square_starts(double cell)
+ {
+ Assert.Equal(0, HideTool.CellStart(0, cell));
+ for (var pixel = 0; pixel < 500; pixel++)
+ {
+ var square = HideTool.CellOf(pixel, cell);
+ Assert.InRange(pixel, HideTool.CellStart(square, cell), HideTool.CellStart(square + 1, cell) - 1);
+ }
+ // Whole-pixel squares start on their multiples.
+ Assert.Equal((0, 10, 20), (HideTool.CellStart(0, 10), HideTool.CellStart(1, 10), HideTool.CellStart(2, 10)));
+ Assert.Equal((0, 2, 5), (HideTool.CellStart(0, 2.5), HideTool.CellStart(1, 2.5), HideTool.CellStart(2, 2.5)));
+ }
+
+ // ───────────────────────── The tool and its conversion ─────────────────────────
+
+ [Fact]
+ public void The_built_in_tool_pixelates_at_the_default_strength_and_names_its_pictures_name_hidden()
+ {
+ var tool = Tool();
+ Assert.True(tool.IsTool);
+ Assert.True(tool.IsHideTool);
+ Assert.False(tool.IsCropTool || tool.IsClipTool);
+ Assert.Equal(("preset.hide", BuiltInData.SameAsSource, "{name}_hidden"), (tool.NameKey, tool.TargetFormat, tool.Output.FileNamePattern));
+ Assert.Equal((HideStyle.Pixelate, HideTool.DefaultStrength), (tool.Image.HideStyle, tool.Image.HideStrength));
+ Assert.Null(tool.Image.HiddenAreas);
+ Assert.False(tool.Image.HidesAreas);
+ Assert.False(new Preset { Kind = PresetKind.Tool, Tool = "crop" }.IsHideTool);
+ Assert.False(new Preset { Tool = Preset.HideTool }.IsHideTool); // a conversion, not a tool
+ }
+
+ [Fact]
+ public void The_tool_becomes_a_conversion_with_its_parts_and_never_keeps_the_original_for_being_smaller()
+ {
+ var tool = Tool();
+ tool.Name = "Redact";
+ tool.Image.HideStyle = HideStyle.Blur;
+ tool.Image.HideStrength = 42; // a hand-edited file
+ tool.Output.OnlyIfSmaller = true;
+
+ var conversion = HideTool.ConversionOf(tool, "png", [Area(0.1, 0.1, 0.2, 0.2), Area(0.5, 0.5, -0.1, 0.2), Area(2, 2, 1, 1)]);
+
+ Assert.Equal(PresetKind.Convert, conversion.Kind);
+ Assert.Null(conversion.Tool);
+ Assert.Equal("png", conversion.TargetFormat);
+ Assert.Equal(("tool-hide", "Redact"), (conversion.Id, conversion.Name));
+ Assert.Equal(HideStyle.Blur, conversion.Image.HideStyle);
+ Assert.Equal(HideTool.MaxStrength, conversion.Image.HideStrength);
+ // The part drawn backwards is turned around; the one off the picture is left out.
+ Assert.Equal(2, conversion.Image.HiddenAreas!.Count);
+ var turned = conversion.Image.HiddenAreas[1];
+ Assert.Equal((0.4, 0.5, 0.1, 0.2), (Math.Round(turned.X, 9), Math.Round(turned.Y, 9), Math.Round(turned.Width, 9), Math.Round(turned.Height, 9)));
+ Assert.True(conversion.Image.HidesAreas);
+ Assert.True(conversion.Image.ReworksPixels);
+ Assert.False(conversion.Output.OnlyIfSmaller);
+ // The tool itself is untouched, and a copy of the conversion has its own parts.
+ Assert.True(tool.IsHideTool);
+ Assert.Null(tool.Image.HiddenAreas);
+ Assert.True(tool.Output.OnlyIfSmaller);
+ var copy = conversion.Clone();
+ copy.Image.HiddenAreas![0].X = 0.9;
+ Assert.Equal(0.1, conversion.Image.HiddenAreas[0].X);
+ }
+
+ [Fact]
+ public void The_choice_is_remembered_in_the_tool()
+ {
+ var tool = Tool();
+ HideTool.Remember(tool, HideStyle.Blur, 8);
+ Assert.Equal((HideStyle.Blur, 8), (tool.Image.HideStyle, tool.Image.HideStrength));
+ HideTool.Remember(tool, HideStyle.Pixelate, -3);
+ Assert.Equal((HideStyle.Pixelate, HideTool.MinStrength), (tool.Image.HideStyle, tool.Image.HideStrength));
+ }
+
+ [Fact]
+ public void A_picture_keeps_its_format_where_it_can_be_written_else_becomes_png()
+ {
+ var magick = new FakeConverter("magick", new ConversionEdge("jpg", "jpg"), new ConversionEdge("raw", "png"), new ConversionEdge("png", "png"));
+ var planner = new ConverterCatalog([magick]).CreatePlanner();
+
+ Assert.Equal(BuiltInData.SameAsSource, HideTool.TargetFor("jpg", planner));
+ Assert.Equal(HideTool.FallbackTarget, HideTool.TargetFor("raw", planner)); // a camera RAW is read only
+ Assert.Equal(HideTool.FallbackTarget, HideTool.TargetFor("webp", planner)); // no engine here
+ Assert.True(HideTool.CanHide("jpg"));
+ Assert.False(HideTool.CanHide("pdf"));
+ Assert.False(HideTool.CanHide("mp4"));
+ }
+
+ // ───────────────────────── Saved, and read by an older Filee ─────────────────────────
+
+ [Fact]
+ public void The_choice_is_saved_by_name_and_the_parts_never_reach_a_saved_tool()
+ {
+ var tool = Tool();
+ HideTool.Remember(tool, HideStyle.Blur, 7);
+ var json = JsonSerializer.Serialize(new List<Preset> { tool }, FileeJsonContext.Default.ListPreset);
+ Assert.Contains("\"tool\": \"hide\"", json);
+ Assert.Contains("\"hideStyle\": \"Blur\"", json);
+ Assert.Contains("\"hideStrength\": 7", json);
+ Assert.DoesNotContain("hiddenAreas", json);
+
+ var read = JsonSerializer.Deserialize(json, FileeJsonContext.Default.ListPreset)!.Single();
+ Assert.True(read.IsHideTool);
+ Assert.Equal((HideStyle.Blur, 7), (read.Image.HideStyle, read.Image.HideStrength));
+
+ // A conversion keeps its parts.
+ var conversion = HideTool.ConversionOf(read, "jpg", [Area(0.1, 0.2, 0.3, 0.4)]);
+ var again = JsonSerializer.Deserialize(JsonSerializer.Serialize(new List<Preset> { conversion }, FileeJsonContext.Default.ListPreset),
+ FileeJsonContext.Default.ListPreset)!.Single();
+ var kept = again.Image.HiddenAreas![0];
+ Assert.Equal((0.1, 0.2, 0.3, 0.4), (Math.Round(kept.X, 9), Math.Round(kept.Y, 9), Math.Round(kept.Width, 9), Math.Round(kept.Height, 9)));
+ }
+
+ [Fact]
+ public void A_style_from_a_newer_Filee_reads_as_pixelate_instead_of_failing_the_whole_file()
+ {
+ var json = JsonSerializer.Serialize(new List<Preset> { Tool() }, FileeJsonContext.Default.ListPreset)
+ .Replace("\"hideStyle\": \"Pixelate\"", "\"hideStyle\": \"Smudge\"", StringComparison.Ordinal);
+ Assert.Contains("Smudge", json);
+ var read = JsonSerializer.Deserialize(json, FileeJsonContext.Default.ListPreset)!.Single();
+ Assert.Equal(HideStyle.Pixelate, read.Image.HideStyle);
+ }
+
+ [Fact]
+ public void Every_new_option_is_a_field_of_its_own_so_an_older_Filee_reads_the_presets_as_before()
+ {
+ // 2.1.0 crashes on a value its enums don't know: the tool only adds new fields (which it skips) and a tool name
+ // (which it greys out), and leaves every value it knows as it was.
+ var tool = Tool();
+ HideTool.Remember(tool, HideStyle.Blur, 9);
+ using var document = JsonDocument.Parse(JsonSerializer.Serialize(new List<Preset> { tool }, FileeJsonContext.Default.ListPreset));
+ var saved = document.RootElement[0];
+ Assert.Equal("Tool", saved.GetProperty("kind").GetString());
+ var image = saved.GetProperty("image");
+ Assert.Equal("None", image.GetProperty("resize").GetString());
+ Assert.Equal("None", image.GetProperty("rotation").GetString());
+ Assert.Equal("None", image.GetProperty("flip").GetString());
+ Assert.Equal("Lzw", image.GetProperty("tiffCompression").GetString());
+ }
+
+ [Fact]
+ public void A_failed_conversion_with_hidden_parts_offers_no_retry_an_older_Filee_would_run_without_them()
+ {
+ var conversion = HideTool.ConversionOf(Tool(), BuiltInData.SameAsSource, [Area(0.1, 0.1, 0.2, 0.2)]);
+ var job = new ConversionJob(["shot.png"], conversion, "Pixelate / blur");
+ job.Files[0].State = FileState.Failed;
+ Assert.Null(HistoryEntry.From(job).Preset);
+
+ var plain = new ConversionJob(["shot.png"], new Preset { TargetFormat = "jpg" }, "JPG");
+ plain.Files[0].State = FileState.Failed;
+ Assert.NotNull(HistoryEntry.From(plain).Preset);
+ }
+
+ // ───────────────────────── The job queue ─────────────────────────
+
+ [Fact]
+ public async Task The_parts_are_covered_once_by_the_first_engine_that_applies_image_options()
+ {
+ // EPS → PNG (Ghostscript) → JPG (ImageMagick): covered in the first step, the second gets the picture covered.
+ using var dir = new TempDir();
+ var art = dir.File("art.eps");
+ var reader = new AreaRecorder("ghostscript", transforms: true, new ConversionEdge("eps", "png"));
+ var writer = new AreaRecorder("magick", transforms: true, new ConversionEdge("png", "jpg"));
+ await using var queue = new JobQueue(new ConverterCatalog([reader, writer]));
+
+ var job = new ConversionJob([art], HideTool.ConversionOf(Tool(), "jpg", [Area(0.1, 0.1, 0.2, 0.2)]), "Test");
+ await queue.RunAsync(job);
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ Assert.Equal([1], reader.Areas);
+ Assert.Equal([0], writer.Areas);
+ }
+
+ [Fact]
+ public async Task A_route_without_an_engine_that_covers_them_fails_instead_of_writing_the_picture_as_it_is()
+ {
+ using var dir = new TempDir();
+ var picture = dir.File("scan.png");
+ var copier = new AreaRecorder("copier", transforms: false, new ConversionEdge("png", "png"));
+ await using var queue = new JobQueue(new ConverterCatalog([copier]));
+
+ var job = new ConversionJob([picture], HideTool.ConversionOf(Tool(), BuiltInData.SameAsSource, [Area(0.1, 0.1, 0.2, 0.2)]), "Test");
+ await queue.RunAsync(job);
+
+ var file = Assert.Single(job.Files);
+ Assert.Equal(FileState.Failed, file.State);
+ Assert.Equal("error.cannot_hide", file.ErrorKey);
+ Assert.Empty(copier.Areas);
+ Assert.Empty(job.Outputs);
+ }
+
+ [Fact]
+ public async Task Only_if_smaller_never_puts_the_original_back_over_a_covered_picture()
+ {
+ using var dir = new TempDir();
+ var picture = dir.File("shot.png"); // 1 byte: any result is larger
+ var magick = new AreaRecorder("magick", transforms: true, new ConversionEdge("png", "png"));
+ await using var queue = new JobQueue(new ConverterCatalog([magick]));
+ var conversion = HideTool.ConversionOf(Tool(), BuiltInData.SameAsSource, [Area(0.1, 0.1, 0.2, 0.2)]);
+ conversion.Output.OnlyIfSmaller = true; // set again after the tool turned it off
+
+ var job = new ConversionJob([picture], conversion, "Test");
+ await queue.RunAsync(job);
+
+ var output = Assert.Single(job.Outputs);
+ Assert.NotEqual("x", File.ReadAllText(output));
+ }
+
+ // ───────────────────────── Settings schema 52 ─────────────────────────
+
+ [Fact]
- public void A_new_library_has_the_tool_after_crop_and_on_the_images_donut_after_half_size()
++ public void A_new_library_has_the_tool_after_edit_pictures_in_the_library_and_on_the_images_donut()
+ {
+ var presets = BuiltInData.CreatePresets();
- Assert.Equal("tool-crop", presets[presets.FindIndex(p => p.Id == "tool-hide") - 1].Id);
++ Assert.Equal("tool-image-edit", presets[presets.FindIndex(p => p.Id == "tool-hide") - 1].Id);
+ var images = BuiltInData.CreateProfiles().Single(p => p.Id == "images");
- Assert.Equal("tool-hide", images.PresetIds[images.PresetIds.IndexOf("half-size") + 1]);
++ Assert.Equal(["half-size", "tool-image-edit", "tool-hide"], images.PresetIds.Skip(images.PresetIds.IndexOf("half-size")));
+ Assert.DoesNotContain("tool-hide", images.BackPresetIds!);
+ Assert.InRange(images.PresetIds.Count, 1, ToolbarProfile.MaxSlices);
+ }
+
- private static (List<Preset> Presets, List<ToolbarProfile> Profiles, ToolbarProfile Images) Version50()
++ private static (List<Preset> Presets, List<ToolbarProfile> Profiles, ToolbarProfile Images) Version51()
+ {
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "tool-hide");
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.PresetIds.Remove("tool-hide");
+ return (presets, profiles, images);
+ }
+
+ [Fact]
- public void Version_50_libraries_get_the_tool_after_half_size_once()
++ public void Version_51_libraries_get_the_tool_after_edit_pictures_once()
+ {
- var (presets, profiles, images) = Version50();
++ var (presets, profiles, images) = Version51();
+
- Assert.True(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
++ Assert.True(SettingsMigrations.ApplyToLibrary(51, presets, profiles));
+
+ Assert.Equal(BuiltInData.CreatePresets().Select(p => p.Id), presets.Select(p => p.Id));
+ Assert.True(presets.Single(p => p.Id == "tool-hide").IsHideTool);
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "images").PresetIds, images.PresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(52, presets, profiles)); // once only
+ Assert.Equal(52, AppSettings.CurrentSchemaVersion);
+ }
+
+ [Fact]
- public void After_edit_pictures_when_that_follows_half_size()
++ public void After_edit_pictures_when_that_follows_half_size_else_after_half_size()
+ {
- var (presets, profiles, images) = Version50();
- images.PresetIds.Insert(images.PresetIds.IndexOf("half-size") + 1, "tool-image-edit");
-
++ var (presets, profiles, images) = Version51();
+ SettingsMigrations.ApplyToLibrary(51, presets, profiles);
-
+ Assert.Equal(["half-size", "tool-image-edit", "tool-hide"], images.PresetIds.Skip(images.PresetIds.IndexOf("half-size")).Take(3));
++
++ // "Edit pictures" moved to the back face by the user: right after "Half size".
++ (presets, profiles, images) = Version51();
++ images.PresetIds.Remove("tool-image-edit");
++ images.BackPresetIds!.Remove("grayscale");
++ images.BackPresetIds.Insert(0, "tool-image-edit");
++ SettingsMigrations.ApplyToLibrary(51, presets, profiles);
++ Assert.Equal(["half-size", "tool-hide"], images.PresetIds.Skip(images.PresetIds.IndexOf("half-size")).Take(2));
+ }
+
+ [Fact]
+ public void A_full_front_puts_it_on_the_back_and_a_full_donut_or_the_users_own_place_is_left_alone()
+ {
+ // Front full: at the end of the back face (before "Compress into one archive") when that has room.
- var (presets, profiles, images) = Version50();
++ var (presets, profiles, images) = Version51();
+ while (images.PresetIds.Count < ToolbarProfile.MaxSlices)
+ images.PresetIds.Add("to-gif");
+ images.BackPresetIds!.Remove("grayscale");
- SettingsMigrations.ApplyToLibrary(50, presets, profiles);
++ SettingsMigrations.ApplyToLibrary(51, presets, profiles);
+ Assert.DoesNotContain("tool-hide", images.PresetIds);
+ Assert.Equal("tool-hide", images.BackPresetIds[images.BackPresetIds.IndexOf("zip-all") - 1]);
+
+ // Both full: in the library only.
- (presets, profiles, images) = Version50();
++ (presets, profiles, images) = Version51();
+ while (images.PresetIds.Count < ToolbarProfile.MaxSlices)
+ images.PresetIds.Add("to-gif");
+ var front = images.PresetIds.ToList();
+ var back = images.BackPresetIds!.ToList();
- Assert.True(SettingsMigrations.ApplyToLibrary(50, presets, profiles));
++ Assert.True(SettingsMigrations.ApplyToLibrary(51, presets, profiles));
+ Assert.Equal(front, images.PresetIds);
+ Assert.Equal(back, images.BackPresetIds);
+ Assert.Contains(presets, p => p.Id == "tool-hide");
+
+ // Already on the donut where the user put it (a build of this branch): stays there.
- (presets, profiles, images) = Version50();
++ (presets, profiles, images) = Version51();
+ images.BackPresetIds!.Remove("grayscale");
+ images.BackPresetIds.Insert(0, "tool-hide");
+ presets.Insert(0, Tool());
- SettingsMigrations.ApplyToLibrary(50, presets, profiles);
++ SettingsMigrations.ApplyToLibrary(51, presets, profiles);
+ Assert.DoesNotContain("tool-hide", images.PresetIds);
+ Assert.Equal("tool-hide", images.BackPresetIds[0]);
+ }
+
+ [Fact]
+ public void Back_from_a_Filee_before_2_1_the_tool_hides_parts_again_and_keeps_the_users_changes()
+ {
+ // A Filee before 45 (2.0) drops the tool's name: the tool reads as a crop there and is saved so.
+ var presets = BuiltInData.CreatePresets();
+ var hide = presets.Single(p => p.Id == "tool-hide");
+ hide.Tool = null;
+ hide.Name = "Redact";
+ hide.Output.FileNamePattern = "{name}_safe";
+ Assert.True(hide.IsCropTool);
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(51, presets, BuiltInData.CreateProfiles()));
+
+ Assert.True(hide.IsHideTool);
+ Assert.Equal(("Redact", "{name}_safe"), (hide.Name, hide.Output.FileNamePattern));
+ Assert.Single(presets, p => p.Id == "tool-hide");
+
+ // One that read it as a group.
+ hide.Kind = PresetKind.Group;
+ hide.TargetFormat = Preset.GroupTarget;
+ Assert.True(SettingsMigrations.ApplyToLibrary(51, presets, BuiltInData.CreateProfiles()));
+ Assert.True(hide.IsHideTool);
+ Assert.Equal(BuiltInData.SameAsSource, hide.TargetFormat);
+ }
+
+ /// <summary>An engine that records how many hidden parts each step was given; it may say it applies image options.</summary>
+ private sealed class AreaRecorder(string id, bool transforms, params ConversionEdge[] edges) : IConverter, IImageTransformer
+ {
+ private readonly FakeConverter _writer = new(id, edges);
+
+ public string Id => id;
+ public string DisplayName => id;
+ public IReadOnlyList<ConversionEdge> Edges => edges;
+ public int MaxParallelism => 0;
+ public List<int> Areas { get; } = [];
+
+ public bool Transforms(string from, string to) => transforms;
+
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ lock (Areas)
+ Areas.Add(step.Preset.Image.HiddenAreas?.Count ?? 0);
+ return _writer.ConvertAsync(step, progress, cancellationToken);
+ }
+ }
+}