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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Convert vector graphics, ICNS and more image formats
KnifeLemonedb6d0bd610b
diff --git a/Directory.Packages.props b/Directory.Packages.propsindex 7fbcbe54..fa83795c 100644--- a/Directory.Packages.props+++ b/Directory.Packages.props@@ -34,6 +34,10 @@<PackageVersion Include="Unhwp" Version="0.13.0" /><PackageVersion Include="Markdig" Version="1.4.0" /><PackageVersion Include="ExcelNumberFormat" Version="1.1.0" />+ <!-- 5.2+ requires SkiaSharp 4 (see PDFtoImage above); 5.1.1 uses SkiaSharp 3.119 and HarfBuzzSharp 8.3 like Avalonia. -->+ <PackageVersion Include="Svg.Skia" Version="5.1.1" />+ <!-- Managed zstd / bzip2 for unpacking downloaded engines (conda packages). -->+ <PackageVersion Include="SharpCompress" Version="1.0.0" /></ItemGroup><ItemGroup Label="Tests">diff --git a/README.ko.md b/README.ko.mdindex 70dca7c5..82396696 100644--- a/README.ko.md+++ b/README.ko.md@@ -57,7 +57,8 @@| 원본 | 변환 대상 ||---|---|-| **이미지**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, HEIC(읽기) | 모든 이미지 형식, PDF |+| **이미지**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM; HEIC, 김프 XCF, 카메라 RAW, EMF/WMF(읽기) | 모든 이미지 형식, ICNS, PDF |+| **벡터**: SVG, SVGZ, AI, EPS, PS; ICNS | PDF(벡터 그대로), PNG 등 이미지, SVG ↔ SVGZ, PDF → EPS/PS || **PDF** | PNG, JPG, TIFF, 합치기, 나누기, 페이지 범위 || **문서**: DOCX, DOC, ODT, RTF | PDF, HWPX, 서로 변환, TXT, HTML || **스프레드시트**: XLSX, XLS, ODS, CSV | PDF, XLSX ↔ CSV, HWPX, HTML |@@ -67,7 +68,8 @@DOCX·XLSX·CSV·PPTX → PDF, 한글 파일, 마크다운은 설치하자마자 변환됩니다. MS 오피스·한컴오피스·LibreOffice가 없어도되고, PC에 설치된 프로그램은 쓰지 않습니다. 오래된 형식(DOC·XLS·PPT·OpenDocument)과 DOCX·ODT로 저장하기는-LibreOffice, HTML과 마크다운 ↔ 워드는 Pandoc을 쓰는데, 둘 다 처음 실행할 때 받을지 물어보는 추가 엔진입니다.+LibreOffice, HTML과 마크다운 ↔ 워드는 Pandoc, EPS·PostScript는 Ghostscript를 쓰는데, 모두 처음 실행할 때 받을지+물어보는 추가 엔진입니다.HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)에 있습니다.## 스크린샷diff --git a/README.md b/README.mdindex 273f687a..aad89711 100644--- a/README.md+++ b/README.md@@ -61,7 +61,8 @@| From | To ||---|---|-| **Images**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, HEIC (read) | any image format, PDF |+| **Images**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM; HEIC, GIMP XCF, camera RAW, EMF/WMF (read) | any image format, ICNS, PDF |+| **Vector**: SVG, SVGZ, AI, EPS, PS; ICNS | PDF (vector), PNG and other images, SVG ↔ SVGZ, PDF → EPS/PS || **PDF** | PNG, JPG, TIFF, merge, split, page ranges || **Documents**: DOCX, DOC, ODT, RTF | PDF, HWPX, each other, TXT, HTML || **Spreadsheets**: XLSX, XLS, ODS, CSV | PDF, XLSX ↔ CSV, HWPX, HTML |@@ -71,8 +72,8 @@DOCX, XLSX, CSV and PPTX → PDF, everything HWP and Markdown work out of the box: no Microsoft Office, Hancom Office orLibreOffice needed, and Filee never uses programs installed on your PC. Older formats (DOC, XLS, PPT, OpenDocument)-and saving as DOCX / ODT use LibreOffice, HTML / Markdown ↔ Word use Pandoc: optional engines that Filee offers to-download on first start.+and saving as DOCX / ODT use LibreOffice, HTML / Markdown ↔ Word use Pandoc, EPS / PostScript use Ghostscript: optional+engines that Filee offers to download on first start.How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).## Screenshotsdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex 6ff3096d..28cc5685 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -57,7 +57,8 @@| 源格式 | 目标格式 ||---|---|-| **图片**:JPG、PNG、WEBP、TIFF、BMP、GIF、ICO、AVIF、HEIC(读取) | 任意图片格式、PDF |+| **图片**:JPG、PNG、WEBP、TIFF、BMP、GIF、ICO、AVIF、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM;HEIC、GIMP XCF、相机 RAW、EMF/WMF(读取) | 任意图片格式、ICNS、PDF |+| **矢量图**:SVG、SVGZ、AI、EPS、PS;ICNS | PDF(保持矢量)、PNG 等图片、SVG ↔ SVGZ、PDF → EPS/PS || **PDF** | PNG、JPG、TIFF、合并、拆分、页码范围 || **文档**:DOCX、DOC、ODT、RTF | PDF、HWPX、互相转换、TXT、HTML || **电子表格**:XLSX、XLS、ODS、CSV | PDF、XLSX ↔ CSV、HWPX、HTML |@@ -67,7 +68,7 @@DOCX、XLSX、CSV、PPTX → PDF,所有 HWP 转换和 Markdown 装好即用:无需 Microsoft Office、韩文办公软件或 LibreOffice,Filee 也从不调用电脑上已安装的程序。较旧的格式(DOC、XLS、PPT、OpenDocument)以及保存为 DOCX / ODT 使用 LibreOffice,-HTML 与 Markdown ↔ Word 使用 Pandoc,这两个可选引擎会在首次启动时询问是否下载。+HTML 与 Markdown ↔ Word 使用 Pandoc,EPS / PostScript 使用 Ghostscript,这些可选引擎会在首次启动时询问是否下载。HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)。## 截图diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdindex 05fb3bc0..1c014c61 100644--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@ -17,6 +17,9 @@ Each component remains under its own license.| PDFtoImage | MIT | https://github.com/sungaila/PDFtoImage || PDFium (bblanchon.PDFium) | BSD-3-Clause / Apache-2.0 | https://pdfium.googlesource.com/pdfium || SkiaSharp | MIT | https://github.com/mono/SkiaSharp |+| Svg.Skia (incl. Svg, ShimSkiaSharp, ExCSS; text shaping in `Filee.Engines/Vector/OutlinedTextPlayback.cs` adapted from it) | MIT | https://github.com/wieslawsoltes/Svg.Skia |+| HarfBuzzSharp | MIT | https://github.com/mono/SkiaSharp |+| SharpCompress (zstd decompression for engine downloads) | MIT | https://github.com/adamhathcock/sharpcompress || Unhwp | MIT | https://github.com/iyulab/unhwp || Markdig | BSD-2-Clause | https://github.com/xoofx/markdig || ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |@@ -40,6 +43,8 @@ Downloaded from their official release pages when the user chooses to install th| H2Orestart (HWP/HWPX import for LibreOffice) | GPL-3.0 | https://github.com/ebandal/H2Orestart || Eclipse Temurin JRE (for H2Orestart) | GPL-2.0 with Classpath Exception | https://adoptium.net || Pandoc | GPL-2.0-or-later | https://github.com/jgm/pandoc |+| Ghostscript (conda-forge build) | AGPL-3.0 | https://www.ghostscript.com, https://github.com/conda-forge/ghostscript-feedstock |+| Microsoft Visual C++ Redistributable (for Ghostscript, conda-forge `vc14_runtime`) | Microsoft Visual C++ Redistributable license | https://github.com/conda-forge/vc-feedstock |These programs run as separate processes. Their source code is available from the linked projects.diff --git a/build/fetch-engines.ps1 b/build/fetch-engines.ps1index 932fa812..b4fd7c3b 100644--- a/build/fetch-engines.ps1+++ b/build/fetch-engines.ps1@@ -12,6 +12,8 @@jre/ Eclipse Temurin JRE 21 (GPLv2 + Classpath Exception), used by H2Orestartrhwp/ rhwp command line (MIT), HWP/HWPX -> PDFpandoc/ Pandoc (GPL-2.0-or-later, separate program), Markdown/HTML and MD/HTML/ODT/RTF -> HWPX+ ghostscript/ Ghostscript (AGPL-3.0, separate program) from conda-forge, EPS/PS <-> PDF, with the Microsoft+ C++ runtime DLLs (vcruntime/) copied next to gswin64c.exeEvery download is pinned to a version and verified with SHA-256 (src/Filee.Engines/Infrastructure/engines.json,shared with the app). Downloads are cached in build/.cache.@@ -81,6 +83,23 @@ function Expand-Flat([string]$zip, [string]$target) {Remove-Item $tmp -Recurse -Force}+# Unpacks the Windows binaries (Library/bin) of a conda-forge package: a zip holding pkg-*.tar.zst. Windows' own+# tar.exe (bsdtar with zstd, Windows 10 1803 and later) reads the tarball; the app uses a managed decompressor.+function Expand-Conda([string]$conda, [string]$target) {+ $tmp = Join-Path $cache ('c-' + [Guid]::NewGuid().ToString('N').Substring(0, 8))+ Add-Type -AssemblyName System.IO.Compression.FileSystem+ [System.IO.Compression.ZipFile]::ExtractToDirectory($conda, $tmp)+ $pkg = Get-ChildItem $tmp -Filter 'pkg-*.tar.zst' | Select-Object -First 1+ if (-not $pkg) { throw "$conda is not a conda package." }+ $files = Join-Path $tmp 'files'+ New-Item -ItemType Directory -Force -Path $files | Out-Null+ & (Join-Path $env:SystemRoot 'System32\tar.exe') -xf $pkg.FullName -C $files+ if ($LASTEXITCODE -ne 0) { throw "tar.exe could not unpack $($pkg.Name) (it needs zstd support)." }+ Reset-Folder $target+ Get-ChildItem (Join-Path $files 'Library\bin') -Force | Move-Item -Destination $target+ Remove-Item $tmp -Recurse -Force+}+# Removes parts of LibreOffice that headless conversion never uses (~500 MB):# help, readmes, the MSI stub copied by the admin install, the gallery, and spell-check dictionaries except# English and Korean (their hyphenation patterns can affect page layout when exporting PDFs).@@ -155,4 +174,16 @@ if ('h2orestart' -in $selected) {}}+if ('vcruntime' -in $selected -or 'ghostscript' -in $selected) {+ Expand-Conda (Get-Engine 'vcruntime') (Join-Path $Destination 'vcruntime')+}++if ('ghostscript' -in $selected) {+ $target = Join-Path $Destination 'ghostscript'+ Expand-Conda (Get-Engine 'ghostscript') $target+ if (-not (Test-Path (Join-Path $target 'gswin64c.exe'))) { throw 'gswin64c.exe not found in the Ghostscript package.' }+ # App-local Microsoft C++ runtime next to gswin64c.exe, as EngineInstaller does.+ Copy-Item (Join-Path $Destination 'vcruntime\*.dll') $target -Force+}+Write-Host "Engines ready in $Destination"diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 15adb4d1..0463f68e 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -5,7 +5,9 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| Engine | How it gets there | Handles ||---|---|---|-| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF ↔ each other; HEIC read |+| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM ↔ each other; HEIC, XCF, camera RAW (LibRaw) and EMF/WMF (Windows) read |+| Vector graphics | built in (Svg.Skia, SkiaSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, PDF-compatible AI → PDF |+| ICNS | built in | images → ICNS (16–1024 px), ICNS → images || PDFsharp | built in (library) | images → PDF, merge, split, page ranges || PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) || Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |@@ -15,6 +17,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** || LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT || Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |+| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium) |DOCX, XLSX and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPXand rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.@@ -37,12 +40,37 @@ they can be installed or removed later in Settings → *Engines*. A conversion tinstall root, so uninstalling removes them.- LibreOffice comes as an MSI and is unpacked with an administrative install (`msiexec /a`): files only, noregistry entries, no admin rights. Help, gallery and most dictionaries are removed afterwards (~500 MB).+- Ghostscript comes from conda-forge (Artifex publishes only an NSIS installer): a `.conda` package is a zip with a+ zstd tarball, of which only `Library/bin` is unpacked (SharpCompress; `fetch-engines.ps1` uses Windows' `tar.exe`).+ Its fonts and resources are compiled into `gsdll64.dll`. The Microsoft C++ runtime it was built against+ (`vcruntime` component) is copied next to `gswin64c.exe`, so it runs on PCs without the VC++ Redistributable.To bump a version, change `url`, `sha256` and `size` in engines.json together, run`pwsh build/fetch-engines.ps1`, test, and update `THIRD-PARTY-NOTICES.md`. When the LibreOffice team retires aversion from `download.documentfoundation.org/libreoffice/stable/`, its URL stops working: keep the pinned versioncurrent.+## Images and vector graphics++- **Layered files.** PSD/PSB convert from Photoshop's composite (ImageMagick merges the layers when a file was saved+ without "maximize compatibility"). GIMP XCF layers are composited at their offsets with their blend modes; hidden+ layers are left out. ImageMagick reads 8-bit XCF without zlib tile compression (GIMP 2.10+ "better but slower+ compression" files give a clear error).+- **Camera RAW** (DNG, CR2, CR3, NEF, ARW, …, and `.raw`) is decoded by LibRaw with the camera's white balance,+ sRGB output and AHD demosaicing, then turned upright from the EXIF orientation.+- **EMF/WMF** are rendered through GDI+ (Windows only) at the preset's render DPI (at least 150), keeping their+ physical size in PDF output.+- **SVG → PDF** replays the drawing into Skia's PDF backend: paths, gradients and clips stay vector. Text is written+ as glyph outlines (shaped with HarfBuzz), because SkiaSharp's PDF backend has no font subsetter and would embed+ every font whole (13 MB for one line of Korean). SVG → images is rendered at its final size: the preset's DPI, at+ least 1024 px on the long edge, or exactly the preset's resize target. External files next to the SVG are+ loaded; nothing is fetched from the network and scripts don't run.+- **ICNS** files are written with every size iconutil makes (16–1024 px, PNG), the picture centred on a transparent+ square; reading takes the largest image (PNG, JPEG 2000 or the old RLE + mask entries).+- **Illustrator** files saved with "Create PDF compatible file" (the default since Illustrator 9) are PDFs and need+ nothing extra; PostScript-based ones need Ghostscript.+- EPS, PS and AI reach PNG, JPG, … through PDF (Ghostscript → PDFium), and SVG reaches EPS through PDF.+## HWPX writerFilee writes OWPML (HWPX) itself, so saving as HWPX needs no Hancom Office and shows no approval dialog.diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex ca855ad4..a341b8e0 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -240,6 +240,8 @@"engines.package.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, conversions to DOCX, ODT and ODS, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX and CSV convert without it.","engines.package.pandoc.name": "Pandoc (HTML and Markdown ↔ Word)","engines.package.pandoc.description": "Markdown ↔ DOCX, ODT and RTF, and HTML, ODT and RTF → HWPX. Markdown → PDF, HWPX, HTML and TXT, and DOCX → HWPX work without it.",+ "engines.package.ghostscript.name": "Ghostscript (EPS and PostScript)",+ "engines.package.ghostscript.description": "EPS, PS and older Illustrator files → PDF, PNG and other images, and PDF or SVG → EPS/PS. SVG and AI files saved with PDF compatibility convert without it.","engines.package.size": "Download {0} · {1} on disk","engines.install": "Install","engines.cancel": "Cancel",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex c45e8822..dd0f5954 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -240,6 +240,8 @@"engines.package.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, DOCX·ODT·ODS로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV는 없어도 변환돼요.","engines.package.pandoc.name": "Pandoc (HTML·마크다운 ↔ 워드)","engines.package.pandoc.description": "마크다운 ↔ DOCX·ODT·RTF 변환과 HTML·ODT·RTF → HWPX 변환을 추가합니다. 마크다운 → PDF·HWPX·HTML·TXT와 DOCX → HWPX는 없어도 됩니다.",+ "engines.package.ghostscript.name": "Ghostscript (EPS·PostScript)",+ "engines.package.ghostscript.description": "EPS·PS 파일과 예전 일러스트레이터 파일을 PDF·PNG 등 이미지로, PDF·SVG를 EPS·PS로 변환해요. SVG와 PDF 호환으로 저장한 AI 파일은 없어도 변환돼요.","engines.package.size": "다운로드 {0} · 설치 후 {1}","engines.install": "설치","engines.cancel": "취소",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex de9260d8..8aeda4c9 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -240,6 +240,8 @@"engines.package.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,转换为 DOCX、ODT 和 ODS,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX 和 CSV 无需它即可转换。","engines.package.pandoc.name": "Pandoc(HTML 与 Markdown ↔ Word)","engines.package.pandoc.description": "支持 Markdown ↔ DOCX、ODT、RTF,以及 HTML、ODT、RTF → HWPX。Markdown → PDF、HWPX、HTML、TXT 和 DOCX → HWPX 无需此引擎。",+ "engines.package.ghostscript.name": "Ghostscript(EPS 与 PostScript)",+ "engines.package.ghostscript.description": "EPS、PS 和旧版 Illustrator 文件 → PDF、PNG 等图片,以及 PDF 或 SVG → EPS/PS。SVG 和以 PDF 兼容方式保存的 AI 文件无需它即可转换。","engines.package.size": "下载 {0} · 占用 {1}","engines.install": "安装","engines.cancel": "取消",diff --git a/src/Filee.App/ViewModels/EngineSetupViewModel.cs b/src/Filee.App/ViewModels/EngineSetupViewModel.csindex 04e564f6..ab48212a 100644--- a/src/Filee.App/ViewModels/EngineSetupViewModel.cs+++ b/src/Filee.App/ViewModels/EngineSetupViewModel.cs@@ -20,9 +20,9 @@ public sealed partial class EngineSetupViewModel : ObservableObject_loc = loc;foreach (var package in Packages){- // LibreOffice is large and only needed for older formats (DOC, XLS, PPT, OpenDocument): offered, not- // pre-selected.- package.Selected = !package.IsInstalled && package.Package.Id != "libreoffice";+ // LibreOffice is large and only needed for older formats (DOC, XLS, PPT, OpenDocument), Ghostscript only+ // for EPS/PostScript: offered, not pre-selected.+ package.Selected = !package.IsInstalled && package.Package.Id is not ("libreoffice" or "ghostscript");package.PropertyChanged += OnPackageChanged;}}diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 31b45a74..0d5ea55e 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -3,11 +3,13 @@using Filee.Core.Conversion;using Filee.Engines.Hwp;using Filee.Engines.Hwp.Hwpx;+using Filee.Engines.Icns;using Filee.Engines.Infrastructure;using Filee.Engines.Magick;using Filee.Engines.Office;using Filee.Engines.Pdf;using Filee.Engines.Text;+using Filee.Engines.Vector;namespace Filee.Engines;@@ -29,7 +31,10 @@ public static class EngineRegistrynew MarkdownConverter(),new SpreadsheetConverter(),new HwpxConverter(),+ new VectorConverter(),+ new IcnsConverter(),new PandocConverter(),+ new GhostscriptConverter(),new LibreOfficeConverter(env),];diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csprojindex af7d20a6..ac5a6676 100644--- a/src/Filee.Engines/Filee.Engines.csproj+++ b/src/Filee.Engines/Filee.Engines.csproj@@ -18,6 +18,8 @@<PackageReference Include="Unhwp" /><PackageReference Include="Markdig" /><PackageReference Include="ExcelNumberFormat" />+ <PackageReference Include="Svg.Skia" />+ <PackageReference Include="SharpCompress" /><PackageReference Include="Microsoft.Extensions.Logging.Abstractions" /></ItemGroup>diff --git a/src/Filee.Engines/Icns/IcnsConverter.cs b/src/Filee.Engines/Icns/IcnsConverter.csnew file mode 100644index 00000000..8123beb3--- /dev/null+++ b/src/Filee.Engines/Icns/IcnsConverter.cs@@ -0,0 +1,120 @@+// macOS icons (.icns) without macOS: writes them from any raster image and reads them back, built in.+// The container is handled by IcnsFile; ImageMagick resizes and encodes/decodes the PNG and JPEG 2000 entries.++using Filee.Core.Conversion;+using Filee.Engines.Magick;+using ImageMagick;++namespace Filee.Engines.Icns;++/// <summary>Raster image → ICNS and ICNS → raster image.</summary>+public sealed class IcnsConverter : IConverter+{+ public string Id => "icns";+ public string DisplayName => "ICNS (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ .. ImageEncoder.Sources.Select(source => new ConversionEdge(source, "icns")),+ .. ImageEncoder.Writable.Select(target => new ConversionEdge("icns", target)),+ ];++ public EngineStatus GetStatus() => EngineStatus.Available();++ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>+ Task.Run(() => step.From == "icns"+ ? ReadIcon(step, progress, cancellationToken)+ : WriteIcon(step, progress, cancellationToken), cancellationToken);++ /// <summary>+ /// Makes an icon with every size iconutil produces (16 to 1024 px, PNG encoded). The picture is centred on a+ /// transparent square first, so nothing is stretched or cut off.+ /// </summary>+ private static IReadOnlyList<string> WriteIcon(ConversionStep step, IProgress<double>? progress, CancellationToken ct)+ {+ using var images = ImageReader.Read(step.InputPath, step.From, step.Preset);+ // An icon holds one picture: the first page/frame, or the largest icon of an .ico.+ var master = ImageEncoder.SelectFrames(images, step.From, "icns")[0];+ ImageEncoder.ApplyOptions(master, step.Preset.Image, "icns");+ MakeSquare(master);+ progress?.Report(0.2);++ var entries = new List<IcnsEntry>();+ var encoded = new Dictionary<int, byte[]>();+ foreach (var (type, size) in IcnsFile.WrittenTypes)+ {+ ct.ThrowIfCancellationRequested();+ if (!encoded.TryGetValue(size, out var png))+ {+ using var icon = master.Clone();+ icon.FilterType = FilterType.Lanczos;+ icon.Resize(new MagickGeometry((uint)size, (uint)size) { IgnoreAspectRatio = true });+ icon.Strip(); // EXIF/XMP would be repeated in all ten entries+ png = icon.ToByteArray(MagickFormat.Png32);+ encoded[size] = png;+ }+ entries.Add(new IcnsEntry(type, png));+ progress?.Report(0.2 + 0.7 * entries.Count / IcnsFile.WrittenTypes.Length);+ }++ var path = step.Output.Allocate("icns");+ if (path is null)+ return [];+ File.WriteAllBytes(path, IcnsFile.Write(entries));+ progress?.Report(1);+ return [path];+ }++ /// <summary>Converts the largest image of an .icns file to <see cref="ConversionStep.To"/>.</summary>+ private static IReadOnlyList<string> ReadIcon(ConversionStep step, IProgress<double>? progress, CancellationToken ct)+ {+ var entries = IcnsFile.Parse(File.ReadAllBytes(step.InputPath));+ var candidates = IcnsFile.Candidates(entries);+ if (candidates.Count == 0)+ throw new InvalidDataException("The ICNS file contains no image Filee can read (only 1-bit or 8-bit palette icons).");+ progress?.Report(0.2);++ using var image = DecodeLargest(candidates, ct);+ ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);+ progress?.Report(0.7);+ var written = ImageEncoder.Write([image], step.To, step.Output, step.Preset.Image);+ progress?.Report(1);+ return written;+ }++ /// <summary>Decodes the largest image; a broken entry falls back to the next smaller one.</summary>+ private static MagickImage DecodeLargest(List<IcnsFile.Candidate> candidates, CancellationToken ct)+ {+ Exception? first = null;+ foreach (var candidate in candidates)+ {+ ct.ThrowIfCancellationRequested();+ try+ {+ if (candidate.Encoded is not null)+ return new MagickImage(candidate.Encoded);+ var bitmap = candidate.Decode!();+ var image = new MagickImage();+ image.ReadPixels(bitmap.Rgba, new PixelReadSettings((uint)bitmap.Width, (uint)bitmap.Height, StorageType.Char, PixelMapping.RGBA));+ return image;+ }+ catch (Exception ex) when (ex is MagickException or InvalidDataException or ArgumentException)+ {+ first ??= ex;+ }+ }+ throw new InvalidDataException("No image in the ICNS file could be decoded.", first);+ }++ /// <summary>Pads the shorter side with transparency so the picture becomes a centred square.</summary>+ private static void MakeSquare(IMagickImage<byte> image)+ {+ image.Alpha(AlphaOption.Set);+ if (image.Width == image.Height)+ return;+ var side = Math.Max(image.Width, image.Height);+ image.BackgroundColor = MagickColors.Transparent;+ image.Extent(side, side, Gravity.Center);+ }+}diff --git a/src/Filee.Engines/Icns/IcnsFile.cs b/src/Filee.Engines/Icns/IcnsFile.csnew file mode 100644index 00000000..424cde41--- /dev/null+++ b/src/Filee.Engines/Icns/IcnsFile.cs@@ -0,0 +1,227 @@+// Reads and writes Apple icon files (.icns): a list of typed entries, each holding one icon size as PNG, JPEG 2000+// or (in old files) run-length encoded RGB plus a separate 8-bit mask. ImageMagick has no ICNS coder.++using System.Buffers.Binary;+using System.Text;++namespace Filee.Engines.Icns;++/// <summary>One entry of an .icns file.</summary>+/// <param name="Type">Four-character type code, e.g. <c>"ic08"</c>.</param>+/// <param name="Data">Entry payload (without the 8-byte entry header).</param>+internal sealed record IcnsEntry(string Type, byte[] Data);++/// <summary>A decoded icon: straight (non-premultiplied) RGBA pixels, row by row.</summary>+internal sealed record IcnsBitmap(int Width, int Height, byte[] Rgba);++/// <summary>ICNS container parsing, writing and the legacy RLE codec.</summary>+internal static class IcnsFile+{+ /// <summary>Entry types written for a new icon, smallest first, with their pixel size (iconutil's set).</summary>+ public static readonly (string Type, int Size)[] WrittenTypes =+ [+ ("icp4", 16),+ ("ic11", 32), // 16 pt @2x+ ("icp5", 32),+ ("ic12", 64), // 32 pt @2x+ ("ic07", 128),+ ("ic13", 256), // 128 pt @2x+ ("ic08", 256),+ ("ic14", 512), // 256 pt @2x+ ("ic09", 512),+ ("ic10", 1024), // 512 pt @2x+ ];++ /// <summary>Pixel size of the image types that carry PNG or JPEG 2000 data (or ARGB for ic04/ic05).</summary>+ private static readonly Dictionary<string, int> ImageTypes = new(StringComparer.Ordinal)+ {+ ["icp4"] = 16, ["icp5"] = 32, ["icp6"] = 64, ["ic07"] = 128, ["ic08"] = 256, ["ic09"] = 512, ["ic10"] = 1024,+ ["ic11"] = 32, ["ic12"] = 64, ["ic13"] = 256, ["ic14"] = 512, ["ic04"] = 16, ["ic05"] = 32,+ ["icsb"] = 18, ["icsB"] = 36, ["sb24"] = 24, ["SB24"] = 48,+ };++ /// <summary>Legacy RLE RGB types, their size and the type of their 8-bit mask.</summary>+ private static readonly Dictionary<string, (int Size, string Mask)> LegacyTypes = new(StringComparer.Ordinal)+ {+ ["is32"] = (16, "s8mk"),+ ["il32"] = (32, "l8mk"),+ ["ih32"] = (48, "h8mk"),+ ["it32"] = (128, "t8mk"),+ };++ private static ReadOnlySpan<byte> PngSignature => [0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A];+ private static ReadOnlySpan<byte> Jp2Signature => [0, 0, 0, 0x0C, (byte)'j', (byte)'P', 0x20, 0x20];+ private static ReadOnlySpan<byte> J2kSignature => [0xFF, 0x4F, 0xFF, 0x51];++ // ───────────────────────── Container ─────────────────────────++ /// <summary>Parses the top-level entries of an .icns file.</summary>+ /// <exception cref="InvalidDataException">The data is not an ICNS file.</exception>+ public static List<IcnsEntry> Parse(ReadOnlySpan<byte> file)+ {+ if (file.Length < 8 || !file[..4].SequenceEqual("icns"u8))+ throw new InvalidDataException("Not an ICNS file (the 'icns' signature is missing).");+ var declared = BinaryPrimitives.ReadUInt32BigEndian(file[4..]);+ var end = (int)Math.Min(declared, (uint)file.Length);++ var entries = new List<IcnsEntry>();+ for (var offset = 8; offset + 8 <= end;)+ {+ var type = Encoding.Latin1.GetString(file.Slice(offset, 4));+ var length = BinaryPrimitives.ReadUInt32BigEndian(file[(offset + 4)..]);+ if (length < 8 || offset + length > end)+ break; // truncated or corrupt: keep what was readable+ entries.Add(new IcnsEntry(type, file.Slice(offset + 8, (int)length - 8).ToArray()));+ offset += (int)length;+ }+ return entries;+ }++ /// <summary>Writes entries, preceded by a table of contents like iconutil does.</summary>+ public static byte[] Write(IReadOnlyList<IcnsEntry> entries)+ {+ var tocLength = 8 + 8 * entries.Count;+ var total = 8 + tocLength + entries.Sum(e => 8 + e.Data.Length);+ var buffer = new byte[total];+ var span = buffer.AsSpan();+ "icns"u8.CopyTo(span);+ BinaryPrimitives.WriteUInt32BigEndian(span[4..], (uint)total);++ var offset = 8;+ "TOC "u8.CopyTo(span[offset..]);+ BinaryPrimitives.WriteUInt32BigEndian(span[(offset + 4)..], (uint)tocLength);+ offset += 8;+ foreach (var entry in entries)+ {+ Encoding.Latin1.GetBytes(entry.Type, span.Slice(offset, 4));+ BinaryPrimitives.WriteUInt32BigEndian(span[(offset + 4)..], (uint)(8 + entry.Data.Length));+ offset += 8;+ }+ foreach (var entry in entries)+ {+ Encoding.Latin1.GetBytes(entry.Type, span.Slice(offset, 4));+ BinaryPrimitives.WriteUInt32BigEndian(span[(offset + 4)..], (uint)(8 + entry.Data.Length));+ entry.Data.CopyTo(span[(offset + 8)..]);+ offset += 8 + entry.Data.Length;+ }+ return buffer;+ }++ // ───────────────────────── Choosing an image ─────────────────────────++ /// <summary>An icon image found in the file, not decoded yet.</summary>+ /// <param name="Size">Nominal pixel size from the entry type.</param>+ /// <param name="Encoded">PNG or JPEG 2000 bytes, decoded by ImageMagick; null for legacy/ARGB data.</param>+ /// <param name="Decode">Decoder for legacy/ARGB data.</param>+ public sealed record Candidate(string Type, int Size, byte[]? Encoded, Func<IcnsBitmap>? Decode);++ /// <summary>All images of the file, largest first (PNG / JPEG 2000 before legacy data of the same size).</summary>+ public static List<Candidate> Candidates(IReadOnlyList<IcnsEntry> entries)+ {+ var byType = entries.GroupBy(e => e.Type).ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal);+ var result = new List<Candidate>();+ foreach (var entry in entries)+ {+ if (ImageTypes.TryGetValue(entry.Type, out var size))+ {+ if (IsEncodedImage(entry.Data))+ result.Add(new Candidate(entry.Type, size, entry.Data, null));+ else if (entry.Data.AsSpan().StartsWith("ARGB"u8))+ result.Add(new Candidate(entry.Type, size, null, () => DecodeArgb(entry.Data, size)));+ }+ else if (LegacyTypes.TryGetValue(entry.Type, out var legacy))+ {+ var mask = byType.GetValueOrDefault(legacy.Mask)?.Data;+ result.Add(new Candidate(entry.Type, legacy.Size, null, () => DecodeLegacy(entry.Type, entry.Data, mask, legacy.Size)));+ }+ }+ return result.OrderByDescending(c => c.Size).ThenBy(c => c.Encoded is null ? 1 : 0).ToList();+ }++ /// <summary>True for PNG and JPEG 2000 (JP2 container or raw codestream) data.</summary>+ public static bool IsEncodedImage(ReadOnlySpan<byte> data) =>+ data.StartsWith(PngSignature) || data.StartsWith(Jp2Signature) || data.StartsWith(J2kSignature);++ // ───────────────────────── Legacy codecs ─────────────────────────++ /// <summary>+ /// Decodes is32/il32/ih32/it32: RGB stored channel after channel (all red, then green, then blue), each run-length+ /// encoded, plus an optional 8-bit mask entry as alpha. it32 data starts with four zero bytes. Data exactly+ /// 4 × size² bytes long is uncompressed ARGB, which some writers use for is32/il32.+ /// </summary>+ public static IcnsBitmap DecodeLegacy(string type, byte[] data, byte[]? mask, int size)+ {+ var pixels = size * size;+ var rgba = new byte[pixels * 4];+ if (data.Length == pixels * 4)+ {+ for (var i = 0; i < pixels; i++)+ {+ rgba[i * 4] = data[i * 4 + 1];+ rgba[i * 4 + 1] = data[i * 4 + 2];+ rgba[i * 4 + 2] = data[i * 4 + 3];+ }+ }+ else+ {+ var planes = UnpackBits(data.AsSpan(type == "it32" ? 4 : 0), pixels * 3);+ for (var i = 0; i < pixels; i++)+ {+ rgba[i * 4] = planes[i];+ rgba[i * 4 + 1] = planes[pixels + i];+ rgba[i * 4 + 2] = planes[2 * pixels + i];+ }+ }+ for (var i = 0; i < pixels; i++)+ rgba[i * 4 + 3] = mask is not null && mask.Length >= pixels ? mask[i] : (byte)255;+ return new IcnsBitmap(size, size, rgba);+ }++ /// <summary>Decodes ic04/ic05 "ARGB" entries: the tag, then A, R, G and B planes run-length encoded.</summary>+ public static IcnsBitmap DecodeArgb(byte[] data, int size)+ {+ var pixels = size * size;+ var planes = UnpackBits(data.AsSpan(4), pixels * 4);+ var rgba = new byte[pixels * 4];+ for (var i = 0; i < pixels; i++)+ {+ rgba[i * 4] = planes[pixels + i];+ rgba[i * 4 + 1] = planes[2 * pixels + i];+ rgba[i * 4 + 2] = planes[3 * pixels + i];+ rgba[i * 4 + 3] = planes[i];+ }+ return new IcnsBitmap(size, size, rgba);+ }++ /// <summary>+ /// Apple's icon RLE: a control byte below 0x80 copies the next (n + 1) bytes, a control byte of 0x80 or more+ /// repeats the next byte (n − 125) times. Missing data (truncated files) stays zero.+ /// </summary>+ public static byte[] UnpackBits(ReadOnlySpan<byte> source, int length)+ {+ var output = new byte[length];+ var written = 0;+ var i = 0;+ while (written < length && i < source.Length)+ {+ int control = source[i++];+ if (control < 0x80)+ {+ var count = Math.Min(control + 1, Math.Min(length - written, source.Length - i));+ source.Slice(i, count).CopyTo(output.AsSpan(written));+ i += control + 1;+ written += count;+ }+ else+ {+ if (i >= source.Length)+ break;+ var value = source[i++];+ var count = Math.Min(control - 125, length - written);+ output.AsSpan(written, count).Fill(value);+ written += count;+ }+ }+ return output;+ }+}diff --git a/src/Filee.Engines/Infrastructure/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.csindex ace46435..04f23e1c 100644--- a/src/Filee.Engines/Infrastructure/EngineDownloads.cs+++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs@@ -6,7 +6,10 @@ using System.Text.Json;namespace Filee.Engines.Infrastructure;/// <summary>One download from engines.json.</summary>-/// <param name="Kind">"zip" (extracted), "msi" (administrative install, no system changes) or "oxt" (LibreOffice extension).</param>+/// <param name="Kind">+/// "zip" (extracted), "msi" (administrative install, no system changes), "oxt" (LibreOffice extension) or "conda"+/// (conda-forge package: its Windows binaries are extracted).+/// </param>/// <param name="Size">Download size in bytes.</param>public sealed record EngineComponent(string Id, string Version, string Url, string Sha256, long Size, string Kind);@@ -28,6 +31,8 @@ public static class EngineDownloads[new("libreoffice", ["libreoffice", "h2orestart", "jre"], 1_265_000_000, ["libreoffice"]),new("pandoc", ["pandoc"], 236_000_000, ["pandoc"]),+ // Ghostscript from conda-forge plus the Microsoft C++ runtime it was built against (copied next to it).+ new("ghostscript", ["ghostscript", "vcruntime"], 31_000_000, ["ghostscript"]),];/// <summary>Total download size of a package in bytes.</summary>diff --git a/src/Filee.Engines/Infrastructure/EngineInstaller.cs b/src/Filee.Engines/Infrastructure/EngineInstaller.csindex 4515af24..49486a03 100644--- a/src/Filee.Engines/Infrastructure/EngineInstaller.cs+++ b/src/Filee.Engines/Infrastructure/EngineInstaller.cs@@ -5,13 +5,17 @@// cancelled install never leaves a half-installed engine behind.// * The LibreOffice MSI is unpacked with an administrative install (msiexec /a): files only, no registry entries,// no admin rights. Parts headless conversion never uses (help, gallery, most dictionaries) are removed.+// * conda-forge packages (Ghostscript, the Microsoft C++ runtime) are zip files holding zstd-compressed tarballs;+// only their Windows binaries (Library/bin) are unpacked, with a managed decompressor (no 7-Zip, no installer).// * A marker file with the component's hash records what is installed, so an engines.json update is detected.using System.Diagnostics;+using System.Formats.Tar;using System.IO.Compression;using System.Security.Cryptography;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Logging.Abstractions;+using SharpCompress.Compressors.ZStandard;namespace Filee.Engines.Infrastructure;@@ -81,6 +85,8 @@ public sealed class EngineInstallerdone += component.Size;_logger.LogInformation("Installed engine component {Component} {Version}", component.Id, component.Version);}+ if (pending.Count > 0)+ CopyRuntime(package);}/// <summary>Removes the package's folders. Fails if an engine is running (its files are locked).</summary>@@ -179,6 +185,10 @@ public sealed class EngineInstallerTrimLibreOffice(libreOffice);Replace(component.Id, libreOffice);break;+ case "conda":+ UnpackConda(file, staging, cancellationToken);+ Replace(component.Id, staging);+ break;case "oxt":// LibreOffice registers bundled extensions (plain folders under share/extensions) on start-up.var extensions = Path.Combine(FolderOf("libreoffice"), "share", "extensions");@@ -260,6 +270,58 @@ public sealed class EngineInstaller}}+ /// <summary>+ /// Unpacks the Windows binaries of a conda package (.conda = zip with pkg-*.tar.zst): the files under Library/bin+ /// land directly in <paramref name="target"/>. Resources such as Ghostscript's fonts are compiled into its DLL.+ /// </summary>+ internal static void UnpackConda(string condaFile, string target, CancellationToken cancellationToken)+ {+ const string prefix = "Library/bin/";+ using var zip = ZipFile.OpenRead(condaFile);+ var payload = zip.Entries.FirstOrDefault(e => e.FullName.StartsWith("pkg-", StringComparison.Ordinal) && e.FullName.EndsWith(".tar.zst", StringComparison.Ordinal))+ ?? throw new InvalidDataException("Not a conda package (pkg-*.tar.zst is missing).");+ Directory.CreateDirectory(target);+ var root = Path.GetFullPath(target) + Path.DirectorySeparatorChar;+ var count = 0;+ using (var zstd = new DecompressionStream(payload.Open(), leaveOpen: false))+ using (var tar = new TarReader(zstd))+ {+ while (tar.GetNextEntry() is { } entry)+ {+ cancellationToken.ThrowIfCancellationRequested();+ var name = entry.Name.Replace('\\', '/');+ if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile) || !name.StartsWith(prefix, StringComparison.Ordinal))+ continue;+ var path = Path.GetFullPath(Path.Combine(target, name[prefix.Length..]));+ if (!path.StartsWith(root, StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException($"Unsafe path in conda package: {entry.Name}");+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ entry.ExtractToFile(path, overwrite: true);+ count++;+ }+ }+ if (count == 0)+ throw new InvalidDataException("The conda package contains no Windows binaries (Library/bin).");+ }++ /// <summary>+ /// App-local Microsoft C++ runtime: when a package includes the "vcruntime" component, its DLLs are copied next+ /// to the programs of the package's other conda components. Windows looks for DLLs in a program's folder before+ /// System32, so the runtime a program was built for is used even when the PC has none or an older one.+ /// </summary>+ private void CopyRuntime(EnginePackage package)+ {+ const string runtime = "vcruntime";+ if (!package.Components.Contains(runtime) || !Directory.Exists(FolderOf(runtime)))+ return;+ var dlls = Directory.GetFiles(FolderOf(runtime), "*.dll");+ foreach (var id in package.Components.Where(c => c != runtime && _components[c].Kind == "conda"))+ {+ foreach (var dll in dlls)+ File.Copy(dll, Path.Combine(FolderOf(id), Path.GetFileName(dll)), overwrite: true);+ }+ }+/// <summary>An archive with a single top-level folder is unpacked without that extra level.</summary>private static string SingleRoot(string folder){diff --git a/src/Filee.Engines/Infrastructure/engines.json b/src/Filee.Engines/Infrastructure/engines.jsonindex 02d25ed7..e81386da 100644--- a/src/Filee.Engines/Infrastructure/engines.json+++ b/src/Filee.Engines/Infrastructure/engines.json@@ -35,6 +35,20 @@"sha256": "CBEA23BC37861361BBC534BC0675E5BC67B36F712072490F82A9BF410D7C04D8","size": 606257,"kind": "oxt"+ },+ "ghostscript": {+ "version": "10.08.0",+ "url": "https://conda.anaconda.org/conda-forge/win-64/ghostscript-10.08.0-hac47afa_0.conda",+ "sha256": "512BE9413C58B0AD3A2CD95A63EAEA73CBE32D9A6B9170C848BF825694A4ADB0",+ "size": 19295904,+ "kind": "conda"+ },+ "vcruntime": {+ "version": "14.44.35208",+ "url": "https://conda.anaconda.org/conda-forge/win-64/vc14_runtime-14.44.35208-h818238b_41.conda",+ "sha256": "EC706FE9368B837FBD05AF4851F5EBEF12BEF8C471A273F4805F7AF788407317",+ "size": 682908,+ "kind": "conda"}}}diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.csindex fc905bb0..abfa6a32 100644--- a/src/Filee.Engines/Magick/ImageEncoder.cs+++ b/src/Filee.Engines/Magick/ImageEncoder.cs@@ -9,20 +9,39 @@ namespace Filee.Engines.Magick;internal static class ImageEncoder{- /// <summary>Image formats ImageMagick can read.</summary>- public static readonly string[] Readable = ["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif", "heic"];+ /// <summary>+ /// Image formats ImageMagick can read (see <see cref="ImageReader"/> for RAW, layered and metafile sources).+ /// Camera RAW is decoded by LibRaw, XCF and HEIC are read only. EMF/WMF are Windows metafiles, which ImageMagick+ /// renders through GDI+ on Windows only (<see cref="Metafiles"/>).+ /// </summary>+ public static readonly string[] Readable =+ [+ "png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif", "heic",+ "jxl", "jp2", "psd", "psb", "tga", "ppm", "xcf", "raw",+ ];++ /// <summary>Vector metafiles ImageMagick rasterizes (Windows only: it uses GDI+).</summary>+ public static readonly string[] Metafiles = ["emf", "wmf"];/// <summary>/// Image formats ImageMagick can write. HEIC is missing on purpose: the bundled build has no HEVC encoder/// (patent licensing), so we offer AVIF instead./// </summary>- public static readonly string[] Writable = ["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif"];+ public static readonly string[] Writable =+ [+ "png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif",+ "jxl", "jp2", "psd", "psb", "tga", "ppm",+ ];/// <summary>Formats that store several frames/pages in one file.</summary>private static readonly HashSet<string> MultiFrame = ["tiff", "gif"];/// <summary>Formats without an alpha channel: transparent pixels are flattened onto the background colour.</summary>- private static readonly HashSet<string> NoAlpha = ["jpg"];+ private static readonly HashSet<string> NoAlpha = ["jpg", "ppm"];++ /// <summary>Every format ImageMagick reads as input: the raster formats plus, on Windows, the metafiles.</summary>+ public static IEnumerable<string> Sources =>+ OperatingSystem.IsWindows() ? [.. Readable, .. Metafiles] : Readable;public static MagickFormat ToMagickFormat(string formatId) => formatId switch{@@ -35,12 +54,38 @@ internal static class ImageEncoder"ico" => MagickFormat.Icon,"avif" => MagickFormat.Avif,"heic" => MagickFormat.Heic,+ "jxl" => MagickFormat.Jxl,+ "jp2" => MagickFormat.Jp2,+ "psd" => MagickFormat.Psd,+ "psb" => MagickFormat.Psb,+ "tga" => MagickFormat.Tga,+ "ppm" => MagickFormat.Ppm,_ => throw new NotSupportedException($"ImageMagick cannot handle '{formatId}'."),};+ /// <summary>+ /// ImageMagick format and file extension for writing <paramref name="targetFormat"/>. The "ppm" format covers the+ /// Netpbm family: a grayscale result, or a .pgm/.pbm source kept as such, is written as PGM/PBM with its own extension.+ /// </summary>+ /// <param name="sourcePath">Input file of the step, used to keep the Netpbm sub-format of .pgm/.pbm sources.</param>+ public static (MagickFormat Format, string Extension) OutputFormat(string targetFormat, ImageOptions options, string? sourcePath = null)+ {+ if (targetFormat != "ppm")+ return (ToMagickFormat(targetFormat), targetFormat);+ var sourceExtension = sourcePath is null ? "" : Path.GetExtension(sourcePath).TrimStart('.').ToLowerInvariant();+ return sourceExtension switch+ {+ "pbm" => (MagickFormat.Pbm, "pbm"),+ "pgm" => (MagickFormat.Pgm, "pgm"),+ _ when options.Grayscale => (MagickFormat.Pgm, "pgm"),+ _ => (MagickFormat.Ppm, "ppm"),+ };+ }+/// <summary>/// Chooses which frames of a (possibly multi-frame) source are converted.- /// ICO: the largest icon. GIF → single-frame target: the first frame. Otherwise: all frames/pages.+ /// ICO: the largest icon. GIF → single-frame target: the first frame. PSD/PSB: the composite (frame 0; any+ /// further frames are layers). Otherwise: all frames/pages./// </summary>public static List<IMagickImage<byte>> SelectFrames(MagickImageCollection images, string sourceFormat, string targetFormat){@@ -50,6 +95,8 @@ internal static class ImageEncodervar frames = images.ToList();if (frames.Count <= 1)return frames;+ if (sourceFormat is "psd" or "psb")+ return [frames[0]];if (sourceFormat == "ico")return [frames.OrderByDescending(f => (long)f.Width * f.Height).First()];if (sourceFormat == "gif" && !MultiFrame.Contains(targetFormat))@@ -95,6 +142,11 @@ internal static class ImageEncodercase "avif":image.Quality = quality;break;+ case "jxl":+ case "jp2":+ // 100 means lossless for both encoders (JPEG XL distance 0, JPEG 2000 reversible 5/3 wavelet).+ image.Quality = quality;+ break;case "webp":image.Quality = quality;if (options.WebpLossless)@@ -111,6 +163,12 @@ internal static class ImageEncodercase "ico":PrepareIcon(image, options);break;+ case "psd":+ case "psb":+ // ImageMagick writes a broken layer section for palette images with transparency (as read from+ // PNG or GIF): store them as direct colour.+ image.ClassType = ClassType.Direct;+ break;}}@@ -118,14 +176,17 @@ internal static class ImageEncoder/// Writes frames using the allocator. Multi-frame targets get one file; other targets get one file per frame/// with a <c>_p{n}</c> suffix when there is more than one frame./// </summary>- public static List<string> Write(IReadOnlyList<IMagickImage<byte>> frames, string targetFormat, IOutputAllocator output)+ /// <param name="options">Options of the preset (the Netpbm sub-format depends on them).</param>+ /// <param name="sourcePath">Input file of the step, see <see cref="OutputFormat"/>.</param>+ public static List<string> Write(IReadOnlyList<IMagickImage<byte>> frames, string targetFormat, IOutputAllocator output,+ ImageOptions? options = null, string? sourcePath = null){var written = new List<string>();- var format = ToMagickFormat(targetFormat);+ var (format, extension) = OutputFormat(targetFormat, options ?? new ImageOptions(), sourcePath);if (frames.Count > 1 && MultiFrame.Contains(targetFormat)){- var path = output.Allocate(targetFormat);+ var path = output.Allocate(extension);if (path is null)return written;using var collection = new MagickImageCollection();@@ -138,7 +199,7 @@ internal static class ImageEncoderfor (var i = 0; i < frames.Count; i++){- var path = output.Allocate(targetFormat, frames.Count > 1 ? $"_p{i + 1}" : null);+ var path = output.Allocate(extension, frames.Count > 1 ? $"_p{i + 1}" : null);if (path is null)continue;frames[i].Write(path, format);diff --git a/src/Filee.Engines/Magick/ImageReader.cs b/src/Filee.Engines/Magick/ImageReader.csnew file mode 100644index 00000000..681c17dc--- /dev/null+++ b/src/Filee.Engines/Magick/ImageReader.cs@@ -0,0 +1,132 @@+// Reads source images with ImageMagick, handling the formats that need more than "open the file": camera RAW+// (LibRaw settings), layered PSD/PSB/XCF (one flattened picture instead of one file per layer) and Windows+// metafiles (rendered at the preset's DPI). Used by every engine that takes a raster image as input.++using System.Buffers.Binary;+using Filee.Core.Presets;+using ImageMagick;+using ImageMagick.Formats;++namespace Filee.Engines.Magick;++/// <summary>Opens images for conversion.</summary>+internal static class ImageReader+{+ /// <summary>Smallest density metafiles are rendered at, so EMF/WMF output is never blurry.</summary>+ private const int MinimumMetafileDpi = 150;++ /// <summary>+ /// Reads <paramref name="path"/> as format <paramref name="formatId"/>. Layered formats come back as a single,+ /// flattened image; other multi-frame formats (TIFF pages, GIF frames, ICO sizes) keep all frames.+ /// </summary>+ public static MagickImageCollection Read(string path, string formatId, Preset preset)+ {+ var images = new MagickImageCollection();+ var settings = Settings(formatId, preset);+ try+ {+ images.Read(path, settings);+ }+ catch (MagickException ex) when (formatId == "xcf")+ {+ images.Dispose();+ throw new InvalidOperationException(+ "This GIMP file can't be read. Filee reads 8-bit XCF files saved without \"better but slower compression\"; " ++ "in GIMP, export the picture as PNG or PSD instead. (" + ex.Message + ")", ex);+ }+ catch+ {+ images.Dispose();+ throw;+ }++ // The metafile was rendered at this density, but ImageMagick doesn't record it on the image: without it,+ // an EMF placed in a PDF would come out at 96 dpi instead of its real size.+ if (formatId is "emf" or "wmf" && settings.Density is { } density)+ {+ foreach (var image in images)+ image.Density = density;+ }++ if (formatId == "xcf" && images.Count > 0)+ {+ var flat = FlattenXcf(images, XcfCanvasSize(path));+ images.Dispose();+ return [flat];+ }+ return images;+ }++ /// <summary>Read settings per source format.</summary>+ internal static MagickReadSettings Settings(string formatId, Preset preset)+ {+ var settings = new MagickReadSettings();+ switch (formatId)+ {+ case "raw":+ // LibRaw decodes every camera format; forcing the DNG coder also covers extensions ImageMagick doesn't+ // register (.srw) and ".raw", which ImageMagick would otherwise read as headerless pixel data.+ // LibRaw doesn't rotate (ImageMagick records the orientation), so ApplyOptions' AutoOrient turns it.+ settings.Format = MagickFormat.Dng;+ settings.SetDefines(new DngReadDefines+ {+ UseCameraWhiteBalance = true,+ UseAutoWhiteBalance = false,+ OutputColor = DngOutputColor.SRGB,+ InterpolationQuality = DngInterpolation.Ahd,+ DisableAutoBrightness = false,+ });+ break;+ case "psd":+ case "psb":+ // Frame 0 is Photoshop's composite of all visible layers (ImageMagick builds it from the layers when a+ // file was saved without "maximize compatibility"); asking for that frame only skips decoding layers.+ settings.FrameIndex = 0;+ settings.FrameCount = 1;+ break;+ case "emf":+ case "wmf":+ var dpi = Math.Max(MinimumMetafileDpi, Math.Clamp(preset.Pdf.RenderDpi, 36, 1200));+ settings.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);+ settings.BackgroundColor = MagickColors.Transparent;+ break;+ }+ return settings;+ }++ /// <summary>+ /// Composites GIMP layers onto a canvas of the document's size. ImageMagick returns the layers bottom-up with+ /// their offsets, blend mode as compose operator and hidden layers marked <see cref="CompositeOperator.No"/>, but+ /// not the canvas size, which comes from the file header.+ /// </summary>+ private static MagickImage FlattenXcf(MagickImageCollection layers, (uint Width, uint Height)? canvasSize)+ {+ var (width, height) = canvasSize ?? (layers[0].Page.Width is > 0 ? layers[0].Page.Width : layers[0].Width,+ layers[0].Page.Height is > 0 ? layers[0].Page.Height : layers[0].Height);+ var canvas = new MagickImage(MagickColors.Transparent, width, height);+ foreach (var layer in layers)+ {+ if (layer.Compose == CompositeOperator.No)+ continue; // hidden layer+ var compose = layer.Compose == CompositeOperator.Undefined ? CompositeOperator.Over : layer.Compose;+ canvas.Composite(layer, layer.Page.X, layer.Page.Y, compose);+ }+ canvas.Page = new MagickGeometry(0, 0, width, height);+ if (layers[0].ColorType is ColorType.Grayscale or ColorType.GrayscaleAlpha)+ canvas.ColorType = ColorType.GrayscaleAlpha;+ return canvas;+ }++ /// <summary>Width and height of an XCF document ("gimp xcf " magic, version, NUL, then two big-endian uint32).</summary>+ internal static (uint Width, uint Height)? XcfCanvasSize(string path)+ {+ Span<byte> header = stackalloc byte[22];+ using var stream = File.OpenRead(path);+ if (stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false) < header.Length+ || !header[..9].SequenceEqual("gimp xcf "u8))+ return null;+ var width = BinaryPrimitives.ReadUInt32BigEndian(header[14..]);+ var height = BinaryPrimitives.ReadUInt32BigEndian(header[18..]);+ return width is > 0 and <= 524_288 && height is > 0 and <= 524_288 ? (width, height) : null;+ }+}diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.csindex e425a3b5..a116bc1f 100644--- a/src/Filee.Engines/Magick/MagickImageConverter.cs+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs@@ -5,7 +5,10 @@ using ImageMagick;namespace Filee.Engines.Magick;-/// <summary>Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF and HEIC (read only).</summary>+/// <summary>+/// Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA and PPM, and reads+/// HEIC, XCF, camera RAW and (on Windows) EMF/WMF.+/// </summary>public sealed class MagickImageConverter : IConverter{public string Id => "magick";@@ -13,7 +16,7 @@ public sealed class MagickImageConverter : IConverterpublic int MaxParallelism => 0;public IReadOnlyList<ConversionEdge> Edges { get; } =- (from source in ImageEncoder.Readable+ (from source in ImageEncoder.Sourcesfrom target in ImageEncoder.Writableselect new ConversionEdge(source, target)).ToList();@@ -23,7 +26,7 @@ public sealed class MagickImageConverter : IConverterpublic Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>Task.Run<IReadOnlyList<string>>(() =>{- using var images = new MagickImageCollection(step.InputPath);+ using var images = ImageReader.Read(step.InputPath, step.From, step.Preset);cancellationToken.ThrowIfCancellationRequested();progress?.Report(0.3);@@ -35,7 +38,7 @@ public sealed class MagickImageConverter : IConverter}progress?.Report(0.7);- var written = ImageEncoder.Write(frames, step.To, step.Output);+ var written = ImageEncoder.Write(frames, step.To, step.Output, step.Preset.Image, step.InputPath);progress?.Report(1);return written;}, cancellationToken);diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.csindex ad4e62af..165fc582 100644--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs@@ -22,7 +22,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMergerpublic IReadOnlyList<ConversionEdge> Edges { get; } =[- .. ImageEncoder.Readable.Select(source => new ConversionEdge(source, "pdf")),+ .. ImageEncoder.Sources.Select(source => new ConversionEdge(source, "pdf")),new("pdf", "pdf"),];@@ -52,7 +52,7 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger{var options = step.Preset.Image;var pdfOptions = step.Preset.Pdf;- using var images = new MagickImageCollection(step.InputPath);+ using var images = ImageReader.Read(step.InputPath, step.From, step.Preset);var frames = ImageEncoder.SelectFrames(images, step.From, "pdf");using var document = new PdfDocument();@@ -147,7 +147,12 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger}else{- frame.Write(stream, MagickFormat.Png);+ // No palette PNGs: PDFsharp's decoder rejects them with transparency, and ImageMagick writes them for+ // pictures with few colours (charts, metafiles, pixel art). Grayscale stays grayscale.+ var format = frame.HasAlpha ? MagickFormat.Png32+ : frame.ColorType is ColorType.Grayscale or ColorType.Bilevel ? MagickFormat.Png+ : MagickFormat.Png24;+ frame.Write(stream, format);}stream.Position = 0;return stream;diff --git a/src/Filee.Engines/Pdf/PdfiumConverter.cs b/src/Filee.Engines/Pdf/PdfiumConverter.csindex 02c1b0f9..684c7b3e 100644--- a/src/Filee.Engines/Pdf/PdfiumConverter.cs+++ b/src/Filee.Engines/Pdf/PdfiumConverter.cs@@ -12,7 +12,7 @@ using SkiaSharp;namespace Filee.Engines.Pdf;-/// <summary>PDF → PNG / JPG / WEBP / TIFF / BMP / GIF / AVIF / ICO.</summary>+/// <summary>PDF → every raster format ImageMagick writes (PNG, JPG, WEBP, TIFF, …, PSD, TGA, PPM).</summary>public sealed class PdfiumConverter : IConverter{private static readonly HashSet<string> MultiPageTargets = ["tiff", "gif"];@@ -38,6 +38,7 @@ public sealed class PdfiumConverter : IConvertervar options = new RenderOptions(Dpi: dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White);var written = new List<string>();var collected = new List<IMagickImage<byte>>();+ var (format, extension) = ImageEncoder.OutputFormat(step.To, step.Preset.Image);try{@@ -59,10 +60,10 @@ public sealed class PdfiumConverter : IConverter{using (frame){- var path = step.Output.Allocate(step.To, pages.Count > 1 ? $"_p{pageNumber}" : null);+ var path = step.Output.Allocate(extension, pages.Count > 1 ? $"_p{pageNumber}" : null);if (path is not null){- frame.Write(path, ImageEncoder.ToMagickFormat(step.To));+ frame.Write(path, format);written.Add(path);}}@@ -71,7 +72,7 @@ public sealed class PdfiumConverter : IConverter}if (collected.Count > 0)- written.AddRange(ImageEncoder.Write(collected, step.To, step.Output));+ written.AddRange(ImageEncoder.Write(collected, step.To, step.Output, step.Preset.Image));}finally{diff --git a/src/Filee.Engines/Vector/GhostscriptConverter.cs b/src/Filee.Engines/Vector/GhostscriptConverter.csnew file mode 100644index 00000000..c9092ac8--- /dev/null+++ b/src/Filee.Engines/Vector/GhostscriptConverter.cs@@ -0,0 +1,194 @@+// PostScript and EPS with Ghostscript (AGPL-3.0, a separate program downloaded on demand into engines/ghostscript).+// EPS/PS → PDF with pdfwrite; PDF → EPS/PS with eps2write/ps2write. Everything else (EPS → PNG, SVG → EPS, …) is+// planned through PDF by the route planner.++using Filee.Core.Conversion;+using Filee.Engines.Infrastructure;+using PdfSharp.Pdf.IO;++namespace Filee.Engines.Vector;++/// <summary>EPS, PS and PostScript-based AI ↔ PDF through Ghostscript.</summary>+public sealed class GhostscriptConverter : IConverter+{+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(5);++ /// <summary>+ /// Environment variables Ghostscript would otherwise read from the user's system (extra options, resource and+ /// font search paths). Filee's copy has its resources compiled in and must behave the same on every PC.+ /// </summary>+ private static readonly Dictionary<string, string> CleanEnvironment = new()+ {+ ["GS_OPTIONS"] = "",+ ["GS_LIB"] = "",+ ["GS_FONTPATH"] = "",+ };++ private string? _executable;++ public string Id => "ghostscript";+ public string DisplayName => "Ghostscript";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ new("eps", "pdf"),+ new("ps", "pdf"),+ new("pdf", "eps"),+ new("pdf", "ps"),+ ];++ public EngineStatus GetStatus()+ {+ _executable = Locate();+ return _executable is null ? EngineStatus.Unavailable("engine.reason.not_installed") : EngineStatus.Available(_executable);+ }++ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var gs = _executable ?? Locate() ?? throw new InvalidOperationException("Ghostscript is not installed.");+ progress?.Report(0.05);+ IReadOnlyList<string> written = step.To switch+ {+ "pdf" => await ToPdfAsync(gs, step, cancellationToken, progress),+ "ps" => await ToPostScriptAsync(gs, step, cancellationToken, progress),+ "eps" => await ToEpsAsync(gs, step, cancellationToken, progress),+ _ => throw new NotSupportedException($"Ghostscript cannot write '{step.To}'."),+ };+ progress?.Report(1);+ return written;+ }++ /// <summary>Filee's own Ghostscript (engines/ghostscript, downloaded on demand), never one installed on the system.</summary>+ internal static string? Locate() =>+ EngineEnvironment.FindBundled("ghostscript") is { } folder+ ? EngineEnvironment.FirstExisting(Path.Combine(folder, OperatingSystem.IsWindows() ? "gswin64c.exe" : "gs"))+ : null;++ /// <summary>+ /// Converts PostScript (PS, EPS, PostScript-based Illustrator files) to PDF. EPS pages are cropped to the+ /// bounding box. Used by <see cref="VectorConverter"/> for AI files saved without PDF compatibility.+ /// </summary>+ internal static async Task ConvertToPdfAsync(string gs, string input, string output, bool crop, string workDirectory,+ CancellationToken cancellationToken, IProgress<double>? progress = null)+ {+ var scratch = NewScratch(workDirectory);+ var target = Path.Combine(scratch, "out.pdf");+ List<string> args = ["-sDEVICE=pdfwrite", "-dAutoRotatePages=/None"];+ if (crop)+ args.Add("-dEPSCrop");+ await RunAsync(gs, args, target, input, cancellationToken, progress);+ File.Move(target, output, overwrite: true);+ }++ private static async Task<IReadOnlyList<string>> ToPdfAsync(string gs, ConversionStep step, CancellationToken ct, IProgress<double>? progress)+ {+ var output = step.Output.Allocate("pdf");+ if (output is null)+ return [];+ await ConvertToPdfAsync(gs, step.InputPath, output, crop: step.From == "eps", step.WorkDirectory, ct, progress);+ return [output];+ }++ private static async Task<IReadOnlyList<string>> ToPostScriptAsync(string gs, ConversionStep step, CancellationToken ct, IProgress<double>? progress)+ {+ var output = step.Output.Allocate("ps");+ if (output is null)+ return [];+ var target = Path.Combine(NewScratch(step.WorkDirectory), "out.ps");+ List<string> args = ["-sDEVICE=ps2write"];+ if (SelectedPages(step) is { } pages)+ args.Add("-sPageList=" + string.Join(',', pages.Select(p => p + 1)));+ await RunAsync(gs, args, target, step.InputPath, ct, progress);+ File.Move(target, output, overwrite: true);+ return [output];+ }++ /// <summary>EPS holds one page: a multi-page PDF becomes one EPS per page (<c>_p{n}</c> like PDF → PNG).</summary>+ private static async Task<IReadOnlyList<string>> ToEpsAsync(string gs, ConversionStep step, CancellationToken ct, IProgress<double>? progress)+ {+ var scratch = NewScratch(step.WorkDirectory);+ var pages = SelectedPages(step);+ List<string> args = ["-sDEVICE=eps2write"];+ if (pages is not null)+ args.Add("-sPageList=" + string.Join(',', pages.Select(p => p + 1)));+ // %d makes Ghostscript write one numbered file per page (1, 2, 3 … in output order).+ await RunAsync(gs, args, Path.Combine(scratch, "page-%d.eps"), step.InputPath, ct, progress);++ var files = Directory.GetFiles(scratch, "page-*.eps")+ .Select(f => (Path: f, Index: int.Parse(Path.GetFileNameWithoutExtension(f)["page-".Length..], System.Globalization.CultureInfo.InvariantCulture)))+ .OrderBy(f => f.Index)+ .ToList();+ if (files.Count == 0)+ throw new InvalidOperationException("Ghostscript wrote no EPS file.");++ var written = new List<string>();+ foreach (var (file, index) in files)+ {+ var pageNumber = pages is not null && index - 1 < pages.Count ? pages[index - 1] + 1 : index;+ var path = step.Output.Allocate("eps", files.Count > 1 ? $"_p{pageNumber}" : null);+ if (path is null)+ continue;+ File.Move(file, path, overwrite: true);+ written.Add(path);+ }+ return written;+ }++ /// <summary>The preset's page range as zero-based pages, or null for every page (also when the PDF can't be read).</summary>+ private static IReadOnlyList<int>? SelectedPages(ConversionStep step)+ {+ if (string.IsNullOrWhiteSpace(step.Preset.Pdf.PageRange))+ return null;+ try+ {+ using var document = PdfReader.Open(step.InputPath, PdfDocumentOpenMode.Import);+ return PageRange.Parse(step.Preset.Pdf.PageRange, document.PageCount);+ }+ catch (Exception ex) when (ex is not OperationCanceledException)+ {+ return null; // PDFsharp can't open every PDF Ghostscript can: convert all pages rather than fail+ }+ }++ /// <summary>+ /// Runs Ghostscript in safe mode. Outputs go to an ASCII-named scratch folder first: in -sOutputFile a '%' is a+ /// page-number placeholder, so arbitrary user paths can't be passed there.+ /// </summary>+ private static async Task RunAsync(string gs, List<string> deviceArgs, string outputFile, string input, CancellationToken ct, IProgress<double>? progress)+ {+ List<string> args =+ [+ "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dQUIET",+ .. deviceArgs,+ "-sOutputFile=" + outputFile,+ "-f", Path.GetFullPath(input),+ ];+ ProcessResult result;+ using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(2)))+ result = await ProcessRunner.RunAsync(gs, args, Timeout, ct, environment: CleanEnvironment);++ var produced = outputFile.Contains('%', StringComparison.Ordinal)+ ? Directory.EnumerateFiles(Path.GetDirectoryName(outputFile)!).Any()+ : File.Exists(outputFile) && new FileInfo(outputFile).Length > 0;+ if (result.ExitCode != 0 || !produced)+ {+ var detail = LastLines(result.StandardError + "\n" + result.StandardOutput);+ throw new InvalidOperationException($"Ghostscript failed (exit {result.ExitCode}). {detail}".Trim());+ }+ }++ private static string NewScratch(string workDirectory)+ {+ var folder = Path.Combine(workDirectory, "gs-" + Guid.NewGuid().ToString("N")[..8]);+ Directory.CreateDirectory(folder);+ return folder;+ }++ /// <summary>The end of Ghostscript's messages: the actual error is at the bottom.</summary>+ private static string LastLines(string text)+ {+ var lines = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);+ return string.Join(" ", lines.TakeLast(6));+ }+}diff --git a/src/Filee.Engines/Vector/OutlinedTextPlayback.cs b/src/Filee.Engines/Vector/OutlinedTextPlayback.csnew file mode 100644index 00000000..79494975--- /dev/null+++ b/src/Filee.Engines/Vector/OutlinedTextPlayback.cs@@ -0,0 +1,220 @@+// Draws an Svg.Skia drawing with its text converted to glyph outlines, for PDF output. SkiaSharp's PDF backend is+// built without a font subsetter and embeds every font file whole: one line of Korean text adds the 13 MB Malgun+// Gothic font to the PDF. Outlines keep the text's exact shape at a few kilobytes (it is no longer selectable).+// Text is shaped with HarfBuzz the way Svg.Skia does it (adapted from SkiaModel.TextShaping.cs, Svg.Skia, MIT).++using System.Runtime.InteropServices;+using HarfBuzzSharp;+using ShimSkiaSharp;+using Svg.Skia;+using Buffer = HarfBuzzSharp.Buffer;+using SKCanvas = SkiaSharp.SKCanvas;+using SKFont = SkiaSharp.SKFont;+using SKPath = SkiaSharp.SKPath;+using SKPoint = SkiaSharp.SKPoint;+using SKTextAlign = SkiaSharp.SKTextAlign;+using SKTypeface = SkiaSharp.SKTypeface;++namespace Filee.Engines.Vector;++/// <summary>Plays back an Svg.Skia picture model, drawing text commands as paths.</summary>+internal sealed class OutlinedTextPlayback(SkiaModel model) : IDisposable+{+ /// <summary>HarfBuzz works in integer units: positions are computed at this scale and divided back.</summary>+ private const int HarfBuzzScale = 512;++ private readonly Dictionary<string, Font?> _shapers = new(StringComparer.Ordinal);++ /// <summary>Draws every command of <paramref name="picture"/> onto <paramref name="canvas"/>.</summary>+ public void Draw(ShimSkiaSharp.SKPicture picture, SKCanvas canvas)+ {+ if (picture.Commands is null)+ return;+ foreach (var command in picture.Commands)+ Draw(command, canvas);+ }++ private void Draw(CanvasCommand command, SKCanvas canvas)+ {+ var handled = command switch+ {+ DrawPictureCanvasCommand { Picture: { } nested } => DrawNested(nested, canvas),+ DrawTextCanvasCommand text => DrawText(text, canvas),+ DrawTextBlobCanvasCommand blob => DrawTextBlob(blob, canvas),+ DrawPositionedTextRunCanvasCommand run => DrawPositionedRun(run, canvas),+ _ => false,+ };+ // Everything else, and text that can't be shaped (text on a path, fonts without outlines), is drawn by+ // Svg.Skia itself.+ if (!handled)+ model.Draw(command, canvas);+ }++ private bool DrawNested(ShimSkiaSharp.SKPicture picture, SKCanvas canvas)+ {+ Draw(picture, canvas);+ return true;+ }++ private bool DrawText(DrawTextCanvasCommand command, SKCanvas canvas)+ {+ if (command.Paint is null || string.IsNullOrEmpty(command.Text))+ return command.Paint is not null;+ using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);+ var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint.TextAlign);+ using var path = new SKPath();+ if (font?.Typeface is null || !AppendShaped(path, command.Text, font, command.X, command.Y, align))+ return false;+ return Fill(canvas, path, command.Paint);+ }++ private bool DrawTextBlob(DrawTextBlobCanvasCommand command, SKCanvas canvas)+ {+ if (command.Paint is null || command.TextBlob?.Points is not { } points)+ return command.Paint is not null;+ using var font = command.TextBlob.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);+ if (font is null)+ return false;+ var glyphs = command.TextBlob.Glyphs is { Length: > 0 } ids ? ids+ : command.TextBlob.Text is { } text ? font.GetGlyphs(text)+ : [];+ if (glyphs.Length != points.Length)+ return false;+ using var path = new SKPath();+ for (var i = 0; i < glyphs.Length; i++)+ AppendGlyph(path, font, glyphs[i], command.X + points[i].X, command.Y + points[i].Y);+ return Fill(canvas, path, command.Paint);+ }++ private bool DrawPositionedRun(DrawPositionedTextRunCanvasCommand command, SKCanvas canvas)+ {+ if (command.Paint is null || command.Fragments is not { Count: > 0 })+ return command.Paint is not null;+ using var font = command.Font is { } shimFont ? model.ToSKFont(shimFont) : model.ToSKFont(command.Paint);+ if (font?.Typeface is null)+ return false;+ var align = model.ToSKTextAlign(command.TextAlign ?? command.Paint.TextAlign);+ using var path = new SKPath();+ foreach (var fragment in command.Fragments)+ {+ using var part = new SKPath();+ if (!AppendShaped(part, fragment.Text, font, fragment.Point.X, fragment.Point.Y, align))+ continue;+ // Per-character rotation (SVG "rotate") and horizontal scaling (textLength), as Svg.Skia applies them.+ var transform = SkiaSharp.SKMatrix.Identity;+ if (fragment.RotationDegrees != 0f)+ transform = SkiaSharp.SKMatrix.CreateRotationDegrees(fragment.RotationDegrees, fragment.Point.X, fragment.Point.Y);+ if (fragment.ScaleX != 1f)+ transform = transform.PreConcat(SkiaSharp.SKMatrix.CreateScale(fragment.ScaleX, 1f, fragment.ScaleOriginX, fragment.Point.Y));+ part.Transform(transform);+ path.AddPath(part);+ }+ return Fill(canvas, path, command.Paint);+ }++ /// <summary>Draws the outlines with the text's paint (fill or stroke, colour, gradient, opacity).</summary>+ private bool Fill(SKCanvas canvas, SKPath path, SKPaint shimPaint)+ {+ using var paint = model.ToSKPaint(shimPaint);+ if (paint is not null && !path.IsEmpty)+ canvas.DrawPath(path, paint);+ return true;+ }++ /// <summary>Shapes <paramref name="text"/> and appends its glyph outlines, aligned at (<paramref name="x"/>, <paramref name="y"/>).</summary>+ private bool AppendShaped(SKPath path, string text, SKFont font, float x, float y, SKTextAlign align)+ {+ if (string.IsNullOrEmpty(text))+ return true;+ var shaper = ShaperFor(font.Typeface);+ if (shaper is null)+ return false;++ using var buffer = new Buffer();+ buffer.ClusterLevel = ClusterLevel.Characters;+ buffer.AddUtf16(text);+ buffer.GuessSegmentProperties();+ shaper.Shape(buffer);++ var infos = buffer.GlyphInfos;+ var positions = buffer.GlyphPositions;+ var scaleY = font.Size / HarfBuzzScale;+ var scaleX = scaleY * font.ScaleX;+ var width = 0f;+ foreach (var position in positions)+ width += position.XAdvance * scaleX;+ var penX = x - align switch+ {+ SKTextAlign.Center => width / 2,+ SKTextAlign.Right => width,+ _ => 0f,+ };+ var penY = y;+ for (var i = 0; i < infos.Length; i++)+ {+ AppendGlyph(path, font, (ushort)infos[i].Codepoint, penX + positions[i].XOffset * scaleX, penY - positions[i].YOffset * scaleY);+ penX += positions[i].XAdvance * scaleX;+ penY -= positions[i].YAdvance * scaleY;+ }+ return true;+ }++ private static void AppendGlyph(SKPath path, SKFont font, ushort glyph, float x, float y)+ {+ using var outline = font.GetGlyphPath(glyph);+ if (outline is { IsEmpty: false })+ path.AddPath(outline, x, y);+ }++ /// <summary>A HarfBuzz font for the typeface (cached), or null when its font data can't be read.</summary>+ private Font? ShaperFor(SKTypeface typeface)+ {+ var key = $"{typeface.FamilyName}|{typeface.FontWeight}|{typeface.FontWidth}|{typeface.FontSlant}";+ if (_shapers.TryGetValue(key, out var cached))+ return cached;++ Font? font = null;+ var asset = typeface.OpenStream(out var index);+ if (asset is not null)+ {+ using var blob = ToBlob(asset);+ using var face = new Face(blob, index) { Index = index, UnitsPerEm = typeface.UnitsPerEm };+ font = new Font(face);+ font.SetScale(HarfBuzzScale, HarfBuzzScale);+ font.SetFunctionsOpenType();+ }+ _shapers[key] = font;+ return font;+ }++ /// <summary>Wraps Skia's font data for HarfBuzz without copying when Skia has it in memory.</summary>+ private static Blob ToBlob(SkiaSharp.SKStreamAsset asset)+ {+ var size = asset.Length;+ var memory = asset.GetMemoryBase();+ Blob blob;+ if (memory != IntPtr.Zero)+ {+ blob = new Blob(memory, size, MemoryMode.ReadOnly, asset.Dispose);+ }+ else+ {+ var copy = Marshal.AllocCoTaskMem(size);+ asset.Read(copy, size);+ blob = new Blob(copy, size, MemoryMode.ReadOnly, () =>+ {+ Marshal.FreeCoTaskMem(copy);+ asset.Dispose();+ });+ }+ blob.MakeImmutable();+ return blob;+ }++ public void Dispose()+ {+ foreach (var font in _shapers.Values)+ font?.Dispose();+ _shapers.Clear();+ }+}diff --git a/src/Filee.Engines/Vector/SvgRenderer.cs b/src/Filee.Engines/Vector/SvgRenderer.csnew file mode 100644index 00000000..e43de355--- /dev/null+++ b/src/Filee.Engines/Vector/SvgRenderer.cs@@ -0,0 +1,185 @@+// Loads SVG/SVGZ with Svg.Skia (MIT) and draws it with SkiaSharp: onto PDF pages as real vector graphics, or onto+// a bitmap for raster targets.++using System.IO.Compression;+using Filee.Core.Presets;+using ImageMagick;+using SkiaSharp;+using Svg;+using Svg.Skia;++namespace Filee.Engines.Vector;++/// <summary>SVG → PDF and SVG → bitmap.</summary>+internal static class SvgRenderer+{+ /// <summary>CSS pixels per inch: SVG user units are CSS pixels.</summary>+ public const float CssDpi = 96f;++ /// <summary>Small drawings (icons) are rendered at least this large on the long edge.</summary>+ public const int MinimumLongEdge = 1024;++ /// <summary>Upper bounds for rendered bitmaps, so a huge drawing doesn't exhaust memory.</summary>+ private const int MaximumLongEdge = 16384;+ private const long MaximumPixels = 100_000_000;++ static SvgRenderer()+ {+ // An SVG may reference images, other SVGs and XML entities by URL. Files next to the drawing are fine;+ // network access is not: converting a file must not fetch anything (tracking pixels, slow servers).+ SvgDocument.ResolveExternalImages = ExternalType.Local;+ SvgDocument.ResolveExternalElements = ExternalType.Local;+ SvgDocument.ResolveExternalXmlEntites = ExternalType.None;+ }++ /// <summary>A loaded drawing. Dispose it after drawing.</summary>+ public sealed class Drawing(SKSvg svg, SKPicture picture, SKRect bounds) : IDisposable+ {+ /// <summary>The loaded document (its model is replayed for PDF output).</summary>+ public SKSvg Svg { get; } = svg;++ /// <summary>The drawing as a Skia picture, in CSS pixels.</summary>+ public SKPicture Picture { get; } = picture;++ /// <summary>The SVG viewport (width/height or viewBox) in CSS pixels.</summary>+ public SKRect Bounds { get; } = bounds;++ public void Dispose() => Svg.Dispose();+ }++ /// <summary>Loads an SVG or SVGZ (gzip) file.</summary>+ /// <exception cref="InvalidDataException">The file is not a drawable SVG.</exception>+ public static Drawing Load(string path)+ {+ var bytes = ReadSvgBytes(path);+ var svg = new SKSvg();+ svg.Settings.EnableJavaScript = false;+ svg.Settings.EnableExternalJavaScript = false;+ SKPicture? picture;+ try+ {+ using var stream = new MemoryStream(bytes, writable: false);+ picture = svg.Load(stream, null, new Uri(Path.GetFullPath(path)));+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ svg.Dispose();+ throw new InvalidDataException("The SVG file could not be read: " + ex.Message, ex);+ }+ var bounds = picture?.CullRect ?? SKRect.Empty;+ if (picture is null || bounds.Width <= 0 || bounds.Height <= 0 || float.IsInfinity(bounds.Width) || float.IsInfinity(bounds.Height))+ {+ svg.Dispose();+ throw new InvalidDataException("The SVG file has no drawable content or no size.");+ }+ return new Drawing(svg, picture, bounds);+ }++ /// <summary>The file's SVG text as bytes: SVGZ (or a gzipped .svg) is decompressed.</summary>+ public static byte[] ReadSvgBytes(string path)+ {+ var bytes = File.ReadAllBytes(path);+ if (!IsGzip(bytes))+ return bytes;+ using var gzip = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress);+ using var plain = new MemoryStream();+ gzip.CopyTo(plain);+ return plain.ToArray();+ }++ /// <summary>True when the data starts with the gzip magic number.</summary>+ public static bool IsGzip(ReadOnlySpan<byte> data) => data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;++ /// <summary>+ /// Writes a one-page PDF the size of the drawing. Paths, gradients and text stay vector (text as glyph outlines,+ /// see <see cref="OutlinedTextPlayback"/>); only effects PDF can't express (filters such as blur) are rasterized at+ /// 300 dpi.+ /// </summary>+ public static void WritePdf(Drawing drawing, string output, string title, bool pdfA)+ {+ const float pointsPerPixel = 72f / CssDpi;+ var metadata = SKDocumentPdfMetadata.Default;+ metadata.Title = title;+ metadata.Creator = "Filee";+ metadata.Producer = "Filee (Skia PDF)";+ metadata.Creation = DateTime.Now;+ metadata.Modified = DateTime.Now;+ metadata.RasterDpi = 300;+ metadata.EncodingQuality = 95;+ metadata.PdfA = pdfA;++ using (var stream = File.Create(output))+ using (var document = SKDocument.CreatePdf(stream, metadata))+ {+ var canvas = document.BeginPage(drawing.Bounds.Width * pointsPerPixel, drawing.Bounds.Height * pointsPerPixel);+ canvas.Scale(pointsPerPixel);+ canvas.Translate(-drawing.Bounds.Left, -drawing.Bounds.Top);+ if (drawing.Svg.Model is { } model)+ {+ using var playback = new OutlinedTextPlayback(drawing.Svg.SkiaModel);+ playback.Draw(model, canvas);+ }+ else+ {+ canvas.DrawPicture(drawing.Picture);+ }+ document.EndPage();+ document.Close();+ }+ if (new FileInfo(output).Length == 0)+ throw new InvalidOperationException("Skia could not write the PDF.");+ }++ /// <summary>+ /// Scale from CSS pixels to output pixels. Vector drawings are rendered at the size they end up at: at the preset's+ /// render DPI, at least <see cref="MinimumLongEdge"/> on the long edge, or exactly at the preset's resize target.+ /// </summary>+ public static float RasterScale(SKRect bounds, ImageOptions image, PdfOptions pdf)+ {+ var longEdge = Math.Max(bounds.Width, bounds.Height);+ var dpi = Math.Clamp(pdf.RenderDpi, 36, 1200);+ var scale = Math.Max(dpi / CssDpi, MinimumLongEdge / longEdge);+ switch (image.Resize)+ {+ case ResizeMode.LongEdge when image.LongEdge > 0:+ scale = image.LongEdge / longEdge;+ break;+ case ResizeMode.Percent when image.ResizePercent is > 0 and not 100:+ scale *= image.ResizePercent / 100f;+ break;+ }+ var limit = Math.Min(MaximumLongEdge / longEdge, MathF.Sqrt(MaximumPixels / (bounds.Width * bounds.Height)));+ return Math.Max(Math.Min(scale, limit), 1e-3f);+ }++ /// <summary>Renders the drawing on a transparent bitmap and hands it to ImageMagick for encoding.</summary>+ public static MagickImage Rasterize(Drawing drawing, float scale)+ {+ var width = Math.Max(1, (int)Math.Ceiling(drawing.Bounds.Width * scale));+ var height = Math.Max(1, (int)Math.Ceiling(drawing.Bounds.Height * scale));+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));+ using (var canvas = new SKCanvas(bitmap))+ {+ canvas.Clear(SKColors.Transparent);+ canvas.Scale(scale);+ canvas.Translate(-drawing.Bounds.Left, -drawing.Bounds.Top);+ canvas.DrawPicture(drawing.Picture);+ }++ // Skia draws premultiplied; ImageMagick expects straight alpha.+ using var straight = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Unpremul));+ using (var source = bitmap.PeekPixels())+ using (var target = straight.PeekPixels())+ {+ if (!source.ReadPixels(target))+ throw new InvalidOperationException("Could not read the rendered SVG.");+ }+ var pixels = straight.GetPixelSpan().ToArray();++ var image = new MagickImage();+ image.ReadPixels(pixels, new PixelReadSettings((uint)width, (uint)height, StorageType.Char, PixelMapping.RGBA));+ var dpi = CssDpi * scale;+ image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);+ return image;+ }+}diff --git a/src/Filee.Engines/Vector/VectorConverter.cs b/src/Filee.Engines/Vector/VectorConverter.csnew file mode 100644index 00000000..958b494f--- /dev/null+++ b/src/Filee.Engines/Vector/VectorConverter.cs@@ -0,0 +1,165 @@+// Built-in vector graphics: SVG/SVGZ → PDF (vector) and → raster images with Svg.Skia and SkiaSharp, SVG ↔ SVGZ,+// and Illustrator files → PDF. Other vector formats reach PNG, JPG, … through PDF and PDFium.++using System.IO.Compression;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Engines.Magick;++namespace Filee.Engines.Vector;++/// <summary>SVG, SVGZ and AI conversions that need no external program.</summary>+public sealed class VectorConverter : IConverter+{+ public string Id => "vector";+ public string DisplayName => "Vector graphics (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ new("svg", "pdf"),+ new("svgz", "pdf"),+ new("svg", "svgz"),+ new("svgz", "svg"),+ .. ImageEncoder.Writable.SelectMany(target => new ConversionEdge[] { new("svg", target), new("svgz", target) }),+ // Illustrator files are PDF inside (or PostScript, see ConvertIllustratorAsync).+ new("ai", "pdf"),+ ];++ public EngineStatus GetStatus() => EngineStatus.Available();++ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var written = (step.From, step.To) switch+ {+ ("ai", "pdf") => await ConvertIllustratorAsync(step, progress, cancellationToken),+ ("svg", "svgz") => await Task.Run(() => Compress(step), cancellationToken),+ ("svgz", "svg") => await Task.Run(() => Decompress(step), cancellationToken),+ (_, "pdf") => await Task.Run(() => ToPdf(step, cancellationToken), cancellationToken),+ _ => await Task.Run(() => ToRaster(step, progress, cancellationToken), cancellationToken),+ };+ progress?.Report(1);+ return written;+ }++ private static IReadOnlyList<string> ToPdf(ConversionStep step, CancellationToken ct)+ {+ using var drawing = SvgRenderer.Load(step.InputPath);+ ct.ThrowIfCancellationRequested();+ var output = step.Output.Allocate("pdf");+ if (output is null)+ return [];+ SvgRenderer.WritePdf(drawing, output, FormatRegistry.NameWithoutExtension(step.InputPath), step.Preset.Document.PdfA);+ return [output];+ }++ private static IReadOnlyList<string> ToRaster(ConversionStep step, IProgress<double>? progress, CancellationToken ct)+ {+ using var drawing = SvgRenderer.Load(step.InputPath);+ progress?.Report(0.2);+ var scale = SvgRenderer.RasterScale(drawing.Bounds, step.Preset.Image, step.Preset.Pdf);+ using var image = SvgRenderer.Rasterize(drawing, scale);+ ct.ThrowIfCancellationRequested();+ progress?.Report(0.6);++ // The drawing was rendered at its final size, so the preset's resize must not scale the bitmap again.+ var options = step.Preset.Image.Clone();+ options.Resize = Core.Presets.ResizeMode.None;+ ImageEncoder.ApplyOptions(image, options, step.To);+ return ImageEncoder.Write([image], step.To, step.Output, options);+ }++ private static IReadOnlyList<string> Compress(ConversionStep step)+ {+ var bytes = File.ReadAllBytes(step.InputPath);+ if (!SvgRenderer.IsGzip(bytes))+ RequireSvgText(bytes);+ var output = step.Output.Allocate("svgz");+ if (output is null)+ return [];+ if (SvgRenderer.IsGzip(bytes))+ {+ File.WriteAllBytes(output, bytes); // a gzipped file named .svg: already SVGZ+ return [output];+ }+ using (var file = File.Create(output))+ using (var gzip = new GZipStream(file, CompressionLevel.SmallestSize))+ gzip.Write(bytes);+ return [output];+ }++ private static IReadOnlyList<string> Decompress(ConversionStep step)+ {+ var bytes = SvgRenderer.ReadSvgBytes(step.InputPath);+ RequireSvgText(bytes);+ var output = step.Output.Allocate("svg");+ if (output is null)+ return [];+ File.WriteAllBytes(output, bytes);+ return [output];+ }++ /// <summary>Guards SVG ↔ SVGZ, which never parse the drawing, against renamed non-SVG files.</summary>+ private static void RequireSvgText(byte[] bytes)+ {+ var head = Encoding.UTF8.GetString(bytes, 0, Math.Min(bytes.Length, 4096));+ if (!head.Contains("<svg", StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException("The file is not an SVG drawing (no <svg> element).");+ }++ // ───────────────────────── Illustrator ─────────────────────────++ /// <summary>+ /// Illustrator 9 and later save a complete PDF inside the .ai file ("Create PDF compatible file", on by+ /// default), so the file is copied as a PDF after checking its header. Files saved without it (and Illustrator 8+ /// and older) are PostScript, which needs Ghostscript.+ /// </summary>+ private static async Task<IReadOnlyList<string>> ConvertIllustratorAsync(ConversionStep step, IProgress<double>? progress, CancellationToken ct)+ {+ var kind = IllustratorKind(step.InputPath);+ if (kind == AiKind.Unknown)+ throw new InvalidDataException("The file is not an Adobe Illustrator document (neither PDF nor PostScript inside).");++ var output = step.Output.Allocate("pdf");+ if (output is null)+ return [];+ if (kind == AiKind.Pdf)+ {+ File.Copy(step.InputPath, output, overwrite: true);+ return [output];+ }++ var gs = GhostscriptConverter.Locate()+ ?? throw new InvalidOperationException(+ "This Illustrator file was saved without PDF compatibility, so it is PostScript. " ++ "Install Ghostscript in Settings → Engines to convert it, or save it in Illustrator with \"Create PDF compatible file\".");+ await GhostscriptConverter.ConvertToPdfAsync(gs, step.InputPath, output, crop: true, step.WorkDirectory, ct, progress);+ return [output];+ }++ internal enum AiKind+ {+ Unknown,+ Pdf,+ PostScript,+ }++ /// <summary>+ /// Looks at the header: PDF-compatible files start with "%PDF-" (a PDF reader accepts it within the first 1 KB);+ /// PostScript-based ones with "%!PS-Adobe" or the binary header of a DOS EPS file (C5 D0 D3 C6).+ /// </summary>+ internal static AiKind IllustratorKind(string path)+ {+ var buffer = new byte[1024];+ int read;+ using (var file = File.OpenRead(path))+ read = file.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false);+ var head = buffer.AsSpan(0, read);+ if (head.IndexOf("%PDF-"u8) >= 0)+ return AiKind.Pdf;+ if (head.StartsWith("%!PS"u8) || head.StartsWith((ReadOnlySpan<byte>)[0xC5, 0xD0, 0xD3, 0xC6]))+ return AiKind.PostScript;+ return AiKind.Unknown;+ }+}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex 6810f317..4eb7bfa7 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -66,8 +66,8 @@ public class RenderTestswindow.Show();Pump();- // Everything not installed is offered; all but the large LibreOffice pre-selected.- Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.Equal(p.Package.Id != "libreoffice", p.Selected));+ // Everything not installed is offered; all but the large LibreOffice and the EPS-only Ghostscript pre-selected.+ Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.Equal(p.Package.Id is not ("libreoffice" or "ghostscript"), p.Selected));Assert.Equal(vm.Packages.Any(p => p.Selected && p.CanInstall), vm.InstallCommand.CanExecute(null));Save(window, $"engine-setup-{language}.png");window.Close();diff --git a/tests/Filee.Engines.Tests/EngineInstallerTests.cs b/tests/Filee.Engines.Tests/EngineInstallerTests.csindex be0133de..5de9a3f9 100644--- a/tests/Filee.Engines.Tests/EngineInstallerTests.cs+++ b/tests/Filee.Engines.Tests/EngineInstallerTests.cs@@ -1,9 +1,12 @@// Optional engine downloads without the network: a fake HTTP handler serves generated archives.+using System.Formats.Tar;using System.IO.Compression;using System.Net;using System.Security.Cryptography;+using System.Text;using Filee.Engines.Infrastructure;+using SharpCompress.Compressors.ZStandard;namespace Filee.Engines.Tests;@@ -49,6 +52,28 @@ public sealed class EngineInstallerTests : IDisposablereturn buffer.ToArray();}+ /// <summary>A conda package: a zip with metadata and the files as a zstd-compressed tarball.</summary>+ private static byte[] Conda(params (string Path, string Text)[] files)+ {+ using var tarball = new MemoryStream();+ using (var zstd = new CompressionStream(tarball, level: 3, leaveOpen: true))+ using (var tar = new TarWriter(zstd, TarEntryFormat.Pax, leaveOpen: true))+ {+ foreach (var (path, text) in files)+ tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, path) { DataStream = new MemoryStream(Encoding.UTF8.GetBytes(text)) });+ }++ using var buffer = new MemoryStream();+ using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))+ {+ using (var writer = new StreamWriter(zip.CreateEntry("metadata.json").Open()))+ writer.Write("{\"conda_pkg_format_version\": 2}");+ using (var entry = zip.CreateEntry("pkg-tool-1.0-0.tar.zst").Open())+ entry.Write(tarball.ToArray());+ }+ return buffer.ToArray();+ }+private static EngineComponent Component(string id, string kind, byte[] bytes, string? sha256 = null) =>new(id, "1.0", $"https://example.test/{id}.{kind}", sha256 ?? Convert.ToHexString(SHA256.HashData(bytes)), bytes.Length, kind);@@ -120,6 +145,36 @@ public sealed class EngineInstallerTests : IDisposableAssert.True(File.Exists(Path.Combine(_root, "tool", "tool.exe")));}+ [Fact]+ public async Task Conda_packages_unpack_their_windows_binaries_and_get_the_runtime_next_to_them()+ {+ var gs = Conda(("Library/bin/gswin64c.exe", "exe"), ("Library/bin/gsdll64.dll", "dll"), ("Library/share/doc.txt", "doc"), ("info/index.json", "{}"));+ var runtime = Conda(("Library/bin/vcruntime140.dll", "runtime"), ("Library/bin/msvcp140.dll", "c++"));+ var ghostscript = Component("ghostscript", "conda", gs);+ var vcruntime = Component("vcruntime", "conda", runtime);+ var installer = Installer(new FakeServer(new() { [ghostscript.Url] = gs, [vcruntime.Url] = runtime }), ghostscript, vcruntime);+ var package = new EnginePackage("ghostscript", ["ghostscript", "vcruntime"], 1, ["ghostscript"]);++ await installer.InstallAsync(package, null, TestContext.Current.CancellationToken);++ var folder = Path.Combine(_root, "ghostscript");+ Assert.Equal(["gsdll64.dll", "gswin64c.exe", "msvcp140.dll", "vcruntime140.dll"],+ Directory.GetFiles(folder).Select(Path.GetFileName).Where(n => !n!.StartsWith('.')).Order(StringComparer.Ordinal));+ Assert.Equal("runtime", File.ReadAllText(Path.Combine(folder, "vcruntime140.dll")));+ Assert.True(installer.IsInstalled(package));+ }++ [Fact]+ public void Conda_packages_cannot_write_outside_the_engine_folder()+ {+ Directory.CreateDirectory(_root);+ var file = Path.Combine(_root, "evil.conda");+ File.WriteAllBytes(file, Conda(("Library/bin/../../../evil.txt", "evil")));++ Assert.Throws<InvalidDataException>(() => EngineInstaller.UnpackConda(file, Path.Combine(_root, "target"), CancellationToken.None));+ Assert.False(File.Exists(Path.Combine(_root, "evil.txt")));+ }+[Fact]public async Task LibreOffice_extensions_go_into_the_installed_LibreOffice_and_need_it(){diff --git a/tests/Filee.Engines.Tests/GraphicsBuilders.cs b/tests/Filee.Engines.Tests/GraphicsBuilders.csnew file mode 100644index 00000000..a8bb5f24--- /dev/null+++ b/tests/Filee.Engines.Tests/GraphicsBuilders.cs@@ -0,0 +1,407 @@+// Generates graphics test inputs that ImageMagick can't write: GIMP XCF files, linear DNG camera RAW files, ICNS+// entries in Apple's legacy RLE format, Windows metafiles (through GDI) and SVG / EPS documents.++using System.Buffers.Binary;+using System.Runtime.InteropServices;+using System.Text;++namespace Filee.Engines.Tests;++internal static class GraphicsBuilders+{+ // ───────────────────────── SVG and EPS ─────────────────────────++ /// <summary>A 400×200 drawing with a gradient, a Bézier path, a circle and text; transparent background.</summary>+ public const string Svg = """+ <?xml version="1.0" encoding="UTF-8"?>+ <svg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200">+ <defs>+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="0">+ <stop offset="0" stop-color="#7F77DD"/>+ <stop offset="1" stop-color="#1D9E75"/>+ </linearGradient>+ </defs>+ <rect x="20" y="20" width="160" height="80" rx="12" fill="url(#g)"/>+ <path d="M 220 150 C 260 40, 320 40, 360 150 Z" fill="#E4572E" stroke="#222" stroke-width="3"/>+ <circle cx="200" cy="100" r="30" fill="#FF0000"/>+ <text x="20" y="170" font-family="Arial, sans-serif" font-size="28" fill="#222">Filee SVG 한글</text>+ </svg>+ """;++ /// <summary>A 200×100 EPS: a filled triangle and a line of text.</summary>+ public const string Eps = """+ %!PS-Adobe-3.0 EPSF-3.0+ %%BoundingBox: 0 0 200 100+ %%EndComments+ newpath 10 10 moveto 190 90 lineto 190 10 lineto closepath 0.2 0.5 0.8 setrgbcolor fill+ /Helvetica findfont 18 scalefont setfont 0 0 0 setrgbcolor 20 70 moveto (Filee EPS) show+ showpage+ %%EOF+ """;++ // ───────────────────────── GIMP XCF ─────────────────────────++ /// <summary>A solid-colour XCF layer.</summary>+ public sealed record XcfLayer(string Name, int Width, int Height, int X, int Y, byte R, byte G, byte B, byte A = 255, bool Visible = true);++ /// <summary>+ /// Writes an 8-bit RGB XCF (format version 0, RLE tiles) with the layers given top-most first, as GIMP stores them.+ /// </summary>+ public static byte[] Xcf(int width, int height, params XcfLayer[] layers)+ {+ var w = new BigEndianWriter();+ w.Bytes("gimp xcf file\0"u8);+ w.U32(width);+ w.U32(height);+ w.U32(0); // RGB+ w.U32(17); w.U32(1); w.Byte(1); // PROP_COMPRESSION = RLE+ w.U32(0); w.U32(0); // PROP_END++ var layerTable = w.Position;+ foreach (var _ in layers)+ w.U32(0);+ w.U32(0); // end of layers+ w.U32(0); // no channels++ for (var i = 0; i < layers.Length; i++)+ {+ var layer = layers[i];+ w.Patch(layerTable + 4 * i, w.Position);+ w.U32(layer.Width);+ w.U32(layer.Height);+ w.U32(1); // RGBA+ var name = Encoding.UTF8.GetBytes(layer.Name + "\0");+ w.U32(name.Length);+ w.Bytes(name);+ w.U32(6); w.U32(4); w.U32(255); // PROP_OPACITY+ w.U32(8); w.U32(4); w.U32(layer.Visible ? 1 : 0); // PROP_VISIBLE+ w.U32(15); w.U32(8); w.U32(layer.X); w.U32(layer.Y); // PROP_OFFSETS+ w.U32(7); w.U32(4); w.U32(0); // PROP_MODE normal+ w.U32(0); w.U32(0); // PROP_END+ var hierarchyPointer = w.Position;+ w.U32(0);+ w.U32(0); // no layer mask++ w.Patch(hierarchyPointer, w.Position);+ w.U32(layer.Width);+ w.U32(layer.Height);+ w.U32(4); // bytes per pixel+ var levelPointer = w.Position;+ w.U32(0);+ w.U32(0); // no smaller levels++ w.Patch(levelPointer, w.Position);+ w.U32(layer.Width);+ w.U32(layer.Height);+ var columns = (layer.Width + 63) / 64;+ var rows = (layer.Height + 63) / 64;+ var tileTable = w.Position;+ for (var t = 0; t < columns * rows; t++)+ w.U32(0);+ w.U32(0);+ for (var t = 0; t < columns * rows; t++)+ {+ w.Patch(tileTable + 4 * t, w.Position);+ var tileWidth = Math.Min(64, layer.Width - t % columns * 64);+ var tileHeight = Math.Min(64, layer.Height - t / columns * 64);+ foreach (var value in new[] { layer.R, layer.G, layer.B, layer.A })+ {+ // One long run per channel: 127, 16-bit count, value.+ w.Byte(127);+ w.Byte((byte)(tileWidth * tileHeight >> 8));+ w.Byte((byte)(tileWidth * tileHeight));+ w.Byte(value);+ }+ }+ }+ return w.ToArray();+ }++ // ───────────────────────── DNG ─────────────────────────++ /// <summary>+ /// A minimal "linear" DNG (demosaiced RGB, 16 bit, uncompressed) as written by raw converters: enough for LibRaw.+ /// The left half is red, the right half blue.+ /// </summary>+ public static byte[] LinearDng(int width, int height, ushort orientation)+ {+ var pixels = new byte[width * height * 6];+ for (var y = 0; y < height; y++)+ {+ for (var x = 0; x < width; x++)+ {+ var (r, g, b) = x < width / 2 ? (50000, 3000, 3000) : (3000, 3000, 50000);+ var i = (y * width + x) * 6;+ BinaryPrimitives.WriteUInt16LittleEndian(pixels.AsSpan(i), (ushort)r);+ BinaryPrimitives.WriteUInt16LittleEndian(pixels.AsSpan(i + 2), (ushort)g);+ BinaryPrimitives.WriteUInt16LittleEndian(pixels.AsSpan(i + 4), (ushort)b);+ }+ }++ // XYZ → camera: the camera is linear sRGB, so this is the XYZ → linear sRGB matrix.+ int[] colorMatrix = [32406, -15372, -4986, -9689, 18758, 415, 557, -2040, 10570];+ var entries = new List<(ushort Tag, ushort Type, uint Count, byte[] Value)>+ {+ (254, 4, 1, U32(0)),+ (256, 4, 1, U32((uint)width)),+ (257, 4, 1, U32((uint)height)),+ (258, 3, 3, [.. U16(16), .. U16(16), .. U16(16)]),+ (259, 3, 1, U16(1)),+ (262, 3, 1, U16(34892)), // LinearRaw+ (271, 2, 6, "Filee\0"u8.ToArray()),+ (272, 2, 5, "Test\0"u8.ToArray()),+ (273, 4, 1, U32(0)), // strip offset, patched below+ (274, 3, 1, U16(orientation)),+ (277, 3, 1, U16(3)),+ (278, 4, 1, U32((uint)height)),+ (279, 4, 1, U32((uint)pixels.Length)),+ (284, 3, 1, U16(1)),+ (50706, 1, 4, [1, 4, 0, 0]),+ (50707, 1, 4, [1, 1, 0, 0]),+ (50708, 2, 11, "Filee Test\0"u8.ToArray()),+ (50717, 4, 1, U32(65535)),+ (50721, 10, 9, colorMatrix.SelectMany(v => (byte[])[.. U32((uint)v), .. U32(10000)]).ToArray()),+ (50728, 5, 3, [.. U32(1), .. U32(1), .. U32(1), .. U32(1), .. U32(1), .. U32(1)]),+ (50778, 3, 1, U16(21)), // D65+ };++ using var stream = new MemoryStream();+ var ifdSize = 2 + entries.Count * 12 + 4;+ var extra = 8 + ifdSize;+ var extraData = new MemoryStream();+ var ifd = new byte[ifdSize];+ BinaryPrimitives.WriteUInt16LittleEndian(ifd, (ushort)entries.Count);+ var stripOffsetField = 0;+ for (var e = 0; e < entries.Count; e++)+ {+ var (tag, type, count, value) = entries[e];+ var at = 2 + e * 12;+ BinaryPrimitives.WriteUInt16LittleEndian(ifd.AsSpan(at), tag);+ BinaryPrimitives.WriteUInt16LittleEndian(ifd.AsSpan(at + 2), type);+ BinaryPrimitives.WriteUInt32LittleEndian(ifd.AsSpan(at + 4), count);+ if (value.Length <= 4)+ {+ value.CopyTo(ifd, at + 8);+ }+ else+ {+ BinaryPrimitives.WriteUInt32LittleEndian(ifd.AsSpan(at + 8), (uint)(extra + extraData.Length));+ extraData.Write(value);+ if (extraData.Length % 2 == 1)+ extraData.WriteByte(0);+ }+ if (tag == 273)+ stripOffsetField = at + 8;+ }+ BinaryPrimitives.WriteUInt32LittleEndian(ifd.AsSpan(stripOffsetField), (uint)(extra + extraData.Length));++ stream.Write("II*\0"u8);+ stream.Write(U32(8));+ stream.Write(ifd);+ extraData.Position = 0;+ extraData.CopyTo(stream);+ stream.Write(pixels);+ return stream.ToArray();++ static byte[] U16(ushort v) => BitConverter.GetBytes(v);+ static byte[] U32(uint v) => BitConverter.GetBytes(v);+ }++ // ───────────────────────── ICNS ─────────────────────────++ /// <summary>An .icns file from raw entries (no table of contents, as old files have).</summary>+ public static byte[] Icns(params (string Type, byte[] Data)[] entries)+ {+ var w = new BigEndianWriter();+ w.Bytes("icns"u8);+ w.U32(8 + entries.Sum(e => 8 + e.Data.Length));+ foreach (var (type, data) in entries)+ {+ w.Bytes(Encoding.Latin1.GetBytes(type));+ w.U32(8 + data.Length);+ w.Bytes(data);+ }+ return w.ToArray();+ }++ /// <summary>Legacy RGB entry data (is32, il32, ih32, it32): R, G and B planes of one colour, RLE encoded.</summary>+ public static byte[] LegacyRgb(int size, byte r, byte g, byte b, bool it32 = false)+ {+ var planes = new byte[size * size * 3];+ planes.AsSpan(0, size * size).Fill(r);+ planes.AsSpan(size * size, size * size).Fill(g);+ planes.AsSpan(2 * size * size, size * size).Fill(b);+ // Vary the first row so the encoder emits literal runs too.+ for (var x = 0; x < size; x += 2)+ planes[x] = (byte)(r ^ 1);+ var packed = PackBits(planes);+ return it32 ? [0, 0, 0, 0, .. packed] : packed;+ }++ /// <summary>Apple's icon RLE (see IcnsFile.UnpackBits): literal runs of 1..128 bytes, repeats of 3..130.</summary>+ public static byte[] PackBits(ReadOnlySpan<byte> source)+ {+ var output = new List<byte>();+ var i = 0;+ while (i < source.Length)+ {+ var run = 1;+ while (i + run < source.Length && run < 130 && source[i + run] == source[i])+ run++;+ if (run >= 3)+ {+ output.Add((byte)(run + 125));+ output.Add(source[i]);+ i += run;+ continue;+ }+ var start = i;+ while (i < source.Length && i - start < 128+ && !(i + 2 < source.Length && source[i] == source[i + 1] && source[i] == source[i + 2]))+ i++;+ output.Add((byte)(i - start - 1));+ for (var j = start; j < i; j++)+ output.Add(source[j]);+ }+ return [.. output];+ }++ // ───────────────────────── Windows metafiles ─────────────────────────++ /// <summary>+ /// Records an EMF of <paramref name="widthMm"/> × <paramref name="heightMm"/> with GDI: a white frame filled+ /// with a teal rectangle whose left third is orange.+ /// </summary>+ public static void Emf(string path, int widthMm, int heightMm)+ {+ var frame = new Rect { Right = widthMm * 100, Bottom = heightMm * 100 }; // .01 mm units+ var dc = CreateEnhMetaFileW(IntPtr.Zero, path, ref frame, "Filee test\0\0");+ Assert.NotEqual(IntPtr.Zero, dc);+ DrawSample(dc, widthMm, heightMm);+ DeleteEnhMetaFile(CloseEnhMetaFile(dc));+ }++ /// <summary>+ /// Writes a placeable WMF (Aldus header + Windows metafile), converted from an EMF by GDI, 1440 units per inch.+ /// </summary>+ public static void Wmf(string path, int widthMm, int heightMm)+ {+ var emf = Path.ChangeExtension(path, ".tmp.emf");+ Emf(emf, widthMm, heightMm);+ var handle = GetEnhMetaFileW(emf);+ var screen = GetDC(IntPtr.Zero);+ try+ {+ var size = GetWinMetaFileBits(handle, 0, null, 8 /* MM_ANISOTROPIC */, screen);+ var bits = new byte[size];+ GetWinMetaFileBits(handle, size, bits, 8, screen);++ const int unitsPerInch = 1440;+ var right = (short)(widthMm * unitsPerInch / 25.4);+ var bottom = (short)(heightMm * unitsPerInch / 25.4);+ var header = new byte[22];+ BinaryPrimitives.WriteUInt32LittleEndian(header, 0x9AC6CDD7);+ BinaryPrimitives.WriteInt16LittleEndian(header.AsSpan(10), right);+ BinaryPrimitives.WriteInt16LittleEndian(header.AsSpan(12), bottom);+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(14), unitsPerInch);+ ushort checksum = 0;+ for (var i = 0; i < 20; i += 2)+ checksum ^= BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(i));+ BinaryPrimitives.WriteUInt16LittleEndian(header.AsSpan(20), checksum);+ File.WriteAllBytes(path, [.. header, .. bits]);+ }+ finally+ {+ _ = ReleaseDC(IntPtr.Zero, screen);+ DeleteEnhMetaFile(handle);+ File.Delete(emf);+ }+ }++ private static void DrawSample(IntPtr dc, int widthMm, int heightMm)+ {+ // Device units of the reference DC (the screen): convert millimetres with its resolution.+ var pixelsX = GetDeviceCaps(dc, 88 /* LOGPIXELSX */) / 25.4;+ var pixelsY = GetDeviceCaps(dc, 90 /* LOGPIXELSY */) / 25.4;+ var w = (int)(widthMm * pixelsX);+ var h = (int)(heightMm * pixelsY);+ Fill(dc, 0, 0, w, h, 0x7F9E1D); // teal (COLORREF is 0x00BBGGRR)+ Fill(dc, 0, 0, w / 3, h, 0x1E7FFF); // orange++ static void Fill(IntPtr dc, int left, int top, int right, int bottom, uint color)+ {+ var brush = CreateSolidBrush(color);+ var rect = new Rect { Left = left, Top = top, Right = right, Bottom = bottom };+ _ = FillRect(dc, ref rect, brush);+ DeleteObject(brush);+ }+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct Rect+ {+ public int Left, Top, Right, Bottom;+ }++ [DllImport("gdi32.dll", CharSet = CharSet.Unicode)]+ private static extern IntPtr CreateEnhMetaFileW(IntPtr reference, string path, ref Rect frame, string description);++ [DllImport("gdi32.dll")]+ private static extern IntPtr CloseEnhMetaFile(IntPtr dc);++ [DllImport("gdi32.dll")]+ private static extern bool DeleteEnhMetaFile(IntPtr metafile);++ [DllImport("gdi32.dll", CharSet = CharSet.Unicode)]+ private static extern IntPtr GetEnhMetaFileW(string path);++ [DllImport("gdi32.dll")]+ private static extern int GetWinMetaFileBits(IntPtr metafile, int size, byte[]? buffer, int mapMode, IntPtr reference);++ [DllImport("gdi32.dll")]+ private static extern int GetDeviceCaps(IntPtr dc, int index);++ [DllImport("gdi32.dll")]+ private static extern IntPtr CreateSolidBrush(uint color);++ [DllImport("gdi32.dll")]+ private static extern bool DeleteObject(IntPtr handle);++ [DllImport("user32.dll")]+ private static extern int FillRect(IntPtr dc, ref Rect rect, IntPtr brush);++ [DllImport("user32.dll")]+ private static extern IntPtr GetDC(IntPtr window);++ [DllImport("user32.dll")]+ private static extern int ReleaseDC(IntPtr window, IntPtr dc);++ /// <summary>Big-endian writer with back-patching of 32-bit offsets.</summary>+ private sealed class BigEndianWriter+ {+ private readonly MemoryStream _stream = new();++ public int Position => (int)_stream.Position;++ public void Byte(byte value) => _stream.WriteByte(value);++ public void Bytes(ReadOnlySpan<byte> value) => _stream.Write(value);++ public void U32(int value)+ {+ Span<byte> buffer = stackalloc byte[4];+ BinaryPrimitives.WriteInt32BigEndian(buffer, value);+ _stream.Write(buffer);+ }++ public void Patch(int position, int value)+ {+ var end = _stream.Position;+ _stream.Position = position;+ U32(value);+ _stream.Position = end;+ }++ public byte[] ToArray() => _stream.ToArray();+ }+}diff --git a/tests/Filee.Engines.Tests/GraphicsTests.cs b/tests/Filee.Engines.Tests/GraphicsTests.csnew file mode 100644index 00000000..634a2f5f--- /dev/null+++ b/tests/Filee.Engines.Tests/GraphicsTests.cs@@ -0,0 +1,604 @@+// Images and vector graphics: the extra raster formats (JPEG XL, JPEG 2000, PSD, TGA, PPM, XCF, camera RAW,+// EMF/WMF), SVG → PDF/PNG, SVGZ, ICNS, Illustrator files and Ghostscript (EPS/PS, skipped when not installed).++using System.IO.Compression;+using System.Text;+using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Icns;+using Filee.Engines.Magick;+using Filee.Engines.Vector;+using ImageMagick;+using PdfSharp.Pdf;+using PdfSharp.Pdf.IO;++namespace Filee.Engines.Tests;++public class GraphicsTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static bool GhostscriptInstalled => GhostscriptConverter.Locate() is not null;++ private static void AssertDone(ConversionJob job)+ {+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");+ Assert.All(job.Outputs, o => Assert.True(new FileInfo(o).Length > 0, o));+ }++ private static IMagickColor<byte> Pixel(IMagickImage<byte> image, int x, int y) =>+ image.GetPixels().GetPixel(x, y).ToColor()!;++ private static string Write(string folder, string name, string text)+ {+ var path = Path.Combine(folder, name);+ File.WriteAllText(path, text);+ return path;+ }++ // ───────────────────────── Raster formats ─────────────────────────++ [Theory]+ [InlineData("jxl", MagickFormat.Jxl, true)]+ [InlineData("jp2", MagickFormat.Jp2, true)]+ [InlineData("psd", MagickFormat.Psd, true)]+ [InlineData("psb", MagickFormat.Psb, true)]+ [InlineData("tga", MagickFormat.Tga, true)]+ [InlineData("ppm", MagickFormat.Ppm, false)]+ public async Task Png_converts_to_the_new_raster_formats_and_back(string target, MagickFormat expected, bool keepsAlpha)+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png);++ var job = await fx.ConvertAsync([source], new Preset { Name = target, TargetFormat = target, Image = { Quality = 100 } });++ AssertDone(job);+ var output = job.Outputs.Single();+ Assert.Equal("." + target, Path.GetExtension(output));+ using (var result = new MagickImage(output))+ {+ Assert.Equal(expected, result.Format);+ Assert.Equal((320u, 200u), (result.Width, result.Height));+ // The transparent corner survives where the format has alpha, else it becomes the white background.+ var corner = Pixel(result, 5, 5);+ if (keepsAlpha)+ Assert.Equal(0, corner.A);+ else+ Assert.True(corner.R > 250 && corner.G > 250 && corner.B > 250, corner.ToString());+ }++ // … and back to PNG through the same engine.+ var back = await fx.ConvertAsync([output], new Preset { TargetFormat = "png", Output = { FileNamePattern = "{name}_back" } });+ AssertDone(back);+ using var png = new MagickImage(back.Outputs.Single());+ Assert.Equal((320u, 200u), (png.Width, png.Height));+ }++ [Fact]+ public async Task Jpeg_xl_quality_comes_from_the_preset_and_100_is_lossless()+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png, 640, 400);++ var low = await fx.ConvertAsync([source], new Preset { TargetFormat = "jxl", Image = { Quality = 40 }, Output = { FileNamePattern = "{name}_40" } });+ var high = await fx.ConvertAsync([source], new Preset { TargetFormat = "jxl", Image = { Quality = 95 }, Output = { FileNamePattern = "{name}_95" } });+ var lossless = await fx.ConvertAsync([source], new Preset { TargetFormat = "jxl", Image = { Quality = 100 }, Output = { FileNamePattern = "{name}_100" } });++ AssertDone(low);+ AssertDone(high);+ AssertDone(lossless);+ Assert.True(new FileInfo(low.Outputs.Single()).Length < new FileInfo(high.Outputs.Single()).Length);+ using var original = new MagickImage(source);+ using var exact = new MagickImage(lossless.Outputs.Single());+ Assert.Equal(0, original.Compare(exact, ErrorMetric.Absolute));+ }++ [Fact]+ public async Task Layered_psd_becomes_one_image_of_the_composite()+ {+ var dir = fx.NewFolder();+ var path = Path.Combine(dir, "layers.psd");+ using (var layers = new MagickImageCollection())+ {+ var background = new MagickImage(MagickColors.Red, 120, 80);+ var box = new MagickImage(MagickColors.Blue, 40, 30) { Page = new MagickGeometry(60, 20, 40, 30) };+ // Photoshop stores the composite first, then the layers.+ using var composite = background.Clone();+ composite.Composite(box, 60, 20, CompositeOperator.Over);+ layers.Add(composite.Clone());+ layers.Add(background);+ layers.Add(box);+ layers.Write(path, MagickFormat.Psd);+ }+ using (var check = new MagickImageCollection(path))+ Assert.True(check.Count >= 3, "the test file should contain the composite and two layers");++ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var result = new MagickImage(job.Outputs.Single());+ Assert.Equal("layers.png", Path.GetFileName(job.Outputs.Single()));+ Assert.Equal((120u, 80u), (result.Width, result.Height));+ Assert.True(Pixel(result, 10, 10).R > 200, "background layer");+ Assert.True(Pixel(result, 80, 35).B > 200 && Pixel(result, 80, 35).R < 50, "the upper layer is composited at its offset");+ }++ [Fact]+ public async Task Gimp_layers_are_flattened_at_their_offsets_and_hidden_layers_are_left_out()+ {+ var dir = fx.NewFolder();+ var path = Path.Combine(dir, "drawing.xcf");+ File.WriteAllBytes(path, GraphicsBuilders.Xcf(96, 64,+ new GraphicsBuilders.XcfLayer("Hidden", 96, 64, 0, 0, 0, 0, 255, Visible: false),+ new GraphicsBuilders.XcfLayer("Box", 16, 16, 60, 8, 0, 200, 0),+ new GraphicsBuilders.XcfLayer("Background", 48, 64, 0, 0, 220, 30, 30)));++ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using var result = new MagickImage(job.Outputs.Single());+ Assert.Equal((96u, 64u), (result.Width, result.Height));+ var background = Pixel(result, 10, 10);+ Assert.True(background.R > 200 && background.B < 50, "background: " + background);+ var box = Pixel(result, 66, 12);+ Assert.True(box.G > 180 && box.R < 50 && box.B < 50, "box: " + box);+ Assert.Equal(0, Pixel(result, 80, 50).A); // outside every visible layer: transparent, not the hidden blue+ }++ [Fact]+ public async Task Netpbm_keeps_its_kind_and_grayscale_becomes_pgm()+ {+ var dir = fx.NewFolder();+ var png = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png);+ var pgm = EngineFixture.MakeImage(dir, "scan.pgm", MagickFormat.Pgm);++ var gray = await fx.ConvertAsync([png], new Preset { TargetFormat = "ppm", Image = { Grayscale = true } });+ var half = await fx.ConvertAsync([pgm], new Preset+ {+ TargetFormat = BuiltInData.SameAsSource,+ Image = { Resize = ResizeMode.Percent, ResizePercent = 50 },+ Output = { FileNamePattern = "{name}_50" },+ });++ AssertDone(gray);+ AssertDone(half);+ Assert.Equal("a.pgm", Path.GetFileName(gray.Outputs.Single()));+ Assert.Equal("scan_50.pgm", Path.GetFileName(half.Outputs.Single()));+ using var result = new MagickImage(half.Outputs.Single());+ Assert.Equal(MagickFormat.Pgm, result.Format);+ Assert.Equal(160u, result.Width);+ }++ [Theory]+ [InlineData("photo.dng")]+ [InlineData("photo.raw")] // ImageMagick alone would read ".raw" as headerless pixels+ public async Task Camera_raw_is_decoded_by_LibRaw_and_turned_upright(string name)+ {+ var dir = fx.NewFolder();+ var path = Path.Combine(dir, name);+ // Orientation 6: the camera was turned; the picture must be rotated 90° clockwise for display.+ File.WriteAllBytes(path, GraphicsBuilders.LinearDng(60, 40, orientation: 6));++ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "jpg" });++ AssertDone(job);+ using var result = new MagickImage(job.Outputs.Single());+ Assert.Equal((40u, 60u), (result.Width, result.Height));+ // Left half red → after turning clockwise it is the top half.+ var top = Pixel(result, 20, 10);+ var bottom = Pixel(result, 20, 50);+ Assert.True(top.R > top.B + 60, "top should be red: " + top);+ Assert.True(bottom.B > bottom.R + 60, "bottom should be blue: " + bottom);+ }++ [Fact]+ public void Camera_raw_uses_the_camera_white_balance_and_srgb()+ {+ var settings = ImageReader.Settings("raw", new Preset());++ Assert.Equal(MagickFormat.Dng, settings.Format);+ Assert.Equal("true", settings.GetDefine(MagickFormat.Dng, "use-camera-wb"));+ Assert.Equal("false", settings.GetDefine(MagickFormat.Dng, "use-auto-wb"));+ Assert.Equal("1", settings.GetDefine(MagickFormat.Dng, "output-color"));+ }++ [Fact]+ public async Task Windows_metafiles_are_rendered_at_the_preset_dpi()+ {+ Assert.SkipUnless(OperatingSystem.IsWindows(), "EMF/WMF are read through GDI+ on Windows only.");+ var dir = fx.NewFolder();+ var emf = Path.Combine(dir, "chart.emf");+ var wmf = Path.Combine(dir, "clip.wmf");+ GraphicsBuilders.Emf(emf, 60, 30);+ GraphicsBuilders.Wmf(wmf, 60, 30);++ var job = await fx.ConvertAsync([emf, wmf], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 200 } });+ var pdf = await fx.ConvertAsync([emf], new Preset { TargetFormat = "pdf" });++ AssertDone(job);+ AssertDone(pdf);+ foreach (var output in job.Outputs)+ {+ using var image = new MagickImage(output);+ // 60 mm at 200 dpi = 472 px (a pixel or two either way from GDI's rounding).+ Assert.InRange((int)image.Width, 460, 485);+ Assert.InRange((int)image.Height, 225, 245);+ var left = Pixel(image, (int)image.Width / 6, (int)image.Height / 2);+ var right = Pixel(image, (int)image.Width * 5 / 6, (int)image.Height / 2);+ Assert.True(left.R > 200 && left.B < 100, Path.GetFileName(output) + " left: " + left);+ Assert.True(right.G > 120 && right.R < 60, Path.GetFileName(output) + " right: " + right);+ }+ using var document = PdfReader.Open(pdf.Outputs.Single(), PdfDocumentOpenMode.Import);+ Assert.InRange(document.Pages[0].Width.Millimeter, 58, 62);+ }++ // ───────────────────────── SVG ─────────────────────────++ [Fact]+ public async Task Svg_to_pdf_is_vector()+ {+ var dir = fx.NewFolder();+ var svg = Write(dir, "drawing.svg", GraphicsBuilders.Svg);++ var job = await fx.ConvertAsync([svg], new Preset { TargetFormat = "pdf" });++ AssertDone(job);+ using var document = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);+ Assert.Equal(1, document.PageCount);+ var page = document.Pages[0];+ // 400 × 200 CSS px = 300 × 150 pt.+ Assert.Equal(300, page.Width.Point, 1);+ Assert.Equal(150, page.Height.Point, 1);++ var content = new StringBuilder(Encoding.Latin1.GetString(page.Contents.CreateSingleContent().Stream.UnfilteredValue));+ var images = new List<(int Width, int Height)>();+ var fonts = 0;+ CollectResources(page.Resources, content, images, ref fonts, 0);+ var text = content.ToString();+ Assert.Matches(@"\s(c|l|re)\s", text); // path operators: curves, lines, rectangles+ Assert.Matches(@"\sf\*?\s", text); // fills+ // Text is drawn as glyph outlines: Skia would embed whole font files (13 MB for one line of Korean).+ Assert.DoesNotContain("BT", text);+ Assert.Equal(0, fonts);+ Assert.True(new FileInfo(job.Outputs.Single()).Length < 100_000, "the PDF should be small");+ Assert.DoesNotContain(images, i => i.Width > 64 || i.Height > 64); // no picture of the drawing+ }++ /// <summary>Collects content of form XObjects, image sizes and font count, recursively.</summary>+ private static void CollectResources(PdfDictionary? resources, StringBuilder content, List<(int, int)> images, ref int fonts, int depth)+ {+ if (resources is null || depth > 5)+ return;+ fonts += resources.Elements.GetDictionary("/Font")?.Elements.Count ?? 0;+ var xobjects = resources.Elements.GetDictionary("/XObject");+ if (xobjects is null)+ return;+ foreach (var key in xobjects.Elements.Keys)+ {+ if (xobjects.Elements.GetDictionary(key) is { } dictionary)+ {+ var subtype = dictionary.Elements.GetName("/Subtype");+ if (subtype == "/Image")+ {+ images.Add((dictionary.Elements.GetInteger("/Width"), dictionary.Elements.GetInteger("/Height")));+ }+ else if (subtype == "/Form")+ {+ content.Append(Encoding.Latin1.GetString(dictionary.Stream.UnfilteredValue));+ CollectResources(dictionary.Elements.GetDictionary("/Resources"), content, images, ref fonts, depth + 1);+ }+ }+ }+ }++ [Fact]+ public async Task Svg_to_png_is_rendered_large_enough_and_keeps_transparency()+ {+ var dir = fx.NewFolder();+ var svg = Write(dir, "drawing.svg", GraphicsBuilders.Svg);++ var job = await fx.ConvertAsync([svg], new Preset { TargetFormat = "png" });+ var sized = await fx.ConvertAsync([svg], new Preset+ {+ TargetFormat = "webp",+ Image = { Resize = ResizeMode.LongEdge, LongEdge = 300, WebpLossless = true },+ });+ var jpg = await fx.ConvertAsync([svg], new Preset { TargetFormat = "jpg" });++ AssertDone(job);+ AssertDone(sized);+ AssertDone(jpg);+ using (var png = new MagickImage(job.Outputs.Single()))+ {+ // At least 1024 px on the long edge (the default 150 dpi would give only 625 px).+ Assert.Equal((1024u, 512u), (png.Width, png.Height));+ Assert.Equal(0, Pixel(png, 3, 3).A);+ var circle = Pixel(png, 512, 256);+ Assert.True(circle.R > 240 && circle.G < 20 && circle.A == 255, circle.ToString());+ }+ using (var webp = new MagickImage(sized.Outputs.Single()))+ Assert.Equal((300u, 150u), (webp.Width, webp.Height)); // rendered at exactly that size+ using (var flat = new MagickImage(jpg.Outputs.Single()))+ Assert.True(Pixel(flat, 3, 3).R > 245, "JPG gets the preset background");+ }++ [Fact]+ public async Task Svgz_round_trip()+ {+ var dir = fx.NewFolder();+ var svg = Write(dir, "logo.svg", GraphicsBuilders.Svg);++ var packed = await fx.ConvertAsync([svg], new Preset { TargetFormat = "svgz" });+ AssertDone(packed);+ var svgz = packed.Outputs.Single();+ Assert.Equal([0x1F, 0x8B], File.ReadAllBytes(svgz)[..2]);++ var unpacked = await fx.ConvertAsync([svgz], new Preset { TargetFormat = "svg", Output = { FileNamePattern = "{name}_plain" } });+ var rendered = await fx.ConvertAsync([svgz], new Preset { TargetFormat = "png", Image = { Resize = ResizeMode.LongEdge, LongEdge = 200 } });++ AssertDone(unpacked);+ AssertDone(rendered);+ Assert.Equal(File.ReadAllBytes(svg), File.ReadAllBytes(unpacked.Outputs.Single()));+ using var png = new MagickImage(rendered.Outputs.Single());+ Assert.Equal(200u, png.Width);+ }++ [Fact]+ public async Task Files_that_are_not_svg_fail_with_a_message()+ {+ var dir = fx.NewFolder();+ var fake = Write(dir, "fake.svg", "just text, no drawing");++ var job = await fx.ConvertAsync([fake], new Preset { TargetFormat = "svgz" });++ Assert.Equal(FileState.Failed, job.Files.Single().State);+ Assert.Contains("not an SVG", job.Files.Single().ErrorDetail);+ }++ // ───────────────────────── ICNS ─────────────────────────++ [Fact]+ public async Task Icns_holds_every_size_as_a_padded_square()+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "app.png", MagickFormat.Png, 300, 200);++ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "icns" });++ AssertDone(job);+ var entries = IcnsFile.Parse(File.ReadAllBytes(job.Outputs.Single()));+ Assert.Equal(["TOC ", "icp4", "ic11", "icp5", "ic12", "ic07", "ic13", "ic08", "ic14", "ic09", "ic10"], entries.Select(e => e.Type));+ foreach (var (type, size) in IcnsFile.WrittenTypes)+ {+ using var icon = new MagickImage(entries.Single(e => e.Type == type).Data);+ Assert.Equal(MagickFormat.Png, icon.Format);+ Assert.Equal(((uint)size, (uint)size), (icon.Width, icon.Height));+ }+ using var large = new MagickImage(entries.Single(e => e.Type == "ic10").Data);+ Assert.Equal(0, Pixel(large, 512, 20).A); // padding above the landscape picture+ Assert.Equal(255, Pixel(large, 512, 512).A); // the picture itself+ }++ [Fact]+ public async Task Icns_converts_back_from_its_largest_image()+ {+ var dir = fx.NewFolder();+ var source = EngineFixture.MakeImage(dir, "app.png", MagickFormat.Png, 256, 256);+ var icns = (await fx.ConvertAsync([source], new Preset { TargetFormat = "icns" })).Outputs.Single();++ var png = await fx.ConvertAsync([icns], new Preset { TargetFormat = "png", Output = { FileNamePattern = "{name}_icon" } });+ var jpg = await fx.ConvertAsync([icns], new Preset { TargetFormat = "jpg", Image = { Resize = ResizeMode.LongEdge, LongEdge = 100 } });++ AssertDone(png);+ AssertDone(jpg);+ using (var image = new MagickImage(png.Outputs.Single()))+ Assert.Equal((1024u, 1024u), (image.Width, image.Height));+ using (var image = new MagickImage(jpg.Outputs.Single()))+ Assert.Equal((100u, 100u), (image.Width, image.Height));+ }++ [Fact]+ public async Task Legacy_and_jpeg_2000_icns_entries_are_read()+ {+ var dir = fx.NewFolder();+ var mask = new byte[128 * 128];+ mask.AsSpan(0, 64 * 128).Fill(255); // top half opaque, bottom half transparent+ var legacy = Path.Combine(dir, "legacy.icns");+ File.WriteAllBytes(legacy, GraphicsBuilders.Icns(+ ("is32", GraphicsBuilders.LegacyRgb(16, 200, 0, 0)),+ ("s8mk", Enumerable.Repeat((byte)255, 256).ToArray()),+ ("it32", GraphicsBuilders.LegacyRgb(128, 0, 180, 40, it32: true)),+ ("t8mk", mask)));++ using var jp2Source = new MagickImage(MagickColors.Navy, 256, 256);+ var jpeg2000 = Path.Combine(dir, "jp2.icns");+ File.WriteAllBytes(jpeg2000, GraphicsBuilders.Icns(+ ("il32", GraphicsBuilders.LegacyRgb(32, 0, 0, 200)),+ ("ic08", jp2Source.ToByteArray(MagickFormat.Jp2))));++ var job = await fx.ConvertAsync([legacy, jpeg2000], new Preset { TargetFormat = "png" });++ AssertDone(job);+ using (var image = new MagickImage(job.Outputs.Single(o => Path.GetFileName(o) == "legacy.png")))+ {+ Assert.Equal((128u, 128u), (image.Width, image.Height)); // it32 is larger than is32+ var top = Pixel(image, 64, 32);+ Assert.True(top.G > 170 && top.R < 10 && top.A == 255, top.ToString());+ Assert.Equal(0, Pixel(image, 64, 100).A);+ }+ using (var image = new MagickImage(job.Outputs.Single(o => Path.GetFileName(o) == "jp2.png")))+ {+ Assert.Equal((256u, 256u), (image.Width, image.Height));+ Assert.True(Pixel(image, 10, 10).B > 100);+ }+ }++ [Fact]+ public void Icns_rle_decodes_literal_and_repeat_runs()+ {+ byte[] data = [.. Enumerable.Range(0, 300).Select(i => (byte)(i < 100 ? i : 7))];++ var decoded = IcnsFile.UnpackBits(GraphicsBuilders.PackBits(data), data.Length);++ Assert.Equal(data, decoded);+ }++ // ───────────────────────── Illustrator ─────────────────────────++ [Fact]+ public async Task Pdf_compatible_illustrator_files_convert_through_pdf()+ {+ var dir = fx.NewFolder();+ var svg = Write(dir, "art.svg", GraphicsBuilders.Svg);+ var pdf = (await fx.ConvertAsync([svg], new Preset { TargetFormat = "pdf" })).Outputs.Single();+ var ai = Path.Combine(dir, "artwork.ai");+ File.Copy(pdf, ai);++ var toPdf = await fx.ConvertAsync([ai], new Preset { TargetFormat = "pdf" });+ var toPng = await fx.ConvertAsync([ai], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 96 } });++ AssertDone(toPdf);+ AssertDone(toPng);+ Assert.Equal(File.ReadAllBytes(ai), File.ReadAllBytes(toPdf.Outputs.Single()));+ using var png = new MagickImage(toPng.Outputs.Single());+ Assert.Equal((400u, 200u), (png.Width, png.Height));+ }++ [Fact]+ public async Task PostScript_illustrator_files_need_ghostscript()+ {+ var dir = fx.NewFolder();+ var ai = Write(dir, "old.ai", GraphicsBuilders.Eps);+ var garbage = Write(dir, "garbage.ai", "not an illustrator file");++ var job = await fx.ConvertAsync([ai, garbage], new Preset { TargetFormat = "pdf" });++ var old = job.Files.Single(f => f.SourcePath == ai);+ if (GhostscriptInstalled)+ {+ Assert.Equal(FileState.Done, old.State);+ }+ else+ {+ Assert.Equal(FileState.Failed, old.State);+ Assert.Contains("Ghostscript", old.ErrorDetail);+ }+ var bad = job.Files.Single(f => f.SourcePath == garbage);+ Assert.Equal(FileState.Failed, bad.State);+ Assert.Contains("not an Adobe Illustrator", bad.ErrorDetail);+ }++ // ───────────────────────── Ghostscript ─────────────────────────++ [Fact]+ public async Task Eps_converts_to_pdf_cropped_and_to_png()+ {+ Assert.SkipUnless(GhostscriptInstalled, "Ghostscript is not installed (pwsh build/fetch-engines.ps1 -Only ghostscript).");+ var dir = Path.Combine(fx.NewFolder(), "한글 폴더");+ Directory.CreateDirectory(dir);+ var eps = Write(dir, "그림 1.eps", GraphicsBuilders.Eps);++ var pdf = await fx.ConvertAsync([eps], new Preset { TargetFormat = "pdf" });+ var png = await fx.ConvertAsync([eps], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 144 } });++ AssertDone(pdf);+ AssertDone(png);+ using (var document = PdfReader.Open(pdf.Outputs.Single(), PdfDocumentOpenMode.Import))+ {+ Assert.Equal(200, document.Pages[0].Width.Point, 1);+ Assert.Equal(100, document.Pages[0].Height.Point, 1);+ }+ using var image = new MagickImage(png.Outputs.Single());+ Assert.Equal((400u, 200u), (image.Width, image.Height));+ var triangle = Pixel(image, 360, 170);+ Assert.True(triangle.B > 150 && triangle.R < 100, triangle.ToString());+ }++ [Fact]+ public async Task Pdf_converts_to_eps_per_page_and_to_postscript()+ {+ Assert.SkipUnless(GhostscriptInstalled, "Ghostscript is not installed (pwsh build/fetch-engines.ps1 -Only ghostscript).");+ var dir = fx.NewFolder();+ var pdf = (await fx.ConvertAsync([EngineFixture.MakeMultiPageTiff(dir, 3)], new Preset { TargetFormat = "pdf" })).Outputs.Single();++ var eps = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "eps", Pdf = { PageRange = "2-3" } });+ var ps = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "ps" });++ AssertDone(eps);+ AssertDone(ps);+ Assert.Equal(["pages_p2.eps", "pages_p3.eps"], eps.Outputs.Select(Path.GetFileName).Order(StringComparer.Ordinal));+ Assert.All(eps.Outputs, o => Assert.StartsWith("%!PS-Adobe-3.0 EPSF-3.0", File.ReadAllText(o)));+ var postScript = File.ReadAllText(ps.Outputs.Single());+ Assert.StartsWith("%!PS-Adobe-3.0", postScript);+ Assert.Equal(3, postScript.Split("%%Page:").Length - 1);+ }++ [Fact]+ public async Task Svg_converts_to_eps_through_pdf()+ {+ Assert.SkipUnless(GhostscriptInstalled, "Ghostscript is not installed (pwsh build/fetch-engines.ps1 -Only ghostscript).");+ var dir = fx.NewFolder();+ var svg = Write(dir, "logo.svg", GraphicsBuilders.Svg);++ var job = await fx.ConvertAsync([svg], new Preset { TargetFormat = "eps" });++ AssertDone(job);+ var eps = File.ReadAllText(job.Outputs.Single());+ Assert.StartsWith("%!PS-Adobe-3.0 EPSF-3.0", eps);+ // eps2write crops to the drawn content, which lies inside the 300 × 150 pt page.+ var box = System.Text.RegularExpressions.Regex.Match(eps, @"%%BoundingBox: (\d+) (\d+) (\d+) (\d+)");+ Assert.True(box.Success, "no bounding box");+ var (left, bottom, right, top) = (int.Parse(box.Groups[1].Value), int.Parse(box.Groups[2].Value), int.Parse(box.Groups[3].Value), int.Parse(box.Groups[4].Value));+ Assert.InRange(left, 0, 30);+ Assert.InRange(bottom, 0, 40);+ Assert.InRange(right, 250, 300);+ Assert.InRange(top, 120, 150);+ }++ // ───────────────────────── Routes ─────────────────────────++ [Theory]+ [InlineData("svg", "png", "vector")]+ [InlineData("svg", "pdf", "vector")]+ [InlineData("ai", "png", "vector,pdfium")]+ [InlineData("eps", "png", "ghostscript,pdfium")]+ [InlineData("svg", "eps", "vector,ghostscript")]+ [InlineData("raw", "jpg", "magick")]+ [InlineData("xcf", "psd", "magick")]+ [InlineData("png", "icns", "icns")]+ [InlineData("icns", "webp", "icns")]+ [InlineData("pdf", "icns", "pdfium,icns")]+ [InlineData("psd", "pdf", "pdfsharp")]+ public void Graphics_routes_use_the_expected_engines(string from, string to, string engines)+ {+ var route = fx.Catalog.CreatePlanner(["ghostscript"]).Plan(from, to);++ Assert.NotNull(route);+ Assert.Equal(engines, string.Join(',', route.Steps.Select(s => s.Converter.Id)));+ }++ [Fact]+ public void Illustrator_headers_are_recognised()+ {+ var dir = fx.NewFolder();+ var pdf = Path.Combine(dir, "a.ai");+ File.WriteAllBytes(pdf, [.. "%PDF-1.6\n"u8]);+ var ps = Write(dir, "b.ai", "%!PS-Adobe-3.0\n");+ var dos = Path.Combine(dir, "c.ai");+ File.WriteAllBytes(dos, [0xC5, 0xD0, 0xD3, 0xC6, 0, 0, 0, 0]);++ Assert.Equal(VectorConverter.AiKind.Pdf, VectorConverter.IllustratorKind(pdf));+ Assert.Equal(VectorConverter.AiKind.PostScript, VectorConverter.IllustratorKind(ps));+ Assert.Equal(VectorConverter.AiKind.PostScript, VectorConverter.IllustratorKind(dos));+ }++ [Fact]+ public void Svgz_detection_uses_the_gzip_signature()+ {+ using var buffer = new MemoryStream();+ using (var gzip = new GZipStream(buffer, CompressionLevel.Fastest, leaveOpen: true))+ gzip.Write("<svg/>"u8);++ Assert.True(SvgRenderer.IsGzip(buffer.ToArray()));+ Assert.False(SvgRenderer.IsGzip("<svg/>"u8));+ }+}