Skip to content
2 changes: 1 addition & 1 deletion src/Filee.App/ViewModels/PresetEditorViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,7 @@ public bool Apply()
pdf.PageSize = PageSize.Value;
pdf.MarginMm = Math.Clamp(MarginMm, 0, 100);
pdf.RenderDpi = Math.Clamp(RenderDpi, 36, 1200);
pdf.PageRange = PageRange.Trim();
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);
Expand Down
40 changes: 36 additions & 4 deletions src/Filee.Core/Conversion/JobQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -361,10 +361,23 @@ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count),
FailFile(job, f, ex.ErrorKey, ex.Detail);
return;
}
catch
catch (OperationCanceledException) when (job.CancellationToken.IsCancellationRequested)
{
// Only a real cancel counts: a timeout inside the merger is also an OperationCanceledException and is an error below.
allocator.Discard();
throw;
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))
Expand Down Expand Up @@ -413,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) when (job.CancellationToken.IsCancellationRequested)
{
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]))
Expand Down
8 changes: 5 additions & 3 deletions src/Filee.Core/Conversion/PageRange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public static IReadOnlyList<int> 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();

Expand All @@ -25,16 +27,16 @@ public static IReadOnlyList<int> 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;
}
else
{
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;
}
Expand Down
154 changes: 154 additions & 0 deletions tests/Filee.Core.Tests/JobQueueTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,160 @@ public Task MergeAsync(IReadOnlyList<PdfMergeInput> 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")));
}

/// <summary>Writes half an output, runs <paramref name="before"/> (a cancel, say), then throws what <paramref name="failure"/> makes.</summary>
private sealed class FailingMerger(Func<Exception> failure, Action? before = null) : IPdfMerger, ITiffMerger
{
public Task MergeAsync(IReadOnlyList<PdfMergeInput> inputs, string outputPath, bool sourceBookmarks, PdfMergePaper? paper,
CancellationToken cancellationToken) => Fail(outputPath);

public Task MergeAsync(IReadOnlyList<string> 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"));
Expand Down
6 changes: 6 additions & 0 deletions tests/Filee.Core.Tests/SmallParsersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
Loading