From 720881974c6df6be2e0133977272d68c26a44eb3 Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Tue, 17 Nov 2026 16:41:12 +0000 Subject: [PATCH 1/9] Add files via upload --- src/Filee.Core/Conversion/PageRange.cs | 88 +++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 3 deletions(-) diff --git a/src/Filee.Core/Conversion/PageRange.cs b/src/Filee.Core/Conversion/PageRange.cs index 3952731a1..11b51ca43 100644 --- a/src/Filee.Core/Conversion/PageRange.cs +++ b/src/Filee.Core/Conversion/PageRange.cs @@ -15,6 +15,8 @@ public static IReadOnlyList Parse(string? expression, int pageCount) { if (pageCount <= 0) return []; + // Other keyboards' digits, dashes and commas, as Check reads them: "2–5" is pages 2 to 5, not every page. + expression = Normalize(expression ?? ""); if (string.IsNullOrWhiteSpace(expression)) return Enumerable.Range(0, pageCount).ToList(); @@ -25,7 +27,7 @@ public static IReadOnlyList Parse(string? expression, int pageCount) int start, end; if (dash < 0) { - if (!int.TryParse(raw, out start)) + if (!int.TryParse(raw, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out start)) continue; end = start; } @@ -33,8 +35,8 @@ public static IReadOnlyList Parse(string? expression, int pageCount) { var left = raw[..dash].Trim(); var right = raw[(dash + 1)..].Trim(); - start = left.Length == 0 ? 1 : int.TryParse(left, out var l) ? l : -1; - end = right.Length == 0 ? pageCount : int.TryParse(right, out var r) ? r : -1; + start = left.Length == 0 ? 1 : int.TryParse(left, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var l) ? l : -1; + end = right.Length == 0 ? pageCount : int.TryParse(right, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var r) ? r : -1; if (start < 0 || end < 0) continue; } @@ -47,4 +49,84 @@ public static IReadOnlyList Parse(string? expression, int pageCount) return pages.Count == 0 ? Enumerable.Range(0, pageCount).ToList() : pages.ToList(); } + + /// + /// Checks a range typed by hand (the "Choose pages" window, filee convert --pages), which + /// would quietly make the best of: every part must be a page number or a span of them, from 1, + /// and none past the last page when is known. What a keyboard in another language + /// types is read too: other digits (Devanagari, Arabic-Indic, Thai, full-width), en, em and full-width dashes, + /// full-width, ideographic and Arabic commas. Empty means every page. + /// + public static PageRangeCheck Check(string? expression, int? pageCount) + { + var text = Normalize(expression ?? "").Trim(); + if (text.Length == 0) + return new(PageRangeProblem.None, "", pageCount); + + var last = 0; + foreach (var raw in text.Split(',')) + { + var part = raw.Trim(); + if (part.Length == 0) + continue; + var dash = part.IndexOf('-'); + var left = dash < 0 ? part : part[..dash].Trim(); + var right = dash < 0 ? part : part[(dash + 1)..].Trim(); + if (dash >= 0 && left.Length == 0 && right.Length == 0) + return new(PageRangeProblem.Invalid, text, null); + if (!Page(left, out var start) || !Page(right, out var end)) + return new(PageRangeProblem.Invalid, text, null); + last = Math.Max(last, Math.Max(start, end)); + } + if (last == 0 && !text.Contains('-')) + return new(PageRangeProblem.Invalid, text, null); + if (pageCount is { } count && last > count) + return new(PageRangeProblem.PastTheEnd, text, null); + return new(PageRangeProblem.None, text, pageCount is { } total ? Parse(text, total).Count : null); + + // A side left empty ("7-", "-4") is open; anything else must be a whole number from 1. + static bool Page(string side, out int page) + { + page = 0; + if (side.Length == 0) + return true; + return side.All(char.IsAsciiDigit) && int.TryParse(side, System.Globalization.CultureInfo.InvariantCulture, out page) && page >= 1; + } + } + + /// The range in the digits, hyphens and commas reads. + private static string Normalize(string expression) => + string.Create(expression.Length, expression, (chars, source) => + { + for (var i = 0; i < source.Length; i++) + { + var c = source[i]; + chars[i] = c switch + { + '\u2013' or '\u2014' or '\u2212' or '\uFF0D' => '-', // en, em, minus and full-width dashes + '\uFF0C' or '\u3001' or '\u060C' => ',', // full-width, ideographic and Arabic commas + _ when !char.IsAsciiDigit(c) && char.IsDigit(c) => (char)('0' + (int)char.GetNumericValue(c)), + _ => c, + }; + } + }); +} + +/// What is wrong with a range typed by hand (). +public enum PageRangeProblem +{ + None, + /// A part that is not a page number or a span of them ("abc", "3-x", "0"). + Invalid, + /// A page after the last one of the PDF. + PastTheEnd, +} + +/// +/// The result of : is the range as it is used (dashes made hyphens, +/// trimmed); how many pages it takes, when the page count is known and the range is fine. +/// +public readonly record struct PageRangeCheck(PageRangeProblem Problem, string Text, int? Pages) +{ + public bool IsValid => Problem == PageRangeProblem.None; } From bb5abf6b8c2de592fa7450761a7e4759c1e2bd22 Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Tue, 17 Nov 2026 16:42:16 +0000 Subject: [PATCH 2/9] Add files via upload --- .../ViewModels/PresetEditorViewModel.cs | 732 ++++++++++++++++-- 1 file changed, 684 insertions(+), 48 deletions(-) diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs index 916946e8f..8dde26509 100644 --- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs +++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs @@ -3,11 +3,17 @@ // // Works on a clone; Apply() copies the edits back into the original preset (Cancel = just drop the VM). +using System.Collections.ObjectModel; using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Filee.App.Services; using Filee.Core.Formats; using Filee.Core.Localization; using Filee.Core.Presets; +using Filee.Core.Settings; using Filee.Engines.Ocr; +using Filee.Engines.Translation; +using Filee.Engines.Upscale; namespace Filee.App.ViewModels; @@ -29,12 +35,51 @@ public enum FileSizeUnit MB, } +/// The unit of a video's size limit in the preset editor (#680); the preset itself keeps megabytes or a percentage. +public enum VideoSizeUnit +{ + MB, + Percent, +} + +/// +/// The number of a video split into parts in the preset editor (#1259): seconds or minutes per part, or the equal parts. +/// The preset itself keeps seconds (MediaOptions.SplitEverySeconds) or the parts (MediaOptions.SplitParts). +/// +public enum VideoSplitKind +{ + Seconds, + Minutes, + EqualParts, +} + /// A value with a localized label for combo boxes. public sealed record Choice(T Value, string Label, string? Detail = null) : IChoice { public override string ToString() => Label; } +/// +/// A language in the preset editor's OCR lists. Whether it needs a download depends on the other languages chosen +/// (), so the lists keep one object per language and only its changes. +/// +/// The size of its download, or null when its data is there already. +public sealed partial class OcrLanguageChoice(string value, string label, bool visionReads, string? download) : ObservableObject, IChoice +{ + public string Value => value; + public string Label => label; + + /// Apple Vision reads it on this computer. + public bool VisionReads => visionReads; + + [ObservableProperty] private string? _detail; + + /// Tesseract reads the chosen languages, not Apple Vision: it needs the data of each. + public void ShowDownload(bool tesseractReads) => Detail = tesseractReads || !visionReads ? download : null; + + public override string ToString() => Label; +} + /// Selections bound to properties that always hold a value (a choice, the open page). public static class Choices { @@ -60,27 +105,45 @@ public sealed partial class PresetEditorViewModel : ObservableObject private static readonly HashSet LosslessAudioTargets = ["wav", "flac", "aiff", "wv", "tta", "w64"]; private static readonly int[] MaxHeightSteps = [0, 2160, 1440, 1080, 720, 480]; - // 32-64 kbit/s: speech (Opus is still clear at 32 kbit/s mono), small files. - private static readonly int[] BitrateSteps = [0, 32, 48, 64, 96, 128, 192, 256, 320]; + /// + /// The audio bitrates offered, 0 for the one the quality picks (also in the compression window, #1353). 32-64 kbit/s: + /// speech (Opus is still clear at 32 kbit/s mono), small files. + /// + internal static readonly int[] BitrateSteps = [0, 32, 48, 64, 96, 128, 192, 256, 320]; private static readonly int[] SampleRateSteps = [0, 8000, 16000, 22050, 44100, 48000]; private readonly Preset _original; private readonly Preset _edit; private readonly ILocalizer _loc; - public PresetEditorViewModel(Preset preset, ILocalizer loc) + /// "From the preset gallery (…)" for a preset installed from there (#1530); null for every other. + public string? GalleryNote { get; } + + public PresetEditorViewModel(Preset preset, ILocalizer loc, IReadOnlySet? turnedOff = null, bool folderInput = false) + : this(preset, loc, turnedOff, null, folderInput) + { + } + + /// Which languages Apple Vision reads, for tests; by default what this computer's does. + internal PresetEditorViewModel(Preset preset, ILocalizer loc, IReadOnlySet? turnedOff, Func? visionReads, + bool folderInput = false) { _original = preset; _edit = preset.Clone(); _loc = loc; + FolderInput = folderInput || preset.TargetFormat == "iso"; + Labels = new SliceLabelFields(preset, loc); + GalleryNote = preset.Gallery is { } gallery ? loc.Format("presets.from_gallery", gallery) : null; // ~150 formats in registry order, which groups them by category; the category is shown next to each name // and typing the first letters of a name jumps to it. Targets = [ - new Choice(BuiltInData.SameAsSource, loc["presets.same_as_source"]), + .. FolderInput ? Array.Empty>() : [new Choice(BuiltInData.SameAsSource, loc["presets.same_as_source"]), + // #1490: a video's sound as it is; on other files the preset is greyed (PresetAvailability). + new Choice(BuiltInData.SameAsAudio, loc["presets.same_as_audio"], FormatLabels.Category(loc, FormatCategory.Video))], .. FormatRegistry.Known - .Where(f => f.Writable) + .Where(f => f.Writable && (!FolderInput || BuiltInData.SupportsFolderTarget(f.Id)) && (turnedOff is null || FormatFields.IsShown(f.Id, turnedOff))) .Select(f => new Choice( f.Id, f.Id == FormatRegistry.Folder ? loc["presets.target_folder"] : f.DisplayName, @@ -94,14 +157,13 @@ .. FormatRegistry.Known PageSizes = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.page_size.{v}"])).ToList(); CompressionLevels = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.pdf_compression.{v}"])).ToList(); // Each language under its own name; one not downloaded yet shows its size (it downloads with the first file). - // On a Mac, Apple Vision reads the common languages without a download. + // On a Mac, Apple Vision reads the common languages without a download (ShowOcrDownloads). var vision = new VisionConverter(); OcrHint = loc[vision.GetStatus().IsAvailable ? "presets.ocr_hint_macos" : "presets.ocr_hint"]; OcrLanguageChoices = [.. OcrLanguages.All .OrderBy(l => l.Code != OcrLanguages.Default).ThenBy(l => l.NativeName, StringComparer.CurrentCulture) - .Select(l => new Choice(l.Code, l.NativeName, - OcrLanguages.IsInstalled(l.Code) || vision.Reads(l.Code) ? null - : loc.Format("presets.ocr_language_size", $"{l.Size / 1_000_000.0:0.#} MB")))]; + .Select(l => new OcrLanguageChoice(l.Code, l.NativeName, (visionReads ?? vision.Reads)(l.Code), + OcrLanguages.IsInstalled(l.Code) ? null : loc.Format("presets.ocr_language_size", $"{l.Size / 1_000_000.0:0.#} MB")))]; // "Ask every time" (#521) is a bool of its own on the preset (OutputRule.AskEveryTime): its choice has no location. Locations = [.. Enum.GetValues().Select(v => new Choice(v, loc[$"presets.location.{v}"])), new Choice(null, loc["presets.location.Ask"])]; @@ -117,17 +179,45 @@ .. FormatRegistry.Known FitsTiffModes = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.fits_tiff.{v}"])).ToList(); MediaQualities = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.media_quality.{v}"])).ToList(); MaxHeights = Steps(MaxHeightSteps, _edit.Media.MaxHeight, h => h == 0 ? loc["presets.max_height.original"] : $"{h}p"); + // A ratio set outside the editor (a hand-edited preset file) is offered too, instead of being lost. + // "Pages per sheet" (#737): a number set outside the editor (a hand-edited preset file) is offered too. + SheetLayouts = [.. PdfOptions.SheetLayouts.Append(_edit.Pdf.PagesPerSheet).Where(n => n is > 1 and <= 16).Distinct().Order() + .Select(n => new Choice(n, $"{n}"))]; + PageOutputChoices = + [ + new(ViewModels.PageOutput.OnePdf, loc["pages.one_pdf"]), + new(ViewModels.PageOutput.EachPage, loc["presets.split"]), + new(ViewModels.PageOutput.Groups, loc["pages.groups"]), + ]; + GroupKinds = PageOutputs.Kinds(loc); + VideoOutputChoices = [new(false, loc["presets.video_one"]), new(true, loc["presets.video_parts"])]; + VideoSplitKinds = + [ + new(ViewModels.VideoSplitKind.Seconds, loc["presets.split_seconds"]), + new(ViewModels.VideoSplitKind.Minutes, loc["presets.split_minutes"]), + new(ViewModels.VideoSplitKind.EqualParts, loc["pages.equal_parts"]), + ]; + SheetPapers = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.sheet_paper.{v}"])).ToList(); + SheetOrientations = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.sheet_orientation.{v}"])).ToList(); + SheetOrders = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.sheet_order.{v}"])).ToList(); + CropFrames = [new(VideoCrop.Auto, loc["presets.crop_frame.auto"]), + .. VideoCrop.Ratios.Append(_edit.Media.CropFrame).Where(r => VideoCrop.TryParseRatio(r, out _, out _)).Distinct() + .Select(r => new Choice(r, r))]; AudioBitrates = Steps(BitrateSteps, _edit.Media.AudioBitrateKbps, k => k == 0 ? loc["presets.audio_bitrate.auto"] : $"{k} kbps"); AudioChannelChoices = new[] { 0, 1, 2 }.Select(c => new Choice(c, loc[$"presets.audio_channels.{c}"])).ToList(); SampleRates = Steps(SampleRateSteps, _edit.Media.AudioSampleRate, r => r == 0 ? loc["presets.sample_rate.source"] : $"{r / 1000.0:0.##} kHz"); WavFormats = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.wav_format.{v}"])).ToList(); + IsoFileSystems = Enum.GetValues().Select(v => new Choice(v, v == Core.Presets.IsoFileSystem.Joliet ? "ISO 9660 + Joliet" : "UDF 2.01")).ToList(); ArchiveLevels = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.archive_level.{v}"])).ToList(); TraceModes = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.trace_mode.{v}"])).ToList(); // Version names stay as AutoCAD calls them, in every language. CadVersions = Enum.GetValues().Select(v => new Choice(v, v == Core.Presets.CadVersion.SameAsSource ? loc["presets.cad_version.same"] : "AutoCAD " + v.ToString()["AutoCad".Length..])).ToList(); CadColorChoices = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.cad_colors.{v}"])).ToList(); + GcodeViews = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.gcode_view.{v}"])).ToList(); + // G-code belongs to the 3D and CAD fields only: with both off, its card is left out like its files' slots. + _gcodeShown = turnedOff is null || FormatFields.IsShown("gcode", turnedOff); // A speed set outside the editor (a hand-edited preset file) is offered too, instead of being lost. AnimationSpeeds = [.. ImageOptions.AnimationSpeeds.Append(_edit.Image.PlaybackSpeed).Distinct().Order() .Select(s => new Choice(s, s == 1 ? loc["presets.animation_speed.original"] : SpeedLabel(s)))]; @@ -140,7 +230,15 @@ .. WhisperLanguages.All ]; _name = string.IsNullOrWhiteSpace(_edit.Name) ? loc.DisplayName(_edit) : _edit.Name; - _target = Targets.FirstOrDefault(t => t.Value == _edit.TargetFormat) ?? Targets[1]; + if (FormatRegistry.FindById(_edit.TargetFormat) is { Writable: true } hidden + && turnedOff is not null && !FormatFields.IsShown(hidden.Id, turnedOff)) + { + _target = new Choice(hidden.Id, hidden.DisplayName, FormatLabels.Category(loc, hidden.Category)); + _hiddenTarget = hidden.DisplayName; + _hiddenTargetNote = loc.Format("presets.target_hidden", hidden.DisplayName); + } + else + _target = Targets.FirstOrDefault(t => t.Value == _edit.TargetFormat) ?? Targets.First(t => t.Value == (FolderInput ? "iso" : BuiltInData.SameAsSource)); _resize = ResizeModes.First(r => r.Value == (_edit.Image.CustomSize is not null ? ResizeMode.Custom : _edit.Image.ClampedMinShortEdge is not null ? ResizeMode.MinShortEdge : _edit.Image.Resize)); @@ -153,7 +251,11 @@ .. WhisperLanguages.All _pageNumbers = _edit.Pdf.PageNumbers; _pdfPassword = _edit.Pdf.Password; _ocr = _edit.Pdf.Ocr; - _ocrLanguage = OcrLanguageChoices.FirstOrDefault(l => l.Value == _edit.Pdf.OcrLanguage) ?? OcrLanguageChoices[0]; + var ocrLanguages = OcrLanguages.Parse(_edit.Pdf.OcrLanguage).Select(l => OcrLanguageChoices.First(c => c.Value == l.Code)).ToList(); + _ocrLanguage = ocrLanguages[0]; + MoreOcrLanguages = [.. ocrLanguages.Skip(1)]; + MoreOcrLanguages.CollectionChanged += (_, _) => RefreshOcrLanguagesToAdd(); + RefreshOcrLanguagesToAdd(); _location = _edit.Output.AskEveryTime ? Locations[^1] : Locations.First(l => l.Value == _edit.Output.Location); _conflict = Conflicts.First(c => c.Value == _edit.Output.Conflict); _tiffCompression = TiffCompressions.First(t => t.Value == _edit.Image.TiffCompression); @@ -161,8 +263,27 @@ .. WhisperLanguages.All _fitsDebayer = _edit.Image.FitsDebayer; _mediaQuality = MediaQualities.First(q => q.Value == _edit.Media.Quality); _maxHeight = MaxHeights.First(h => h.Value == _edit.Media.MaxHeight); + _cropFrame = CropFrames.FirstOrDefault(c => c.Value == _edit.Media.CropFrame) ?? CropFrames[0]; + _pagesPerSheet = SheetLayouts.FirstOrDefault(c => c.Value == _edit.Pdf.PagesPerSheet) ?? SheetLayouts.First(c => c.Value == 4); + _sheetPaper = SheetPapers.FirstOrDefault(c => c.Value == _edit.Pdf.SheetPaper) ?? SheetPapers[0]; + _sheetOrientation = SheetOrientations.FirstOrDefault(c => c.Value == _edit.Pdf.SheetOrientation) ?? SheetOrientations[0]; + _sheetOrder = SheetOrders.FirstOrDefault(c => c.Value == _edit.Pdf.SheetOrder) ?? SheetOrders[0]; + _sheetMarginMm = _edit.Pdf.SheetMarginMm; + _sheetGapMm = _edit.Pdf.SheetGapMm; + _sheetBorders = _edit.Pdf.SheetBorders; _audioBitrate = AudioBitrates.First(b => b.Value == _edit.Media.AudioBitrateKbps); _removeAudio = _edit.Media.RemoveAudio; + _videoOutput = VideoOutputChoices[_edit.Media.Splits ? 1 : 0]; + // Whole minutes show as minutes; 90 seconds stays 90 seconds. + var (splitKind, splitSize) = _edit.Media switch + { + { SplitParts: > 1 } m => (ViewModels.VideoSplitKind.EqualParts, m.SplitParts), + { SplitEverySeconds: > 0 } m when m.SplitEverySeconds % 60 == 0 => (ViewModels.VideoSplitKind.Minutes, m.SplitEverySeconds / 60), + { SplitEverySeconds: > 0 } m => (ViewModels.VideoSplitKind.Seconds, m.SplitEverySeconds), + _ => (ViewModels.VideoSplitKind.Minutes, 10), + }; + _videoSplitKind = VideoSplitKinds.First(k => k.Value == splitKind); + _videoSplitSize = splitSize; _audioChannels = AudioChannelChoices.FirstOrDefault(c => c.Value == _edit.Media.AudioChannels) ?? AudioChannelChoices[0]; _sampleRate = SampleRates.First(r => r.Value == _edit.Media.AudioSampleRate); _wavFormat = WavFormats.First(f => f.Value == _edit.Media.WavFormat); @@ -172,6 +293,37 @@ .. WhisperLanguages.All _caption = _edit.Media.Caption; _spokenLanguage = SpokenLanguageChoices.FirstOrDefault(l => string.Equals(l.Value, _edit.Media.SpokenLanguage, StringComparison.OrdinalIgnoreCase)) ?? SpokenLanguageChoices[0]; + TranslationLanguageChoices = + [ + new Choice("en", "English"), + new Choice("es", "Español"), + new Choice("fr", "Français"), + new Choice("de", "Deutsch"), + new Choice("zh", "中文"), + new Choice("hi", "हिन्दी"), + new Choice("ja", "日本語"), + new Choice("ko", "한국어"), + new Choice("ru", "Русский"), + new Choice("uk", "Українська"), + new Choice("pt", "Português"), + new Choice("ar", "العربية"), + new Choice("fa", "فارسی"), + new Choice("it", "Italiano"), + new Choice("nl", "Nederlands"), + new Choice("pl", "Polski"), + new Choice("tr", "Türkçe"), + new Choice("ne", "नेपाली"), + new Choice("th", "ไทย"), + new Choice("id", "Bahasa Indonesia"), + new Choice("vi", "Tiếng Việt"), + new Choice("bn", "বাংলা") + ]; + _targetLanguage = TranslationLanguageChoices.FirstOrDefault(l => string.Equals(l.Value, _edit.Translate.TargetLanguage, StringComparison.OrdinalIgnoreCase)) + ?? TranslationLanguageChoices[0]; + _upscaleScale = _edit.Upscale.Scale > 0 ? _edit.Upscale.Scale : 4; + _selectedUpscaleModel = UpscaleModels.FirstOrDefault(m => string.Equals(m.Id, _edit.Upscale.Model, StringComparison.OrdinalIgnoreCase)) + ?? UpscaleModels.FirstOrDefault(); + _isoFileSystem = IsoFileSystems.First(v => v.Value == _edit.Archive.IsoFileSystem); _archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level); _combineIntoOne = _edit.Archive.CombineIntoOne; _saveEveryFrame = _edit.Media.SaveEveryFrame; @@ -180,6 +332,9 @@ .. WhisperLanguages.All _livePhotoStart = _edit.Media.LivePhotoStart; _livePhotoLength = _edit.Media.LivePhotoLength; _livePhotoCover = _edit.Media.LivePhotoCover; + _ringtoneStart = _edit.Media.RingtoneStart; + _ringtoneLength = _edit.Media.RingtoneLength; + _askRingtonePart = _edit.Media.AskRingtonePart; _frameInterval = _edit.Media.FrameInterval > 0 ? _edit.Media.FrameInterval : 1; _isSlideshow = _edit.Media.Slideshow; _slideSeconds = _edit.Media.SlideDuration; @@ -187,6 +342,7 @@ .. WhisperLanguages.All _traceMode = TraceModes.First(m => m.Value == _edit.Trace.Mode); _cadVersion = CadVersions.First(v => v.Value == _edit.Cad.Version); _cadColors = CadColorChoices.FirstOrDefault(c => c.Value == _edit.Cad.Colors) ?? CadColorChoices[0]; + _gcodeView = GcodeViews.FirstOrDefault(v => v.Value == _edit.Gcode.View) ?? GcodeViews[0]; _animationSpeed = AnimationSpeeds.First(s => s.Value == _edit.Image.PlaybackSpeed); _traceColors = Math.Clamp(_edit.Trace.Colors, TracingOptions.MinColors, TracingOptions.MaxColors); _traceDetail = Math.Clamp(_edit.Trace.Detail, 0, 100); @@ -197,13 +353,22 @@ .. WhisperLanguages.All var perMegabyte = _imageSizeUnit.Value == FileSizeUnit.KB ? 1000m : 1m; _imageMaxSize = (decimal)_edit.Image.MaxSizeMb * perMegabyte; _imageMinSize = (decimal)_edit.Image.MinSizeMb * perMegabyte; - _videoMaxSizeMb = (decimal)_edit.Media.MaxSizeMb; + _videoSizeUnitChoice = _edit.Media.MaxSizePercent > 0 ? VideoSizeUnits[1] : VideoSizeUnits[0]; + _videoMaxSizeMb = _edit.Media.MaxSizeMb > 0 ? (decimal)_edit.Media.MaxSizeMb : null; + _videoMaxSizePercent = _edit.Media.MaxSizePercent > 0 ? _edit.Media.MaxSizePercent : null; _resizePercent = _edit.Image.ResizePercent; _longEdge = _edit.Image.LongEdge; _width = _edit.Image.Width; _customWidth = _edit.Image.CustomSize?.Width ?? 1920; _customHeight = _edit.Image.CustomSize?.Height ?? 1080; _lockAspect = _edit.Image.CustomSize?.LockAspect ?? false; + _shrinkOnly = _edit.Image.CustomSize?.ShrinkOnly ?? false; + // A side left empty is stored as the largest one (CustomImageSize.FreeSide) and comes back empty. + if (_lockAspect && _customWidth >= CustomImageSize.FreeSide) + _customWidth = null; + if (_lockAspect && _customHeight >= CustomImageSize.FreeSide) + _customHeight = null; + _maxSizeKeepsPixels = _edit.Image.MaxSizeKeepsPixels; _minShortEdge = _edit.Image.ClampedMinShortEdge ?? 1080; _setDpi = _edit.Image.Dpi.HasValue; _dpi = _edit.Image.Dpi ?? 300; @@ -218,10 +383,18 @@ .. WhisperLanguages.All _multiPageTiff = _edit.Image.MultiPageTiff; _icoSizes = string.Join(", ", _edit.Image.IcoSizes); _merge = _edit.Pdf.MergeIntoSingle; + _sourceBookmarks = _edit.Pdf.SourceBookmarks; + _normalizeMergePaper = _edit.Pdf.NormalizeMergePaper; + _mergePaper = SheetPapers.First(c => c.Value == _edit.Pdf.MergePaper); + _mergeOrientation = SheetOrientations.First(c => c.Value == _edit.Pdf.MergeOrientation); _marginMm = _edit.Pdf.MarginMm; _renderDpi = _edit.Pdf.RenderDpi; _pageRange = _edit.Pdf.PageRange; - _splitPages = _edit.Pdf.SplitPages; + _askPageRange = _edit.Pdf.AskPageRange; + _askCompression = _edit.AskCompression; + _pageOutput = PageOutputChoices.First(c => c.Value == PageOutputs.Of(_edit.Pdf)); + _groupKind = GroupKinds.First(k => k.Value == PageOutputs.KindOf(_edit.Pdf)); + _groupSize = PageOutputs.SizeOf(_edit.Pdf); _combinePages = _edit.Pdf.CombinePages; _trimPageMargins = _edit.Pdf.TrimPageMargins; _splitTallImage = _edit.Pdf.SplitTallImage; @@ -234,6 +407,8 @@ .. WhisperLanguages.All _keepDates = _edit.Output.KeepDates; _zipResult = _edit.Output.ZipResult; _replaceOriginal = _edit.Output.ReplaceOriginal; + _trashOriginal = _edit.Output.TrashOriginalAfterConvert; + _moveInsteadOfCopy = _edit.Output.MoveInsteadOfCopy; } public string PresetId => _original.Id; @@ -244,6 +419,9 @@ .. WhisperLanguages.All public bool IsTool => _original.IsTool; public bool CanChangeTarget => !IsTool; + /// Folder actions only offer directory-capable targets and preserve the source directory. + public bool FolderInput { get; } + public bool ShowReplaceOriginal => !FolderInput && !IsCopyToFolder; public IReadOnlyList> Targets { get; } public IReadOnlyList> ResizeModes { get; } @@ -254,10 +432,65 @@ .. WhisperLanguages.All public IReadOnlyList> PageSizes { get; } /// Languages Tesseract reads (PdfOptions.OcrLanguage), English first. - public IReadOnlyList> OcrLanguageChoices { get; } + public IReadOnlyList OcrLanguageChoices { get; } + + /// Languages read next to , for text that mixes them (#1123); PdfOptions.OcrLanguage holds them all. + public ObservableCollection MoreOcrLanguages { get; } + + /// The languages not chosen yet, for the "add a language" list. + public ObservableCollection OcrLanguagesToAdd { get; } = []; + /// The spoken languages Whisper recognizes (MediaOptions.SpokenLanguage), Auto first. public IReadOnlyList> SpokenLanguageChoices { get; } + public IReadOnlyList> TranslationLanguageChoices { get; } + + [ObservableProperty] private Choice _targetLanguage; + + public bool ShowTranslate => _original.Id == "translate" || _edit.Translate.Enabled; + + [ObservableProperty] private string _testTranslationResult = ""; + [ObservableProperty] private bool _isTestingTranslation; + [ObservableProperty] private bool _testTranslationHasError; + + [RelayCommand] + public async Task TestTranslationAsync() + { + if (IsTestingTranslation) return; + IsTestingTranslation = true; + TestTranslationHasError = false; + TestTranslationResult = _loc["engines.ollama.connecting"]; + + try + { + var targetLang = TargetLanguage?.Value ?? "es"; + var preferred = AppHost.Get()?.Settings.PreferredOllamaModel; + var model = !string.IsNullOrWhiteSpace(_edit.Translate.Model) ? _edit.Translate.Model + : !string.IsNullOrWhiteSpace(preferred) ? preferred + : await TranslationService.GetPreferredLocalOllamaModelAsync(); + var service = new TranslationService(new TranslateOptions { TargetLanguage = targetLang, Model = model }); + var sample = "Hello, world!"; + var translated = await service.TranslateTextAsync(sample, targetLang); + TestTranslationResult = $"\"{sample}\" → \"{translated}\" ({model ?? "local model"})"; + TestTranslationHasError = false; + } + catch (Exception ex) + { + TestTranslationResult = $"{_loc["engines.ollama.error"]} {ex.Message}"; + TestTranslationHasError = true; + } + finally + { + IsTestingTranslation = false; + } + } + + public bool ShowUpscale => _original.IsUpscaleTool || _edit.Upscale.Enabled; + public IReadOnlyList UpscaleModels { get; } = Filee.Engines.Upscale.UpscaleModels.All; + [ObservableProperty] private UpscaleModel? _selectedUpscaleModel; + [ObservableProperty] private int _upscaleScale = 4; + + /// What "Recognize text" needs: Tesseract, or on a Mac Apple Vision (Tesseract only for other languages). public string OcrHint { get; } @@ -271,10 +504,25 @@ .. WhisperLanguages.All public IReadOnlyList> FitsTiffModes { get; } public IReadOnlyList> MediaQualities { get; } public IReadOnlyList> MaxHeights { get; } + /// "Crop video": the picture inside the black bars, or a ratio. + public IReadOnlyList> CropFrames { get; } + public IReadOnlyList> SheetLayouts { get; } + + /// PDF → PDF: one PDF, one file per page, or several pages per file (#1259). + public IReadOnlyList> PageOutputChoices { get; } + public IReadOnlyList> GroupKinds { get; } + + /// Video → video: one video, or several parts copied as they are (#1259). + public IReadOnlyList> VideoOutputChoices { get; } + public IReadOnlyList> VideoSplitKinds { get; } + public IReadOnlyList> SheetPapers { get; } + public IReadOnlyList> SheetOrientations { get; } + public IReadOnlyList> SheetOrders { get; } public IReadOnlyList> AudioBitrates { get; } public IReadOnlyList> AudioChannelChoices { get; } public IReadOnlyList> SampleRates { get; } public IReadOnlyList> WavFormats { get; } + public IReadOnlyList> IsoFileSystems { get; } public IReadOnlyList> ArchiveLevels { get; } public IReadOnlyList> TraceModes { get; } @@ -284,26 +532,62 @@ .. WhisperLanguages.All /// The colours a drawing is drawn in: as drawn, black and white, grayscale (CadOptions.Colors, #411). public IReadOnlyList> CadColorChoices { get; } + /// What a G-code file shows: from above, isometric, the slicer's preview (GcodeOptions.View). + public IReadOnlyList> GcodeViews { get; } + + private readonly bool _gcodeShown; + /// Playback speeds of animations, 0.25× to 4× (ImageOptions.AnimationSpeed). public IReadOnlyList> AnimationSpeeds { get; } [ObservableProperty, NotifyPropertyChangedFor(nameof(NameError), nameof(IsValid))] private string _name; + partial void OnNameChanged(string value) => Labels.NameChanged(value); + + /// The slice's icon, short name and what it shows. + public SliceLabelFields Labels { get; } + [ObservableProperty] [NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco), nameof(ShowFitsTiff), nameof(ShowFitsDebayer), - nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPdfCombine), - nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowOcr), nameof(ShowPageSize), nameof(ShowPdfTablesNote), + nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowSourceBookmarks), nameof(ShowMergePaper), nameof(ShowMergePaperSettings), + nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCombine), + nameof(ShowAskPages), nameof(ShowAskPagesHint), nameof(ShowAskCompressionImage), nameof(ShowAskCompressionMedia), nameof(ShowAskCompressionPdf), + nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowSheets), nameof(ShowOcr), nameof(ShowPageSize), nameof(ShowPdfTablesNote), nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowVideoMaxSize), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio), + nameof(ShowVideoSplit), nameof(ShowVideoParts), nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding), nameof(ShowCaption), - nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec), - nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), - nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowCad), nameof(ShowCadColors), nameof(ShowExtractMotionPhoto), nameof(ShowSlideshow), + nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec), nameof(ShowRingtone), + nameof(ShowIso), nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), + nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowCad), nameof(ShowCadColors), nameof(ShowGcode), nameof(ShowExtractMotionPhoto), nameof(ShowSlideshow), nameof(ShowLivePhotoChoice), nameof(LivePhotoKinds), nameof(LivePhotoChoice), nameof(IsLivePhoto), nameof(LivePhotoHint), - nameof(ShowImageSize), nameof(SizeRangeError), nameof(IsValid))] + nameof(ShowImageSize), nameof(SizeRangeError), nameof(CustomSizeError), nameof(IsValid))] private Choice _target; + // A target whose fields are all turned off isn't added to Targets (the list follows the switches), but it stays the + // target: the box shows its name as a placeholder with a note, and Apply saves it unless another one is picked. + [ObservableProperty] private string? _hiddenTarget; + [ObservableProperty] private string? _hiddenTargetNote; + + /// The target box has no selection while the current target is hidden by its field switch. + public Choice? TargetSelection + { + get => HiddenTarget is null ? Target : null; + set + { + if (value is null) + { + if (HiddenTarget is null) + OnPropertyChanged(nameof(TargetSelection)); + return; + } + HiddenTarget = null; + HiddenTargetNote = null; + Target = value; + } + } + private LivePhotoKind _livePhotoValue; /// What a video becomes for a JPG or HEIC target: one still frame, or a Live / Motion Photo it can be written as. @@ -328,7 +612,7 @@ public Choice LivePhotoChoice return; _livePhotoValue = value.Value; OnPropertyChanged(); - foreach (var name in (string[])[nameof(IsLivePhoto), nameof(LivePhotoHint), nameof(ShowImage), nameof(ShowPdf), nameof(ShowSaveEveryFrame), nameof(ShowImageSize), nameof(SizeRangeError), nameof(IsValid)]) + foreach (var name in (string[])[nameof(IsLivePhoto), nameof(LivePhotoHint), nameof(ShowImage), nameof(ShowPdf), nameof(ShowSaveEveryFrame), nameof(ShowImageSize), nameof(SizeRangeError), nameof(CustomSizeError), nameof(IsValid)]) OnPropertyChanged(name); } } @@ -337,6 +621,13 @@ public Choice LivePhotoChoice [ObservableProperty] private double _livePhotoLength; [ObservableProperty] private double _livePhotoCover; + /// M4R (iPhone ringtone): where the ringtone starts in the sound, and how long it is (at most 40 s). + [ObservableProperty] private double _ringtoneStart; + [ObservableProperty] private double _ringtoneLength; + + /// "Ask every time" for the ringtone's part, in the Cut a clip window (MediaOptions.AskRingtonePart, #1291). + [ObservableProperty] private bool _askRingtonePart; + /// The clip's video codec: H.264, or HEVC for smaller files (MediaOptions.VideoCodec). public IReadOnlyList> LivePhotoCodecs => [ @@ -420,6 +711,7 @@ public Choice AudioCodecChoice } [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge), nameof(ShowWidth), nameof(ShowCustom), nameof(ShowMinShortEdge))] + [NotifyPropertyChangedFor(nameof(CustomSizeError), nameof(IsValid))] private Choice _resize; [ObservableProperty] private Choice _rotation; @@ -442,7 +734,13 @@ public Choice AudioCodecChoice /// A picture's size range (#553, #662) in ; 0 or empty = none. [ObservableProperty, NotifyPropertyChangedFor(nameof(SizeRangeError), nameof(IsValid))] private decimal? _imageMinSize; - [ObservableProperty, NotifyPropertyChangedFor(nameof(SizeRangeError), nameof(IsValid))] private decimal? _imageMaxSize; + [ObservableProperty, NotifyPropertyChangedFor(nameof(SizeRangeError), nameof(IsValid), nameof(HasImageMaxSize))] private decimal? _imageMaxSize; + + /// With a maximum: keep the pixels and lower only the quality (ImageOptions.MaxSizeKeepsPixels, #1270). + [ObservableProperty] private bool _maxSizeKeepsPixels; + + /// A maximum is set, so keeping the pixels has something to do. + public bool HasImageMaxSize => ImageMaxSize > 0; /// KB or MB, for both ends of the range; not saved (the preset keeps megabytes). [ObservableProperty, NotifyPropertyChangedFor(nameof(SizeFormat), nameof(SizeIncrement))] private Choice _imageSizeUnit; @@ -463,15 +761,46 @@ public Choice AudioCodecChoice /// A minimum over the maximum, while the boxes are shown; a maximum of 0 is no maximum. public string? SizeRangeError => ShowImageSize && ImageMaxSize > 0 && ImageMinSize > ImageMaxSize ? _loc["presets.size_range_invalid"] : null; - /// "Size limit (MB)" for a video (0 = none, #553). - [ObservableProperty] private decimal? _videoMaxSizeMb; + /// The unit of the video size limit: MB or % of original (#680). + public IReadOnlyList> VideoSizeUnits { get; } = + [new(VideoSizeUnit.MB, "MB"), new(VideoSizeUnit.Percent, "%")]; + + [ObservableProperty] private Choice _videoSizeUnitChoice; + + /// Video size limit in MB (0 or empty = none, #553). + [ObservableProperty, NotifyPropertyChangedFor(nameof(VideoMaxSize))] private decimal? _videoMaxSizeMb; + + /// Video size limit as percentage of original (1–99, 0 or empty = none, #680). + [ObservableProperty, NotifyPropertyChangedFor(nameof(VideoMaxSize))] private decimal? _videoMaxSizePercent; + + /// The value bound to the video size NumericUpDown. + public decimal? VideoMaxSize + { + get => VideoSizeUnitChoice.Value == VideoSizeUnit.Percent ? VideoMaxSizePercent : VideoMaxSizeMb; + set + { + if (VideoSizeUnitChoice.Value == VideoSizeUnit.Percent) + VideoMaxSizePercent = value; + else + VideoMaxSizeMb = value; + OnPropertyChanged(); + } + } + + /// Maximum value for the video size NumericUpDown: 99 for %, 4096 for MB. + public decimal VideoSizeMaximum => VideoSizeUnitChoice.Value == VideoSizeUnit.Percent ? 99 : 4096; + public decimal VideoSizeIncrement => 1; + public string VideoSizeFormat => VideoSizeUnitChoice.Value == VideoSizeUnit.Percent ? "0" : "0.#"; [ObservableProperty] private int _resizePercent; [ObservableProperty] private int _longEdge; [ObservableProperty] private int _width; - [ObservableProperty] private int _customWidth; - [ObservableProperty] private int _customHeight; + /// With Custom: the box, in px; one of them may be left empty while the aspect is kept (#1270). + [ObservableProperty, NotifyPropertyChangedFor(nameof(CustomSizeError), nameof(IsValid))] private int? _customWidth; + [ObservableProperty, NotifyPropertyChangedFor(nameof(CustomSizeError), nameof(IsValid))] private int? _customHeight; /// With Custom: keep each file's shape and fit inside, instead of stretching (ImageOptions.LockAspect). - [ObservableProperty] private bool _lockAspect; + [ObservableProperty, NotifyPropertyChangedFor(nameof(CustomSizeError), nameof(IsValid))] private bool _lockAspect; + /// With Custom and the aspect kept: never enlarge a picture that already fits (CustomImageSize.ShrinkOnly). + [ObservableProperty] private bool _shrinkOnly; /// With MinShortEdge: the shortest the shorter edge may be (ImageOptions.MinShortEdge). [ObservableProperty] private int _minShortEdge; [ObservableProperty] private bool _setDpi; @@ -506,11 +835,42 @@ public bool ColorProfileChecked [ObservableProperty] private bool _webpLossless; [ObservableProperty] private bool _multiPageTiff; [ObservableProperty] private string _icoSizes; - [ObservableProperty] private bool _merge; + [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowAskPages), nameof(ShowAskPagesHint), nameof(ShowSourceBookmarks), + nameof(ShowMergePaper), nameof(ShowMergePaperSettings), nameof(ShowAskCompressionPdf))] + private bool _merge; + [ObservableProperty] private bool _sourceBookmarks; + + /// Fit all merged pages to one paper without changing the image or N-up page settings. + [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowMergePaperSettings))] + private bool _normalizeMergePaper; + + /// The shared paper of the merged PDF, retained while its controls are hidden. + [ObservableProperty] private Choice _mergePaper; + + /// The shared orientation of the merged PDF, chosen once when automatic. + [ObservableProperty] private Choice _mergeOrientation; [ObservableProperty] private double _marginMm; [ObservableProperty] private int _renderDpi; [ObservableProperty] private string _pageRange; - [ObservableProperty] private bool _splitPages; + + /// "Ask every time" for the pages (PdfOptions.AskPageRange, #981). + [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowAskPagesHint))] + private bool _askPageRange; + + /// One PDF, one file per page or several pages per file (PdfOptions.SplitPages, SplitEvery, SplitParts). + [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPageGroups))] + private Choice _pageOutput; + + partial void OnPageOutputChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => PageOutput = v); + + /// With several pages per file: the number is the pages per file, or the equal parts. + [ObservableProperty] private Choice _groupKind; + + partial void OnGroupKindChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => GroupKind = v); + + [ObservableProperty] private int _groupSize; [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPdfCompressionOptions))] private Choice _compressionLevel; @@ -536,7 +896,7 @@ partial void OnPdfPasswordChanged(string value) /// Recognize the text of scans and pictures (PdfOptions.Ocr), in . [ObservableProperty] - [NotifyPropertyChangedFor(nameof(ShowPdfSplit), nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowPageSize))] + [NotifyPropertyChangedFor(nameof(ShowPdfSplit), nameof(ShowPageGroups), nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions), nameof(ShowPageSize))] private bool _ocr; /// @@ -544,7 +904,72 @@ partial void OnPdfPasswordChanged(string value) /// file per page, compression (and with it removing metadata), page size and margin don't apply and are hidden. /// private bool Recognizes => ShowOcr && Ocr; - [ObservableProperty] private Choice _ocrLanguage; + [ObservableProperty] private OcrLanguageChoice _ocrLanguage; + + /// Picked in the "add a language" list, until adds it. + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(AddOcrLanguageCommand))] + private OcrLanguageChoice? _ocrLanguageToAdd; + + public bool HasMoreOcrLanguages => MoreOcrLanguages.Count > 0; + + [RelayCommand(CanExecute = nameof(CanAddOcrLanguage))] + private void AddOcrLanguage() + { + if (OcrLanguageToAdd is not { } language) + return; + OcrLanguageToAdd = null; + MoreOcrLanguages.Add(language); + } + + private bool CanAddOcrLanguage() => OcrLanguageToAdd is not null; + + [RelayCommand] + private void RemoveOcrLanguage(OcrLanguageChoice language) => MoreOcrLanguages.Remove(language); + + partial void OnOcrLanguageChanged(OcrLanguageChoice? oldValue, OcrLanguageChoice newValue) + { + if (Choices.Restore(oldValue, newValue, v => OcrLanguage = v)) + return; + // An added language made the main one trades places with it: the text still has the old main language. + if (oldValue is not null && MoreOcrLanguages.IndexOf(newValue) is >= 0 and var index) + MoreOcrLanguages[index] = oldValue; + RefreshOcrLanguagesToAdd(); + } + + partial void OnOcrLanguageToAddChanged(OcrLanguageChoice? value) => ShowOcrDownloads(); + + private void RefreshOcrLanguagesToAdd() + { + // In place, not cleared and filled again: a combo box drops its selection with its items, and a language picked + // but not added yet stays picked while it is still in the list. + var available = OcrLanguageChoices.Where(l => l != OcrLanguage && !MoreOcrLanguages.Contains(l)).ToList(); + for (var i = OcrLanguagesToAdd.Count - 1; i >= 0; i--) + { + if (!available.Contains(OcrLanguagesToAdd[i])) + OcrLanguagesToAdd.RemoveAt(i); + } + for (var i = 0; i < available.Count; i++) + { + if (i == OcrLanguagesToAdd.Count || OcrLanguagesToAdd[i] != available[i]) + OcrLanguagesToAdd.Insert(i, available[i]); + } + if (OcrLanguageToAdd is { } picked && !available.Contains(picked)) + OcrLanguageToAdd = null; + OnPropertyChanged(nameof(HasMoreOcrLanguages)); + ShowOcrDownloads(); + } + + /// + /// One language Apple Vision doesn't read sends all the chosen ones to Tesseract, which needs the data of each + /// (VisionConverter): then the languages Vision reads show their download too. Off a Mac that is always so. + /// + private void ShowOcrDownloads() + { + var tesseractReads = !OcrLanguage.VisionReads || MoreOcrLanguages.Any(l => !l.VisionReads) || OcrLanguageToAdd is { VisionReads: false }; + foreach (var language in OcrLanguageChoices) + language.ShowDownload(tesseractReads); + } /// PDF → image: one tall image of all pages. [ObservableProperty] private bool _combinePages; @@ -566,20 +991,71 @@ partial void OnPdfPasswordChanged(string value) [ObservableProperty] private bool _zipResult; /// The result takes the original's place, which goes to the Recycle Bin / Trash (OutputRule.ReplaceOriginal). [ObservableProperty] private bool _replaceOriginal; + /// The original goes to the Recycle Bin / Trash after a conversion to another format (OutputRule.TrashOriginalAfterConvert, #1387). + [ObservableProperty] private bool _trashOriginal; + /// Copy to folder: the files are moved instead of copied (OutputRule.MoveInsteadOfCopy, #856). + [ObservableProperty, NotifyPropertyChangedFor(nameof(CopyHint), nameof(CopyAction))] + private bool _moveInsteadOfCopy; + + /// Copy to folder's Action: copy (the default) or move. + public IReadOnlyList> CopyActions => + [new(false, _loc["presets.copy_to_folder"]), new(true, _loc["presets.move_to_folder"])]; + + public Choice CopyAction + { + get => CopyActions[MoveInsteadOfCopy ? 1 : 0]; + set + { + if (value is not null) + MoveInsteadOfCopy = value.Value; + } + } + + /// What Copy to folder does with the originals, as the box below it is set. + public string CopyHint => _loc[MoveInsteadOfCopy ? "presets.move_hint" : "presets.copy_hint"]; [ObservableProperty] private Choice _mediaQuality; [ObservableProperty] private Choice _maxHeight; + [ObservableProperty] private Choice _cropFrame; + + /// "Pages per sheet" (#737), for the presets that make sheets (). + [ObservableProperty] private Choice _pagesPerSheet; + [ObservableProperty] private Choice _sheetPaper; + [ObservableProperty] private Choice _sheetOrientation; + [ObservableProperty] private Choice _sheetOrder; + [ObservableProperty] private double _sheetMarginMm; + [ObservableProperty] private double _sheetGapMm; + [ObservableProperty] private bool _sheetBorders; [ObservableProperty] private Choice _audioBitrate; [ObservableProperty] private Choice _audioChannels; [ObservableProperty] private Choice _sampleRate; [ObservableProperty] private Choice _wavFormat; [ObservableProperty] private bool _removeAudio; + /// One video or several parts (MediaOptions.SplitEverySeconds, SplitParts). + [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowVideoParts))] + private Choice _videoOutput; + + partial void OnVideoOutputChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => VideoOutput = v); + + /// With several parts: the number is seconds or minutes per part, or the equal parts. + [ObservableProperty] private Choice _videoSplitKind; + + partial void OnVideoSplitKindChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => VideoSplitKind = v); + + [ObservableProperty] private int _videoSplitSize; + /// Encode H.264 / HEVC / AV1 on the graphics chip when one works (MediaOptions.HardwareEncoding). [ObservableProperty] private bool _hardwareEncoding; /// Burn subtitles from speech recognized by Whisper AI (MediaOptions.Caption). [ObservableProperty] private bool _caption; /// Language spoken in the audio for Whisper transcription (MediaOptions.SpokenLanguage). [ObservableProperty] private Choice _spokenLanguage; + [ObservableProperty] private Choice _isoFileSystem; + + partial void OnIsoFileSystemChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, value => IsoFileSystem = value); [ObservableProperty] private Choice _archiveLevel; [ObservableProperty] private bool _combineIntoOne; [ObservableProperty] private bool _saveEveryFrame; @@ -603,11 +1079,30 @@ partial void OnPdfPasswordChanged(string value) [ObservableProperty] private int _traceColors; [ObservableProperty] private Choice _cadVersion; [ObservableProperty] private Choice _cadColors; + [ObservableProperty] private Choice _gcodeView; [ObservableProperty] private int _traceDetail; [ObservableProperty] private Choice _animationSpeed; // A combo box that loses its selection sets null: every choice keeps its value (see Choices.Restore). - partial void OnTargetChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => Target = v); + partial void OnTargetChanged(Choice? oldValue, Choice newValue) + { + Choices.Restore(oldValue, newValue, v => Target = v); + OnPropertyChanged(nameof(TargetSelection)); + } + + partial void OnVideoSizeUnitChoiceChanged(Choice? oldValue, Choice newValue) + { + if (Choices.Restore(oldValue, newValue, v => VideoSizeUnitChoice = v) || oldValue is null || oldValue.Value == newValue.Value) + return; + var toPercent = newValue.Value == VideoSizeUnit.Percent; + if (!toPercent) + OnPropertyChanged(nameof(VideoSizeMaximum)); + OnPropertyChanged(nameof(VideoSizeIncrement)); + OnPropertyChanged(nameof(VideoSizeFormat)); + OnPropertyChanged(nameof(VideoMaxSize)); + if (toPercent) + OnPropertyChanged(nameof(VideoSizeMaximum)); + } /// /// Both ends keep their size in the other unit: 500 KB becomes 0.5 MB. The boxes' maximum is raised before the @@ -638,6 +1133,16 @@ partial void OnFitsTiffModeChanged(Choice? oldValue, Choice FitsTiffMode = v); partial void OnMediaQualityChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => MediaQuality = v); partial void OnMaxHeightChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => MaxHeight = v); + partial void OnCropFrameChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => CropFrame = v); + partial void OnPagesPerSheetChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => PagesPerSheet = v); + partial void OnSheetPaperChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => SheetPaper = v); + partial void OnSheetOrientationChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => SheetOrientation = v); + partial void OnMergePaperChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => MergePaper = v); + partial void OnMergeOrientationChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, v => MergeOrientation = v); + partial void OnSheetOrderChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => SheetOrder = v); partial void OnAudioBitrateChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => AudioBitrate = v); partial void OnAudioChannelsChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => AudioChannels = v); partial void OnSampleRateChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => SampleRate = v); @@ -646,6 +1151,7 @@ partial void OnFitsTiffModeChanged(Choice? oldValue, Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => TraceMode = v); partial void OnCadVersionChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => CadVersion = v); partial void OnCadColorsChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => CadColors = v); + partial void OnGcodeViewChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => GcodeView = v); partial void OnCompressionLevelChanged(Choice? oldValue, Choice newValue) => Choices.Restore(oldValue, newValue, v => CompressionLevel = v); partial void OnAnimationSpeedChanged(Choice? oldValue, Choice newValue) => @@ -688,15 +1194,46 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne /// "Save as ZIP" is offered for geospatial targets, whose results are several files (a Shapefile) or travel zipped. public bool ShowZipResult => TargetCategory == FormatCategory.Geo; public bool ShowPdfBuild => TargetId == "pdf"; + public bool ShowSourceBookmarks => ShowPdfBuild && Merge; + + /// The merge paper option is offered only for a merged PDF. + public bool ShowMergePaper => ShowPdfBuild && Merge; + + /// The shared paper and orientation are shown only while fitting is enabled. + public bool ShowMergePaperSettings => ShowMergePaper && NormalizeMergePaper; /// Page size and margin of a PDF built from pictures; not with text recognition (). public bool ShowPageSize => ShowPdfBuild && !Recognizes; public bool ShowPdfSplit => TargetId == "pdf" && !Recognizes; + public bool ShowPageGroups => ShowPdfSplit && PageOutput.Value == ViewModels.PageOutput.Groups; + + /// + /// "Ask every time" under Pages: wherever the pages are, except a merge, where one range would go for every file + /// (AskedPages.Asks). + /// + public bool ShowAskPages => ShowPdf && !(TargetId == "pdf" && Merge); + public bool ShowAskPagesHint => ShowAskPages && AskPageRange; + + /// + /// "Ask every time" for the compression (Preset.AskCompression, #1353), under the setting it asks for: the picture + /// quality, the video quality and audio bitrate, or the PDF level. Not for a merge (AskedCompression.Asks). + /// + [ObservableProperty] + private bool _askCompression; + + /// + /// Only for the targets the window can estimate (AskedCompression.LossyImageTargets) or the source's own format: + /// a HEIC target keeps its quality slider, but would never open the window. + /// + public bool ShowAskCompressionImage => ShowImage && ShowQuality && !_original.JoinsImages + && (TargetId == BuiltInData.SameAsSource || AskedCompression.LossyImageTargets.Contains(TargetId)); + public bool ShowAskCompressionMedia => !IsTool && ShowMediaQuality && !_original.JoinsIntoOneMedia; + public bool ShowAskCompressionPdf => ShowPdfCompression && !Merge; /// Compression is for PDF → PDF; Ghostscript and metadata only matter while it is on. public bool ShowPdfCompression => TargetId == "pdf" && !Recognizes; - /// XLSX: what a PDF becomes (its ruled tables, PdfTablesConverter). + /// XLSX: what a PDF, a Word document or a web page becomes (its tables, PdfTablesConverter and DocumentTablesConverter). public bool ShowPdfTablesNote => TargetId == "xlsx"; public bool ShowPdfCompressionOptions => ShowPdfCompression && CompressionLevel.Value != PdfCompression.None; @@ -709,7 +1246,10 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne public bool ShowDocument => TargetId == "pdf"; /// Markdown can't hold pictures: they go into a folder next to it, or are left out. public bool ShowLeaveOutPictures => TargetId == "md"; - public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec || ShowCaption; + public bool ShowMedia => ShowCropFrame || ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec || ShowCaption + || ShowRingtone; + /// An iPhone ringtone (M4R) is a part of the sound of at most 40 s: where it starts and how long it is. + public bool ShowRingtone => !IsTool && TargetId == "m4r"; /// Mono / stereo for every audio target but AMR, which is mono by definition. public bool ShowAudioChannels => TargetIsAudio && TargetId != "amr"; /// Sample rate and sample format: the PCM of WAV and W64 takes any. @@ -718,19 +1258,34 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne public bool ShowVideoCodec => TargetIsVideo && VideoCodecs.Count > 1; /// Hardware encoding applies to H.264, HEVC and AV1 only (not VP9, MPEG-2, …). public bool ShowHardwareEncoding => TargetIsVideo && MediaCodecs.TakesHardwareEncoding(TargetId, _videoCodecValue); - /// Generate Whisper AI subtitles for speech. - public bool ShowCaption => TargetId == "srt"; + /// Generate Whisper AI subtitles for speech, or its text alone for TXT. + public bool ShowCaption => MediaOptions.CaptionTargets.Contains(TargetId); /// M4A / M4B can hold Apple Lossless besides AAC. public bool ShowAudioCodec => AudioCodecs.Count > 1; public bool ShowMediaQuality => TargetIsLossyMedia; public bool ShowMaxHeight => TargetIsVideo; + /// "Crop video" presets (#830), which keep the video's own format. + public bool ShowCropFrame => _original.CropsVideo; + + /// "Pages per sheet": shown for the presets that put several PDF pages on a sheet, while they write a PDF. + public bool ShowSheets => ShowPdfBuild && _original.Pdf.MakesSheets; /// A size limit for a converted video; a clip is cut, not fitted. public bool ShowVideoMaxSize => TargetCategory == FormatCategory.Video && !_original.IsClipTool // Not where nothing fits it: a join or slideshow, or VOB and DV, which have a fixed bitrate. && !_original.Media.JoinIntoOne && !_isSlideshow && TargetId is not ("vob" or "dv"); public bool ShowAudioBitrate => TargetIsLossyMedia; public bool ShowRemoveAudio => TargetIsVideo; - public bool ShowArchive => TargetCategory == FormatCategory.Archive; + + /// + /// Split into parts (#1259): a video converted to a video. Not for a tool (a clip is cut, not split), a join, a + /// slideshow or "Crop video", which make one file of their own. + /// + public bool ShowVideoSplit => TargetCategory == FormatCategory.Video && !IsTool && !_original.Media.JoinIntoOne && !_isSlideshow + && !ShowCropFrame; + public bool ShowVideoParts => ShowVideoSplit && VideoOutput.Value; + /// ISO creation has no archive compression settings. + public bool ShowIso => TargetId == "iso"; + public bool ShowArchive => TargetCategory == FormatCategory.Archive && TargetId != "iso"; public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder; /// "Extract" has nothing to set; a line says what it does instead. public bool ShowExtractNote => TargetId == FormatRegistry.Folder; @@ -741,10 +1296,10 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne /// The video of a Live / Motion Photo: MP4 and MOV (). public bool ShowExtractMotionPhoto => !IsTool && MediaOptions.MotionPhotoTargets.Contains(TargetId); /// - /// Playback speed: for the formats an animation stays animated in (an animated GIF, WebP, APNG or MNG, or a video - /// made into a GIF or APNG). Other targets get one frame. + /// Playback speed: for the formats an animation stays animated in (an animated GIF, WebP, APNG, MNG or AVIF, or a + /// video made into a GIF or APNG). Other targets get one frame. /// - public bool ShowAnimationSpeed => TargetId is "gif" or "webp" or "apng" or "mng" or BuiltInData.SameAsSource; + public bool ShowAnimationSpeed => TargetId is "gif" or "webp" or "apng" or "mng" or "jxl" or "avif" or BuiltInData.SameAsSource; /// /// Tracing options: raster images reach SVG (and DXF / DWG through it) only by tracing. For other sources (a /// drawing, a CAD file) the options are ignored. @@ -756,6 +1311,9 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne /// The colours, for the targets a DWG or DXF is drawn into: PDF, SVG and pictures. public bool ShowCadColors => !IsTool && (TargetId is "pdf" or "svg" || TargetCategory == FormatCategory.Image); + + /// The G-code view, for the targets a toolpath is drawn into, while the 3D or CAD field is on. + public bool ShowGcode => _gcodeShown && ShowCadColors; public bool ShowTraceColors => TraceMode.Value == TracingMode.Color; public bool ShowPercent => Resize.Value == ResizeMode.Percent; public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge; @@ -770,7 +1328,14 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne private static double SizeLimit(decimal? megabytes) => (double)Math.Clamp(megabytes ?? 0, 0, 4096); public string? NameError => string.IsNullOrWhiteSpace(Name) ? _loc["presets.name_required"] : null; - public bool IsValid => NameError is null && SizeRangeError is null && DestinationError is null; + public bool IsValid => NameError is null && SizeRangeError is null && DestinationError is null && CustomSizeError is null; + + /// + /// The width × height boxes, while shown: a stretch needs both sides, a box that keeps the aspect at least one. + /// + public string? CustomSizeError => ShowImage && ShowCustom && (LockAspect ? CustomWidth is null && CustomHeight is null : CustomWidth is null || CustomHeight is null) + ? _loc["presets.custom_size_missing"] + : null; /// A size from the range's boxes in megabytes. private decimal? Megabytes(decimal? size) => ImageSizeUnit.Value == FileSizeUnit.KB ? size / 1000 : size; @@ -784,6 +1349,7 @@ public bool Apply() // Keep a built-in preset's translatable name unless the user actually renamed it. if (_original.NameKey is null || Name.Trim() != _loc.DisplayName(_original)) _original.Name = Name.Trim(); + Labels.Apply(_original); _original.TargetFormat = TargetId; var image = _original.Image; @@ -791,13 +1357,20 @@ public bool Apply() // Only where the field is shown, as with SaveEveryFrame below: a limit left behind by a JPG target fits nothing. image.MaxSizeMb = ShowQuality ? SizeLimit(Megabytes(ImageMaxSize)) : 0; image.MinSizeMb = ShowImageSize ? SizeLimit(Megabytes(ImageMinSize)) : 0; + image.MaxSizeKeepsPixels = image.MaxSizeMb > 0 && MaxSizeKeepsPixels; if (Resize.Value == ResizeMode.Custom) { // Custom sizing is stored as CustomSize with Resize None, never as a resize name an older version rejects // (it would read presets.json as broken and fall back to the built-in presets, and the next save would // write those over the user's own; issue #576). image.Resize = ResizeMode.None; - image.CustomSize = new CustomImageSize { Width = Math.Clamp(CustomWidth, CustomImageSize.MinSide, CustomImageSize.MaxSide), Height = Math.Clamp(CustomHeight, CustomImageSize.MinSide, CustomImageSize.MaxSide), LockAspect = LockAspect }; + // An empty side is free with the aspect kept (#1270). The card can be hidden for another target, where a box + // nobody can fix falls back to the defaults instead of blocking the save. + var (width, height) = (CustomWidth, CustomHeight); + if (!LockAspect || width is null && height is null) + (width, height) = (width ?? 1920, height ?? 1080); + static int Side(int? side) => side is { } px ? Math.Clamp(px, CustomImageSize.MinSide, CustomImageSize.MaxSide) : CustomImageSize.FreeSide; + image.CustomSize = new CustomImageSize { Width = Side(width), Height = Side(height), LockAspect = LockAspect, ShrinkOnly = LockAspect && ShrinkOnly }; image.MinShortEdge = null; } else if (Resize.Value == ResizeMode.MinShortEdge) @@ -845,16 +1418,36 @@ public bool Apply() var pdf = _original.Pdf; pdf.MergeIntoSingle = Merge; + pdf.SourceBookmarks = SourceBookmarks; + pdf.NormalizeMergePaper = NormalizeMergePaper; + pdf.MergePaper = MergePaper.Value; + pdf.MergeOrientation = MergeOrientation.Value; pdf.PageSize = PageSize.Value; pdf.MarginMm = Math.Clamp(MarginMm, 0, 100); pdf.RenderDpi = Math.Clamp(RenderDpi, 36, 1200); - pdf.PageRange = PageRange.Trim(); - pdf.SplitPages = SplitPages; + pdf.PageRange = Filee.Core.Conversion.PageRange.Check(PageRange, null) is { IsValid: true } checkedRange ? checkedRange.Text : PageRange.Trim(); + pdf.AskPageRange = ShowAskPages && AskPageRange; + _original.AskCompression = AskCompression && (ShowAskCompressionImage || ShowAskCompressionMedia || ShowAskCompressionPdf); + var (split, every, parts) = PageOutputs.Settings(PageOutput.Value, GroupKind.Value, GroupSize); + pdf.SplitPages = split; + // One PDF keeps the numbers of a split, as the pages window does, for when it is chosen again. + if (split) + (pdf.SplitEvery, pdf.SplitParts) = (every, parts); pdf.CombinePages = CombinePages; pdf.TrimPageMargins = TrimPageMargins; pdf.SplitTallImage = SplitTallImage; pdf.Compression = CompressionLevel.Value; pdf.CompressWithGhostscript = CompressWithGhostscript; + if (ShowSheets) + { + pdf.PagesPerSheet = PagesPerSheet.Value; + pdf.SheetPaper = SheetPaper.Value; + pdf.SheetOrientation = SheetOrientation.Value; + pdf.SheetOrder = SheetOrder.Value; + pdf.SheetMarginMm = Math.Clamp(SheetMarginMm, 0, 50); + pdf.SheetGapMm = Math.Clamp(SheetGapMm, 0, 50); + pdf.SheetBorders = SheetBorders; + } // Only for a PDF target, where they are shown: a password left behind by it must not lock nothing. pdf.Watermark = ShowPdfBuild ? Watermark.Trim() : ""; pdf.PageNumbers = ShowPdfBuild && PageNumbers; @@ -863,7 +1456,8 @@ public bool Apply() pdf.PasswordLeftOut = false; // Only where the option is shown, as with SaveEveryFrame below. pdf.Ocr = Recognizes; - pdf.OcrLanguage = OcrLanguage.Value; + AddOcrLanguage(); // picked in the list without pressing Add: it looks chosen, so it counts + pdf.OcrLanguage = OcrLanguages.Join([OcrLanguage.Value, .. MoreOcrLanguages.Select(l => l.Value)]); if (pdf.Ocr) { // Hidden while text is recognized, so nothing is kept behind it that the PDF wouldn't do (Recognizes). @@ -880,9 +1474,35 @@ public bool Apply() var media = _original.Media; media.Quality = MediaQuality.Value; media.MaxHeight = MaxHeight.Value; - media.MaxSizeMb = ShowVideoMaxSize ? SizeLimit(VideoMaxSizeMb) : 0; + if (ShowCropFrame) + media.CropFrame = CropFrame.Value; + if (ShowVideoMaxSize) + { + if (VideoSizeUnitChoice.Value == VideoSizeUnit.Percent) + { + media.MaxSizeMb = 0; + media.MaxSizePercent = VideoMaxSizePercent is > 0 and < 100 ? (int)Math.Clamp(VideoMaxSizePercent.Value, 1, 99) : 0; + } + else + { + media.MaxSizePercent = 0; + media.MaxSizeMb = SizeLimit(VideoMaxSizeMb); + } + } + else + { + media.MaxSizeMb = 0; + media.MaxSizePercent = 0; + } media.AudioBitrateKbps = AudioBitrate.Value; media.RemoveAudio = RemoveAudio; + // Only where the option is shown, as with SaveEveryFrame below. + (media.SplitEverySeconds, media.SplitParts) = !ShowVideoParts ? (0, 0) : VideoSplitKind.Value switch + { + ViewModels.VideoSplitKind.EqualParts => (0, Math.Clamp(VideoSplitSize, 2, MediaOptions.MaxSplitParts)), + ViewModels.VideoSplitKind.Minutes => (Math.Clamp(VideoSplitSize, 1, 24 * 60) * 60, 0), + _ => (Math.Clamp(VideoSplitSize, 1, 24 * 3600), 0), + }; media.AudioChannels = AudioChannels.Value; media.AudioSampleRate = SampleRate.Value; media.WavFormat = WavFormat.Value; @@ -909,8 +1529,12 @@ static double Seconds(double value, double fallback, double min, double max) => media.LivePhotoStart = Seconds(LivePhotoStart, 0, 0, 24 * 3600); media.LivePhotoLength = Seconds(LivePhotoLength, 3, MediaOptions.MinLivePhotoLength, MediaOptions.MaxLivePhotoLength); media.LivePhotoCover = Seconds(LivePhotoCover, 1.5, 0, MediaOptions.MaxLivePhotoLength); + media.RingtoneStart = Seconds(RingtoneStart, 0, 0, 24 * 3600); + media.RingtoneLength = Seconds(RingtoneLength, MediaOptions.DefaultRingtoneLength, MediaOptions.MinRingtoneLength, MediaOptions.MaxRingtoneLength); + media.AskRingtonePart = ShowRingtone && AskRingtonePart; + _original.Archive.IsoFileSystem = IsoFileSystem.Value; _original.Archive.Level = ArchiveLevel.Value; - _original.Archive.CombineIntoOne = CombineIntoOne; + _original.Archive.CombineIntoOne = TargetId != "iso" && CombineIntoOne; _original.Trace.Mode = TraceMode.Value; _original.Trace.Colors = Math.Clamp(TraceColors, TracingOptions.MinColors, TracingOptions.MaxColors); _original.Trace.Detail = Math.Clamp(TraceDetail, 0, 100); @@ -918,6 +1542,16 @@ static double Seconds(double value, double fallback, double min, double max) => // black and white chosen for PDF and left behind by a DWG target. _original.Cad.Version = ShowCad ? CadVersion.Value : default; _original.Cad.Colors = ShowCadColors ? CadColors.Value : default; + // A view kept while the card is hidden by the field switches: turning them on again shows it unchanged. + _original.Gcode.View = ShowCadColors ? GcodeView.Value : default; + _original.Translate.TargetLanguage = TargetLanguage.Value; + _original.Translate.Enabled = ShowTranslate; + if (ShowUpscale) + { + _original.Upscale.Enabled = true; + _original.Upscale.Model = SelectedUpscaleModel?.Id; + _original.Upscale.Scale = UpscaleScale; + } var output = _original.Output; // Asking keeps the location it had: a Filee that can't ask (or one from before it) saves there. @@ -933,7 +1567,9 @@ static double Seconds(double value, double fallback, double min, double max) => output.KeepDates = KeepDates; // Only for geospatial targets, where it is offered: a box ticked for Shapefile must not zip a later PNG. output.ZipResult = ShowZipResult && ZipResult; - output.ReplaceOriginal = !IsCopyToFolder && ReplaceOriginal; + output.ReplaceOriginal = ShowReplaceOriginal && ReplaceOriginal; + output.TrashOriginalAfterConvert = ShowReplaceOriginal && TrashOriginal; + output.MoveInsteadOfCopy = IsCopyToFolder && MoveInsteadOfCopy; return true; } From 978ade4d24d3587bfec45f8e329cf9415755156d Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Tue, 17 Nov 2026 16:42:51 +0000 Subject: [PATCH 3/9] Add files via upload --- tests/Filee.Core.Tests/SmallParsersTests.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/Filee.Core.Tests/SmallParsersTests.cs b/tests/Filee.Core.Tests/SmallParsersTests.cs index 395bd0b67..195b3372f 100644 --- a/tests/Filee.Core.Tests/SmallParsersTests.cs +++ b/tests/Filee.Core.Tests/SmallParsersTests.cs @@ -16,6 +16,12 @@ public class PageRangeTests [InlineData("4-2", 5, new[] { 1, 2, 3 })] [InlineData("9-12", 5, new[] { 0, 1, 2, 3, 4 })] // nothing valid → everything [InlineData("x, 2", 5, new[] { 1 })] + [InlineData("2\u20135", 10, new[] { 1, 2, 3, 4 })] // en dash + [InlineData("2\u20145", 10, new[] { 1, 2, 3, 4 })] // em dash + [InlineData("\u0662-\u0665", 10, new[] { 1, 2, 3, 4 })] // Arabic-Indic digits + [InlineData("\uFF12\uFF0D\uFF14", 10, new[] { 1, 2, 3 })] // full-width digits and dash + [InlineData("1\u060C3", 10, new[] { 0, 2 })] // Arabic comma + [InlineData("1\uFF0C3", 10, new[] { 0, 2 })] // full-width comma public void Parses_ranges(string expression, int pages, int[] expected) => Assert.Equal(expected, PageRange.Parse(expression, pages)); } @@ -35,6 +41,7 @@ public class FormatRegistryTests [InlineData("archive.7z.001", "split")] [InlineData("archive.zip.001", "split")] [InlineData("archive.tar.001", "split")] + [InlineData("sketch.kra~", "kra")] // Krita's backup of the previous save public void Detects_formats(string path, string id) => Assert.Equal(id, FormatRegistry.Detect(path)?.Id); [Fact] From 1b0ee6da88f2f0e83170af5fd0bcc7857a52eabd Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Tue, 17 Nov 2026 16:43:15 +0000 Subject: [PATCH 4/9] Add files via upload --- src/Filee.Core/Conversion/JobQueue.cs | 331 ++++++++++++++++++++++---- 1 file changed, 288 insertions(+), 43 deletions(-) diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs index 2c0506110..23e02ee3d 100644 --- a/src/Filee.Core/Conversion/JobQueue.cs +++ b/src/Filee.Core/Conversion/JobQueue.cs @@ -4,6 +4,7 @@ using System.Collections.Concurrent; using System.Threading.Channels; using Filee.Core.Formats; +using Filee.Core.Platform; using Filee.Core.Presets; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -31,6 +32,8 @@ public sealed partial class JobQueue : IAsyncDisposable private readonly Task _worker; private readonly Func? _moveToTrash; private int _busy; + /// The jobs that wait in the queue or run: "Move the original to the Trash" keeps a source another one still lists (#1387). + private readonly List _live = []; /// Converters and their priority. /// Used by "Merge into one PDF" presets. @@ -66,10 +69,13 @@ public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger< /// Adds a job to the queue and returns it immediately. /// Saves sources that aren't files yet (files from a browser) when the job runs. - public ConversionJob Enqueue(IReadOnlyList sources, Preset preset, string presetDisplayName, ISourceFetcher? fetcher = null) + public ConversionJob Enqueue(IReadOnlyList sources, Preset preset, string presetDisplayName, ISourceFetcher? fetcher = null, + IReadOnlySet? folderSources = null) { - var job = new ConversionJob(sources, preset, presetDisplayName, fetcher); + var job = new ConversionJob(sources, preset, presetDisplayName, fetcher, folderSources); Interlocked.Increment(ref _busy); // until the worker is done with it + lock (_live) + _live.Add(job); _channel.Writer.TryWrite(job); JobUpdated?.Invoke(this, job); return job; @@ -79,12 +85,19 @@ public ConversionJob Enqueue(IReadOnlyList sources, Preset preset, strin public async Task RunAsync(ConversionJob job) { Interlocked.Increment(ref _busy); + lock (_live) + { + if (!_live.Contains(job)) + _live.Add(job); + } try { await RunJobAsync(job); } finally { + lock (_live) + _live.Remove(job); Interlocked.Decrement(ref _busy); } } @@ -259,10 +272,41 @@ private async Task FinishPdfsAsync(Preset preset, IReadOnlyList outputs, await finisher.FinishAsync(pdf, preset.Pdf, ct); } + /// + /// Makes the PDFs among PDF/A when the preset asks for it (), + /// after the finishing, which would undo it. Without Ghostscript they stay as they are and the file says so, rather + /// than pass for PDF/A. Otherwise the file says when form fields were made page content, which can't be filled in. + /// + /// Rewritten since the engine wrote it: a PDF/A from LibreOffice no longer is one. + private async Task ArchivePdfsAsync(Preset preset, IReadOnlyList outputs, FileResult file, string workDir, bool changed, + CancellationToken ct) + { + if (!preset.Document.PdfA) + return; + var archiver = _catalog.All.OfType().FirstOrDefault(); + var notArchived = false; + var withoutFormFields = false; + foreach (var pdf in outputs.Where(o => FormatRegistry.Detect(o)?.Id == "pdf")) + { + var outcome = archiver is null ? PdfArchiveOutcome.NotArchived : await archiver.ArchiveAsync(pdf, changed, workDir, ct); + notArchived |= outcome == PdfArchiveOutcome.NotArchived; + withoutFormFields |= outcome == PdfArchiveOutcome.ArchivedWithoutFormFields; + } + // A PDF that didn't become PDF/A matters more than fields that can't be filled in any more. + if (notArchived) + file.NoticeKey = "notice.pdfa_needs_ghostscript"; + else if (withoutFormFields) + { + file.NoticeKey = "notice.pdfa_form_fields"; + file.NoticeReasonKey = null; + file.NoticeDetail = null; + } + } + /// Converts every file to PDF in the work directory, then merges them into one output. private async Task RunMergedAsync(ConversionJob job, RoutePlanner planner, string workDir) { - var parts = new string?[job.Files.Count]; + var parts = new PdfMergeInput?[job.Files.Count]; await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async (i, _) => @@ -278,14 +322,15 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), if (job.Preset.Image.ReworksPixels) FailUnturned(job, file, "pdf → pdf"); else - parts[i] = file.SourcePath; + parts[i] = new(file.SourcePath, Path.GetFileName(file.SourcePath)); return; } var produced = await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false); - parts[i] = produced.FirstOrDefault(); + if (produced.FirstOrDefault() is { } pdfPath) + parts[i] = new(pdfPath, Path.GetFileName(file.SourcePath)); }); - var inputs = parts.OfType().ToList(); + var inputs = parts.OfType().ToList(); if (inputs.Count == 0 || job.CancellationToken.IsCancellationRequested) return; @@ -300,14 +345,39 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), try { - await _pdfMerger!.MergeAsync(inputs, output, job.CancellationToken); - // Once for the merged PDF, so its pages are numbered through. + var pdf = job.Preset.Pdf; + PdfMergePaper? paper = pdf.NormalizeMergePaper ? new(pdf.MergePaper, pdf.MergeOrientation) : null; + await _pdfMerger!.MergeAsync(inputs, output, pdf.SourceBookmarks, paper, job.CancellationToken); + // Once for the merged PDF, so its pages are numbered through. PDFsharp wrote it, so it is no PDF/A yet. await FinishPdfsAsync(job.Preset, [output], job.CancellationToken); + await ArchivePdfsAsync(job.Preset, [output], first, workDir, changed: true, job.CancellationToken); } - catch + catch (ConversionRefusedException ex) { + // A refusal (a page the paper size can't be fitted to, say) is told on every merged file, as joining does. allocator.Discard(); - throw; + _log.LogInformation("Merging {Count} file(s) into {Output} was refused: {Reason}", inputs.Count, output, ex.Message); + foreach (var f in job.Files.Where(f => !Stopped(f))) + FailFile(job, f, ex.ErrorKey, ex.Detail); + return; + } + catch (OperationCanceledException) + { + // A cancel while merging is a cancel, not a failure of the job. + allocator.Discard(); + foreach (var f in job.Files.Where(f => !Stopped(f))) + f.State = FileState.Cancelled; + Notify(job); + return; + } + catch (Exception ex) + { + // Disk full, a locked output, a PDF the merger can't read: told on the merged files instead of failing the job silently. + allocator.Discard(); + _log.LogWarning(ex, "Merging {Count} file(s) into {Output} failed", inputs.Count, output); + foreach (var f in job.Files.Where(f => !Stopped(f))) + FailFile(job, f, "error.conversion_failed", ex.Message); + return; } first.Outputs.Add(output); foreach (var f in job.Files.Where(f => f.State != FileState.Failed)) @@ -356,10 +426,29 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), { await _tiffMerger!.MergeAsync(inputs, output, job.Preset.Image, job.CancellationToken); } - catch + catch (OperationCanceledException) { allocator.Discard(); - throw; + foreach (var f in job.Files.Where(f => !Stopped(f))) + f.State = FileState.Cancelled; + Notify(job); + return; + } + catch (ConversionRefusedException ex) + { + allocator.Discard(); + _log.LogInformation("Merging {Count} file(s) into {Output} was refused: {Reason}", inputs.Count, output, ex.Message); + foreach (var f in job.Files.Where(f => !Stopped(f))) + FailFile(job, f, ex.ErrorKey, ex.Detail); + return; + } + catch (Exception ex) + { + allocator.Discard(); + _log.LogWarning(ex, "Merging {Count} page(s) into {Output} failed", inputs.Count, output); + foreach (var f in job.Files.Where(f => !Stopped(f))) + FailFile(job, f, "error.conversion_failed", ex.Message); + return; } // Not checked against the maximum (as before), but a picture under the minimum gets its notice (#662). if (SizeLimit.IsUnderMinimum(job.Preset, [output])) @@ -397,6 +486,9 @@ private async Task RunJoinedMediaAsync(ConversionJob job, RoutePlanner planner, FailFile(job, f, "error.too_many_pictures", $"{pictures} > {MediaOptions.MaxSlides}"); return; } + // Songs go under videos only: on their own they would make a video of nothing. + var withVideo = !slideshow && target.Category == FormatCategory.Video + && job.Files.Any(f => !Stopped(f) && FormatRegistry.Detect(f.SourcePath)?.Category == FormatCategory.Video); var parts = new IReadOnlyList?[job.Files.Count]; await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, @@ -424,9 +516,10 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), ceiling: PicturesReadyShare); return; } - // A video's sound can join an audio file; a picture or a document joins nothing. + // A video's sound can join an audio file, and an audio file plays as music under videos (#1402); a + // picture or a document joins nothing. var joins = source.Category == FormatCategory.Video - || source.Category == FormatCategory.Audio && target.Category == FormatCategory.Audio; + || source.Category == FormatCategory.Audio && (target.Category == FormatCategory.Audio || withVideo); if (!joins) { FailFile(job, file, "error.no_route", $"{source.Id} → {target.Id}"); @@ -437,6 +530,13 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), var joined = job.Files.Where((f, i) => parts[i] is { Count: > 0 } && f.State != FileState.Failed).ToList(); var inputs = parts.Where(p => p is not null).SelectMany(p => p!).ToList(); + // The merged video is named after its first video, also when a song comes before it in the order. + if (withVideo && joined.FindIndex(f => FormatRegistry.Detect(f.SourcePath)?.Category == FormatCategory.Video) is > 0 and var video) + { + var named = joined[video]; + joined.RemoveAt(video); + joined.Insert(0, named); + } if (inputs.Count == 0 || job.CancellationToken.IsCancellationRequested) { Notify(job); @@ -539,7 +639,7 @@ private async Task WriteJoinedAsync(ConversionJob job, List joined, try { await write(output, progress); - SizeLimit.Check(job.Preset, [output]); // joined media aren't fitted: one over the limit is refused (#553) + SizeLimit.Check(job.Preset, [output], joined.Select(f => f.SourcePath)); // joined media aren't fitted: one over the limit is refused (#553) if (SizeLimit.IsUnderMinimum(job.Preset, [output])) first.UnderMinimumSize = true; first.Outputs.Add(output); @@ -581,11 +681,23 @@ private void FailFile(ConversionJob job, FileResult file, string key, string? de Notify(job); } - /// A file that would be used as it is although the preset turns, mirrors or covers parts of it. + /// + /// Why a file the preset turns, mirrors, covers parts of, draws on or sets on a background can't be: no step of its + /// route changes images. + /// + private static string CannotReworkKey(ImageOptions image) => + image.HidesAreas ? "error.cannot_hide" + : image.HasAnnotations || image.AddsBackdrop ? "error.images_only" + : "error.cannot_turn"; + + /// + /// A file that would be used as it is although the preset turns, mirrors, covers parts of, draws on or sets it on a + /// background. + /// private void FailUnturned(ConversionJob job, FileResult file, string detail) { file.State = FileState.Failed; - file.ErrorKey = job.Preset.Image.HidesAreas ? "error.cannot_hide" : "error.cannot_turn"; + file.ErrorKey = CannotReworkKey(job.Preset.Image); file.ErrorDetail = detail; file.Progress = 1; Notify(job); @@ -650,7 +762,11 @@ private async Task RunCombinedAsync(ConversionJob job, string workDir) files.Add(file); } } + // An archive with a file from the internet in it still came from there, whichever file that was. + var mark = Platform.MarkOfTheWeb.ReadFirst(files, _log, job.CancellationToken); await _combiner!.CombineAsync(files, output, format.Id, job.Preset, workDir, progress, job.CancellationToken); + if (mark is not null && File.Exists(output)) + Platform.MarkOfTheWeb.TryWrite(output, mark, _log); inputs[0].Outputs.Add(output); foreach (var f in inputs) { @@ -751,7 +867,7 @@ private async Task> RunFileAsync( var runWith = options ?? job.Preset; if (Stopped(file)) return []; - var source = FormatRegistry.Detect(file.SourcePath); + var source = file.IsFolder ? FormatRegistry.FindById(FormatRegistry.Folder) : FormatRegistry.Detect(file.SourcePath); if (source is null) return Fail(file, "error.unsupported_source", "." + FormatRegistry.ExtensionOf(file.SourcePath)); // A file just made with "New" in the file manager stays 0 bytes until its app saves it: no engine can read it, @@ -759,30 +875,89 @@ private async Task> RunFileAsync( if (IsEmptyFile(file.SourcePath)) return Fail(file, "error.empty_file", null); + // An envelope (a signed .p7m) is converted as the file inside it: the route opens it first, and everything + // below that depends on the format (same format, frames, OCR, …) asks about the file inside. + var from = source; + var opener = _catalog.All.OfType().FirstOrDefault(o => o.Opens(source.Id)); + if (opener is not null) + { + try + { + from = FormatRegistry.Get(opener.InnerFormat(file.SourcePath, source.Id)); + } + catch (ConversionRefusedException ex) + { + _log.LogInformation("Opening {File} was refused: {Reason}", file.SourcePath, ex.Message); + return Fail(file, ex.ErrorKey, ex.Detail); + } + } + var target = !finalOutput ? intermediate - : runWith.TargetFormat == BuiltInData.SameAsSource ? source.Id + : runWith.TargetFormat == BuiltInData.SameAsSource ? runWith.CropsVideo ? VideoCrop.TargetFor(from.Id) : from.Id : runWith.TargetFormat; + // "Same format as the audio" (#1490): the format that holds the video's sound as it is, read from the file. + if (target == BuiltInData.SameAsAudio) + { + var reader = _catalog.All.OfType().FirstOrDefault(); + if (from.Category != FormatCategory.Video || reader is null || reader is IConverter { } engine && !engine.GetStatus().IsAvailable) + return Fail(file, "error.no_route", $"{from.Id} → mka", new RouteRequest(from.Id, "mka")); + try + { + target = await reader.AudioCopyTargetAsync(file.SourcePath, ct); + } + catch (OperationCanceledException) + { + file.State = FileState.Cancelled; + Notify(job); + return []; + } + catch (ConversionRefusedException ex) + { + return Fail(file, ex.ErrorKey, ex.Detail); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Reading the sound of {File} failed", file.SourcePath); + return Fail(file, "error.conversion_failed", ex.Message); + } + } + // "Save every frame": a video becomes a folder of pictures in one step of its own; "Extract Live/Motion Photo // video" likewise takes a photo's video, and "Live / Motion Photo" makes one of a video. Never for an // intermediate file, and never on the way to another format (video → JPG is otherwise one still frame, photo → // MP4 a video of the still picture). - var frames = finalOutput && runWith.SavesFramesOf(source.Id); - var motionPhoto = finalOutput && runWith.ExtractsMotionOf(source.Id); - var livePhoto = finalOutput && runWith.MakesLivePhotoOf(source.Id); - var caption = finalOutput && runWith.CaptionsVideo(source.Id); + var frames = finalOutput && runWith.SavesFramesOf(from.Id); + var motionPhoto = finalOutput && runWith.ExtractsMotionOf(from.Id); + var livePhoto = finalOutput && runWith.MakesLivePhotoOf(from.Id); + var caption = finalOutput && runWith.CaptionsVideo(from.Id); + var translate = finalOutput && runWith.Translate.Enabled; + if (translate && !runWith.TranslatesDocument(from.Id)) + return Fail(file, "error.no_route", $"{from.Id} → {target}", new RouteRequest(from.Id, target, Translate: true)); + var upscale = finalOutput && runWith.Upscale.Enabled; + if (upscale && !UpscaleTool.CanUpscale(from.Id)) + return Fail(file, "error.no_route", $"{from.Id} → {target}", new RouteRequest(from.Id, target, Upscale: true)); // "Recognize text": Tesseract writes a searchable PDF first, read on into DOCX, TXT, … from there. Also for the // PDFs that are merged into one. - var ocr = (finalOutput || target == "pdf") && runWith.RecognizesTextOf(source.Id); - var route = planner.Plan(source.Id, target, frames, motionPhoto: motionPhoto, livePhoto: livePhoto, ocr: ocr, caption: caption); + var ocr = (finalOutput || target == "pdf") && runWith.RecognizesTextOf(from.Id); + // "Metadata": only an engine that writes the metadata and nothing else, never a route that re-encodes the file. + // An envelope has no such edge: opening it for the file inside would drop the changes without a word. + var metadata = finalOutput && runWith.EditsMetadata; + var route = opener is null || metadata + ? planner.Plan(source.Id, target, frames, motionPhoto: motionPhoto, livePhoto: livePhoto, ocr: ocr, caption: caption, translate: translate, + metadata: metadata, upscale: upscale) + : planner.PlanThrough(source.Id, from.Id, target, frames, motionPhoto: motionPhoto, livePhoto: livePhoto, ocr: ocr, caption: caption, translate: translate, + upscale: upscale); if (route is null) - return Fail(file, "error.no_route", $"{source.Id} → {target}", - new RouteRequest(source.Id, target, Frames: frames, MotionPhoto: motionPhoto, LivePhoto: livePhoto, Ocr: ocr)); + return Fail(file, "error.no_route", $"{from.Id} → {target}", + new RouteRequest(from.Id, target, Frames: frames, MotionPhoto: motionPhoto, LivePhoto: livePhoto, Ocr: ocr, Translate: translate, Metadata: metadata, + Upscale: upscale)); // A step that draws text without shaping (rhwp) would break Arabic, Hebrew, Indic or Thai text: such a file // takes a route without it (LibreOffice), or is refused with the reason rather than written broken. One - // scan of the file's text answers this and the widths question below. - var scripts = route.Steps.FirstOrDefault(s => s.Unshaped)?.Converter is ITextShapingCheck check + // scan of the file's text answers this and the widths question below. Not for an envelope, whose own bytes + // aren't the document's. + var scripts = opener is null && route.Steps.FirstOrDefault(s => s.Unshaped)?.Converter is ITextShapingCheck check ? ScanScripts(check, file.SourcePath, source.Id) : null; if (scripts?.NeedsShaping is { } script) @@ -809,7 +984,7 @@ private async Task> RunFileAsync( // Parts of a picture to hide likewise, once: a route that can't cover them must not write the picture uncovered. var turnAt = runWith.Image.ReworksPixels ? route.FirstTransformStep() : -1; if (runWith.Image.ReworksPixels && turnAt < 0) - return Fail(file, runWith.Image.HidesAreas ? "error.cannot_hide" : "error.cannot_turn", $"{source.Id} → {target}"); + return Fail(file, CannotReworkKey(runWith.Image), $"{source.Id} → {target}"); var unturned = turnAt < 0 ? runWith : Unturned(runWith); file.State = FileState.Running; @@ -832,7 +1007,7 @@ private async Task> RunFileAsync( var isLast = s == route.Steps.Count - 1; IOutputAllocator allocator = isLast && finalOutput && !zipResult ? final = CreateFinalAllocator(job, file.SourcePath, index) - : new TempAllocator(workDir, FormatRegistry.NameWithoutExtension(file.SourcePath)); + : new TempAllocator(workDir, file.IsFolder ? Path.GetFileName(Path.TrimEndingDirectorySeparator(file.SourcePath)) : FormatRegistry.NameWithoutExtension(file.SourcePath)); var outputs = new List(); foreach (var input in inputs) @@ -862,7 +1037,7 @@ private async Task> RunFileAsync( if (preset.Image.ChangesSpeed && !(isLast && finalOutput)) preset = AtOriginalSpeed(preset); // Likewise the size limit: only the result has to fit, not a picture passed to the next engine. - if ((preset.Image.MaxSizeMb > 0 || preset.Image.MinSizeMb > 0 || preset.Media.MaxSizeMb > 0) && !(isLast && finalOutput)) + if ((preset.Image.MaxSizeMb > 0 || preset.Image.MinSizeMb > 0 || preset.Media.MaxSizeMb > 0 || preset.Media.MaxSizePercent > 0) && !(isLast && finalOutput)) preset = WithoutSizeLimit(preset); var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, step.FrameSequence, key => file.NoticeKey = key, step.MotionPhoto, step.LivePhoto, fonts => @@ -872,7 +1047,7 @@ private async Task> RunFileAsync( file.MissingFonts = file.MissingFonts.Concat(fonts) .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); Notify(job); - }, file.SourcePath, Caption: step.Caption); + }, file.SourcePath, Caption: step.Caption, Translate: step.Translate); outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct)); } finally @@ -884,17 +1059,21 @@ private async Task> RunFileAsync( } // Under "Save as ZIP" the output is still in the work folder: the source copied over it goes into the ZIP. - // Never with hidden parts: the source copied over the result would show them again. - var copiedSource = finalOutput && runWith.Output.OnlyIfSmaller && !runWith.Image.HidesAreas && inputs.Count == 1 + // Never with hidden parts: the source copied over the result would show them again. Never for an envelope, + // which isn't a file of the result's format. + var copiedSource = finalOutput && runWith.Output.OnlyIfSmaller && !runWith.Image.HidesAreas && opener is null && inputs.Count == 1 && CopyIfNotSmaller(file.SourcePath, inputs[0]); if (copiedSource) file.NoticeKey = "notice.pdf_not_smaller"; - // Watermark, page numbers, password: on every PDF this file became, from whichever engine. + // Watermark, page numbers, password, then PDF/A: on every PDF this file became, from whichever engine. if (finalOutput && runWith.TargetFormat == "pdf") + { await FinishPdfsAsync(runWith, inputs, ct); + await ArchivePdfsAsync(runWith, inputs, file, workDir, changed: runWith.Pdf.FinishesPdf, ct); + } // The size limit (#553): a result the engine couldn't fit (HEIC, a render, an animation) isn't handed over. if (finalOutput) - SizeLimit.Check(runWith, inputs); + SizeLimit.Check(runWith, inputs, file.SourcePath); // The minimum (#662), on the pictures themselves: after the source was copied over, before they go into a ZIP. if (finalOutput && SizeLimit.IsUnderMinimum(runWith, inputs)) file.UnderMinimumSize = true; @@ -905,10 +1084,14 @@ private async Task> RunFileAsync( else if (finalOutput && inputs.Count == 1 && final is { Handed: 1 }) inputs = [NextToSource(job, file, index, inputs[0], final)]; - // The source's dates are read now: "Replace the original" may send it to the Trash below. + // The source's dates and Mark of the Web are read now: "Replace the original" may send it to the Trash below. var dates = finalOutput && runWith.Output.KeepDates ? DatesOf(file.SourcePath) : null; + // A file converted from one that came from the internet still did (Office's macro block, SmartScreen). + var mark = finalOutput ? Platform.MarkOfTheWeb.Read(file.SourcePath) : null; if (finalOutput && !zipResult && inputs.Count == 1) inputs = [ReplaceOriginal(job, file, source.Id, inputs[0], copiedSource)]; + if (finalOutput && !zipResult && !copiedSource) + TrashOriginal(job, file, source.Id, inputs); // A name the engine took but wrote nothing to is free again. final?.Release(except: inputs); @@ -917,6 +1100,9 @@ private async Task> RunFileAsync( file.Outputs.AddRange(inputs); if (dates is { } kept) CopyDates(kept, inputs); + if (mark is not null) + foreach (var output in inputs.Where(File.Exists)) + Platform.MarkOfTheWeb.TryWrite(output, mark, _log); } file.State = inputs.Count == 0 && finalOutput ? FileState.Skipped : FileState.Done; file.Progress = ceiling; @@ -949,6 +1135,8 @@ static Preset Unturned(Preset preset) copy.Image.Rotation = ImageRotation.None; copy.Image.Flip = ImageFlip.None; copy.Image.HiddenAreas = null; + copy.Image.Annotations = null; + copy.Image.Backdrop = null; return copy; } @@ -965,6 +1153,7 @@ static Preset WithoutSizeLimit(Preset preset) copy.Image.MaxSizeMb = 0; copy.Image.MinSizeMb = 0; copy.Media.MaxSizeMb = 0; + copy.Media.MaxSizePercent = 0; return copy; } @@ -1056,7 +1245,8 @@ private SemaphoreSlim GateFor(IConverter converter) => /// The output is one file whatever happens (a merged PDF, a multi-page TIFF, an archive). private FinalAllocator CreateFinalAllocator(ConversionJob job, string sourcePath, int index, bool oneFile = false) => new(this, oneFile ? ForOneFile(job.Preset.Output) : job.Preset.Output, - new OutputPathResolver.Tokens(sourcePath, job.PresetDisplayName, index, job.CreatedAt)); + new OutputPathResolver.Tokens(sourcePath, job.PresetDisplayName, index, job.CreatedAt, + job.Files.Any(f => f.IsFolder && FileSystemPaths.Comparer.Equals(f.SourcePath, sourcePath)))); /// /// The rule for a single output file: with it is saved next to @@ -1090,7 +1280,7 @@ private string NextToSource(ConversionJob job, FileResult file, int index, strin lock (_reservedOutputs) { - var tokens = new OutputPathResolver.Tokens(file.SourcePath, job.PresetDisplayName, index, job.CreatedAt); + var tokens = new OutputPathResolver.Tokens(file.SourcePath, job.PresetDisplayName, index, job.CreatedAt, file.IsFolder); var target = OutputPathResolver.Resolve(rule, tokens, Path.GetExtension(output), p => !PathsEqual(p, output) && (File.Exists(p) || Directory.Exists(p) || _reservedOutputs.ContainsKey(p))); if (target is null || PathsEqual(target, output)) @@ -1238,6 +1428,56 @@ string Kept(Platform.TrashRefusal why, string result) } } + /// True while another queued or running job still has to convert. + private bool UsedByAnotherJob(ConversionJob job, string source) + { + lock (_live) + return _live.Any(other => !ReferenceEquals(other, job) && other.Files.Any(f => + (f.State is FileState.Pending or FileState.Running) + && string.Equals(f.SourcePath, source, Platform.FileSystemPaths.Comparison))); + } + + /// + /// "Move the original to the Recycle Bin / Trash" (, #1387): once + /// every result of is complete and none has the source's format, the source goes to the + /// Trash. A result of the source's own format is "Replace the original"'s, and a result at the source's own path + /// would be moved with it, so either leaves the source alone. When the Trash refuses, the source stays and the + /// file gets a note saying why; nothing is ever deleted for good. + /// + private void TrashOriginal(ConversionJob job, FileResult file, string sourceFormat, IReadOnlyList outputs) + { + var source = file.SourcePath; + if (!job.Preset.Output.TrashOriginalAfterConvert || job.Fetcher is not null || file.OriginalInTrash + || outputs.Count == 0 || !File.Exists(source)) + return; + foreach (var output in outputs) + { + if (string.Equals(Path.GetFullPath(output), Path.GetFullPath(source), Platform.FileSystemPaths.Comparison)) + return; + if (Directory.Exists(output)) + continue; // an output folder (Extract) + if (!File.Exists(output) || FormatRegistry.Detect(output)?.Id == sourceFormat) + return; + } + + // The same file dropped on two presets is two jobs: once this one has moved it, the other would fail as not found. + if (UsedByAnotherJob(job, source)) + { + _log.LogInformation("Kept the original {Source}: another conversion still uses it", source); + file.NoticeKey = "notice.trash_original_busy"; + return; + } + + var refusal = _moveToTrash is null ? new Platform.TrashRefusal("trash.no_recycle_bin") : _moveToTrash(source); + file.OriginalInTrash = refusal is null; + if (refusal is null) + return; + _log.LogInformation("Kept the original {Source}: {Reason} {Detail}", source, refusal.ReasonKey, refusal.Detail); + file.NoticeKey = "notice.trash_original_kept"; + file.NoticeReasonKey = refusal.ReasonKey; + file.NoticeDetail = refusal.Detail; + } + /// Extensions that only spell the same kind of file differently ("Replace the original" may swap them). private static readonly string[][] Spellings = [ @@ -1308,13 +1548,18 @@ private async Task WorkLoopAsync() } finally { + lock (_live) + _live.Remove(job); Interlocked.Decrement(ref _busy); } } } - /// Where every job has its work folder, named by the job's . - public static string DefaultWorkRoot => Path.Combine(Path.GetTempPath(), "Filee"); + /// + /// Where every job has its work folder, named by the job's : a folder only the user + /// can open (). + /// + public static string DefaultWorkRoot => WorkFolders.Root; /// /// Deletes the work folders of jobs a crash, a forced quit or a power cut kept from removing them: intermediate @@ -1327,7 +1572,7 @@ public static void DeleteStaleWorkFolders(string workRoot, TimeSpan age) try { var root = new DirectoryInfo(workRoot); - // A temp folder everyone can write in (/tmp on Linux) may hold a link to somewhere else: never follow one. + // A work root (or a folder in it) may be a link to somewhere else: never follow one. if (!root.Exists || root.LinkTarget is not null) return; foreach (var folder in root.EnumerateDirectories()) From 0df79d6b392db42830c743d71bb25d0b068a65c9 Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Wed, 18 Nov 2026 06:36:25 +0000 Subject: [PATCH 5/9] Fix missing newline at end of SmallParsersTests.cs Added missing newline at the end of the file. From a40585443dc351983018c095f3f131926cfab4a5 Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Wed, 18 Nov 2026 06:36:57 +0000 Subject: [PATCH 6/9] Fix formatting issue in PageRangeCheck struct From f6f8222bfeade31bfc19d7a2f41dc67fd8580bcd Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Wed, 18 Nov 2026 06:37:52 +0000 Subject: [PATCH 7/9] Refactor OperationCanceledException handling in JobQueue --- src/Filee.Core/Conversion/JobQueue.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs index 23e02ee3d..7aea98c3c 100644 --- a/src/Filee.Core/Conversion/JobQueue.cs +++ b/src/Filee.Core/Conversion/JobQueue.cs @@ -361,9 +361,9 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), FailFile(job, f, ex.ErrorKey, ex.Detail); return; } - catch (OperationCanceledException) + catch (OperationCanceledException) when (job.CancellationToken.IsCancellationRequested) { - // A cancel while merging is a cancel, not a failure of the job. + // Only a real cancel counts: a timeout inside the merger is also an OperationCanceledException and is an error below. allocator.Discard(); foreach (var f in job.Files.Where(f => !Stopped(f))) f.State = FileState.Cancelled; @@ -426,7 +426,7 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count), { await _tiffMerger!.MergeAsync(inputs, output, job.Preset.Image, job.CancellationToken); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (job.CancellationToken.IsCancellationRequested) { allocator.Discard(); foreach (var f in job.Files.Where(f => !Stopped(f))) From 88b86084fc89a773874227a0e61d3b3c2146965a Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Wed, 18 Nov 2026 06:38:17 +0000 Subject: [PATCH 8/9] Fix missing newline at end of JobQueue.cs Added a newline at the end of the file. From c5746002d89fe8e0c4120a0055810ba60f75a7ca Mon Sep 17 00:00:00 2001 From: Marouane-elfadli Date: Wed, 18 Nov 2026 06:39:27 +0000 Subject: [PATCH 9/9] Add tests for PDF and multi-page TIFF merge scenarios --- tests/Filee.Core.Tests/JobQueueTests.cs | 154 ++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs index 7ce1431d6..7c3a583a3 100644 --- a/tests/Filee.Core.Tests/JobQueueTests.cs +++ b/tests/Filee.Core.Tests/JobQueueTests.cs @@ -932,6 +932,160 @@ public Task MergeAsync(IReadOnlyList inputs, string outputPath, b } } + private static readonly Preset MergePdfPreset = new() + { + TargetFormat = "pdf", + Pdf = { MergeIntoSingle = true }, + Output = { FileNamePattern = "{name}_merged" } + }; + + private static readonly Preset MultiPageTiffPreset = new() { TargetFormat = "tiff", Image = { MultiPageTiff = true } }; + + [Fact] + public async Task Cancelling_during_a_pdf_merge_cancels_the_job_and_leaves_no_output() + { + using var dir = new TempDir(); + var image = dir.File("photo.jpg"); + var pdf = dir.File("report.pdf"); + ConversionJob? running = null; + var merger = new FailingMerger(() => new OperationCanceledException(), () => running!.Cancel()); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("writer", new ConversionEdge("jpg", "pdf"))]), merger); + + running = new ConversionJob([image, pdf], MergePdfPreset, "Test"); + await queue.RunAsync(running); + + Assert.Equal(JobState.Cancelled, running.State); + Assert.All(running.Files, f => Assert.Equal(FileState.Cancelled, f.State)); + Assert.Empty(running.Outputs); + Assert.False(File.Exists(Path.Combine(dir.Path, "photo_merged.pdf"))); + } + + [Fact] + public async Task A_pdf_merge_that_throws_fails_every_merged_file_with_the_message_and_leaves_no_output() + { + using var dir = new TempDir(); + var image = dir.File("photo.jpg"); + var pdf = dir.File("report.pdf"); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("writer", new ConversionEdge("jpg", "pdf"))]), + new FailingMerger(() => new IOException("disk full"))); + + var job = await Run(queue, [image, pdf], MergePdfPreset); + + Assert.Equal(JobState.Failed, job.State); + Assert.Empty(job.Outputs); + Assert.All(job.Files, f => + { + Assert.Equal(FileState.Failed, f.State); + Assert.Equal("error.conversion_failed", f.ErrorKey); + Assert.Equal("disk full", f.ErrorDetail); + }); + Assert.False(File.Exists(Path.Combine(dir.Path, "photo_merged.pdf"))); + Assert.Equal("x", File.ReadAllText(image)); + Assert.Equal("x", File.ReadAllText(pdf)); + } + + [Fact] + public async Task A_timeout_inside_the_pdf_merger_is_an_error_not_a_cancel() + { + using var dir = new TempDir(); + var image = dir.File("photo.jpg"); + var pdf = dir.File("report.pdf"); + // The merger gives up on its own (not the job's cancel): the files are told as failed, not shown as cancelled. + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("writer", new ConversionEdge("jpg", "pdf"))]), + new FailingMerger(() => new OperationCanceledException("merger timed out"))); + + var job = await Run(queue, [image, pdf], MergePdfPreset); + + Assert.Equal(JobState.Failed, job.State); + Assert.Empty(job.Outputs); + Assert.All(job.Files, f => + { + Assert.Equal(FileState.Failed, f.State); + Assert.Equal("error.conversion_failed", f.ErrorKey); + }); + Assert.False(File.Exists(Path.Combine(dir.Path, "photo_merged.pdf"))); + } + + [Fact] + public async Task Cancelling_during_a_multi_page_tiff_merge_cancels_the_job_and_leaves_no_output() + { + using var dir = new TempDir(); + var a = dir.File("a.jpg"); + var b = dir.File("b.jpg"); + ConversionJob? running = null; + var merger = new FailingMerger(() => new OperationCanceledException(), () => running!.Cancel()); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "tiff"))]), tiffMerger: merger); + + running = new ConversionJob([a, b], MultiPageTiffPreset, "Test"); + await queue.RunAsync(running); + + Assert.Equal(JobState.Cancelled, running.State); + Assert.All(running.Files, f => Assert.Equal(FileState.Cancelled, f.State)); + Assert.Empty(running.Outputs); + Assert.False(File.Exists(Path.Combine(dir.Path, "a.tiff"))); + } + + [Fact] + public async Task A_multi_page_tiff_merge_that_throws_fails_every_file_with_the_message_and_leaves_no_output() + { + using var dir = new TempDir(); + var a = dir.File("a.jpg"); + var b = dir.File("b.jpg"); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "tiff"))]), + tiffMerger: new FailingMerger(() => new IOException("disk full"))); + + var job = await Run(queue, [a, b], MultiPageTiffPreset); + + Assert.Equal(JobState.Failed, job.State); + Assert.Empty(job.Outputs); + Assert.All(job.Files, f => + { + Assert.Equal(FileState.Failed, f.State); + Assert.Equal("error.conversion_failed", f.ErrorKey); + Assert.Equal("disk full", f.ErrorDetail); + }); + Assert.False(File.Exists(Path.Combine(dir.Path, "a.tiff"))); + } + + [Fact] + public async Task A_refused_multi_page_tiff_merge_fails_every_file_with_its_reason_and_leaves_no_output() + { + using var dir = new TempDir(); + var a = dir.File("a.jpg"); + var b = dir.File("b.jpg"); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "tiff"))]), + tiffMerger: new FailingMerger(() => new ConversionRefusedException("error.size_limit", "page 2"))); + + var job = await Run(queue, [a, b], MultiPageTiffPreset); + + Assert.Equal(JobState.Failed, job.State); + Assert.Empty(job.Outputs); + Assert.All(job.Files, f => + { + Assert.Equal(FileState.Failed, f.State); + Assert.Equal("error.size_limit", f.ErrorKey); + Assert.Equal("page 2", f.ErrorDetail); + }); + Assert.False(File.Exists(Path.Combine(dir.Path, "a.tiff"))); + } + + /// Writes half an output, runs (a cancel, say), then throws what makes. + private sealed class FailingMerger(Func failure, Action? before = null) : IPdfMerger, ITiffMerger + { + public Task MergeAsync(IReadOnlyList inputs, string outputPath, bool sourceBookmarks, PdfMergePaper? paper, + CancellationToken cancellationToken) => Fail(outputPath); + + public Task MergeAsync(IReadOnlyList inputPaths, string outputPath, ImageOptions options, CancellationToken cancellationToken) => + Fail(outputPath); + + private Task Fail(string outputPath) + { + File.WriteAllText(outputPath, "half"); + before?.Invoke(); + throw failure(); + } + } + private sealed class MergePaperPipeline(string? failingStage) : IConverter, IPdfMerger, IPdfFinisher, IPdfArchiver { private readonly FakeConverter _writer = new("pipeline", new ConversionEdge("jpg", "pdf"));