Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Keep a single output with what goes with it, and never move over a file

KnifeLemonde720f491261
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index eb9cc8cd..f31960a4 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -592,7 +592,7 @@
"presets.location.CustomFolder": "指定文件夹",
"presets.subfolder": "子文件夹名称",
"presets.subfolder_only_several": "仅在生成多个文件时",
- "presets.subfolder_only_several_hint": "只生成一个文件时保存在原文件旁边;生成多个文件时(例如 PDF 拆分成页面)才新建子文件夹。",
+ "presets.subfolder_only_several_hint": "只生成一个文件时保存在原文件旁边,生成多个文件时(例如 PDF 拆分成页面)才新建子文件夹。",
"presets.custom_folder": "文件夹",
"presets.browse": "浏览…",
"presets.pattern": "文件名",
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index e45210d8..59939816 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -494,6 +494,8 @@ public sealed class JobQueue : IAsyncDisposable
Notify(job);
// A file saved from a browser first has part of its progress already.
var floor = file.Progress;
+ // The last step's allocator: how many paths it handed out tells a single output from several.
+ FinalAllocator? final = null;
try
{
@@ -505,7 +507,7 @@ public sealed class JobQueue : IAsyncDisposable
var step = route.Steps[s];
var isLast = s == route.Steps.Count - 1;
IOutputAllocator allocator = isLast && finalOutput && !zipResult
- ? CreateFinalAllocator(job, file.SourcePath, index)
+ ? final = CreateFinalAllocator(job, file.SourcePath, index)
: new TempAllocator(workDir, FormatRegistry.NameWithoutExtension(file.SourcePath));
var outputs = new List<string>();
@@ -548,7 +550,8 @@ public sealed class JobQueue : IAsyncDisposable
if (zipResult && inputs.Count > 0)
inputs = PackZip(job, file, index, inputs, ct);
- else if (finalOutput && inputs.Count == 1)
+ // One output, and nothing else handed out for it (a Markdown file's picture folder goes with it).
+ else if (finalOutput && inputs.Count == 1 && final is { Handed: 1 })
inputs = [NextToSource(job, file, index, inputs[0])];
if (finalOutput)
@@ -690,7 +693,9 @@ public sealed class JobQueue : IAsyncDisposable
private string NextToSource(ConversionJob job, FileResult file, int index, string output)
{
var rule = ForOneFile(job.Preset.Output);
- if (ReferenceEquals(rule, job.Preset.Output) || !File.Exists(output))
+ if (ReferenceEquals(rule, job.Preset.Output) || !File.Exists(output)
+ // Pandoc writes a document's pictures into "<name>_files" beside it, outside the allocator: they stay together.
+ || Directory.Exists(Path.Combine(Path.GetDirectoryName(output)!, Path.GetFileNameWithoutExtension(output) + "_files")))
return output;
// The name was already made from the pattern and renames: it is kept as it is.
rule.FileNamePattern = Path.GetFileNameWithoutExtension(output);
@@ -705,7 +710,8 @@ public sealed class JobQueue : IAsyncDisposable
return output;
try
{
- File.Move(output, target, overwrite: true);
+ // Over an existing file only when the policy says so: one that appeared since is never replaced.
+ File.Move(output, target, overwrite: rule.Conflict == ConflictPolicy.Overwrite);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -730,7 +736,7 @@ public sealed class JobQueue : IAsyncDisposable
}
static bool PathsEqual(string a, string b) =>
- string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), Platform.FileSystemPaths.Comparison);
}
private void Notify(ConversionJob job)
@@ -788,6 +794,9 @@ public sealed class JobQueue : IAsyncDisposable
/// <summary>Allocates final output paths according to the preset's <see cref="OutputRule"/>.</summary>
private sealed class FinalAllocator(JobQueue queue, OutputRule rule, OutputPathResolver.Tokens tokens) : IOutputAllocator
{
+ /// <summary>How many paths were handed out: an output and the picture folder that goes with it are two.</summary>
+ public int Handed { get; private set; }
+
public string? Allocate(string extension, string? suffix = null)
{
// Reserve under a lock so two parallel files never pick the same name.
@@ -799,6 +808,7 @@ public sealed class JobQueue : IAsyncDisposable
return null;
queue._reservedOutputs.Add(path);
+ Handed++;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
// An empty extension asks for a folder (archive extraction): the converter creates it.
return path;
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 5a5f33b6..8a170ec5 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1067,10 +1067,14 @@ public class RenderTests
Assert.Equal("jpg", preset.TargetFormat);
}
- [AvaloniaFact]
- public void Preset_editor_offers_the_subfolder_only_for_several_files_with_a_subfolder()
+ [AvaloniaTheory]
+ [InlineData("en", false)]
+ [InlineData("ru", false)]
+ [InlineData("ar", true)]
+ public void Preset_editor_offers_the_subfolder_only_for_several_files_with_a_subfolder(string language, bool dark)
{
- TestServices.EnsureInitialized("en");
+ TestServices.EnsureInitialized(language);
+ var theme = AppHost.Get<ThemeService>();
var loc = AppHost.Get<Filee.Core.Localization.ILocalizer>();
// PDF → page images saves into a folder per document.
var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "pdf-split");
@@ -1079,11 +1083,21 @@ public class RenderTests
Assert.False(vm.SubfolderOnlyForSeveralFiles);
vm.SubfolderOnlyForSeveralFiles = true;
- var window = new PresetEditorWindow { DataContext = vm, Height = 1400 };
- window.Show();
- Pump();
- Save(window, "preset-subfolder-en.png");
- window.Close();
+ if (dark)
+ theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language);
+ try
+ {
+ var window = new PresetEditorWindow { DataContext = vm, Height = 1400 };
+ window.Show();
+ Pump();
+ Save(window, $"preset-subfolder-{language}{(dark ? "-dark" : "")}.png");
+ window.Close();
+ }
+ finally
+ {
+ if (dark)
+ theme.Apply(new ThemeSettings(), language);
+ }
Assert.True(vm.Apply());
Assert.True(preset.Output.SubfolderOnlyForSeveralFiles);
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
index c3103a20..c0706262 100644
--- a/tests/Filee.Core.Tests/FakeConverter.cs
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -16,6 +16,12 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :
public bool Throw { get; set; }
+ /// <summary>Also writes a "_files" picture folder beside the output (Markdown), not counted as an output.</summary>
+ public bool PictureFolder { get; set; }
+
+ /// <summary>The picture folder is taken from the allocator (MarkdownPictures) rather than just written (Pandoc).</summary>
+ public bool ReservesPictureFolder { get; set; } = true;
+
/// <summary>Thrown instead of converting, when set.</summary>
public Exception? Failure { get; set; }
@@ -36,6 +42,14 @@ internal sealed class FakeConverter(string id, params ConversionEdge[] edges) :
continue;
File.WriteAllText(path, $"{Path.GetFileName(step.InputPath)}→{step.To} by {id}");
written.Add(path);
+ if (PictureFolder)
+ {
+ var folder = ReservesPictureFolder
+ ? step.Output.Allocate("", "_files")!
+ : Path.Combine(Path.GetDirectoryName(path)!, Path.GetFileNameWithoutExtension(path) + "_files");
+ Directory.CreateDirectory(folder);
+ File.WriteAllText(Path.Combine(folder, "img0001.png"), "picture");
+ }
}
progress?.Report(1);
return Task.FromResult<IReadOnlyList<string>>(written);
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index 6744d417..9f3dcdc7 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -627,6 +627,50 @@ public class JobQueueTests
Assert.False(Directory.Exists(Path.Combine(dir.Path, "a")));
}
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task Subfolder_only_for_several_files_keeps_a_markdown_file_with_its_picture_folder(bool reserved)
+ {
+ using var dir = new TempDir();
+ var converter = new FakeConverter("pandoc", new ConversionEdge("docx", "md")) { PictureFolder = true, ReservesPictureFolder = reserved };
+ await using var queue = new JobQueue(new ConverterCatalog([converter]));
+ var preset = new Preset
+ {
+ TargetFormat = "md",
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}", SubfolderOnlyForSeveralFiles = true },
+ };
+
+ var job = await Run(queue, [dir.File("report.docx")], preset);
+
+ // Its links point into the folder beside it: the two stay together in the subfolder.
+ Assert.Equal([Path.Combine(dir.Path, "report", "report.md")], job.Outputs);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "report", "report_files", "img0001.png")));
+ }
+
+ [Fact]
+ public async Task Subfolder_only_for_several_files_leaves_the_file_in_the_subfolder_when_skip_meets_an_existing_one()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("photo.jpg");
+ dir.File("photo.png", "older");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+ var preset = new Preset
+ {
+ TargetFormat = "png",
+ Output =
+ {
+ Location = OutputLocation.Subfolder, SubfolderName = "{name}", SubfolderOnlyForSeveralFiles = true,
+ Conflict = ConflictPolicy.Skip,
+ },
+ };
+
+ var job = await Run(queue, [photo], preset);
+
+ Assert.Equal([Path.Combine(dir.Path, "photo", "photo.png")], job.Outputs);
+ Assert.Equal("older", File.ReadAllText(Path.Combine(dir.Path, "photo.png")));
+ }
+
[Fact]
public async Task Without_subfolder_only_for_several_files_a_single_output_stays_in_the_subfolder()
{