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
Merge feat/documents
KnifeLemonf5cc1ffa28d5
diff --cc Directory.Packages.propsindex c8e704fa,9ac931fb..e3038add--- a/Directory.Packages.props+++ b/Directory.Packages.props@@@ -34,11 -34,8 +34,13 @@@<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" />+ <PackageVersion Include="ExcelDataReader" Version="3.9.0" />+ <PackageVersion Include="PdfPig" Version="0.1.16" />+ <PackageVersion Include="MimeKitLite" Version="4.18.1" /></ItemGroup><ItemGroup Label="Tests">diff --cc THIRD-PARTY-NOTICES.mdindex 269d2709,1726deff..31814bc1--- a/THIRD-PARTY-NOTICES.md+++ b/THIRD-PARTY-NOTICES.md@@@ -23,11 -20,13 +23,15 @@@ Each component remains under its own li| Unhwp | MIT | https://github.com/iyulab/unhwp || Markdig | BSD-2-Clause | https://github.com/xoofx/markdig || ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |+| ExcelDataReader | MIT | https://github.com/ExcelDataReader/ExcelDataReader |+ | PdfPig (PDF text, layout and pictures) | Apache-2.0 | https://github.com/UglyToad/PdfPig |+ | MimeKitLite (e-mail / MIME parsing) | MIT | https://github.com/jstedfast/MimeKit || pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx || Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |+| cu2qu (fontTools): the cubic-to-quadratic approach followed by `Filee.Engines/Fonts/Cff/CubicToQuadratic.cs` | Apache-2.0, Copyright 2016 Google Inc. | https://github.com/fonttools/fonttools |+ Used by the tests only (not redistributed): DocumentFormat.OpenXml (Open XML SDK, MIT, https://github.com/dotnet/Open-XML-SDK) validates the DOCX files Filee writes.+## EnginesBundled with the installer:diff --cc docs/ENGINES.mdindex dce0f27d,777e7bd3..053c9e12--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@@ -12,17 -10,23 +12,26 @@@ Filee chooses engines automatically. Se| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) || Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML || Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |-| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet), XLSM / XLTX → CSV |+| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |+ | Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / PPSX ↔ PPTX** (macros removed for macro-free types) |-| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), CSV, PPTX (+ PPTM/POTX/PPSX), PDF, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |+| Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; CFF (PostScript) outlines become TrueType for TTF and EOT |- | **HWPX writer** | built in | **DOCX, XLSX, XLS, ODS, CSV, TSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |++| **HWPX writer** | built in | **DOCX (+ DOCM/DOTX/DOTM), XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/PPSX), PDF, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF, reStructuredText, LaTeX → HWPX with Pandoc |+ | **DOCX writer** | built in | **Markdown, TXT, XLSX, CSV, PPTX (+ variants), PDF → DOCX** |+ | PDF text | built in (PdfPig) | **PDF → TXT** (reading order, also two columns; no OCR) |+ | E-mail | built in (MimeKit) | **EML → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments) || rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |+| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |- | LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, PPT, RTF, ODT and ODP → PDF and to each other, output as DOCX/ODT/XLS; 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 |+ | 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/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats |+ | Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, reStructuredText and LaTeX ↔ Markdown/HTML/DOCX/ODT (and → RTF, EPUB, TXT) |+| 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 HWPX+DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX- and rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.+ and rendered by rhwp. Anything the built-in readers understand (including PDF) is written as DOCX by the DOCX writer.+ LibreOffice's and Pandoc's costs are set so the built-in route always wins where one exists.++ All built-in document readers are registered in one place, `Hwp/Hwpx/DocumentReaders.cs` (format id → reader, and+ which formats need Pandoc). The HWPX writer and the DOCX writer take their input formats from it: adding a reader+ there is one line and makes both writers (and every route through them) accept the format.Filee never uses software installed on the system (Microsoft Office, an installed LibreOffice, programs on `PATH`):every engine is built in, bundled or downloaded into Filee's own folder, so a conversion behaves the same on every@@@ -122,60 -103,80 +133,134 @@@ text) and LibreOffice + H2Orestart (opeNot converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.+## Spreadsheets++`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (also `.xlt`), ODS, CSV and TSV (also+`.tab`) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep+the text the spreadsheet shows, the value behind it and its Excel number format.++| Format | Read | Written |+|---|---|---|+| XLSX | own reader: values, number formats, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows | every sheet, numbers and dates as numbers with their formats, booleans, styles, merges, widths, heights, hidden rows / columns, frozen rows |+| XLS (Excel 97–2003, also Excel 5/95) | ExcelDataReader (MIT): values, number formats, merges, horizontal / vertical alignment; widths, heights and hidden rows / columns from the BIFF records (`XlsLayout.cs`) | no (LibreOffice) |+| ODS | own reader (`content.xml`, `styles.xml`, `settings.xml`): repeated rows / columns (the empty repeats up to the end of the sheet are skipped), spans, every value type, the text Calc shows (`text:p`), data styles as Excel codes, cell styles, widths, heights, hidden rows / columns / sheets, frozen and header rows | every sheet, typed cells (float, percentage, currency, date, time, boolean) with data styles and the shown text, styles, merges, widths, heights, hidden rows / columns, frozen rows |+| CSV / TSV | delimiter (CSV: comma, semicolon or tab; TSV: tab) and encoding (UTF-8 / UTF-16 with BOM, else CP949) | UTF-8 with BOM, CRLF, one file per sheet |++- Number formats: Excel codes and OpenDocument data styles are converted both ways (`OdsNumberStyles.cs`) for+ digits, decimals, grouping, thousands scaling, percent, scientific, currency symbols, literal text, colours,+ positive / negative / zero sections, dates, times and durations. Codes with conditions (`[>100]`), fractions or+ text between digits are written as plain numbers (General).+- Column widths use Excel's unit (a digit of Calibri 11 = 7 px); in ODS a character is 5.25 pt. LibreOffice+ measures with its own fonts, so a width can differ by up to a fifth after LibreOffice opens the file.+- XLS cells keep the default font, fill and borders (ExcelDataReader does not expose them); XLS output still+ needs LibreOffice. Password-protected XLS and ODS files stop with a clear message.+- Not converted: formulas (their cached results are kept), charts, pictures, comments, conditional formatting,+ data validation, print areas and page breaks.++## Fonts++Fonts are converted in-process (`Filee.Engines/Fonts`); zlib and Brotli come with .NET. The input format is+recognised by content, so a mislabelled file still converts.++- **WOFF 1.0**: every table zlib-compressed (stored as-is when that isn't smaller). Lossless both ways.+- **WOFF2**: one Brotli stream at the highest quality with the glyf/loca transform and, where it applies, the hmtx+ transform, so files come out the size of Google's reference encoder's. Reading handles both transforms, the+ overlap bitmap, untransformed tables and the first font of a WOFF2 collection. Like other encoders, Filee drops+ the DSIG signature and sets bit 11 of head.flags. Brotli is slow on big fonts (about 10 s per MB, so about a+ minute for a 4.6 MB CJK font); the job shows progress and can be cancelled.+- **EOT**: written as version 0x00020001 (names and OS/2 fields in the header, no MicroType Express compression, no+ XOR obfuscation, no URL restriction). Uncompressed EOT files are read (XOR-obfuscated ones too); MTX-compressed+ ones fail with a clear message.+- **TTF → OTF** keeps the TrueType outlines: TrueType-flavoured OpenType is valid OpenType and what systems and+ browsers expect; cubic outlines would gain nothing.+- **OTF with CFF outlines → TTF** (and → EOT, because Internet Explorer renders only TrueType outlines in EOT)+ converts the glyphs: Type 2 charstrings with subroutines, flex, seac accents and CID-keyed fonts are drawn, curves+ are approximated with quadratic splines within 1/1000 em (the approach of fontTools' cu2qu) and contours are+ reversed to TrueType's direction. glyf, loca, maxp 1.0 and post (format 2 with the CFF glyph names, format 3 for+ CID fonts) are built; head, hhea, hmtx and, from VORG, vmtx are updated; CFF, VORG and DSIG are dropped; every+ other table (cmap, name, OS/2, GSUB, GPOS, kern, ...) is kept. PostScript hints are not converted: the font gets a+ gasp table (smoothing at every size) and a prep that switches on dropout control instead.+- Not supported: CFF2 (variable) outlines to TTF or EOT (to WOFF, WOFF2 and OTF they convert), writing font+ collections, and WOFF/WOFF2 extended metadata (dropped).++`tests/Filee.Engines.Tests/FontTests.cs` checks every conversion with small OFL fonts in+`tests/Filee.Engines.Tests/Fonts` (see `OFL.txt` there): round trips keep every table byte for byte, a WOFF2 made+by Google's encoder decodes to the source font, and converted CFF glyphs are compared with the originals in Skia.++ ## DOCX writer++ The counterpart of the HWPX writer: `Hwp/Hwpx/Docx/DocxWriter*.cs` writes WordprocessingML by hand from the same+ document model, so every reader in `DocumentReaders` can produce an editable Word file without Word, LibreOffice or+ Pandoc. It writes:++ - sections with page size, orientation, margins (header and footer distances), columns, page number restarts;+ columns that change mid-page become continuous section breaks, as Word does it;+ - headers and footers (odd/even pages, "different first page") with PAGE / NUMPAGES fields; a section without its+ own header gets an empty one, since Word would otherwise repeat the previous section's;+ - paragraphs: alignment, indents (first line / hanging), spacing, line spacing (the model's percent of the font+ size is converted back to Word's multiple, the inverse of DocxReader), keep with next / keep lines / widow+ control, tab stops with leaders, page and column breaks;+ - runs: Latin and East Asian fonts, size, bold, italic, underline, strike, colour, highlight (Word's named colours)+ or shading, super/subscript, letter spacing;+ - headings as Word's built-in "heading 1".."heading 9" styles (outline levels, so the navigation pane and tables of+ contents work), lists as real numbering definitions (1., a., 가., ①, bullets, start numbers, nine levels);+ - tables with column widths, horizontal and vertical merges, borders, fills, cell alignment, row heights and+ repeated header rows;+ - pictures inline and floating (anchored to page, margin, column or paragraph, with wrapping), text boxes and+ rectangles / rounded rectangles / ellipses / lines as Word 2010 shapes (wps) with solid or gradient fills and+ outlines, hyperlinks (web and to bookmarks), bookmarks, footnotes and endnotes.++ Parts, relationships and content types are written per part (pictures and links in headers and notes are related+ from their own part), children in schema order. The tests validate every file with the Open XML SDK schema+ validator, read it back with DocxReader (DOCX → model → DOCX → model keeps the layout) and convert it with+ LibreOffice as an independent reader, see `tests/Filee.Engines.Tests/DocxWriterTests.cs`.++ Its edges cost 8, less than Pandoc's and LibreOffice's direct conversions, so Markdown → DOCX, PDF → DOCX, ... use+ it. DOCX → DOCX is no edge; the Word variants are the Office Open XML engine's job.++ ## PDF reader++ `Pdf/PdfDocumentReader*.cs` reads PDFs with PdfPig (Apache-2.0) into the document model, for PDF → DOCX, HWPX and+ (with `PdfTextConverter`) TXT:++ - words with their positions, fonts, sizes and colours → lines → paragraphs: a line continues the paragraph above+ when it follows at about one line pitch, unless it starts with a bullet or number, is indented as a first line,+ or the previous line ended although the next word would have fitted; hyphenated line ends are joined, and no+ space is added between Chinese or Japanese lines;+ - reading order: gutters between columns are found where no narrow paragraph crosses; paragraphs that span the+ columns (titles, figures, closing text) split the page into bands, read column by column;+ - headings from font sizes (short paragraphs clearly larger than the body text, the largest size is level 1), bold+ and italic from the fonts, colours, links from link annotations, alignment, indents, spacing and line pitch;+ - pictures: JPEG streams are kept as they are, others are decoded to PNG, and what PdfPig cannot decode is cut out+ of the rendered page; a picture covering the page behind text (the scan under an OCR layer) is skipped;+ - page size per page and margins shared by the document; running headers and footers that repeat on most pages+ (and bare page numbers) are left out;+ - a page without text (a scan, a page of drawings, a turned page) becomes the rendered page (PDFium, 150 dpi JPEG)+ as a picture behind the text of an empty page, so nothing is lost; there is no OCR. PDF → TXT includes the+ invisible OCR text layer of scanned PDFs that have one.++ Password-protected PDFs fail with a clear message. Not converted: tables (their cells come out as paragraphs in+ reading order), vector drawings on text pages, form fields and annotations other than links.++ ## Office Open XML variants++ `Office/OoxmlConverter.cs` converts between the variants of a family (Word, Excel, PowerPoint) by copying the+ package with the main part's content type rewritten. Going to a macro-free type also removes the VBA project, its+ signatures and data, Word's key map customisations and Excel 4.0 macro sheets (with their sheet entries), and every+ relationship and content type entry pointing to them. The built-in readers take the variants directly (DOCM → HWPX,+ XLSM → CSV, PPSX → DOCX ...).+++ `Email/EmlConverter.cs` reads .eml files with MimeKitLite (MIT), which decodes quoted-printable and base64, encoded+ headers (RFC 2047 / 2231) and charsets including EUC-KR / CP949 and ISO-2022-KR; raw 8-bit header text that is not+ UTF-8 is read as CP949, as older Korean mail programs wrote it.++ - **EML → HTML**: a standalone page with From / To / Cc / Date / Subject / Attachments and the HTML body (its style+ sheets kept, scripts removed) or the text body; pictures sent inline (`cid:`) become data URIs.+ - **EML → TXT**: the same headers and the text body (or the HTML body as text).+ - **EML → ZIP**: the attachments (attached messages as .eml) with safe, unique file names.+## HWP ↔ HWPXrhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goesdiff --cc src/Filee.App/Assets/i18n/en.jsonindex 921988b4,fc66636c..fe25f9f8--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@@ -55,27 -55,6 +55,29 @@@"engine.reason.error": "Error while checking","engine.reason.unsupported_platform": "Not available on this platform","engine.reason.needs_package": "Needs {0} — install it in Settings → Engines",+ "engine.magick.description": "Images: JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, BMP, ICO, PSD, TGA, JPEG XL, camera RAW and more — re-encoded with your preset's quality, size and DPI.",+ "engine.pdfium.description": "Renders PDF pages to PNG, JPG and TIFF (also multi-page TIFF and GIF) at the preset's resolution.",+ "engine.pdfsharp.description": "Makes PDFs from images and merges, splits or cuts page ranges out of PDFs.",+ "engine.rhwp.description": "Renders HWP/HWPX to PDF and converts HWP ↔ HWPX. Every conversion to PDF through the HWPX writer (DOCX, XLSX, PPTX, Markdown, e-books…) is drawn by it.",+ "engine.unhwp.description": "Extracts text, Markdown and HTML from HWP and HWPX.",+ "engine.markdown.description": "Markdown → HTML and plain text.",+ "engine.spreadsheet.description": "XLSX ↔ CSV, one CSV per sheet, with the numbers and dates Excel shows.",+ "engine.ooxml.description": "Macro-enabled files and templates (DOCM, DOTX, XLSM, XLTX, PPTM, POTX, PPSX) ↔ DOCX, XLSX and PPTX; macros are removed.",+ "engine.hwpx-writer.description": "Reads Word, Excel, PowerPoint, PDF, HTML, Markdown and text files and writes HWPX — the first step of every document conversion to PDF, without Office or LibreOffice.",+ "engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, HWPX, Markdown, HTML, text and e-books.",++ "engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).",++ "engine.email.description": "E-mails (EML) to HTML and text with sender, recipients and date, pictures included; attachments into a ZIP.",+ "engine.vector.description": "SVG and SVGZ to vector PDF and to images; Illustrator files saved with PDF content.",+ "engine.icns.description": "macOS app icons (ICNS) from and to images.",+ "engine.font.description": "Fonts: TTF, OTF, WOFF, WOFF2 and EOT into each other.",+ "engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.",+ "engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, GZ, ISO and other archives, repacks them as ZIP, 7Z or TAR.GZ and compresses files into one archive (7-Zip).",+ "engine.ebook.description": "E-books: EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text; documents to EPUB.",+ "engine.ffmpeg.description": "Video and audio: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC and more; extracts the sound of videos and makes GIFs.",+ "engine.pandoc.description": "Markdown, HTML, reStructuredText and LaTeX ↔ Word, ODT and RTF.",+ "engine.ghostscript.description": "EPS, PostScript and older Illustrator files to PDF and images; PDF to EPS and PS.",+ "engine.calibre.description": "Rare e-book formats (LIT, LRF, CHM, PDB, RB…) and Kindle output (MOBI, AZW3).",+ "engine.libreoffice.description": "Older and less common office formats — DOC, XLS, PPT, OpenDocument, Pages, Keynote, WordPerfect, Visio, CorelDRAW… — and saving as DOCX or ODT.","profile.images": "Images","profile.pdf": "PDF",@@@ -313,16 -237,10 +315,16 @@@"engines.optional_description": "Large engines are only downloaded when you want them. They are kept when Filee updates and removed when you uninstall it.","engines.all_title": "All engines","engines.package.libreoffice.name": "LibreOffice (older and rare formats)",- "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.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, WordPerfect, Works, Apple Pages, Numbers and Keynote, Publisher, CorelDRAW and Visio, conversions to ODT, ODS and ODP, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX, CSV and PDF convert without it.",+ "engines.package.pandoc.name": "Pandoc (Markdown, HTML, LaTeX ↔ Word)",+ "engines.package.pandoc.description": "DOCX, ODT and RTF → Markdown, reStructuredText and LaTeX ↔ Markdown, HTML and DOCX, and HTML, ODT, RTF, reStructuredText and LaTeX → HWPX. Markdown → PDF, DOCX, HWPX, HTML and TXT 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.progress_detail": "{0} of {1} · {2}/s · {3}",+ "engines.eta.estimating": "estimating time left…",+ "engines.eta.seconds": "{0} s left",+ "engines.eta.minutes": "{0} min left","engines.install": "Install","engines.cancel": "Cancel","engines.remove": "Remove",diff --cc src/Filee.App/Assets/i18n/ko.jsonindex 45da2b2f,9888c1a5..62a424ee--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@@ -55,27 -55,6 +55,29 @@@"engine.reason.error": "확인 중 오류","engine.reason.unsupported_platform": "이 플랫폼에서는 사용할 수 없음","engine.reason.needs_package": "{0} 필요 — 설정 → 변환 엔진에서 설치",+ "engine.magick.description": "이미지: JPG, PNG, WEBP, AVIF, HEIC, TIFF, GIF, BMP, ICO, PSD, TGA, JPEG XL, 카메라 RAW 등을 프리셋의 품질·크기·DPI로 변환해요.",+ "engine.pdfium.description": "PDF 페이지를 PNG, JPG, TIFF(여러 페이지 TIFF·GIF 포함)로 프리셋 해상도에 맞춰 그려요.",+ "engine.pdfsharp.description": "이미지로 PDF를 만들고, PDF를 합치거나 나누거나 원하는 페이지만 잘라내요.",+ "engine.rhwp.description": "HWP/HWPX를 PDF로 그리고 HWP ↔ HWPX를 변환해요. HWPX 작성기를 거쳐 PDF가 되는 모든 변환(DOCX, XLSX, PPTX, 마크다운, 전자책…)도 이 엔진이 그려요.",+ "engine.unhwp.description": "HWP와 HWPX에서 텍스트, 마크다운, HTML을 뽑아내요.",+ "engine.markdown.description": "마크다운 → HTML, 텍스트.",+ "engine.spreadsheet.description": "XLSX ↔ CSV. 시트마다 CSV 하나로, 엑셀에 보이는 숫자와 날짜 그대로 저장해요.",+ "engine.ooxml.description": "매크로 포함 파일과 서식 파일(DOCM, DOTX, XLSM, XLTX, PPTM, POTX, PPSX) ↔ DOCX, XLSX, PPTX. 매크로는 지워요.",+ "engine.hwpx-writer.description": "워드, 엑셀, 파워포인트, PDF, HTML, 마크다운, 텍스트 파일을 읽어 HWPX로 써요. 오피스나 LibreOffice 없이 문서를 PDF로 바꾸는 첫 단계예요.",+ "engine.docx-writer.description": "PDF, HWPX, 마크다운, HTML, 텍스트, 전자책으로 워드 문서(DOCX)를 만들어요.",++ "engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요. 2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).",++ "engine.email.description": "이메일(EML)을 보낸 사람·받는 사람·날짜와 본문 그림까지 HTML·텍스트로, 첨부 파일은 ZIP으로 모아요.",+ "engine.vector.description": "SVG·SVGZ를 벡터 PDF와 이미지로, PDF 내용이 들어 있는 일러스트레이터 파일도 변환해요.",+ "engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.",+ "engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.",+ "engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.",+ "engine.archive.description": "ZIP, 7Z, RAR, TAR, GZ, ISO 등 압축 파일을 풀고, ZIP·7Z·TAR.GZ로 다시 묶거나 여러 파일을 압축 파일 하나로 만들어요(7-Zip).",+ "engine.ebook.description": "전자책: EPUB, MOBI, AZW3, FB2와 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로, 문서는 EPUB으로 변환해요.",+ "engine.ffmpeg.description": "동영상·오디오: MP4, MOV, MKV, WEBM, AVI, MP3, M4A, WAV, FLAC 등. 동영상에서 소리만 뽑거나 GIF도 만들어요.",+ "engine.pandoc.description": "마크다운, HTML, reStructuredText, LaTeX ↔ 워드, ODT, RTF.",+ "engine.ghostscript.description": "EPS, 포스트스크립트, 예전 일러스트레이터 파일을 PDF와 이미지로, PDF를 EPS·PS로.",+ "engine.calibre.description": "드문 전자책 형식(LIT, LRF, CHM, PDB, RB…)과 킨들용 출력(MOBI, AZW3).",+ "engine.libreoffice.description": "DOC, XLS, PPT, 오픈도큐먼트, Pages, Keynote, 워드퍼펙트, Visio, CorelDRAW 같은 오래되었거나 드문 오피스 형식, 그리고 DOCX·ODT로 저장하기.","profile.images": "이미지","profile.pdf": "PDF",@@@ -313,16 -237,10 +315,16 @@@"engines.optional_description": "용량이 큰 엔진은 원할 때만 내려받습니다. Filee를 업데이트해도 유지되고, 제거하면 함께 지워집니다.","engines.all_title": "전체 엔진","engines.package.libreoffice.name": "LibreOffice (오래되었거나 드문 형식)",- "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.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, 워드퍼펙트·Works, Apple Pages·Numbers·Keynote, Publisher·CorelDRAW·Visio, ODT·ODS·ODP로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV·PDF는 없어도 변환돼요.",+ "engines.package.pandoc.name": "Pandoc (마크다운·HTML·LaTeX ↔ 워드)",+ "engines.package.pandoc.description": "DOCX·ODT·RTF → 마크다운, reStructuredText·LaTeX ↔ 마크다운·HTML·DOCX, HTML·ODT·RTF·reStructuredText·LaTeX → HWPX 변환을 추가해요. 마크다운 → PDF·DOCX·HWPX·HTML·TXT는 없어도 돼요.",+ "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.progress_detail": "{0} / {1} · {2}/s · {3}",+ "engines.eta.estimating": "남은 시간 계산 중…",+ "engines.eta.seconds": "{0}초 남음",+ "engines.eta.minutes": "{0}분 남음","engines.install": "설치","engines.cancel": "취소","engines.remove": "제거",diff --cc src/Filee.App/Assets/i18n/zh-CN.jsonindex 2ef3273b,f3c02285..51395cd7--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@@ -55,27 -55,6 +55,29 @@@"engine.reason.error": "检查时出错","engine.reason.unsupported_platform": "此平台不可用","engine.reason.needs_package": "需要 {0} — 在 设置 → 转换引擎 中安装",+ "engine.magick.description": "图片:JPG、PNG、WEBP、AVIF、HEIC、TIFF、GIF、BMP、ICO、PSD、TGA、JPEG XL、相机 RAW 等,按预设的质量、尺寸和 DPI 转换。",+ "engine.pdfium.description": "按预设分辨率将 PDF 页面渲染为 PNG、JPG、TIFF(也支持多页 TIFF 和 GIF)。",+ "engine.pdfsharp.description": "用图片生成 PDF,合并、拆分 PDF 或截取指定页码。",+ "engine.rhwp.description": "将 HWP/HWPX 渲染为 PDF,并在 HWP ↔ HWPX 之间转换。所有经 HWPX 写入器转为 PDF 的文件(DOCX、XLSX、PPTX、Markdown、电子书…)也由它渲染。",+ "engine.unhwp.description": "从 HWP 和 HWPX 中提取文本、Markdown 和 HTML。",+ "engine.markdown.description": "Markdown → HTML 和纯文本。",+ "engine.spreadsheet.description": "XLSX ↔ CSV,每个工作表一个 CSV,数字和日期与 Excel 中显示的一致。",+ "engine.ooxml.description": "启用宏的文件和模板(DOCM、DOTX、XLSM、XLTX、PPTM、POTX、PPSX)↔ DOCX、XLSX、PPTX,宏会被移除。",+ "engine.hwpx-writer.description": "读取 Word、Excel、PowerPoint、PDF、HTML、Markdown 和文本文件并写成 HWPX——无需 Office 或 LibreOffice 将文档转为 PDF 的第一步。",+ "engine.docx-writer.description": "用 PDF、HWPX、Markdown、HTML、文本和电子书生成 Word 文档(DOCX)。",++ "engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。",++ "engine.email.description": "将电子邮件(EML)连同发件人、收件人、日期和图片转为 HTML 和文本,附件打包为 ZIP。",+ "engine.vector.description": "将 SVG、SVGZ 转为矢量 PDF 和图片;也支持包含 PDF 内容的 Illustrator 文件。",+ "engine.icns.description": "macOS 应用图标(ICNS)与图片互转。",+ "engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。",+ "engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。",+ "engine.archive.description": "解压 ZIP、7Z、RAR、TAR、GZ、ISO 等压缩文件,重新打包为 ZIP、7Z 或 TAR.GZ,或把多个文件压缩成一个(7-Zip)。",+ "engine.ebook.description": "电子书:EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本;文档转为 EPUB。",+ "engine.ffmpeg.description": "视频和音频:MP4、MOV、MKV、WEBM、AVI、MP3、M4A、WAV、FLAC 等;可提取视频中的声音,也能制作 GIF。",+ "engine.pandoc.description": "Markdown、HTML、reStructuredText、LaTeX ↔ Word、ODT、RTF。",+ "engine.ghostscript.description": "EPS、PostScript 和旧版 Illustrator 文件转为 PDF 和图片;PDF 转为 EPS 和 PS。",+ "engine.calibre.description": "少见的电子书格式(LIT、LRF、CHM、PDB、RB…)以及 Kindle 输出(MOBI、AZW3)。",+ "engine.libreoffice.description": "较旧或少见的办公格式——DOC、XLS、PPT、OpenDocument、Pages、Keynote、WordPerfect、Visio、CorelDRAW 等——以及保存为 DOCX 或 ODT。","profile.images": "图片","profile.pdf": "PDF",@@@ -313,16 -237,10 +315,16 @@@"engines.optional_description": "体积较大的引擎仅在需要时下载。更新 Filee 时会保留,卸载时一并删除。","engines.all_title": "全部引擎","engines.package.libreoffice.name": "LibreOffice(旧版和少见格式)",- "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.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,WordPerfect、Works,Apple Pages、Numbers 和 Keynote,Publisher、CorelDRAW 和 Visio,转换为 ODT、ODS 和 ODP,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX、CSV 和 PDF 无需它即可转换。",+ "engines.package.pandoc.name": "Pandoc(Markdown、HTML、LaTeX ↔ Word)",+ "engines.package.pandoc.description": "支持 DOCX、ODT、RTF → Markdown,reStructuredText 和 LaTeX ↔ Markdown、HTML、DOCX,以及 HTML、ODT、RTF、reStructuredText、LaTeX → HWPX。Markdown → PDF、DOCX、HWPX、HTML 和 TXT 无需此引擎。",+ "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.progress_detail": "{0} / {1} · {2}/s · {3}",+ "engines.eta.estimating": "正在估算剩余时间…",+ "engines.eta.seconds": "剩余 {0} 秒",+ "engines.eta.minutes": "剩余 {0} 分钟","engines.install": "安装","engines.cancel": "取消","engines.remove": "删除",diff --cc src/Filee.Engines/Email/EmlConverter.csindex 00000000,446962cb..c33f4cf8mode 000000,100644..100644--- a/src/Filee.Engines/Email/EmlConverter.cs+++ b/src/Filee.Engines/Email/EmlConverter.cs@@@ -1,0 -1,273 +1,274 @@@+ // E-mail messages (.eml, RFC 5322 / MIME) with MimeKitLite (MIT): the message as a web page (the headers and the HTML+ // body, or the plain text; pictures sent inline with "cid:" links become data URIs), as plain text, or its attachments+ // as a ZIP. MimeKit decodes the transfer encodings (quoted-printable, base64), encoded headers (RFC 2047 / 2231) and+ // charsets, including the Korean ones (EUC-KR / CP949, ISO-2022-KR); header text in raw 8-bit that is not UTF-8 is read+ // as CP949, as older Korean mail programs wrote it.++ using System.Globalization;+ using System.IO.Compression;+ using System.Net;+ using System.Text;+ using System.Text.RegularExpressions;+ using Filee.Core.Conversion;++using Filee.Engines.Infrastructure;+ using MimeKit;++ namespace Filee.Engines.Email;++ /// <summary>EML → HTML, TXT and ZIP (attachments).</summary>+ public sealed partial class EmlConverter : IConverter+ {+ public string Id => "email";+ public string DisplayName => "E-mail (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("eml", "html"), new("eml", "txt"), new("eml", "zip")];+- public EngineStatus GetStatus() => EngineStatus.Available("EML → HTML, TXT, ZIP (attachments)");++ public EngineStatus GetStatus() => EngineStatus.Available("EML → HTML, TXT, ZIP (attachments)", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("MimeKitLite", typeof(MimeKit.MimeMessage))}");++ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>+ Task.Run<IReadOnlyList<string>>(() =>+ {+ progress?.Report(0.1);+ var message = Load(step.InputPath, cancellationToken);+ progress?.Report(0.5);+ if (step.To == "zip")+ {+ var attachments = Attachments(message);+ if (attachments.Count == 0)+ throw new InvalidOperationException("The e-mail has no attachments.");+ if (step.Output.Allocate("zip") is not { } zip)+ return [];+ WriteZip(attachments, zip, cancellationToken);+ progress?.Report(1);+ return [zip];+ }++ var output = step.Output.Allocate(step.To);+ if (output is null)+ return [];+ var text = step.To == "html" ? Html(message) : PlainText(message);+ File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: step.To == "txt"));+ progress?.Report(1);+ return [output];+ }, cancellationToken);++ /// <summary>Parses a message; 8-bit header text that is not UTF-8 is read as CP949 (Korean).</summary>+ internal static MimeMessage Load(string path, CancellationToken cancellationToken = default)+ {+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);+ var options = ParserOptions.Default.Clone();+ options.CharsetEncoding = Encoding.GetEncoding(949);+ using var stream = File.OpenRead(path);+ return MimeMessage.Load(options, stream, cancellationToken);+ }++ // ───────────────────────── Headers ─────────────────────────++ /// <summary>The headers shown above the body: name and value, only those the message has.</summary>+ private static List<(string Name, string Value)> Headers(MimeMessage message)+ {+ var headers = new List<(string, string)>();+ void Add(string name, string? value)+ {+ if (!string.IsNullOrWhiteSpace(value))+ headers.Add((name, value.Trim()));+ }+ Add("From", Addresses(message.From));+ Add("To", Addresses(message.To));+ Add("Cc", Addresses(message.Cc));+ if (message.Headers.Contains(HeaderId.Date))+ Add("Date", message.Date.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture));+ Add("Subject", message.Subject);+ var attachments = Attachments(message).Select(a => a.Name).ToList();+ if (attachments.Count > 0)+ Add("Attachments", string.Join(", ", attachments));+ return headers;+ }++ private static string Addresses(InternetAddressList list) =>+ string.Join(", ", list.Mailboxes.Select(m => string.IsNullOrWhiteSpace(m.Name) ? m.Address : $"{m.Name} <{m.Address}>"));++ // ───────────────────────── HTML ─────────────────────────++ /// <summary>A standalone web page: the headers in a table, then the HTML body (or the text body, escaped).</summary>+ internal static string Html(MimeMessage message)+ {+ var styles = new StringBuilder();+ string body;+ if (message.HtmlBody is { } html)+ {+ html = RemoveScripts(InlinePictures(html, message));+ // Keep the style sheets of the message's own <head>, and the content of its <body>.+ foreach (Match style in StyleBlock().Matches(html))+ styles.Append(style.Value);+ var match = BodyContent().Match(html);+ body = match.Success ? match.Groups[1].Value : HeadBlock().Replace(html, "");+ }+ else+ {+ body = $"<pre class=\"filee-mail-text\">{WebUtility.HtmlEncode(message.TextBody ?? "")}</pre>";+ }++ var sb = new StringBuilder();+ sb.Append("<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n");+ sb.Append($"<title>{WebUtility.HtmlEncode(message.Subject ?? "")}</title>\n");+ sb.Append("<style>\n.filee-mail-headers { border-collapse: collapse; margin: 0 0 12px 0; font-family: sans-serif; font-size: 14px; }\n")+ .Append(".filee-mail-headers th { text-align: left; vertical-align: top; padding: 2px 16px 2px 0; color: #555; font-weight: 600; }\n")+ .Append(".filee-mail-headers td { padding: 2px 0; }\n")+ .Append(".filee-mail-text { white-space: pre-wrap; font-family: inherit; }\n</style>\n");+ sb.Append(styles);+ sb.Append("</head>\n<body>\n<table class=\"filee-mail-headers\">\n");+ foreach (var (name, value) in Headers(message))+ sb.Append($"<tr><th>{name}</th><td>{WebUtility.HtmlEncode(value)}</td></tr>\n");+ sb.Append("</table>\n<hr>\n");+ sb.Append(body);+ sb.Append("\n</body>\n</html>\n");+ return sb.ToString();+ }++ /// <summary>"cid:" references → data URIs of the parts with that Content-ID, so the page needs no other files.</summary>+ private static string InlinePictures(string html, MimeMessage message)+ {+ var parts = new Dictionary<string, MimePart>(StringComparer.OrdinalIgnoreCase);+ foreach (var part in message.BodyParts.OfType<MimePart>())+ {+ if (part.ContentId is { Length: > 0 } id)+ parts.TryAdd(id.Trim('<', '>'), part);+ }+ if (parts.Count == 0)+ return html;+ return ContentIdReference().Replace(html, match =>+ {+ var id = Uri.UnescapeDataString(match.Groups[1].Value);+ if (!parts.TryGetValue(id, out var part) || part.Content is null)+ return match.Value;+ using var data = new MemoryStream();+ part.Content.DecodeTo(data);+ return $"data:{part.ContentType.MimeType};base64,{Convert.ToBase64String(data.ToArray())}";+ });+ }++ /// <summary>A converted page is opened in a browser: scripts of the message are not carried over.</summary>+ private static string RemoveScripts(string html) => ScriptBlock().Replace(html, "");++ // ───────────────────────── Text ─────────────────────────++ /// <summary>The headers, an empty line and the text body (or the HTML body as text).</summary>+ internal static string PlainText(MimeMessage message)+ {+ var sb = new StringBuilder();+ foreach (var (name, value) in Headers(message))+ sb.Append(name).Append(": ").Append(value).Append("\r\n");+ sb.Append("\r\n");+ var text = message.TextBody ?? (message.HtmlBody is { } html ? HtmlToText(html) : "");+ sb.Append(text.Replace("\r\n", "\n").Replace("\n", "\r\n").TrimEnd()).Append("\r\n");+ return sb.ToString();+ }++ /// <summary>Rough text of an HTML body: blocks and line breaks become new lines, tags go, entities are decoded.</summary>+ internal static string HtmlToText(string html)+ {+ var text = ScriptBlock().Replace(html, "");+ text = StyleBlock().Replace(text, "");+ text = HeadBlock().Replace(text, "");+ text = LineBreakTag().Replace(text, "\n");+ text = BlockEndTag().Replace(text, "\n");+ text = AnyTag().Replace(text, "");+ text = WebUtility.HtmlDecode(text).Replace(' ', ' ');+ var lines = text.Replace("\r\n", "\n").Split('\n').Select(l => SpaceRun().Replace(l, " ").Trim());+ return MultipleBlankLines().Replace(string.Join("\n", lines), "\n\n").Trim();+ }++ // ───────────────────────── Attachments ─────────────────────────++ /// <summary>Attached files and messages with a unique, safe file name each.</summary>+ internal static List<(string Name, MimeEntity Entity)> Attachments(MimeMessage message)+ {+ var result = new List<(string, MimeEntity)>();+ var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ foreach (var entity in message.BodyParts)+ {+ string? name = entity switch+ {+ MessagePart attached => (attached.ContentDisposition?.FileName ?? attached.Message?.Subject ?? "message") + ".eml",+ MimePart part when part.IsAttachment || (part.FileName is { Length: > 0 } && part.ContentId is null) =>+ part.FileName ?? $"attachment{MimeTypes.TryGetExtension(part.ContentType.MimeType, out var extension) switch { true => extension, false => ".bin" }}",+ _ => null,+ };+ if (name is null)+ continue;+ name = SafeName(name);+ var unique = name;+ for (var i = 2; !names.Add(unique); i++)+ unique = $"{Path.GetFileNameWithoutExtension(name)} ({i}){Path.GetExtension(name)}";+ result.Add((unique, entity));+ }+ return result;+ }++ private static void WriteZip(List<(string Name, MimeEntity Entity)> attachments, string path, CancellationToken cancellationToken)+ {+ var temp = path + ".tmp";+ using (var file = File.Create(temp))+ using (var zip = new ZipArchive(file, ZipArchiveMode.Create))+ {+ foreach (var (name, entity) in attachments)+ {+ cancellationToken.ThrowIfCancellationRequested();+ using var target = zip.CreateEntry(name, CompressionLevel.Optimal).Open();+ switch (entity)+ {+ case MessagePart { Message: { } attached }:+ attached.WriteTo(target, cancellationToken);+ break;+ case MimePart { Content: { } content }:+ content.DecodeTo(target, cancellationToken);+ break;+ }+ }+ }+ File.Move(temp, path, overwrite: true);+ }++ /// <summary>A file name without folders or characters Windows does not allow.</summary>+ private static string SafeName(string name)+ {+ name = Path.GetFileName(name.Replace('\\', '/').Split('/')[^1]);+ var invalid = Path.GetInvalidFileNameChars();+ name = new string([.. name.Select(ch => invalid.Contains(ch) || char.IsControl(ch) ? '_' : ch)]).Trim(' ', '.');+ return name.Length == 0 ? "attachment" : name.Length > 150 ? name[..150] : name;+ }++ // ───────────────────────── Patterns ─────────────────────────++ [GeneratedRegex("<body[^>]*>(.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]+ private static partial Regex BodyContent();++ [GeneratedRegex("<head[^>]*>.*?</head>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]+ private static partial Regex HeadBlock();++ [GeneratedRegex("<style[^>]*>.*?</style>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]+ private static partial Regex StyleBlock();++ [GeneratedRegex("<script[^>]*>.*?</script>", RegexOptions.IgnoreCase | RegexOptions.Singleline)]+ private static partial Regex ScriptBlock();++ [GeneratedRegex("cid:([^\"'\\s)>]+)", RegexOptions.IgnoreCase)]+ private static partial Regex ContentIdReference();++ [GeneratedRegex("<br\\s*/?>", RegexOptions.IgnoreCase)]+ private static partial Regex LineBreakTag();++ [GeneratedRegex("</(p|div|tr|li|h[1-6]|table|blockquote)>", RegexOptions.IgnoreCase)]+ private static partial Regex BlockEndTag();++ [GeneratedRegex("<[^>]+>")]+ private static partial Regex AnyTag();++ [GeneratedRegex("[ \\t]+")]+ private static partial Regex SpaceRun();++ [GeneratedRegex("\\n{3,}")]+ private static partial Regex MultipleBlankLines();+ }diff --cc src/Filee.Engines/EngineRegistry.csindex 3d2aa012,9e9ca0ba..1a38b2c6--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@@ -1,11 -1,9 +1,12 @@@// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.using Filee.Core.Conversion;+using Filee.Engines.Archives;+ using Filee.Engines.Email;+using Filee.Engines.Fonts;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;@@@ -32,13 -29,12 +33,17 @@@ public static class EngineRegistrnew UnhwpConverter(),new MarkdownConverter(),new SpreadsheetConverter(),+ new OoxmlConverter(),new HwpxConverter(),+ new ArchiveConverter(),+ new VectorConverter(),+ new IcnsConverter(),+ new FontConverter(),+ new DocxWriterConverter(),+ new PdfTextConverter(),+ new EmlConverter(),new PandocConverter(),+ new GhostscriptConverter(),new LibreOfficeConverter(env),];diff --cc src/Filee.Engines/Filee.Engines.csprojindex 4bd407ab,07bd092b..4e987b25--- a/src/Filee.Engines/Filee.Engines.csproj+++ b/src/Filee.Engines/Filee.Engines.csproj@@@ -18,9 -18,8 +18,11 @@@<PackageReference Include="Unhwp" /><PackageReference Include="Markdig" /><PackageReference Include="ExcelNumberFormat" />+ <PackageReference Include="Svg.Skia" />+ <PackageReference Include="SharpCompress" />+ <PackageReference Include="ExcelDataReader" />+ <PackageReference Include="PdfPig" />+ <PackageReference Include="MimeKitLite" /><PackageReference Include="Microsoft.Extensions.Logging.Abstractions" /></ItemGroup>diff --cc src/Filee.Engines/Hwp/Hwpx/DocumentReaders.csindex 00000000,1d784d09..55f0276fmode 000000,100644..100644--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs@@@ -1,0 -1,152 +1,155 @@@+ // The one place that knows how to read a file of some format into the document model (HDocument). The HWPX writer+ // (HwpxConverter) and the DOCX writer (DocxWriterConverter) take their input formats from here, so a new reader is one+ // line in BuiltIn and both writers (and every route through them) pick it up.++ using System.Text;+ using System.Text.Json.Nodes;+ using Filee.Engines.Hwp.Hwpx.Docx;+ using Filee.Engines.Hwp.Hwpx.Pptx;+ using Filee.Engines.Infrastructure;+ using Filee.Engines.Office;+ using Filee.Engines.Office.Sheets;+ using Filee.Engines.Pdf;++ namespace Filee.Engines.Hwp.Hwpx;++ /// <summary>Registry of document readers: format id → reader.</summary>+ internal static class DocumentReaders+ {+ private static readonly TimeSpan PandocTimeout = TimeSpan.FromMinutes(2);++ /// <summary>+ /// Readers built into Filee: (input file, folder for extracted pictures) → document. Office Open XML variants+ /// (macro-enabled files, templates, slide shows) share the reader of their family.+ /// </summary>+ private static readonly Dictionary<string, Func<string, string, HDocument>> BuiltIn = new(StringComparer.OrdinalIgnoreCase)+ {+ ["docx"] = DocxReader.Read,+ ["docm"] = DocxReader.Read,+ ["dotx"] = DocxReader.Read,+ ["dotm"] = DocxReader.Read,+ ["txt"] = (path, _) => TextDocument(File.ReadAllBytes(path)),+ ["md"] = (path, _) => MarkdownReader.Read(DecodeText(File.ReadAllBytes(path)), Path.GetDirectoryName(Path.GetFullPath(path))!),+ ["xlsx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),+ ["xlsm"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),+ ["xltx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),+ ["csv"] = (path, _) => SheetDocument.Build(CsvFormat.Read(path)),++ ["tsv"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "tsv")),++ ["xls"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "xls")),++ ["ods"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "ods")),+ ["pptx"] = PptxReader.Read,+ ["pptm"] = PptxReader.Read,+ ["potx"] = PptxReader.Read,+ ["ppsx"] = PptxReader.Read,+ ["pdf"] = PdfDocumentReader.Read,+ };++ /// <summary>+ /// Formats read through Pandoc's JSON AST (PandocAstReader) when Pandoc is installed: format id → Pandoc reader.+ /// A built-in reader for the same format wins.+ /// </summary>+ private static readonly Dictionary<string, string> ThroughPandoc = new(StringComparer.OrdinalIgnoreCase)+ {+ ["odt"] = "odt",+ ["rtf"] = "rtf",+ ["html"] = "html",+ ["rst"] = "rst",+ ["tex"] = "latex",+ };++ /// <summary>Formats read without any optional engine.</summary>+ public static IEnumerable<string> BuiltInFormats => BuiltIn.Keys;++ /// <summary>Formats that need Pandoc (those without a built-in reader).</summary>+ public static IEnumerable<string> PandocFormats => ThroughPandoc.Keys.Where(f => !BuiltIn.ContainsKey(f));++ /// <summary>Every readable format; the Pandoc ones only when Pandoc is available.</summary>+ public static IEnumerable<string> Formats(bool pandoc) => pandoc ? BuiltInFormats.Concat(PandocFormats) : BuiltInFormats;++ /// <summary>True when <paramref name="format"/> can only be read with Pandoc.</summary>+ public static bool NeedsPandoc(string format) => !BuiltIn.ContainsKey(format) && ThroughPandoc.ContainsKey(format);++ /// <summary>Reads <paramref name="path"/> (of format <paramref name="format"/>) into the document model.</summary>+ /// <param name="workDirectory">Scratch folder of the job: extracted pictures go into a new folder inside it.</param>+ public static async Task<HDocument> ReadAsync(string path, string format, string workDirectory, CancellationToken cancellationToken)+ {+ var media = Path.Combine(workDirectory, $"media-{Guid.NewGuid():N}");+ if (BuiltIn.TryGetValue(format, out var reader))+ return await Task.Run(() => reader(path, media), cancellationToken);+ if (ThroughPandoc.TryGetValue(format, out var pandocReader))+ return await ReadWithPandocAsync(path, pandocReader, workDirectory, media, cancellationToken);+ throw new NotSupportedException($"There is no document reader for {format.ToUpperInvariant()} files.");+ }++ // ───────────────────────── Pandoc ─────────────────────────++ private static async Task<HDocument> ReadWithPandocAsync(string path, string pandocReader, string workDirectory, string media, CancellationToken cancellationToken)+ {+ var pandoc = PandocConverter.Locate() ?? throw new InvalidOperationException("Pandoc was not found.");+ var json = Path.Combine(workDirectory, $"ast-{Guid.NewGuid():N}.json");+ var inputFolder = Path.GetDirectoryName(Path.GetFullPath(path))!;++ // Working directory = the input's folder, so relative image paths in HTML and LaTeX resolve.+ var result = await ProcessRunner.RunAsync(pandoc,+ [path, "-f", pandocReader, "-t", "json", "--extract-media=" + media, "-o", json],+ PandocTimeout, cancellationToken, workingDirectory: inputFolder);+ if (!File.Exists(json))+ throw new InvalidOperationException($"Pandoc failed (exit {result.ExitCode}). {result.StandardError.Trim()}");+ var ast = JsonNode.Parse(await File.ReadAllTextAsync(json, cancellationToken))+ ?? throw new InvalidDataException("Pandoc produced an empty document.");+ return PandocAstReader.Read(ast, target => ResolveImage(target, inputFolder));+ }++ /// <summary>Images extracted by Pandoc have absolute paths; HTML may use paths relative to the input.</summary>+ private static string? ResolveImage(string target, string inputFolder)+ {+ if (string.IsNullOrWhiteSpace(target) || target.Contains("://", StringComparison.Ordinal))+ return null;+ var path = Uri.UnescapeDataString(target);+ foreach (var candidate in new[] { path, Path.Combine(inputFolder, path) })+ {+ try+ {+ if (File.Exists(candidate))+ return Path.GetFullPath(candidate);+ }+ catch (ArgumentException) { }+ }+ return null;+ }++ // ───────────────────────── Plain text ─────────────────────────++ /// <summary>Plain text: one paragraph per line, text kept verbatim.</summary>+ internal static HDocument TextDocument(byte[] bytes)+ {+ var section = new HSection();+ foreach (var line in DecodeText(bytes).Replace("\r\n", "\n").Split('\n'))+ {+ var paragraph = new HParagraph();+ if (line.Length > 0)+ paragraph.Inlines.Add(new HText(line, default));+ section.Blocks.Add(paragraph);+ }+ var document = new HDocument();+ document.Sections.Add(section);+ return document;+ }++ /// <summary>UTF-8 (with or without BOM) or UTF-16 with BOM; anything else is read as CP949, common for Korean text.</summary>+ internal static string DecodeText(byte[] bytes)+ {+ if (bytes is [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..])+ return new StreamReader(new MemoryStream(bytes), detectEncodingFromByteOrderMarks: true).ReadToEnd();+ try+ {+ var text = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);+ return text.Length > 0 && text[0] == '' ? text[1..] : text;+ }+ catch (DecoderFallbackException)+ {+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);+ return Encoding.GetEncoding(949).GetString(bytes);+ }+ }+ }diff --cc src/Filee.Engines/Hwp/Hwpx/HwpxConverter.csindex ca05c6f8,428c7a7a..72e20678--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs@@@ -1,20 -1,15 +1,16 @@@- // Anything → HWPX without Hancom Office: a reader turns the source into the HWPX document model and HwpxWriter- // writes the OWPML package.- // * DOCX is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns, text boxes and formatting.- // * TXT needs no reader: one paragraph per line.- // * Markdown is parsed with Markdig (MarkdownReader), no external engine needed.- // * XLSX and CSV are read directly (Office/Sheets); every sheet becomes a table (SheetDocument).- // * PPTX is read directly (Pptx/PptxReader): one page per slide with the objects floating at their places.- // * HTML, ODT and RTF are parsed by Pandoc (optional engine) into its JSON AST (PandocAstReader).+ // Anything → HWPX without Hancom Office: a reader from DocumentReaders turns the source into the HWPX document model+ // and HwpxWriter writes the OWPML package.+ // * DOCX (and DOCM / DOTX / DOTM) is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns,+ // text boxes and formatting.+ // * TXT needs no reader: one paragraph per line. Markdown is parsed with Markdig (MarkdownReader).+ // * XLSX / XLSM / XLTX and CSV are read directly (Office/Sheets); every sheet becomes a table (SheetDocument).+ // * PPTX / PPTM / POTX / PPSX are read directly (Pptx/PptxReader): one page per slide.+ // * PDF is read with PdfPig (Pdf/PdfDocumentReader): text in reading order, headings, pictures, scans as images.+ // * HTML, ODT, RTF, reStructuredText and LaTeX are parsed by Pandoc (optional engine) into its JSON AST.- using System.Text;- using System.Text.Json.Nodes;using Filee.Core.Conversion;- using Filee.Engines.Hwp.Hwpx.Docx;- using Filee.Engines.Hwp.Hwpx.Pptx;+using Filee.Engines.Infrastructure;using Filee.Engines.Office;- using Filee.Engines.Office.Sheets;namespace Filee.Engines.Hwp.Hwpx;@@@ -41,8 -27,13 +28,13 @@@ public sealed class HwpxConverter : ICopublic EngineStatus GetStatus(){- _pandoc = PandocConverter.Locate();- return EngineStatus.Available(_pandoc, EngineVersions.BuiltIn);+ var pandoc = PandocConverter.Locate();+ _pandoc = pandoc is not null;+ var builtIn = string.Join(", ", DocumentReaders.BuiltInFormats.Select(f => f.ToUpperInvariant()));+ var withPandoc = string.Join(", ", DocumentReaders.PandocFormats.Select(f => f.ToUpperInvariant()));+ return EngineStatus.Available(pandoc is null+ ? $"{builtIn} → HWPX. {withPandoc} need Pandoc."- : $"{builtIn}; {withPandoc} with Pandoc ({pandoc})");++ : $"{builtIn}; {withPandoc} with Pandoc ({pandoc})", EngineVersions.BuiltIn);}public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)diff --cc src/Filee.Engines/Office/DocxWriterConverter.csindex 00000000,24b042cb..a4ec81cemode 000000,100644..100644--- a/src/Filee.Engines/Office/DocxWriterConverter.cs+++ b/src/Filee.Engines/Office/DocxWriterConverter.cs@@@ -1,0 -1,43 +1,44 @@@+ // Anything → DOCX without Word, LibreOffice or Pandoc: a built-in reader (DocumentReaders) turns the source into the+ // document model and DocxWriter writes WordprocessingML. Its edges cost less than Pandoc's and LibreOffice's, so the+ // built-in writer is used wherever it can read the source.++ using Filee.Core.Conversion;+ using Filee.Engines.Hwp.Hwpx;+ using Filee.Engines.Hwp.Hwpx.Docx;++using Filee.Engines.Infrastructure;++ namespace Filee.Engines.Office;++ /// <summary>Writes DOCX files with the built-in WordprocessingML writer.</summary>+ public sealed class DocxWriterConverter : IConverter+ {+ /// <summary>Below Pandoc's and LibreOffice's direct edges (10 and more), so the built-in writer wins.</summary>+ private const int Cost = 8;++ /// <summary>Word files themselves: DOCX → DOCX is no conversion, the variants are the OOXML engine's job.</summary>+ private static readonly HashSet<string> WordFormats = new(StringComparer.OrdinalIgnoreCase) { "docx", "docm", "dotx", "dotm" };++ public string Id => "docx-writer";+ public string DisplayName => "DOCX writer (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ DocumentReaders.BuiltInFormats.Where(f => !WordFormats.Contains(f)).Select(f => new ConversionEdge(f, "docx", Cost)).ToList();++ public EngineStatus GetStatus() =>- EngineStatus.Available(string.Join(", ", Edges.Select(e => e.From.ToUpperInvariant())) + " → DOCX");++ EngineStatus.Available(string.Join(", ", Edges.Select(e => e.From.ToUpperInvariant())) + " → DOCX", EngineVersions.BuiltIn);++ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ progress?.Report(0.1);+ var document = await DocumentReaders.ReadAsync(step.InputPath, step.From, step.WorkDirectory, cancellationToken);+ progress?.Report(0.6);++ var output = step.Output.Allocate("docx");+ if (output is null)+ return [];+ await Task.Run(() => DocxWriter.Write(document, output), cancellationToken);+ progress?.Report(1);+ return [output];+ }+ }diff --cc src/Filee.Engines/Office/OoxmlConverter.csindex 00000000,7fa6c9d2..7676db97mode 000000,100644..100644--- a/src/Filee.Engines/Office/OoxmlConverter.cs+++ b/src/Filee.Engines/Office/OoxmlConverter.cs@@@ -1,0 -1,271 +1,272 @@@+ // Office Open XML variants without Office: DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX and PPTM / POTX / PPSX ↔ PPTX.+ // A variant is the same package with another content type for its main part, so the package is copied with that type+ // rewritten. Going to a macro-free type also drops the VBA project, its signatures and data, Word's key map+ // customisations and Excel 4.0 macro sheets, with every relationship pointing to them (Office refuses a macro-free+ // file that still holds them).++ using System.IO.Compression;+ using System.Xml.Linq;+ using Filee.Core.Conversion;++using Filee.Engines.Infrastructure;++ namespace Filee.Engines.Office;++ /// <summary>Converts between the variants of Word, Excel and PowerPoint files by rewriting the package.</summary>+ public sealed class OoxmlConverter : IConverter+ {+ private static readonly XNamespace ContentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types";+ private static readonly XNamespace RelationshipsNs = "http://schemas.openxmlformats.org/package/2006/relationships";+ private static readonly XNamespace OfficeRelationshipsNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+ private static readonly XNamespace SpreadsheetNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";++ /// <summary>Format id → family, content type of the main part, and whether macros are allowed.</summary>+ internal static readonly Dictionary<string, (string Family, string ContentType, bool Macros)> Variants = new(StringComparer.OrdinalIgnoreCase)+ {+ ["docx"] = ("word", "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", false),+ ["docm"] = ("word", "application/vnd.ms-word.document.macroEnabled.main+xml", true),+ ["dotx"] = ("word", "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml", false),+ ["dotm"] = ("word", "application/vnd.ms-word.template.macroEnabledTemplate.main+xml", true),+ ["xlsx"] = ("excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", false),+ ["xlsm"] = ("excel", "application/vnd.ms-excel.sheet.macroEnabled.main+xml", true),+ ["xltx"] = ("excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml", false),+ ["pptx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", false),+ ["pptm"] = ("powerpoint", "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml", true),+ ["potx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml", false),+ ["ppsx"] = ("powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml", false),+ };++ /// <summary>Content types of macro parts, which only macro-enabled files may contain.</summary>+ internal static readonly HashSet<string> MacroContentTypes = new(StringComparer.OrdinalIgnoreCase)+ {+ "application/vnd.ms-office.vbaProject",+ "application/vnd.ms-office.vbaProjectSignature",+ "application/vnd.ms-office.vbaProjectSignatureAgile",+ "application/vnd.ms-office.vbaProjectSignatureV3",+ "application/vnd.ms-word.vbaData+xml",+ "application/vnd.ms-word.keyMapCustomizations+xml",+ "application/vnd.ms-excel.macrosheet+xml",+ "application/vnd.ms-excel.intlmacrosheet+xml",+ };++ public string Id => "ooxml";+ public string DisplayName => "Office Open XML (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } =+ [+ .. from source in Variants+ from target in Variants+ where source.Key != target.Key && source.Value.Family == target.Value.Family+ select new ConversionEdge(source.Key, target.Key),+ ];+- public EngineStatus GetStatus() => EngineStatus.Available("DOCM, DOTX, DOTM ↔ DOCX; XLSM, XLTX ↔ XLSX; PPTM, POTX, PPSX ↔ PPTX");++ public EngineStatus GetStatus() => EngineStatus.Available("DOCM, DOTX, DOTM ↔ DOCX; XLSM, XLTX ↔ XLSX; PPTM, POTX, PPSX ↔ PPTX", EngineVersions.BuiltIn);++ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>+ Task.Run<IReadOnlyList<string>>(() =>+ {+ progress?.Report(0.1);+ var output = step.Output.Allocate(step.To);+ if (output is null)+ return [];+ var temp = output + ".tmp";+ try+ {+ Rewrite(step.InputPath, temp, step.To);+ File.Move(temp, output, overwrite: true);+ }+ finally+ {+ if (File.Exists(temp))+ File.Delete(temp);+ }+ progress?.Report(1);+ return [output];+ }, cancellationToken);++ /// <summary>Copies the package <paramref name="input"/> to <paramref name="output"/> as the variant <paramref name="to"/>.</summary>+ internal static void Rewrite(string input, string output, string to)+ {+ var target = Variants[to];+ using var source = ZipFile.OpenRead(input);+ var types = Load(source, "[Content_Types].xml") ?? throw new InvalidDataException("The file is not an Office Open XML package (no [Content_Types].xml).");+ var root = types.Root!;+ var main = Load(source, "_rels/.rels")?.Root?.Elements(RelationshipsNs + "Relationship")+ .FirstOrDefault(r => ((string?)r.Attribute("Type"))?.EndsWith("/officeDocument", StringComparison.Ordinal) == true)+ ?.Attribute("Target")?.Value.TrimStart('/')+ ?? throw new InvalidDataException("The package has no main document part.");++ // The main part gets the target's content type.+ var mainOverride = root.Elements(ContentTypesNs + "Override")+ .FirstOrDefault(o => string.Equals(((string?)o.Attribute("PartName"))?.TrimStart('/'), main, StringComparison.OrdinalIgnoreCase));+ if (mainOverride is null)+ root.Add(mainOverride = new XElement(ContentTypesNs + "Override", new XAttribute("PartName", "/" + main)));+ mainOverride.SetAttributeValue("ContentType", target.ContentType);++ // Macro parts (and the relationship parts of those parts) go when the target may not contain macros.+ var removed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ if (!target.Macros)+ {+ foreach (var entry in source.Entries)+ {+ if (ContentTypeOf(root, entry.FullName) is { } type && MacroContentTypes.Contains(type))+ removed.Add(entry.FullName);+ }+ foreach (var part in removed.ToList())+ removed.Add(RelationshipsPartOf(part));+ root.Elements(ContentTypesNs + "Override")+ .Where(o => removed.Contains(((string?)o.Attribute("PartName"))?.TrimStart('/') ?? ""))+ .Remove();+ root.Elements(ContentTypesNs + "Default")+ .Where(d => MacroContentTypes.Contains((string?)d.Attribute("ContentType") ?? ""))+ .Remove();+ }++ // Relationships to removed parts, by source part (the workbook's sheet list refers to them by id).+ var removedIds = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase);+ using (var file = File.Create(output))+ using (var zip = new ZipArchive(file, ZipArchiveMode.Create))+ {+ foreach (var entry in source.Entries)+ {+ if (removed.Contains(entry.FullName) || entry.FullName.EndsWith('/'))+ continue;+ if (entry.FullName == "[Content_Types].xml")+ {+ Save(zip, entry.FullName, types);+ }+ else if (removed.Count > 0 && entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))+ {+ var rels = Load(source, entry.FullName)!;+ var owner = OwnerOf(entry.FullName);+ var dropped = rels.Root!.Elements(RelationshipsNs + "Relationship")+ .Where(r => (string?)r.Attribute("TargetMode") != "External"+ && removed.Contains(Resolve(owner, (string?)r.Attribute("Target") ?? "")))+ .ToList();+ if (dropped.Count > 0)+ removedIds[owner] = [.. dropped.Select(r => (string?)r.Attribute("Id") ?? "")];+ dropped.Remove();+ Save(zip, entry.FullName, rels);+ }+ else+ {+ Copy(entry, zip);+ }+ }+ }++ // Excel lists its sheets in the workbook part: a removed macro sheet leaves the list too.+ if (target.Family == "excel" && removedIds.TryGetValue(main, out var sheetIds) && sheetIds.Count > 0)+ RemoveSheets(output, main, sheetIds);+ }++ /// <summary>Removes <sheet> entries (and names scoped to them) whose relationship was removed.</summary>+ private static void RemoveSheets(string package, string workbookPath, HashSet<string> ids)+ {+ using var zip = ZipFile.Open(package, ZipArchiveMode.Update);+ var entry = zip.GetEntry(workbookPath);+ if (entry is null)+ return;+ XDocument workbook;+ using (var stream = entry.Open())+ workbook = XDocument.Load(stream);+ var sheets = workbook.Root?.Element(SpreadsheetNs + "sheets")?.Elements(SpreadsheetNs + "sheet").ToList() ?? [];+ var kept = new List<int>();+ for (var i = 0; i < sheets.Count; i++)+ {+ if (ids.Contains((string?)sheets[i].Attribute(OfficeRelationshipsNs + "id") ?? ""))+ sheets[i].Remove();+ else+ kept.Add(i);+ }+ foreach (var name in workbook.Root?.Element(SpreadsheetNs + "definedNames")?.Elements(SpreadsheetNs + "definedName").ToList() ?? [])+ {+ if (!int.TryParse((string?)name.Attribute("localSheetId"), out var local))+ continue;+ var index = kept.IndexOf(local);+ if (index < 0)+ name.Remove();+ else+ name.SetAttributeValue("localSheetId", index);+ }+ foreach (var view in workbook.Descendants(SpreadsheetNs + "workbookView"))+ {+ view.Attribute("activeTab")?.Remove();+ view.Attribute("firstSheet")?.Remove();+ }+ entry.Delete();+ Save(zip, workbookPath, workbook);+ }++ // ───────────────────────── Package helpers ─────────────────────────++ private static string? ContentTypeOf(XElement types, string partPath)+ {+ var name = "/" + partPath;+ var over = types.Elements(ContentTypesNs + "Override")+ .FirstOrDefault(o => string.Equals((string?)o.Attribute("PartName"), name, StringComparison.OrdinalIgnoreCase));+ if (over is not null)+ return (string?)over.Attribute("ContentType");+ var extension = Path.GetExtension(partPath).TrimStart('.');+ return (string?)types.Elements(ContentTypesNs + "Default")+ .FirstOrDefault(d => string.Equals((string?)d.Attribute("Extension"), extension, StringComparison.OrdinalIgnoreCase))+ ?.Attribute("ContentType");+ }++ /// <summary>"word/vbaProject.bin" → "word/_rels/vbaProject.bin.rels".</summary>+ private static string RelationshipsPartOf(string part)+ {+ var slash = part.LastIndexOf('/');+ return slash < 0 ? $"_rels/{part}.rels" : $"{part[..slash]}/_rels/{part[(slash + 1)..]}.rels";+ }++ /// <summary>"word/_rels/document.xml.rels" → "word/document.xml"; "_rels/.rels" → "".</summary>+ private static string OwnerOf(string relsPath)+ {+ var folder = relsPath[..relsPath.IndexOf("_rels/", StringComparison.Ordinal)];+ var name = Path.GetFileName(relsPath);+ return folder + name[..^".rels".Length];+ }++ /// <summary>A relationship target resolved against its source part, as a zip path.</summary>+ private static string Resolve(string sourcePart, string target)+ {+ if (target.StartsWith('/'))+ return target.TrimStart('/');+ var parts = new List<string>(sourcePart.Contains('/') ? sourcePart[..sourcePart.LastIndexOf('/')].Split('/') : []);+ foreach (var segment in Uri.UnescapeDataString(target).Split('/'))+ {+ if (segment == "..")+ {+ if (parts.Count > 0)+ parts.RemoveAt(parts.Count - 1);+ }+ else if (segment is not ("." or ""))+ {+ parts.Add(segment);+ }+ }+ return string.Join('/', parts);+ }++ private static XDocument? Load(ZipArchive zip, string name)+ {+ if (zip.GetEntry(name) is not { } entry)+ return null;+ using var stream = entry.Open();+ return XDocument.Load(stream);+ }++ private static void Save(ZipArchive zip, string name, XDocument xml)+ {+ using var stream = zip.CreateEntry(name, CompressionLevel.Optimal).Open();+ xml.Save(stream, SaveOptions.DisableFormatting);+ }++ private static void Copy(ZipArchiveEntry entry, ZipArchive zip)+ {+ using var source = entry.Open();+ using var target = zip.CreateEntry(entry.FullName, CompressionLevel.Optimal).Open();+ source.CopyTo(target);+ }+ }diff --cc src/Filee.Engines/Office/SpreadsheetConverter.csindex 95688587,0f300e47..fec814bf--- a/src/Filee.Engines/Office/SpreadsheetConverter.cs+++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs@@@ -1,9 -1,7 +1,10 @@@- // Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS and XLT are read, not written).-// XLSX (and XLSM / XLTX) → CSV and CSV → XLSX without Excel or LibreOffice. XLSX / CSV → PDF, HWPX and HTML go through the HWPX-// writer (sheets become 한글 tables), see HwpxConverter and SheetDocument.++// Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS / XLT and the XLSM / XLTX++// variants are read, not written).+// XLSX / XLS / ODS / CSV / TSV → PDF, HWPX and HTML go through the HWPX writer (sheets become 한글 tables), see+// HwpxConverter and SheetDocument.using Filee.Core.Conversion;+using Filee.Engines.Infrastructure;using Filee.Engines.Office.Sheets;namespace Filee.Engines.Office;@@@ -11,9 -9,6 +12,9 @@@/// <summary>Converts between spreadsheet formats in-process.</summary>public sealed class SpreadsheetConverter : IConverter{- private static readonly string[] Sources = ["xlsx", "xls", "ods", "csv", "tsv"];++ private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xls", "ods", "csv", "tsv"];+ private static readonly string[] Targets = ["xlsx", "ods", "csv", "tsv"];+public string Id => "spreadsheet";public string DisplayName => "Spreadsheets (built-in)";public int MaxParallelism => 0;diff --cc src/Filee.Engines/Pdf/PdfTextConverter.csindex 00000000,1fe4c1db..a91d8353mode 000000,100644..100644--- a/src/Filee.Engines/Pdf/PdfTextConverter.cs+++ b/src/Filee.Engines/Pdf/PdfTextConverter.cs@@@ -1,0 -1,38 +1,39 @@@+ // PDF → TXT with PdfPig (Apache-2.0): the text in reading order (also on two-column pages), one paragraph per line and+ // an empty line between paragraphs. The invisible text layer of OCR-processed scans is included; scans without one+ // have no text to extract (Filee does no OCR).++ using System.Text;+ using Filee.Core.Conversion;++using Filee.Engines.Infrastructure;++ namespace Filee.Engines.Pdf;++ /// <summary>Extracts the text of PDF files.</summary>+ public sealed class PdfTextConverter : IConverter+ {+ public string Id => "pdf-text";+ public string DisplayName => "PDF text (built-in)";+ public int MaxParallelism => 0;++ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("pdf", "txt")];+- public EngineStatus GetStatus() => EngineStatus.Available("PDF → TXT");++ public EngineStatus GetStatus() => EngineStatus.Available("PDF → TXT", $"{EngineVersions.BuiltIn} · {EngineVersions.Library("PdfPig", typeof(UglyToad.PdfPig.PdfDocument))}");++ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>+ Task.Run<IReadOnlyList<string>>(() =>+ {+ progress?.Report(0.1);+ var text = PdfDocumentReader.PlainText(PdfDocumentReader.ReadText(step.InputPath));+ cancellationToken.ThrowIfCancellationRequested();+ if (text.Length == 0)+ throw new InvalidOperationException("The PDF contains no text (it may be scanned; Filee does not recognise text in images).");++ var output = step.Output.Allocate("txt");+ if (output is null)+ return [];+ // UTF-8 with BOM, so Notepad and Excel-era tools pick the right encoding for Korean and Chinese text.+ File.WriteAllText(output, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));+ progress?.Report(1);+ return [output];+ }, cancellationToken);+ }