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.

feat(presets): Edit pictures, size, format and turn chosen each time (#584)

Claudebb54c21731a9
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 3eacdea4..cfbc8d45 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -310,6 +310,10 @@
"clip.no_silence": "لم يُعثر على صمت",
"clip.cannot_play": "لا يمكن تشغيل المقطع",
"preset.half_size": "نصف الحجم",
+ "preset.image_edit": "تعديل الصور",
+ "image_edit.count": "{0} صور",
+ "image_edit.hint": "اختر الحجم والتنسيق والتدوير لهذه الصور. يحتفظ Filee باختياراتك للمرة القادمة.",
+ "image_edit.convert": "تحويل",
"preset.half_size.donut": "نصف الحجم",
"preset.grayscale": "تدرّج رمادي",
"preset.remove_background": "إزالة الخلفية",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index 022a6164..4192f054 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -310,6 +310,10 @@
"clip.no_silence": "Keine Stille gefunden",
"clip.cannot_play": "Der Clip lässt sich nicht abspielen",
"preset.half_size": "Halbe Größe",
+ "preset.image_edit": "Bilder bearbeiten",
+ "image_edit.count": "{0} Bilder",
+ "image_edit.hint": "Wähle Größe, Format und Drehung für diese Bilder. Filee merkt sich deine Wahl für das nächste Mal.",
+ "image_edit.convert": "Konvertieren",
"preset.half_size.donut": "Halbe Größe",
"preset.grayscale": "Graustufen",
"preset.remove_background": "Hintergrund entfernen",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 6ece0638..9dcd8f42 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "The clip can't be played",
"preset.half_size": "Half size",
+ "preset.image_edit": "Edit pictures",
+ "image_edit.count": "{0} pictures",
+ "image_edit.hint": "Choose the size, format and turn for these pictures. Filee keeps your choices for the next time.",
+ "image_edit.convert": "Convert",
"preset.half_size.donut": "Half size",
"preset.grayscale": "Grayscale",
"preset.remove_background": "Remove background",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 8d34dfcf..0c77c94f 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -310,6 +310,10 @@
"clip.no_silence": "No se encontraron silencios",
"clip.cannot_play": "No se puede reproducir el clip",
"preset.half_size": "Reducir 50 %",
+ "preset.image_edit": "Editar imágenes",
+ "image_edit.count": "{0} imágenes",
+ "image_edit.hint": "Elige el tamaño, el formato y el giro de estas imágenes. Filee recuerda tu elección para la próxima vez.",
+ "image_edit.convert": "Convertir",
"preset.half_size.donut": "Reducir 50 %",
"preset.grayscale": "Grises",
"preset.remove_background": "Quitar fondo",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 9d89e5bf..ff43a8a3 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "Impossible de lire l'extrait",
"preset.half_size": "Taille 50 %",
+ "preset.image_edit": "Modifier les images",
+ "image_edit.count": "{0} images",
+ "image_edit.hint": "Choisissez la taille, le format et la rotation de ces images. Filee garde vos choix pour la prochaine fois.",
+ "image_edit.convert": "Convertir",
"preset.half_size.donut": "Taille 50 %",
"preset.grayscale": "Niveaux de gris",
"preset.remove_background": "Détourer",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 431d514a..1ea9136a 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -310,6 +310,10 @@
"clip.no_silence": "कोई चुप्पी नहीं मिली",
"clip.cannot_play": "क्लिप नहीं चल सकती",
"preset.half_size": "आधा आकार",
+ "preset.image_edit": "चित्र संपादित करें",
+ "image_edit.count": "{0} चित्र",
+ "image_edit.hint": "इन चित्रों का आकार, फ़ॉर्मेट और घुमाव चुनें। Filee अगली बार के लिए आपकी पसंद याद रखता है।",
+ "image_edit.convert": "कन्वर्ट करें",
"preset.half_size.donut": "आधा आकार",
"preset.grayscale": "ग्रेस्केल",
"preset.remove_background": "बैकग्राउंड हटाएँ",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index a3411659..e22f8544 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -310,6 +310,10 @@
"clip.no_silence": "無音は見つかりませんでした",
"clip.cannot_play": "クリップを再生できません",
"preset.half_size": "縮小 50%",
+ "preset.image_edit": "画像を編集",
+ "image_edit.count": "{0} 枚の画像",
+ "image_edit.hint": "この画像のサイズ、形式、回転を選んでください。選んだ内容は次回も使われます。",
+ "image_edit.convert": "変換",
"preset.half_size.donut": "縮小 50%",
"preset.grayscale": "グレースケール",
"preset.remove_background": "背景を削除",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 46ccf6cc..f564d1ad 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "클립을 재생할 수 없어요",
"preset.half_size": "50% 축소",
+ "preset.image_edit": "사진 편집",
+ "image_edit.count": "사진 {0}장",
+ "image_edit.hint": "이 사진들의 크기, 형식, 회전을 고르세요. 고른 값은 다음에도 그대로 쓰입니다.",
+ "image_edit.convert": "변환",
"preset.half_size.donut": "50% 축소",
"preset.grayscale": "흑백",
"preset.remove_background": "배경 제거",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index a891cba3..4bcc2212 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -310,6 +310,10 @@
"clip.no_silence": "मौनता भेटिएन",
"clip.cannot_play": "क्लिप बजाउन सकिँदैन",
"preset.half_size": "आधा आकार",
+ "preset.image_edit": "तस्बिरहरू सम्पादन गर्नुहोस्",
+ "image_edit.count": "{0} तस्बिरहरू",
+ "image_edit.hint": "यी तस्बिरहरूको आकार, ढाँचा र घुमाइ छान्नुहोस्। Filee ले अर्को पटकका लागि तपाईंको छनोट सम्झन्छ।",
+ "image_edit.convert": "रूपान्तरण गर्नुहोस्",
"preset.half_size.donut": "आधा आकार",
"preset.grayscale": "ग्रेस्केल",
"preset.remove_background": "पृष्ठभूमि हटाउनुहोस्",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index e350005d..adaf8dd8 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "Nie można odtworzyć klipu",
"preset.half_size": "Połowa rozmiaru",
+ "preset.image_edit": "Edytuj obrazy",
+ "image_edit.count": "Obrazy: {0}",
+ "image_edit.hint": "Wybierz rozmiar, format i obrót tych obrazów. Filee zapamięta wybór na następny raz.",
+ "image_edit.convert": "Konwertuj",
"preset.half_size.donut": "Połowa rozmiaru",
"preset.grayscale": "Skala szarości",
"preset.remove_background": "Usuń tło",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index c5a198ff..6c8de554 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "Não foi possível reproduzir o clipe",
"preset.half_size": "Reduzir 50%",
+ "preset.image_edit": "Editar imagens",
+ "image_edit.count": "{0} imagens",
+ "image_edit.hint": "Escolha o tamanho, o formato e a rotação dessas imagens. O Filee guarda suas escolhas para a próxima vez.",
+ "image_edit.convert": "Converter",
"preset.half_size.donut": "Tamanho 50%",
"preset.grayscale": "Tons de cinza",
"preset.remove_background": "Remover fundo",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index 9752ee85..64acd694 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "Não é possível reproduzir o excerto",
"preset.half_size": "Metade do tamanho",
+ "preset.image_edit": "Editar imagens",
+ "image_edit.count": "{0} imagens",
+ "image_edit.hint": "Escolha o tamanho, o formato e a rotação destas imagens. O Filee guarda as suas escolhas para a próxima vez.",
+ "image_edit.convert": "Converter",
"preset.half_size.donut": "Tamanho 50%",
"preset.grayscale": "Escala de cinzentos",
"preset.remove_background": "Remover fundo",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 8f9feddc..b44e5446 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "Клип не воспроизводится",
"preset.half_size": "Вдвое меньше",
+ "preset.image_edit": "Изменить изображения",
+ "image_edit.count": "Изображений: {0}",
+ "image_edit.hint": "Выберите размер, формат и поворот для этих изображений. Filee запомнит выбор на следующий раз.",
+ "image_edit.convert": "Преобразовать",
"preset.half_size.donut": "Вдвое меньше",
"preset.grayscale": "Оттенки серого",
"preset.remove_background": "Убрать фон",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index c186c2b0..8e44f84a 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -310,6 +310,10 @@
"clip.no_silence": "ไม่พบช่วงเงียบ",
"clip.cannot_play": "เล่นคลิปนี้ไม่ได้",
"preset.half_size": "ขนาดครึ่งหนึ่ง",
+ "preset.image_edit": "แก้ไขรูปภาพ",
+ "image_edit.count": "รูปภาพ {0} รูป",
+ "image_edit.hint": "เลือกขนาด รูปแบบ และการหมุนของรูปภาพเหล่านี้ Filee จะจำตัวเลือกไว้ใช้ครั้งหน้า",
+ "image_edit.convert": "แปลง",
"preset.half_size.donut": "ขนาดครึ่งหนึ่ง",
"preset.grayscale": "ขาวดำ (เกรย์สเกล)",
"preset.remove_background": "ลบพื้นหลัง",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 5d85ce3f..81ecc10a 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -310,6 +310,10 @@
"clip.no_silence": "Sessiz kısım bulunamadı",
"clip.cannot_play": "Klip oynatılamıyor",
"preset.half_size": "Yarı boyut",
+ "preset.image_edit": "Resimleri düzenle",
+ "image_edit.count": "{0} resim",
+ "image_edit.hint": "Bu resimlerin boyutunu, biçimini ve dönüşünü seçin. Filee seçimlerinizi bir dahaki sefere hatırlar.",
+ "image_edit.convert": "Dönüştür",
"preset.half_size.donut": "Yarı boyut",
"preset.grayscale": "Gri tonlama",
"preset.remove_background": "Arka planı kaldır",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 45f8b7d4..08a2cf90 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "无法播放片段",
"preset.half_size": "缩小 50%",
+ "preset.image_edit": "编辑图片",
+ "image_edit.count": "{0} 张图片",
+ "image_edit.hint": "为这些图片选择尺寸、格式和旋转。Filee 会记住你的选择,下次继续使用。",
+ "image_edit.convert": "转换",
"preset.half_size.donut": "缩小 50%",
"preset.grayscale": "灰度",
"preset.remove_background": "去除背景",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 78743df1..e7428768 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -320,6 +320,10 @@
"clip.cannot_play": "無法播放片段",
"preset.half_size": "縮小 50%",
+ "preset.image_edit": "編輯圖片",
+ "image_edit.count": "{0} 張圖片",
+ "image_edit.hint": "為這些圖片選擇尺寸、格式和旋轉。Filee 會記住你的選擇,下次繼續使用。",
+ "image_edit.convert": "轉換",
"preset.half_size.donut": "縮小 50%",
"preset.grayscale": "灰階",
"preset.remove_background": "去除背景",
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
index 687c59bd..d417dded 100644
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -102,6 +102,12 @@ public sealed class PresetAvailability
: new(PresetUse.Unusable, _loc["error.no_route"]);
}
+ // 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.IsTool)
{
if (preset.Id == "tool-sheet-studio")
diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs
index 90a21e0f..bfff8855 100644
--- a/src/Filee.App/Services/WindowService.cs
+++ b/src/Filee.App/Services/WindowService.cs
@@ -36,8 +36,10 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
private CropOverlayWindow? _cropOverlay;
private ClipWindow? _clipWindow;
+ private ImageEditWindow? _imageEdit;
internal ClipWindow? ClipWindow => _clipWindow;
+ internal ImageEditWindow? ImageEdit => _imageEdit;
private readonly HashSet<SpreadsheetPrintStudioWindow> _spreadsheetStudios = [];
internal IReadOnlyCollection<SpreadsheetPrintStudioWindow> SpreadsheetStudios => _spreadsheetStudios;
@@ -128,6 +130,8 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
{
if (preset.IsClipTool)
ShowClipWindow(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")
@@ -173,6 +177,50 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services, Mem
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 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);
+ var win = new ImageEditWindow { DataContext = vm };
+ PrepareWindow(win);
+ win.Closed += (_, _) =>
+ {
+ if (_imageEdit == win)
+ _imageEdit = null;
+ };
+ _imageEdit = win;
+ win.Show();
+ win.Activate();
+ }
+
+ /// <summary>The pixel size of a picture, read from its header; null when ImageMagick can't read it.</summary>
+ private static (int Width, int Height)? PictureSize(string path)
+ {
+ try
+ {
+ var info = new ImageMagick.MagickImageInfo(path);
+ return ((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 --git a/src/Filee.App/ViewModels/ImageEditViewModel.cs b/src/Filee.App/ViewModels/ImageEditViewModel.cs
new file mode 100644
index 00000000..3a52442f
--- /dev/null
+++ b/src/Filee.App/ViewModels/ImageEditViewModel.cs
@@ -0,0 +1,176 @@
+// "Edit pictures" (#584): the size, format, turn and colour of the dropped pictures, chosen right before they are
+// converted instead of in a preset made for each size. The window opens with the tool's last choices; Convert keeps them
+// in the tool and starts ordinary conversions (ImageEditTool), so the toast, cancelling and the output rules work as usual.
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+using Filee.Engines.Magick;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.ViewModels;
+
+public sealed partial class ImageEditViewModel : ObservableObject
+{
+ private readonly Preset _tool;
+ private readonly ILocalizer _loc;
+ private readonly UserDataStore _store;
+ private readonly Func<string, string, string> _targetFor;
+ private readonly Action<IReadOnlyList<string>, Preset> _start;
+ private readonly ILogger? _log;
+ private readonly (int Width, int Height)? _firstSize;
+
+ /// <param name="pictures">The pictures to convert (other files are left out by the caller).</param>
+ /// <param name="tool">The "Edit pictures" tool: its last choices, name and output rule.</param>
+ /// <param name="targetFor">The format a picture (path) is written in for the chosen one (<see cref="ImageEditTool.TargetFor"/>).</param>
+ /// <param name="start">Starts the conversion of some of the pictures.</param>
+ /// <param name="sizeOf">The pixel size of a picture, null when it can't be read; for the size shown in the window.</param>
+ public ImageEditViewModel(IReadOnlyList<string> pictures, Preset tool, ILocalizer loc, UserDataStore store,
+ Func<string, string, string> targetFor, Action<IReadOnlyList<string>, Preset> start,
+ Func<string, (int Width, int Height)?>? sizeOf = null, ILogger? log = null)
+ {
+ Pictures = pictures;
+ _tool = tool;
+ _loc = loc;
+ _store = store;
+ _targetFor = targetFor;
+ _start = start;
+ _log = log;
+ _firstSize = pictures.Count > 0 ? sizeOf?.Invoke(pictures[0]) : null;
+
+ Targets =
+ [
+ new Choice<string>(BuiltInData.SameAsSource, loc["presets.same_as_source"]),
+ .. ImageEditTool.Targets.Select(id => new Choice<string>(id, FormatRegistry.Get(id).DisplayName)),
+ ];
+ ResizeModes = Enum.GetValues<ResizeMode>().Select(v => new Choice<ResizeMode>(v, loc[$"presets.resize.{v}"])).ToList();
+ Rotations = Enum.GetValues<ImageRotation>().Select(v => new Choice<ImageRotation>(v, loc[$"presets.rotation.{v}"])).ToList();
+ Flips = Enum.GetValues<ImageFlip>().Select(v => new Choice<ImageFlip>(v, loc[$"presets.flip.{v}"])).ToList();
+
+ var image = tool.Image;
+ _target = Targets.FirstOrDefault(t => t.Value == tool.TargetFormat) ?? Targets[0];
+ _resize = ResizeModes.FirstOrDefault(r => r.Value == image.Resize) ?? ResizeModes[0];
+ _rotation = Rotations.FirstOrDefault(r => r.Value == image.Rotation) ?? Rotations[0];
+ _flip = Flips.FirstOrDefault(f => f.Value == image.Flip) ?? Flips[0];
+ _resizePercent = image.ResizePercent;
+ _longEdge = image.LongEdge;
+ _width = image.Width;
+ _grayscale = image.Grayscale;
+ _quality = image.Quality;
+ }
+
+ public IReadOnlyList<string> Pictures { get; }
+
+ public IReadOnlyList<Choice<string>> Targets { get; }
+ public IReadOnlyList<Choice<ResizeMode>> ResizeModes { get; }
+ public IReadOnlyList<Choice<ImageRotation>> Rotations { get; }
+ public IReadOnlyList<Choice<ImageFlip>> Flips { get; }
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(ShowQuality))]
+ private Choice<string> _target;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth), nameof(SizeChange))]
+ private Choice<ResizeMode> _resize;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(SizeChange))]
+ private Choice<ImageRotation> _rotation;
+
+ [ObservableProperty] private Choice<ImageFlip> _flip;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(SizeChange))]
+ private int _resizePercent;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(SizeChange))]
+ private int _longEdge;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(SizeChange))]
+ private int _width;
+
+ [ObservableProperty] private bool _grayscale;
+ [ObservableProperty] private int _quality;
+
+ partial void OnTargetChanged(Choice<string>? oldValue, Choice<string> newValue) => Choices.Restore(oldValue, newValue, v => Target = v);
+ partial void OnResizeChanged(Choice<ResizeMode>? oldValue, Choice<ResizeMode> newValue) => Choices.Restore(oldValue, newValue, v => Resize = v);
+ partial void OnRotationChanged(Choice<ImageRotation>? oldValue, Choice<ImageRotation> newValue) => Choices.Restore(oldValue, newValue, v => Rotation = v);
+ partial void OnFlipChanged(Choice<ImageFlip>? oldValue, Choice<ImageFlip> newValue) => Choices.Restore(oldValue, newValue, v => Flip = v);
+
+ public bool ShowPercent => Resize.Value == ResizeMode.Percent;
+ public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;
+ public bool ShowWidth => Resize.Value == ResizeMode.Width;
+
+ /// <summary>JPG, WEBP, AVIF and HEIC, or the source's own format (which may be one of them).</summary>
+ public bool ShowQuality => Target.Value == BuiltInData.SameAsSource || ImageEditTool.LossyTargets.Contains(Target.Value);
+
+ /// <summary>The first picture's name, or how many pictures there are.</summary>
+ public string Heading => Pictures.Count == 1 ? Path.GetFileName(Pictures[0]) : _loc.Format("image_edit.count", Pictures.Count);
+
+ /// <summary>"512 × 512 → 32 × 32" for the first picture; empty when its size can't be read.</summary>
+ public string SizeChange
+ {
+ get
+ {
+ if (_firstSize is not { } size || size.Width <= 0 || size.Height <= 0)
+ return "";
+ var (width, height) = size;
+ var options = Options();
+ var scale = ImageEncoder.ResizeScale(width, height, options);
+ var turned = options.Rotation is ImageRotation.Left90 or ImageRotation.Right90;
+ var (outWidth, outHeight) = (Math.Max(1, (int)Math.Round(width * scale)), Math.Max(1, (int)Math.Round(height * scale)));
+ if (turned)
+ (outWidth, outHeight) = (outHeight, outWidth);
+ return $"{width} × {height} → {outWidth} × {outHeight}";
+ }
+ }
+
+ /// <summary>The tool's picture options with the window's choices.</summary>
+ internal ImageOptions Options()
+ {
+ var image = _tool.Image.Clone();
+ image.Resize = Resize.Value;
+ image.ResizePercent = Math.Clamp(ResizePercent, 1, 1000);
+ image.LongEdge = Math.Clamp(LongEdge, 16, 20000);
+ image.Width = Math.Clamp(Width, 16, 20000);
+ image.Rotation = Rotation.Value;
+ image.Flip = Flip.Value;
+ image.Grayscale = Grayscale;
+ image.Quality = Math.Clamp(Quality, 1, 100);
+ return image;
+ }
+
+ /// <summary>
+ /// Keeps the choices in the tool for the next time and starts the conversions: one for each format the pictures are
+ /// written in (a camera RAW kept in "its own format" becomes PNG).
+ /// </summary>
+ public void Convert()
+ {
+ var image = Options();
+ Remember(image);
+ foreach (var group in Pictures.GroupBy(path => _targetFor(path, Target.Value)))
+ _start([.. group], ImageEditTool.ConversionOf(_tool, group.Key, image));
+ }
+
+ private void Remember(ImageOptions image)
+ {
+ // In the tool as saved, and in the one given to this window (maybe the same).
+ ImageEditTool.Remember(_tool, Target.Value, image);
+ if (_store.FindPreset(_tool.Id) is not { IsImageEditTool: true } saved)
+ return;
+ ImageEditTool.Remember(saved, Target.Value, image);
+ try
+ {
+ _store.SaveLibrary();
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ _log?.LogWarning(ex, "Could not remember the picture edits");
+ }
+ }
+}
diff --git a/src/Filee.App/Views/ImageEditWindow.axaml b/src/Filee.App/Views/ImageEditWindow.axaml
new file mode 100644
index 00000000..a9a0f74f
--- /dev/null
+++ b/src/Filee.App/Views/ImageEditWindow.axaml
@@ -0,0 +1,78 @@
+<!-- "Edit pictures" (#584): the size, format, turn and colour of the dropped pictures, chosen right before they are
+ converted. Convert starts the conversions (shown in the toast); Cancel or closing the window starts nothing. -->
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ x:Class="Filee.App.Views.ImageEditWindow"
+ x:DataType="vm:ImageEditViewModel"
+ Title="{DynamicResource preset.image_edit}"
+ Icon="avares://Filee/Assets/Icons/filee.ico"
+ Width="480" SizeToContent="Height" MinWidth="400" CanResize="False"
+ WindowStartupLocation="CenterScreen">
+ <DockPanel>
+ <Border DockPanel.Dock="Bottom" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{DynamicResource SubtleBorderBrush}"
+ Background="{DynamicResource SurfaceBrush}">
+ <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
+ <Button x:Name="CancelEdit" Content="{DynamicResource common.cancel}" Click="OnCancel" IsCancel="True" />
+ <Button x:Name="StartEdit" Classes="accent" Content="{DynamicResource image_edit.convert}" Click="OnConvert" IsDefault="True" />
+ </StackPanel>
+ </Border>
+ <StackPanel Margin="20,18,20,16" Spacing="12">
+ <StackPanel Spacing="4">
+ <TextBlock Classes="h2" Text="{Binding Heading}" TextTrimming="CharacterEllipsis" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource image_edit.hint}" />
+ </StackPanel>
+
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.target}" />
+ <ComboBox x:Name="TargetChoice" ItemsSource="{Binding Targets}" SelectedItem="{Binding Target}" HorizontalAlignment="Stretch"
+ AutomationProperties.Name="{DynamicResource presets.target}" />
+ </StackPanel>
+
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.resize}" />
+ <ComboBox x:Name="ResizeChoice" ItemsSource="{Binding ResizeModes}" SelectedItem="{Binding Resize}" HorizontalAlignment="Stretch"
+ AutomationProperties.Name="{DynamicResource presets.resize}" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowPercent}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.percent}" />
+ <NumericUpDown Value="{Binding ResizePercent}" Minimum="1" Maximum="1000" Increment="5" FormatString="0" AutomationProperties.Name="{DynamicResource presets.percent}" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowLongEdge}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.long_edge}" />
+ <NumericUpDown Value="{Binding LongEdge}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" AutomationProperties.Name="{DynamicResource presets.long_edge}" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowWidth}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.width}" />
+ <NumericUpDown Value="{Binding Width}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" AutomationProperties.Name="{DynamicResource presets.width}" />
+ </StackPanel>
+ </Grid>
+ <TextBlock x:Name="SizeChange" Classes="caption" Text="{Binding SizeChange}"
+ IsVisible="{Binding SizeChange, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />
+
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.rotation}" />
+ <ComboBox ItemsSource="{Binding Rotations}" SelectedItem="{Binding Rotation}" HorizontalAlignment="Stretch"
+ AutomationProperties.Name="{DynamicResource presets.rotation}" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.flip}" />
+ <ComboBox ItemsSource="{Binding Flips}" SelectedItem="{Binding Flip}" HorizontalAlignment="Stretch"
+ AutomationProperties.Name="{DynamicResource presets.flip}" />
+ </StackPanel>
+ </Grid>
+
+ <StackPanel IsVisible="{Binding ShowQuality}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding Quality}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.quality}" />
+ </DockPanel>
+ <Slider Minimum="1" Maximum="100" Value="{Binding Quality}" TickFrequency="1" IsSnapToTickEnabled="True" AutomationProperties.Name="{DynamicResource presets.quality}" />
+ </StackPanel>
+
+ <CheckBox Content="{DynamicResource presets.grayscale}" IsChecked="{Binding Grayscale}" />
+ </StackPanel>
+ </DockPanel>
+</Window>
diff --git a/src/Filee.App/Views/ImageEditWindow.axaml.cs b/src/Filee.App/Views/ImageEditWindow.axaml.cs
new file mode 100644
index 00000000..db43f634
--- /dev/null
+++ b/src/Filee.App/Views/ImageEditWindow.axaml.cs
@@ -0,0 +1,25 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+
+namespace Filee.App.Views;
+
+public partial class ImageEditWindow : Window
+{
+ public ImageEditWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+ UiZoom.Track(this);
+ }
+
+ private void OnConvert(object? sender, RoutedEventArgs e)
+ {
+ if (DataContext is not ImageEditViewModel vm || vm.Pictures.Count == 0) return;
+ vm.Convert();
+ Close();
+ }
+
+ private void OnCancel(object? sender, RoutedEventArgs e) => Close();
+}
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index ce888074..3d85eb08 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -49,6 +49,7 @@ public static class BuiltInData
Id = "tool-crop", NameKey = "preset.crop", TargetFormat = SameAsSource,
Kind = PresetKind.Tool, Output = { FileNamePattern = "{name}_cropped" },
},
+ .. ImageEditPresets(),
new()
{
Id = "tool-sheet-studio", NameKey = "preset.sheet_studio", TargetFormat = "pdf",
@@ -193,6 +194,19 @@ public static class BuiltInData
},
];
+ /// <summary>
+ /// "Edit pictures" (#584, added in settings schema 49): 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>
/// "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".
@@ -527,7 +541,8 @@ public static class BuiltInData
{
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"],
+ PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size",
+ "tool-image-edit"],
// 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 --git a/src/Filee.Core/Presets/ImageEditTool.cs b/src/Filee.Core/Presets/ImageEditTool.cs
new file mode 100644
index 00000000..82fb19ba
--- /dev/null
+++ b/src/Filee.Core/Presets/ImageEditTool.cs
@@ -0,0 +1,70 @@
+// "Edit pictures" (#584) runs as an ordinary conversion once its window has the user's choices: the tool preset becomes a
+// conversion with that format, size, turn and colour, so the job queue, the toast, cancelling, the output rules and the
+// history work as for any other file. The choices are kept in the tool, so the window opens with them the next time.
+
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+
+namespace Filee.Core.Presets;
+
+/// <summary>Turns the "Edit pictures" tool into the conversions that write the edited pictures.</summary>
+public static class ImageEditTool
+{
+ /// <summary>Where a picture goes when its own format can't be written ("Same format" for a camera RAW, a DICOM …).</summary>
+ public const string FallbackTarget = "png";
+
+ /// <summary>The formats the window offers, after "Same format as the source": the everyday pictures.</summary>
+ public static readonly IReadOnlyList<string> Targets = ["png", "jpg", "webp", "avif", "heic", "gif", "bmp", "tiff", "ico"];
+
+ /// <summary>Formats the quality slider is shown for.</summary>
+ public static readonly IReadOnlySet<string> LossyTargets = new HashSet<string> { "jpg", "webp", "avif", "heic" };
+
+ /// <summary>True when a <paramref name="sourceFormat"/> file is a picture the tool can open.</summary>
+ public static bool CanEdit(string sourceFormat) =>
+ FormatRegistry.FindById(sourceFormat)?.Category == FormatCategory.Image;
+
+ /// <summary>
+ /// The format a <paramref name="sourceFormat"/> picture is written in for the <paramref name="chosen"/> one: as
+ /// chosen, but for "Same format as the source" one that can't be written straight from it becomes
+ /// <see cref="FallbackTarget"/>.
+ /// </summary>
+ public static string TargetFor(string sourceFormat, string chosen, RoutePlanner planner) =>
+ chosen != BuiltInData.SameAsSource
+ ? chosen
+ : FormatRegistry.FindById(sourceFormat) is { Writable: true } && planner.Plan(sourceFormat, sourceFormat) is not null
+ ? BuiltInData.SameAsSource
+ : FallbackTarget;
+
+ /// <summary>
+ /// The conversion that writes pictures as <paramref name="targetFormat"/> with <paramref name="image"/>'s options
+ /// and the tool's name and output rule. The tool itself is left as it is.
+ /// </summary>
+ public static Preset ConversionOf(Preset tool, string targetFormat, ImageOptions image)
+ {
+ var preset = tool.Clone();
+ preset.Kind = PresetKind.Convert;
+ preset.Tool = null;
+ preset.SubPresetIds = [];
+ preset.TargetFormat = targetFormat;
+ preset.Image = image.Clone();
+ return preset;
+ }
+
+ /// <summary>
+ /// Keeps the window's choices in <paramref name="tool"/> for the next time: its format and the picture options the
+ /// window shows. Other options (metadata, ICO sizes …) stay as the tool has them.
+ /// </summary>
+ public static void Remember(Preset tool, string targetFormat, ImageOptions image)
+ {
+ tool.TargetFormat = targetFormat;
+ var kept = tool.Image;
+ kept.Resize = image.Resize;
+ kept.ResizePercent = image.ResizePercent;
+ kept.LongEdge = image.LongEdge;
+ kept.Width = image.Width;
+ kept.Rotation = image.Rotation;
+ kept.Flip = image.Flip;
+ kept.Grayscale = image.Grayscale;
+ kept.Quality = image.Quality;
+ }
+}
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index a795927f..5379240e 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -194,9 +194,16 @@ public sealed class Preset
/// <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="PresetKind.Tool"/>: which window it opens, <see cref="CropTool"/> (or null, as saved before there were
- /// other tools) or <see cref="ClipTool"/>. A tool this version doesn't know (from a newer Filee) opens nothing.
+ /// 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.
/// </summary>
public string? Tool { get; set; }
@@ -209,6 +216,10 @@ public sealed class Preset
[JsonIgnore]
public bool IsClipTool => IsTool && Tool == ClipTool;
+ /// <summary>True for "Edit pictures".</summary>
+ [JsonIgnore]
+ public bool IsImageEditTool => IsTool && Tool == ImageEditTool;
+
/// <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.
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index bede3d9c..b5f953c4 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -123,7 +123,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 48;
+ public const int CurrentSchemaVersion = 49;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index f9c47a37..fdfdd4cd 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -889,6 +889,12 @@ internal static class SettingsMigrations
// v48: fragmented MP4 pieces (.m4s) learn the video donut; custom claims stay put.
if (from < 48)
changed |= LearnExtensions(profiles, out _, ["m4s"]);
+ // v49: "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 49: that one dropped the tool's
+ // name, which made it a crop, so it is put back.
+ if (from < 49)
+ changed |= AddImageEditTool(presets, profiles);
return changed;
}
@@ -1015,6 +1021,40 @@ internal static class SettingsMigrations
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 AddGeo(List<Preset> presets, List<ToolbarProfile> profiles)
{
var changed = false;
diff --git a/tests/Filee.App.Tests/ImageEditWindowTests.cs b/tests/Filee.App.Tests/ImageEditWindowTests.cs
new file mode 100644
index 00000000..490182d8
--- /dev/null
+++ b/tests/Filee.App.Tests/ImageEditWindowTests.cs
@@ -0,0 +1,139 @@
+// The "Edit pictures" window (#584): it opens with the tool's last choices, shows the first picture's size before and
+// after, starts one conversion per format the pictures are written in, and keeps the choices in the tool.
+
+using System.IO;
+using Avalonia.Headless.XUnit;
+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;
+
+namespace Filee.App.Tests;
+
+public class ImageEditWindowTests
+{
+ [AvaloniaFact]
+ public void The_window_shows_the_size_a_picture_gets_and_converts_with_the_choices()
+ {
+ WithWindow(["icon.png", "scan.dcm"], (window, vm, starts) =>
+ {
+ Assert.Equal(AppHost.Get<ILocalizer>().Format("image_edit.count", 2), vm.Heading);
+ Assert.Equal(BuiltInData.SameAsSource, vm.Target.Value);
+ Assert.Equal("512 × 256 → 512 × 256", vm.SizeChange);
+
+ vm.Resize = vm.ResizeModes.Single(r => r.Value == ResizeMode.LongEdge);
+ vm.LongEdge = 32;
+ Assert.True(vm.ShowLongEdge);
+ Assert.Equal("512 × 256 → 32 × 16", vm.SizeChange);
+ vm.Rotation = vm.Rotations.Single(r => r.Value == ImageRotation.Right90);
+ Assert.Equal("512 × 256 → 16 × 32", vm.SizeChange);
+ vm.Grayscale = true;
+
+ vm.Convert();
+
+ // The PNG stays a PNG; the DICOM, which can't be written, becomes one.
+ Assert.Equal(2, starts.Count);
+ var same = starts.Single(s => s.Preset.TargetFormat == BuiltInData.SameAsSource);
+ Assert.Equal(["icon.png"], same.Paths.Select(Path.GetFileName));
+ Assert.Equal(["scan.dcm"], starts.Single(s => s.Preset.TargetFormat == "png").Paths.Select(Path.GetFileName));
+ Assert.All(starts, s =>
+ {
+ Assert.Equal(PresetKind.Convert, s.Preset.Kind);
+ Assert.Equal((ResizeMode.LongEdge, 32, ImageRotation.Right90, true),
+ (s.Preset.Image.Resize, s.Preset.Image.LongEdge, s.Preset.Image.Rotation, s.Preset.Image.Grayscale));
+ });
+ });
+ }
+
+ [AvaloniaFact]
+ public void The_quality_is_offered_for_lossy_formats_only()
+ {
+ WithWindow(["icon.png"], (_, vm, _) =>
+ {
+ Assert.Equal("icon.png", vm.Heading);
+ vm.Target = vm.Targets.Single(t => t.Value == "jpg");
+ Assert.True(vm.ShowQuality);
+ vm.Target = vm.Targets.Single(t => t.Value == "ico");
+ Assert.False(vm.ShowQuality);
+ });
+ }
+
+ [AvaloniaFact]
+ public void The_choices_are_remembered_in_the_tool()
+ {
+ TestServices.EnsureInitialized("en");
+ var store = AppHost.Get<UserDataStore>();
+ var saved = store.FindPreset("tool-image-edit")!;
+ var before = saved.Clone();
+ try
+ {
+ WithWindow(["icon.png"], (_, vm, _) =>
+ {
+ vm.Target = vm.Targets.Single(t => t.Value == "webp");
+ vm.Resize = vm.ResizeModes.Single(r => r.Value == ResizeMode.Width);
+ vm.Width = 640;
+ vm.Convert();
+ }, saved);
+ Assert.Equal(("webp", ResizeMode.Width, 640), (saved.TargetFormat, saved.Image.Resize, saved.Image.Width));
+
+ // Opened again: as left.
+ WithWindow(["icon.png"], (_, vm, _) =>
+ {
+ Assert.Equal("webp", vm.Target.Value);
+ Assert.Equal((ResizeMode.Width, 640), (vm.Resize.Value, vm.Width));
+ Assert.True(vm.ShowWidth);
+ }, saved);
+ }
+ finally
+ {
+ saved.TargetFormat = before.TargetFormat;
+ saved.Image = before.Image;
+ store.SaveLibrary();
+ }
+ }
+
+ private static void WithWindow(string[] names, Action<ImageEditWindow, ImageEditViewModel, List<(IReadOnlyList<string> Paths, Preset Preset)>> act,
+ Preset? tool = null)
+ {
+ TestServices.EnsureInitialized("en");
+ var folder = Directory.CreateTempSubdirectory("filee-image-edit-").FullName;
+ ImageEditWindow? window = null;
+ try
+ {
+ var files = names.Select(name => Path.Combine(folder, name)).ToList();
+ foreach (var file in files)
+ File.WriteAllBytes(file, [0]);
+ using (var picture = new MagickImage(MagickColors.SkyBlue, 512, 256))
+ picture.Write(files[0], MagickFormat.Png);
+ var starts = new List<(IReadOnlyList<string>, Preset)>();
+ tool ??= BuiltInData.ImageEditPresets().Single();
+ var vm = new ImageEditViewModel(files, tool, AppHost.Get<ILocalizer>(), AppHost.Get<UserDataStore>(),
+ (path, chosen) => chosen == BuiltInData.SameAsSource && path.EndsWith(".dcm", StringComparison.Ordinal) ? "png" : chosen,
+ (paths, preset) => starts.Add((paths, preset)),
+ path =>
+ {
+ try
+ {
+ var info = new MagickImageInfo(path);
+ return ((int)info.Width, (int)info.Height);
+ }
+ catch (MagickException)
+ {
+ return null;
+ }
+ });
+ window = new ImageEditWindow { DataContext = vm };
+ window.Show();
+ act(window, vm, starts);
+ }
+ finally
+ {
+ if (window?.IsVisible == true)
+ window.Close();
+ try { Directory.Delete(folder, true); } catch (IOException) { }
+ }
+ }
+}
diff --git a/tests/Filee.Core.Tests/BackFaceTests.cs b/tests/Filee.Core.Tests/BackFaceTests.cs
index 1f15ee4f..46234db2 100644
--- a/tests/Filee.Core.Tests/BackFaceTests.cs
+++ b/tests/Filee.Core.Tests/BackFaceTests.cs
@@ -94,8 +94,8 @@ public class BackFaceTests
[Fact]
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"],
- BuiltIn("images").PresetIds);
+ Assert.Equal(["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size",
+ "tool-image-edit"], 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 --git a/tests/Filee.Core.Tests/ImageEditToolTests.cs b/tests/Filee.Core.Tests/ImageEditToolTests.cs
new file mode 100644
index 00000000..8c59c17b
--- /dev/null
+++ b/tests/Filee.Core.Tests/ImageEditToolTests.cs
@@ -0,0 +1,159 @@
+// "Edit pictures" (#584): the conversion its window starts, the format a picture keeps, the choices kept in the tool, and
+// the tool's place in a new library and in one from before settings schema 49.
+
+using System.Text.Json;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class ImageEditToolTests
+{
+ private static Preset Tool() => BuiltInData.ImageEditPresets().Single();
+
+ [Fact]
+ public void The_tool_is_a_tool_of_its_own_and_survives_saving()
+ {
+ var tool = Tool();
+ Assert.True(tool.IsImageEditTool);
+ Assert.False(tool.IsCropTool);
+ Assert.False(tool.IsClipTool);
+
+ var json = JsonSerializer.Serialize(new List<Preset> { tool }, FileeJsonContext.Default.ListPreset);
+ Assert.Contains("\"tool\": \"image-edit\"", json);
+ var read = JsonSerializer.Deserialize(json, FileeJsonContext.Default.ListPreset)!.Single();
+ Assert.True(read.IsImageEditTool);
+ }
+
+ [Fact]
+ public void The_conversion_has_the_chosen_format_and_options_and_leaves_the_tool_as_it_is()
+ {
+ var tool = Tool();
+ tool.Name = "Icons";
+ tool.Image.KeepMetadata = false; // set in the preset editor, not in the window
+ var image = tool.Image.Clone();
+ image.Resize = ResizeMode.LongEdge;
+ image.LongEdge = 32;
+ image.Rotation = ImageRotation.Right90;
+ image.Grayscale = true;
+
+ var conversion = ImageEditTool.ConversionOf(tool, "jpg", image);
+
+ Assert.Equal(PresetKind.Convert, conversion.Kind);
+ Assert.Null(conversion.Tool);
+ Assert.Equal("jpg", conversion.TargetFormat);
+ Assert.Equal((ResizeMode.LongEdge, 32, ImageRotation.Right90, true, false),
+ (conversion.Image.Resize, conversion.Image.LongEdge, conversion.Image.Rotation, conversion.Image.Grayscale, conversion.Image.KeepMetadata));
+ Assert.Equal(("tool-image-edit", "Icons", "{name}_edited"), (conversion.Id, conversion.Name, conversion.Output.FileNamePattern));
+ Assert.NotSame(image, conversion.Image);
+
+ Assert.True(tool.IsImageEditTool);
+ Assert.Equal((BuiltInData.SameAsSource, ResizeMode.None), (tool.TargetFormat, tool.Image.Resize));
+ }
+
+ [Fact]
+ public void The_choices_are_kept_in_the_tool_and_the_rest_of_it_stays()
+ {
+ var tool = Tool();
+ tool.Image.IcoSizes = [32, 16];
+ var image = new ImageOptions { Resize = ResizeMode.Width, Width = 640, Flip = ImageFlip.Horizontal, Quality = 70, IcoSizes = [256] };
+
+ ImageEditTool.Remember(tool, "webp", image);
+
+ Assert.Equal("webp", tool.TargetFormat);
+ Assert.Equal((ResizeMode.Width, 640, ImageFlip.Horizontal, 70), (tool.Image.Resize, tool.Image.Width, tool.Image.Flip, tool.Image.Quality));
+ Assert.Equal([32, 16], tool.Image.IcoSizes);
+ Assert.True(tool.IsImageEditTool);
+ }
+
+ [Fact]
+ public void A_picture_keeps_its_format_where_it_can_be_written_else_becomes_png()
+ {
+ var magick = new FakeConverter("magick", new ConversionEdge("png", "png"), new ConversionEdge("jpg", "jpg"),
+ new ConversionEdge("dcm", "png"), new ConversionEdge("png", "webp"));
+ var planner = new ConverterCatalog([magick]).CreatePlanner();
+
+ Assert.Equal(BuiltInData.SameAsSource, ImageEditTool.TargetFor("png", BuiltInData.SameAsSource, planner));
+ Assert.Equal(BuiltInData.SameAsSource, ImageEditTool.TargetFor("jpg", BuiltInData.SameAsSource, planner));
+ Assert.Equal("png", ImageEditTool.TargetFor("dcm", BuiltInData.SameAsSource, planner)); // DICOM is only read
+ Assert.Equal("webp", ImageEditTool.TargetFor("png", "webp", planner));
+ Assert.True(ImageEditTool.CanEdit("png"));
+ Assert.False(ImageEditTool.CanEdit("mp4"));
+ Assert.False(ImageEditTool.CanEdit("pdf"));
+ }
+
+ // ───────────────────────── Settings schema 49 ─────────────────────────
+
+ [Fact]
+ public void A_new_library_has_the_tool_after_crop_and_on_the_images_donut_after_half_size()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var edit = presets.Single(p => p.Id == "tool-image-edit");
+ Assert.Equal("tool-crop", presets[presets.IndexOf(edit) - 1].Id);
+ var images = BuiltInData.CreateProfiles().Single(p => p.Id == "images");
+ Assert.Equal("tool-image-edit", images.PresetIds[images.PresetIds.IndexOf("half-size") + 1]);
+ Assert.DoesNotContain("tool-image-edit", images.BackPresetIds!);
+ Assert.InRange(images.PresetIds.Count, 1, ToolbarProfile.MaxSlices);
+ }
+
+ [Fact]
+ public void Version_48_libraries_get_the_tool_on_the_images_donut()
+ {
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "tool-image-edit");
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.PresetIds.Remove("tool-image-edit");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(48, presets, profiles));
+
+ Assert.Equal(BuiltInData.CreatePresets().Select(p => p.Id), presets.Select(p => p.Id));
+ Assert.True(presets.Single(p => p.Id == "tool-image-edit").IsImageEditTool);
+ Assert.Equal(BuiltInData.CreateProfiles().Single(p => p.Id == "images").PresetIds, images.PresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(48, presets, profiles)); // once only
+
+ // A front laid out by the user (without "Half size"), a full one, or the tool already on the back, stays as it is.
+ var own = BuiltInData.CreateProfiles();
+ var ownFront = own.Single(p => p.Id == "images").PresetIds;
+ ownFront.Clear();
+ ownFront.AddRange(["to-webp", "to-png"]);
+ SettingsMigrations.ApplyToLibrary(48, BuiltInData.CreatePresets(), own);
+ Assert.Equal(["to-webp", "to-png"], ownFront);
+
+ var full = BuiltInData.CreateProfiles();
+ var fullFront = full.Single(p => p.Id == "images").PresetIds;
+ fullFront.Remove("tool-image-edit");
+ while (fullFront.Count < ToolbarProfile.MaxSlices)
+ fullFront.Add("to-gif");
+ var before = fullFront.ToList();
+ SettingsMigrations.ApplyToLibrary(48, BuiltInData.CreatePresets(), full);
+ Assert.Equal(before, fullFront);
+
+ var back = BuiltInData.CreateProfiles();
+ var backImages = back.Single(p => p.Id == "images");
+ backImages.PresetIds.Remove("tool-image-edit");
+ backImages.BackPresetIds![^1] = "tool-image-edit";
+ SettingsMigrations.ApplyToLibrary(48, BuiltInData.CreatePresets(), back);
+ Assert.DoesNotContain("tool-image-edit", backImages.PresetIds);
+ }
+
+ [Fact]
+ public void Back_from_an_older_Filee_the_tool_edits_pictures_again_and_keeps_the_users_changes()
+ {
+ // A Filee before 49 reads the unknown "tool" as nothing (a crop) and saves it so.
+ var presets = BuiltInData.CreatePresets();
+ var edit = presets.Single(p => p.Id == "tool-image-edit");
+ edit.Tool = null;
+ edit.Name = "Icons";
+ edit.TargetFormat = "ico";
+ Assert.True(edit.IsCropTool);
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(48, presets, BuiltInData.CreateProfiles()));
+
+ Assert.True(edit.IsImageEditTool);
+ Assert.Equal(("Icons", "ico"), (edit.Name, edit.TargetFormat));
+ Assert.Single(presets, p => p.Id == "tool-image-edit");
+ }
+}