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.

Add "Save as ZIP" for geospatial results

KAPPI19253dec995d301d
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 829db2a0..40009eda 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -729,6 +729,11 @@ also reaches the spreadsheet and data engines (Shapefile → XLSX, GeoJSON → J
as `name.shp`, `.shx`, `.dbf`, `.prj` and `.cpg`; the engine returns all of them. The file names always match: when
the `.shp` name is taken, the next free name is used for the whole set, and a leftover file of the same name (a lone
`.dbf`) is never written over.
+- **Save as ZIP.** A geospatial preset can pack its result into one ZIP (Settings → Presets → *Save the result as a ZIP*,
+ or Settings → General to do it for every geospatial result, or `--zip` on the command line): a Shapefile's five files
+ travel together, and the ZIP, named by the preset's file name pattern and conflict policy, is the only output. The
+ step that writes the files runs in the job's work folder and `JobQueue` packs it afterwards, so the option works for
+ any engine and any number of steps.
- **Same format again** (`shp → shp`, `geojson → geojson`) rewrites the file in WGS 84, which is how a projected
Shapefile is reprojected, and splits mixed geometries (below).
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 8c2eec2e..6ff3468f 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -222,6 +222,8 @@
"general.default_output_hint": "Presets set to “Default save location” save here.\nA preset with its own location keeps it.",
"general.keep_dates": "Keep the original file dates for every conversion",
"general.keep_dates_hint": "Converted files keep the original's created and modified dates, with every preset.\nOff: only presets with \"Keep the original file dates\" do it.",
+ "general.zip_geo": "Save every geospatial result as a ZIP",
+ "general.zip_geo_hint": "Shapefile, GeoJSON, KML, GPX and the other geospatial results are packed into one ZIP per file, with every preset.\nOff: only presets with \"Save the result as a ZIP\" do it.",
"general.check_updates": "Check for updates automatically",
"general.close_action": "When I close the window",
"general.close.Ask": "Ask every time",
@@ -513,6 +515,8 @@
"presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
"presets.keep_dates": "Keep the original file dates",
"presets.keep_dates_hint": "Converted files get the created and modified dates of the original, so photos still sort by date.",
+ "presets.zip_result": "Save the result as a ZIP",
+ "presets.zip_result_hint": "The files of the result (a Shapefile's .shp, .shx, .dbf, .prj and .cpg) are packed into one ZIP next to the source, in place of loose files.",
"presets.conflict": "If the file exists",
"presets.conflict.Rename": "Add a number",
"presets.conflict.Overwrite": "Replace it",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 0f45f043..a9c32177 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -211,6 +211,8 @@
"general.default_output_hint": "Los ajustes preestablecidos configurados en «Carpeta de guardado predeterminada» guardan aquí.\nUn ajuste preestablecido con su propia carpeta la conserva.",
"general.keep_dates": "Conservar las fechas originales de los archivos en todas las conversiones",
"general.keep_dates_hint": "Los archivos convertidos conservan las fechas de creación y modificación del original, con todos los ajustes preestablecidos.\nDesactivado: solo lo hacen los ajustes preestablecidos con «Conservar las fechas del archivo original».",
+ "general.zip_geo": "Guardar todo resultado geoespacial como ZIP",
+ "general.zip_geo_hint": "Shapefile, GeoJSON, KML, GPX y los demás resultados geoespaciales se empaquetan en un ZIP por archivo, con cualquier preajuste.\nDesactivado: solo lo hacen los preajustes con «Guardar el resultado como ZIP».",
"general.check_updates": "Buscar actualizaciones automáticamente",
"general.close_action": "Al cerrar la ventana",
"general.close.Ask": "Preguntar cada vez",
@@ -499,6 +501,8 @@
"presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
"presets.keep_dates": "Conservar las fechas del archivo original",
"presets.keep_dates_hint": "Los archivos convertidos reciben las fechas de creación y modificación del original, así que las fotos siguen ordenándose por fecha.",
+ "presets.zip_result": "Guardar el resultado como ZIP",
+ "presets.zip_result_hint": "Los archivos del resultado (.shp, .shx, .dbf, .prj y .cpg de un Shapefile) se empaquetan en un solo ZIP junto al origen, en lugar de archivos sueltos.",
"presets.conflict": "Si el archivo existe",
"presets.conflict.Rename": "Añadir un número",
"presets.conflict.Overwrite": "Reemplazarlo",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index a7de05af..be8b80f9 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -222,6 +222,8 @@
"general.default_output_hint": "저장 위치가 “기본 저장 위치”인 프리셋은 여기에 저장해요.\n저장 위치를 따로 정한 프리셋은 그대로예요.",
"general.keep_dates": "모든 변환에서 원본 파일 날짜 유지",
"general.keep_dates_hint": "어떤 프리셋이든 원본의 만든 날짜·수정한 날짜를 그대로 써요.\n끄면 \"원본 파일 날짜 유지\"를 켠 프리셋만 그렇게 해요.",
+ "general.zip_geo": "지리 정보 결과를 모두 ZIP으로 저장",
+ "general.zip_geo_hint": "Shapefile, GeoJSON, KML, GPX 등 지리 정보 결과를 모든 프리셋에서 파일마다 ZIP 하나로 묶어요.\n꺼 두면 \"결과를 ZIP으로 저장\"을 켠 프리셋만 묶어요.",
"general.check_updates": "자동으로 업데이트 확인",
"general.close_action": "창을 닫을 때",
"general.close.Ask": "매번 묻기",
@@ -513,6 +515,8 @@
"presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
"presets.keep_dates": "원본 파일 날짜 유지",
"presets.keep_dates_hint": "변환한 파일에 원본의 만든 날짜와 수정한 날짜를 그대로 넣어요.\n그래서 사진을 날짜순으로 정렬해도 순서가 바뀌지 않아요.",
+ "presets.zip_result": "결과를 ZIP으로 저장",
+ "presets.zip_result_hint": "결과 파일들(Shapefile의 .shp, .shx, .dbf, .prj, .cpg)을 낱개로 두지 않고 원본 옆에 ZIP 하나로 묶어요.",
"presets.conflict": "같은 파일이 있으면",
"presets.conflict.Rename": "번호 붙이기",
"presets.conflict.Overwrite": "덮어쓰기",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 732d15c7..8ca67a78 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -222,6 +222,8 @@
"general.default_output_hint": "Ustawienia z „Domyślne miejsce zapisu” zapisują tutaj.\nUstawienie z własnym miejscem je zachowuje.",
"general.keep_dates": "Zachowuj oryginalne daty plików przy każdej konwersji",
"general.keep_dates_hint": "Przekonwertowane pliki zachowują daty utworzenia i modyfikacji oryginału, w każdym ustawieniu.\nWyłączone: robią to tylko ustawienia z „Zachowaj oryginalne daty plików”.",
+ "general.zip_geo": "Zapisuj każdy wynik geoprzestrzenny jako ZIP",
+ "general.zip_geo_hint": "Shapefile, GeoJSON, KML, GPX i inne wyniki geoprzestrzenne są pakowane do jednego ZIP na plik, w każdym ustawieniu.\nWyłączone: robią to tylko ustawienia z opcją „Zapisz wynik jako ZIP”.",
"general.check_updates": "Automatycznie sprawdzaj aktualizacje",
"general.close_action": "Po zamknięciu okna",
"general.close.Ask": "Pytaj za każdym razem",
@@ -513,6 +515,8 @@
"presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
"presets.keep_dates": "Zachowaj oryginalne daty plików",
"presets.keep_dates_hint": "Przekonwertowane pliki dostają daty utworzenia i modyfikacji oryginału, więc zdjęcia nadal sortują się według daty.",
+ "presets.zip_result": "Zapisz wynik jako ZIP",
+ "presets.zip_result_hint": "Pliki wyniku (.shp, .shx, .dbf, .prj i .cpg Shapefile) są pakowane do jednego ZIP obok źródła zamiast luźnych plików.",
"presets.conflict": "Jeśli plik istnieje",
"presets.conflict.Rename": "Dodaj numer",
"presets.conflict.Overwrite": "Zastąp",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index a9143e43..497e54cb 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -222,6 +222,8 @@
"general.default_output_hint": "保存位置为“默认保存位置”的预设会保存到这里。\n单独设置了保存位置的预设不受影响。",
"general.keep_dates": "所有转换都保留原文件日期",
"general.keep_dates_hint": "无论使用哪个预设,转换后的文件都沿用原文件的创建和修改日期。\n关闭后,只有打开“保留原文件日期”的预设会这样做。",
+ "general.zip_geo": "将所有地理信息结果保存为 ZIP",
+ "general.zip_geo_hint": "Shapefile、GeoJSON、KML、GPX 等地理信息结果,对所有预设都按每个文件打包成一个 ZIP。\n关闭后:只有开启了“将结果保存为 ZIP”的预设才会打包。",
"general.check_updates": "自动检查更新",
"general.close_action": "关闭窗口时",
"general.close.Ask": "每次询问",
@@ -513,6 +515,8 @@
"presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
"presets.keep_dates": "保留原文件日期",
"presets.keep_dates_hint": "转换后的文件沿用原文件的创建和修改日期,按日期排序的照片顺序不变。",
+ "presets.zip_result": "将结果保存为 ZIP",
+ "presets.zip_result_hint": "结果文件(Shapefile 的 .shp、.shx、.dbf、.prj 和 .cpg)会打包成原文件旁的一个 ZIP,而不是零散的文件。",
"presets.conflict": "文件已存在时",
"presets.conflict.Rename": "添加编号",
"presets.conflict.Overwrite": "覆盖",
diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
index c67b9e2e..0abffa01 100644
--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
@@ -40,6 +40,7 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable
_defaultSubfolder = output.SubfolderName;
_defaultFolder = output.CustomFolder;
_keepFileDates = store.Settings.KeepFileDates;
+ _zipGeoResults = store.Settings.ZipGeoResults;
CloseChoices = Enum.GetValues<CloseAction>().Select(v => new Choice<CloseAction>(v, loc[$"general.close.{v}"])).ToList();
_closeChoice = CloseChoices.First(c => c.Value == store.Settings.CloseAction);
store.SettingsChanged += OnSettingsChanged;
@@ -80,6 +81,7 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable
partial void OnDefaultFolderChanged(string value) => Save(s => s.DefaultOutput.CustomFolder = value.Trim());
[ObservableProperty] private bool _keepFileDates;
+ [ObservableProperty] private bool _zipGeoResults;
/// <summary>What closing the main window does; its "Don't ask again" also sets it.</summary>
public IReadOnlyList<Choice<CloseAction>> CloseChoices { get; }
@@ -103,6 +105,8 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable
partial void OnKeepFileDatesChanged(bool value) => Save(s => s.KeepFileDates = value);
+ partial void OnZipGeoResultsChanged(bool value) => Save(s => s.ZipGeoResults = value);
+
[ObservableProperty] private Choice<string> _language;
[ObservableProperty] private bool _startWithSystem;
[ObservableProperty] private bool _contextMenu;
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 24cf8f16..43343414 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -156,6 +156,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_customFolder = _edit.Output.CustomFolder;
_pattern = _edit.Output.FileNamePattern;
_keepDates = _edit.Output.KeepDates;
+ _zipResult = _edit.Output.ZipResult;
}
public string PresetId => _original.Id;
@@ -190,7 +191,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowTurnForPdf), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowMultiPageTiff), nameof(ShowWebp), nameof(ShowIco),
- nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
+ nameof(ShowZipResult), nameof(ShowPdf), nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowLeaveOutPictures), nameof(ShowPdfSplit), nameof(ShowPdfCombine),
nameof(ShowPdfCompression), nameof(ShowPdfCompressionOptions),
nameof(ShowMedia), nameof(ShowMediaQuality), nameof(ShowMaxHeight), nameof(ShowAudioBitrate), nameof(ShowRemoveAudio),
nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding),
@@ -330,6 +331,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty] private string _customFolder;
[ObservableProperty] private string _pattern;
[ObservableProperty] private bool _keepDates;
+ /// <summary>Geospatial targets: the result is saved as one ZIP (OutputRule.ZipResult).</summary>
+ [ObservableProperty] private bool _zipResult;
[ObservableProperty] private Choice<MediaQuality> _mediaQuality;
[ObservableProperty] private Choice<int> _maxHeight;
[ObservableProperty] private Choice<int> _audioBitrate;
@@ -402,6 +405,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
/// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font, subtitle, data, e-mail, 3D and geospatial targets.</summary>
public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
or FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D or FormatCategory.Geo) && TargetId != "eml";
+ /// <summary>"Save as ZIP" is offered for geospatial targets, whose results are several files (a Shapefile) or travel zipped.</summary>
+ public bool ShowZipResult => TargetCategory == FormatCategory.Geo;
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
@@ -542,6 +547,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
output.FileNamePattern = string.IsNullOrWhiteSpace(Pattern) ? "{name}" : Pattern.Trim();
output.Conflict = Conflict.Value;
output.KeepDates = KeepDates;
+ output.ZipResult = ZipResult;
return true;
}
diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axaml
index 776ec64a..f7055603 100644
--- a/src/Filee.App/Views/Pages/GeneralPage.axaml
+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml
@@ -50,6 +50,8 @@
</StackPanel>
<ToggleSwitch Content="{DynamicResource general.keep_dates}" IsChecked="{Binding KeepFileDates}" />
<TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource general.keep_dates_hint}" Margin="0,-6,0,0" />
+ <ToggleSwitch Content="{DynamicResource general.zip_geo}" IsChecked="{Binding ZipGeoResults}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource general.zip_geo_hint}" Margin="0,-6,0,0" />
</StackPanel>
</Border>
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index f09800a2..ace394c5 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -340,6 +340,8 @@
</StackPanel>
<CheckBox Content="{DynamicResource presets.keep_dates}" IsChecked="{Binding KeepDates}"
ToolTip.Tip="{DynamicResource presets.keep_dates_hint}" />
+ <CheckBox Content="{DynamicResource presets.zip_result}" IsChecked="{Binding ZipResult}" IsVisible="{Binding ShowZipResult}"
+ ToolTip.Tip="{DynamicResource presets.zip_result_hint}" />
</StackPanel>
</Border>
</StackPanel>
diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs
index 5bd0644d..f6b96b28 100644
--- a/src/Filee.Cli/Cli.cs
+++ b/src/Filee.Cli/Cli.cs
@@ -256,6 +256,8 @@ internal static class Cli
preset.Output.Conflict = conflict;
if (options.KeepDates)
preset.Output.KeepDates = true;
+ if (options.Zip)
+ preset.Output.ZipResult = true;
return preset;
}
diff --git a/src/Filee.Cli/CliOptions.cs b/src/Filee.Cli/CliOptions.cs
index 9631a2f9..8eb1b250 100644
--- a/src/Filee.Cli/CliOptions.cs
+++ b/src/Filee.Cli/CliOptions.cs
@@ -19,6 +19,8 @@ internal sealed record CliOptions
public bool Quiet { get; set; }
public bool MoveOriginals { get; set; }
public bool KeepDates { get; set; }
+
+ public bool Zip { get; set; }
public double? SettleSeconds { get; set; }
public string? Error { get; set; }
@@ -95,6 +97,9 @@ internal sealed record CliOptions
case "--keep-dates":
options.KeepDates = true;
break;
+ case "--zip":
+ options.Zip = true;
+ break;
case "--settle":
var settle = Value();
if (settle is not null)
diff --git a/src/Filee.Cli/Help.cs b/src/Filee.Cli/Help.cs
index 3c4411e5..3ec9e02f 100644
--- a/src/Filee.Cli/Help.cs
+++ b/src/Filee.Cli/Help.cs
@@ -55,6 +55,7 @@ internal static class Help
--overwrite Replace existing output files (default: add a number)
--skip Leave existing output files alone
--keep-dates Give converted files the created and modified dates of the originals
+ --zip Save the result of each file as one ZIP (a Shapefile's files together)
--json Print the result as JSON (for scripts and other programs)
--quiet Print nothing but errors
@@ -75,6 +76,7 @@ internal static class Help
converted at start
--settle <seconds> How long a file must stay unchanged (default 2)
--keep-dates Give converted files the created and modified dates of the originals
+ --zip Save the result of each file as one ZIP (a Shapefile's files together)
--quiet Print nothing but errors
""";
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 7230fb5a..42fd66b2 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -388,11 +388,13 @@ public sealed class JobQueue : IAsyncDisposable
try
{
IReadOnlyList<string> inputs = [file.SourcePath];
+ // "Save as ZIP": the last step writes into the work folder and the files are packed into one ZIP afterwards.
+ var zipResult = finalOutput && job.Preset.Output.ZipResult;
for (var s = 0; s < route.Steps.Count; s++)
{
var step = route.Steps[s];
var isLast = s == route.Steps.Count - 1;
- IOutputAllocator allocator = isLast && finalOutput
+ IOutputAllocator allocator = isLast && finalOutput && !zipResult
? CreateFinalAllocator(job, file.SourcePath, index)
: new TempAllocator(workDir, FormatRegistry.NameWithoutExtension(file.SourcePath));
@@ -434,6 +436,9 @@ public sealed class JobQueue : IAsyncDisposable
inputs = outputs;
}
+ if (zipResult && inputs.Count > 0)
+ inputs = PackZip(job, file, index, inputs, ct);
+
if (finalOutput)
{
file.Outputs.AddRange(inputs);
@@ -488,6 +493,43 @@ public sealed class JobQueue : IAsyncDisposable
}
}
+ /// <summary>
+ /// Packs the files one source was converted to into one ZIP (named by the preset's output rule, so the conflict
+ /// policy applies to it) and returns it; empty when the rule says to skip an existing ZIP. Files keep their names
+ /// inside, a clash gets "name (2).ext", and a ZIP that can't be completed is deleted.
+ /// </summary>
+ private IReadOnlyList<string> PackZip(ConversionJob job, FileResult file, int index, IReadOnlyList<string> files, CancellationToken ct)
+ {
+ if (CreateFinalAllocator(job, file.SourcePath, index).Allocate("zip") is not { } zipPath)
+ return [];
+ try
+ {
+ using (var stream = new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16))
+ using (var archive = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create))
+ {
+ var used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var path in files)
+ {
+ ct.ThrowIfCancellationRequested();
+ var name = Path.GetFileName(path);
+ for (var n = 2; !used.Add(name); n++)
+ name = $"{Path.GetFileNameWithoutExtension(path)} ({n}){Path.GetExtension(path)}";
+ System.IO.Compression.ZipFileExtensions.CreateEntryFromFile(archive, path, name, System.IO.Compression.CompressionLevel.Optimal);
+ }
+ }
+ }
+ catch
+ {
+ try
+ {
+ File.Delete(zipPath);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
+ throw;
+ }
+ return [zipPath];
+ }
+
private SemaphoreSlim GateFor(IConverter converter) =>
_engineGates.GetOrAdd(converter.Id, _ =>
{
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
index 38a7897f..0ab51377 100644
--- a/src/Filee.Core/Presets/OutputRule.cs
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -64,6 +64,12 @@ public sealed class OutputRule
/// </summary>
public bool KeepDates { get; set; }
+ /// <summary>
+ /// Pack what a conversion writes for one file (a Shapefile's .shp, .shx, .dbf, .prj and .cpg, or a single file)
+ /// into one ZIP named by the rule, instead of leaving the files themselves. The ZIP is the only output.
+ /// </summary>
+ public bool ZipResult { get; set; }
+
public OutputRule Clone()
{
var clone = (OutputRule)MemberwiseClone();
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index d7264a86..173fa2ba 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -159,16 +159,21 @@ public sealed class AppSettings
/// <summary>Every conversion keeps the created and modified dates of the original, whatever the preset says.</summary>
public bool KeepFileDates { get; set; }
+ /// <summary>Every geospatial conversion is saved as a ZIP, whatever the preset says (see <see cref="OutputRule.ZipResult"/>).</summary>
+ public bool ZipGeoResults { get; set; }
+
/// <summary>
/// Returns <paramref name="preset"/> itself, or a copy with the app-wide output settings applied: it saves to
/// <see cref="DefaultOutput"/> when the preset's location is <see cref="OutputLocation.Default"/>, and keeps the
- /// original dates when <see cref="KeepFileDates"/> is on. Name pattern and conflict handling stay the preset's.
+ /// original dates when <see cref="KeepFileDates"/> is on and is saved as a ZIP when <see cref="ZipGeoResults"/> is on and the
+ /// target is geospatial. Name pattern and conflict handling stay the preset's.
/// </summary>
public Preset WithDefaultOutput(Preset preset)
{
var location = preset.Output.Location == OutputLocation.Default;
var dates = KeepFileDates && !preset.Output.KeepDates;
- if (!location && !dates)
+ var zip = ZipGeoResults && !preset.Output.ZipResult && Formats.FormatRegistry.FindById(preset.TargetFormat)?.Category == Formats.FormatCategory.Geo;
+ if (!location && !dates && !zip)
return preset;
var copy = preset.Clone();
if (location)
@@ -179,6 +184,8 @@ public sealed class AppSettings
}
if (dates)
copy.Output.KeepDates = true;
+ if (zip)
+ copy.Output.ZipResult = true;
return copy;
}
}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index eac8f84b..5d912853 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1110,6 +1110,26 @@ public class RenderTests
Assert.False(preset.Document.LeaveOutPictures);
}
+ [AvaloniaFact]
+ public void Preset_editor_offers_save_as_zip_for_geospatial_targets_only()
+ {
+ TestServices.EnsureInitialized("en");
+ var preset = new Filee.Core.Presets.Preset { TargetFormat = "shp", Name = "Shapefile" };
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowZipResult);
+ Assert.Equal("Geospatial", vm.Target.Detail);
+
+ vm.ZipResult = true;
+ Assert.True(vm.Apply());
+ Assert.True(preset.Output.ZipResult);
+
+ vm.Target = vm.Targets.Single(t => t.Value == "kml");
+ Assert.True(vm.ShowZipResult);
+ vm.Target = vm.Targets.Single(t => t.Value == "png");
+ Assert.False(vm.ShowZipResult);
+ Assert.False(vm.ShowPdf && vm.Target.Value == "shp");
+ }
+
[AvaloniaFact]
public void Preset_editor_saves_media_and_archive_options()
{
diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs
index 9dd0fe10..a6d233bf 100644
--- a/tests/Filee.Cli.Tests/CliTests.cs
+++ b/tests/Filee.Cli.Tests/CliTests.cs
@@ -48,6 +48,20 @@ public sealed class CliTests : IDisposable
Assert.True(File.Exists(Path.Combine(outFolder, "b.jpg")));
}
+ [Fact]
+ public async Task Zip_saves_the_result_of_each_file_as_one_zip()
+ {
+ var geojson = Path.Combine(_folder, "places.geojson");
+ File.WriteAllText(geojson, """{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[1,2]}}""");
+
+ var (code, _, _) = await Run("convert", geojson, "--to", "shp", "--zip");
+
+ Assert.Equal(Cli.Success, code);
+ using var zip = System.IO.Compression.ZipFile.OpenRead(Path.Combine(_folder, "places.zip"));
+ Assert.Equal(["places.cpg", "places.dbf", "places.prj", "places.shp", "places.shx"], zip.Entries.Select(e => e.Name).Order().ToArray());
+ Assert.False(File.Exists(Path.Combine(_folder, "places.shp")));
+ }
+
[Fact]
public async Task Keep_dates_copies_the_dates_of_the_originals()
{
diff --git a/tests/Filee.Engines.Tests/GeoZipTests.cs b/tests/Filee.Engines.Tests/GeoZipTests.cs
new file mode 100644
index 00000000..8b2642b6
--- /dev/null
+++ b/tests/Filee.Engines.Tests/GeoZipTests.cs
@@ -0,0 +1,152 @@
+// "Save as ZIP" on geospatial presets: the result of each file is one ZIP in place of loose files, named by the output
+// rule (conflict policy included), with the files of a Shapefile together under matching names, and nothing left over
+// when a conversion fails.
+
+using System.IO.Compression;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.Engines.Tests;
+
+public class GeoZipTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static Action<Preset> Zip => preset => preset.Output.ZipResult = true;
+
+ private static string[] Entries(string zipPath)
+ {
+ using var zip = ZipFile.OpenRead(zipPath);
+ return [.. zip.Entries.Select(e => e.FullName).Order()];
+ }
+
+ private static string[] Names(string folder) => [.. Directory.GetFiles(folder).Select(f => Path.GetFileName(f)!).Order()];
+
+ [Fact]
+ public async Task A_shapefile_becomes_one_zip_with_its_five_files_and_nothing_else()
+ {
+ var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var folder = Path.GetDirectoryName(input)!;
+ var before = Names(folder);
+ var outputs = await fx.ConvertOkAsync(input, "shp", Zip);
+
+ var zip = Assert.Single(outputs);
+ Assert.EndsWith(".zip", zip);
+ Assert.Equal(["gdal_points.cpg", "gdal_points.dbf", "gdal_points.prj", "gdal_points.shp", "gdal_points.shx"], Entries(zip));
+ // The folder gained the ZIP and no loose files: the Shapefile files that were there already are the fixture's own.
+ Assert.Equal([.. before.Append("gdal_points.zip").Order()], Names(folder));
+ }
+
+ [Fact]
+ public async Task The_zipped_shapefile_is_the_same_shapefile_as_the_loose_one()
+ {
+ var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var loose = await fx.ConvertOkAsync(input, "shp");
+ var zip = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
+
+ using var archive = ZipFile.OpenRead(zip);
+ foreach (var file in loose)
+ {
+ var entry = archive.Entries.Single(e => e.Name.EndsWith(Path.GetExtension(file), StringComparison.Ordinal));
+ using var stream = entry.Open();
+ using var memory = new MemoryStream();
+ stream.CopyTo(memory);
+ // The .dbf holds the date it was written: compare everything after the fixed header's date bytes.
+ var expected = File.ReadAllBytes(file);
+ var actual = memory.ToArray();
+ Assert.Equal(expected.Length, actual.Length);
+ Assert.Equal(expected.AsSpan(4).ToArray(), actual.AsSpan(4).ToArray());
+ }
+ }
+
+ [Fact]
+ public async Task Single_file_results_are_zipped_too_and_mixed_geometry_puts_all_three_sets_in_one_zip()
+ {
+ var geojson = GeoFixtures.Copy(fx, "gdal_points", "shp");
+ var zip = (await fx.ConvertOkAsync(geojson, "geojson", Zip)).Single();
+ Assert.Equal(["gdal_points.geojson"], Entries(zip));
+
+ const string mixed = """{"type":"FeatureCollection","features":[{"type":"Feature","properties":{},"geometry":{"type":"Point","coordinates":[1,1]}},{"type":"Feature","properties":{},"geometry":{"type":"LineString","coordinates":[[0,0],[1,1]]}},{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}""";
+ var sets = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "mixed.geojson", mixed), "shp", Zip)).Single();
+ Assert.Equal(15, Entries(sets).Length);
+ Assert.Equal(3, Entries(sets).Select(Path.GetFileNameWithoutExtension).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task Each_source_gets_its_own_zip_in_one_job()
+ {
+ var a = GeoFixtures.Copy(fx, "gdal_points", "shp");
+ var b = GeoFixtures.Copy(fx, "gdal_polygons", "shp");
+ var job = await fx.ConvertAsync([a, b], new Preset { TargetFormat = "kml", Output = { ZipResult = true } });
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(["gdal_points.zip", "gdal_polygons.zip"], job.Outputs.Select(o => Path.GetFileName(o)!).Order().ToArray());
+ Assert.All(job.Outputs, o => Assert.Single(Entries(o)));
+ }
+
+ [Fact]
+ public async Task The_conflict_policy_applies_to_the_zip()
+ {
+ var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var first = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
+ var second = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
+ Assert.Equal("gdal_points.zip", Path.GetFileName(first));
+ Assert.Equal("gdal_points (2).zip", Path.GetFileName(second));
+
+ var length = new FileInfo(first).Length;
+ File.WriteAllText(first, "stale");
+ var skipped = await fx.ConvertAsync(input, "shp", preset => { preset.Output.ZipResult = true; preset.Output.Conflict = ConflictPolicy.Skip; });
+ Assert.Equal(FileState.Skipped, skipped.Files.Single().State);
+ Assert.Equal("stale", File.ReadAllText(first));
+
+ var replaced = (await fx.ConvertOkAsync(input, "shp", preset => { preset.Output.ZipResult = true; preset.Output.Conflict = ConflictPolicy.Overwrite; })).Single();
+ Assert.Equal(first, replaced);
+ Assert.Equal(length, new FileInfo(first).Length);
+ Assert.Equal(5, Entries(first).Length);
+ }
+
+ [Fact]
+ public async Task The_name_pattern_names_the_zip()
+ {
+ var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var zip = (await fx.ConvertOkAsync(input, "shp", preset =>
+ {
+ preset.Output.ZipResult = true;
+ preset.Output.FileNamePattern = "{name}_wgs84";
+ })).Single();
+ Assert.Equal("gdal_points_wgs84.zip", Path.GetFileName(zip));
+ Assert.Contains("gdal_points.shp", Entries(zip)); // the files inside keep the source's name
+ }
+
+ [Fact]
+ public async Task A_failed_conversion_leaves_no_zip()
+ {
+ var folder = fx.NewFolder();
+ var input = Path.Combine(folder, "broken.geojson");
+ File.WriteAllText(input, """{"type":"Point","coordinates":[1]}""");
+ var job = await fx.ConvertAsync(input, "shp", Zip);
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Equal(["broken.geojson"], Names(folder));
+ }
+
+ [Fact]
+ public async Task The_zip_is_the_only_output_when_a_route_has_several_steps()
+ {
+ // Shapefile → CSV → JSON is not geospatial output, but the option still packs whatever the last step writes.
+ var shp = GeoFixtures.Copy(fx, "gdal_points", "shp");
+ var zip = (await fx.ConvertOkAsync(shp, "json", Zip)).Single();
+ Assert.Equal(["gdal_points.json"], Entries(zip));
+ }
+
+ [Fact]
+ public void The_app_wide_setting_zips_geospatial_targets_only()
+ {
+ var settings = new AppSettings { ZipGeoResults = true };
+ Assert.True(settings.WithDefaultOutput(new Preset { TargetFormat = "shp" }).Output.ZipResult);
+ Assert.True(settings.WithDefaultOutput(new Preset { TargetFormat = "geojson", Output = { Location = OutputLocation.SameFolder } }).Output.ZipResult);
+ var png = new Preset { TargetFormat = "png", Output = { Location = OutputLocation.SameFolder } };
+ Assert.Same(png, settings.WithDefaultOutput(png));
+ var own = new Preset { TargetFormat = "kml", Output = { Location = OutputLocation.SameFolder } };
+ Assert.True(settings.WithDefaultOutput(own).Output.ZipResult);
+ Assert.False(own.Output.ZipResult); // a copy: the saved preset is unchanged
+ Assert.Same(own, new AppSettings().WithDefaultOutput(own));
+ }
+}