diff --git a/README.md b/README.md
index d4cf89488..0349efeb3 100644
--- a/README.md
+++ b/README.md
@@ -170,11 +170,11 @@ To undo it, remove the entries in Windows Security → App & browser control →
| From | To |
|---|---|
| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, FITS, JPEG XR (Windows), iPhone Live Photo (LIVP), Insta360 INSP, Windows program icons (EXE, DLL), Valve Texture VTF (Source engine, Garry's Mod), animated cursor (ANI) read; GIMP XCF and Paint.NET PDN (layers kept between XCF, PDN and PSD) | any of these (HEIC⁵), GIMP XCF, Paint.NET PDN, VTF, PDF, SVG (traced), resized, grayscale; Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵), and a video → Live Photo (iPhone) or Motion Photo (Android)⁵, experimental |
-| **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, FODG EPS, PS¹ CDR, binary Visio VSD, CGM² Obsidian Canvas (JSON Canvas) and Excel chart templates (CRTX) read | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, SVG → EMF, WMF, ODG²; Obsidian Canvas → its text as Markdown |
+| **Vector**: SVG, SVGZ, EMF, WMF, AI, Visio VSDX, ODG, OTG, FODG EPS, PS¹ CDR, binary Visio VSD, CGM² Obsidian Canvas (JSON Canvas) and Excel chart templates (CRTX) read | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS, ODG ↔ OTG ↔ FODG, SVG → EMF, WMF, ODG²; Obsidian Canvas → its text as Markdown |
| **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (editable slides, or a picture of each page), SVG², PDF/A¹; merge (in an order you choose first), split (by pages, every N pages or into equal parts), page ranges, compress (smaller PDFs) |
-| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG; OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents), XPS / OpenXPS and FreeMind / Freeplane / XMind mind maps (as outlines) read FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides; DOCX, HTML tables → XLSX, ODS, CSV; MSG → EML FODT, OTT² |
-| **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, CSV, TSV OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML XLT, OTS² |
-| **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPT, ODP, OTP, FODP PowerPoint 95 PPT, Keynote² | PDF, PNG, JPG, ODP, DOCX, HWPX; PPT → PPTX OTP² |
+| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, OTT, FODT, EML, Outlook MSG; OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents), XPS / OpenXPS, DjVu (scanned books) and FreeMind / Freeplane / XMind mind maps (as outlines) read RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, OTT, FODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides; DOCX, HTML tables → XLSX, ODS, CSV; MSG → EML |
+| **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, OTS, FODS, CSV, TSV Numbers, ET² | PDF, XLSX, ODS, OTS, FODS, CSV, TSV, JSON, HWPX, HTML XLT² |
+| **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPT, ODP, OTP, FODP PowerPoint 95 PPT, Keynote² | PDF, PNG, JPG, ODP, OTP, FODP, DOCX, HWPX; PPT → PPTX |
| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML, PPTX and ODP slides |
| **Text**: TXT, LOG, script source (PY, PAC, BAT, COMMAND; read, never run), Arduino and Processing sketches (INO, PDE), Markdown, HTML; MHTML (saved web pages) read Jupyter, reStructuredText, Org, MediaWiki, DocBook, Textile, OPML LaTeX, AsciiDoc, Typst, man³ | UTF-8 TXT, PDF, DOCX, HWPX, EPUB, PPTX and ODP slides (a slide per heading) each other, PPTX and ODP slides³ |
| **E-books**: EPUB, KEPUB, MOBI, AZW3, AZW, AZW4, FB2, CBZ, CBR, CB7, HTMLZ, TXTZ, CHM, PDB, PML, TCR, RB, SNB, OEB LIT, LRF⁴ | PDF, EPUB, KEPUB (Kobo), DOCX, TXT, HTML, HWPX MOBI, AZW3 |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 8046fdbd1..3ed3dc706 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -14,37 +14,40 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **HWP text** | built in | **HWP/HWPX → TXT, Markdown, HTML** with the [HWP](#hwp-reader) and [HWPX readers](#hwpx-reader) (pictures in a `_files` folder next to the Markdown, embedded in the HTML; see [HWP text, Markdown and HTML](#hwp-text-markdown-and-html)) |
| Text & Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT**; **TXT, LOG, CXLOG, PY, PAC, BAT, CMD, COMMAND, LUA, CSS, PS1, SQL, AHK, INI, RSC, C, H, CPP, CC, CXX, HPP, HH, HXX, CS, DART, HQL, DBML, JAVA, INO, PDE → UTF-8 TXT**, preserving source text without running scripts (and → PDF through the Filee renderer, → DOCX through the DOCX writer) |
| **Markup languages** | built in | **Jupyter notebooks (IPYNB), OPML, Textile, MediaWiki, reStructuredText, Org, DocBook 5 → Markdown, HTML, TXT and each other**; every document the built-in readers read → each of them; each → DOCX, ODT, HWPX, PDF through the document writers (see [Lightweight markup languages](#lightweight-markup-languages)); **FreeMind / Freeplane (MM) and XMind mind maps → Markdown, HTML, TXT, OPML** as outlines (see [Mind maps](#mind-maps)) |
-| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLSB, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |
-| **Spreadsheet printing** | built in | **XLSX (+ XLSM/XLTX), XLSB, XLS (+ XLT), ODS → PDF** printed the way Excel prints them: page setup, print areas and titles, scaling and fit to pages, page breaks, headers and footers (see [Spreadsheet printing](#spreadsheet-printing)) |
+| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLSB, XLS, ODS (+ OTS, FODS), CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet; OTS and FODS out through the next engine) |
+| **Spreadsheet printing** | built in | **XLSX (+ XLSM/XLTX), XLSB, XLS (+ XLT), ODS (+ OTS, FODS) → PDF** printed the way Excel prints them: page setup, print areas and titles, scaling and fit to pages, page breaks, headers and footers (see [Spreadsheet printing](#spreadsheet-printing)) |
| Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / POTM / PPSX ↔ PPTX** (macros removed for macro-free types) |
+| **OpenDocument templates and flat files** | built in | **ODT ↔ OTT ↔ FODT, ODS ↔ OTS ↔ FODS, ODP ↔ OTP ↔ FODP, ODG ↔ OTG ↔ FODG** without reading the document into a model, so nothing is lost (see [OpenDocument templates and flat files](#opendocument-templates-and-flat-files)); after the ODT writer and the spreadsheet engine, every document → OTT / FODT and every workbook → OTS / FODS |
| Fonts | built in | **TTF, OTF, WOFF, WOFF2, EOT ↔ each other**; **FON (NE monochrome FNT v2/v3, supported single-byte charsets) → TTF, OTF, WOFF, WOFF2, EOT only**; CFF (PostScript) outlines become TrueType for TTF and EOT |
-| **HWPX writer** | built in | **HWP, DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT, WPS Office WPS), ODT, XLSX (+ XLSM/XLTX), XLS, ODS, CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PPT, ODP (+ OTP, FODP), PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2, CHM, PDB, PML, TCR, RB, SNB, OEB, HWPX, TXT, Markdown, RTF, mind maps (MM, XMind) → HWPX** (and with rhwp → PDF and images); reStructuredText, LaTeX → HWPX with Pandoc |
-| **DOCX writer** | built in | **DOC (+ DOT, WPS Office WPS), ODT, HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → DOCX** |
-| **ODT writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → ODT** (OpenDocument text, LibreOffice Writer) |
-| **PPTX writer** | built in | **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → PPTX slides** (a slide per heading, Pandoc's rules; Pandoc's markup languages too when Pandoc is installed); **PPT → PPTX** as the [PPT reader](#ppt-reader) translates it |
-| **ODP writer** | built in | **PPTX (+ PPTM/POTX/POTM/PPSX), PPT → ODP** with masters, shapes, pictures, tables, lists and speaker notes; **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → ODP slides** laid out as the PPTX writer lays them out (see [ODP writer](#odp-writer)); a deck with what the slide model leaves out (charts without a picture, effects, 3D) keeps LibreOffice's route |
+| **HWPX writer** | built in | **HWP, DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT, WPS Office WPS), ODT (+ OTT, FODT), XLSX (+ XLSM/XLTX), XLS, ODS (+ OTS, FODS), CSV, TSV, PPTX (+ PPTM/POTX/POTM/PPSX), PPT, ODP (+ OTP, FODP), PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2, CHM, PDB, PML, TCR, RB, SNB, OEB, HWPX, TXT, Markdown, RTF, mind maps (MM, XMind) → HWPX** (and with rhwp → PDF and images); reStructuredText, LaTeX → HWPX with Pandoc |
+| **DOCX writer** | built in | **DOC (+ DOT, WPS Office WPS), ODT (+ OTT, FODT), HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS (+ OTS, FODS), CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → DOCX** |
+| **RTF writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), ODT, HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → RTF** (Rich Text Format, see [RTF writer](#rtf-writer)) |
+| **ODT writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), HWPX, HWP, PDF, OFD, UYAP (UDF), HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS (+ OTS, FODS), CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP), mind maps (MM, XMind) → ODT** (OpenDocument text, LibreOffice Writer) |
+| **PPTX writer** | built in | **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT (+ OTT, FODT), HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS (+ OTS, FODS), CSV → PPTX slides** (a slide per heading, Pandoc's rules; Pandoc's markup languages too when Pandoc is installed); **PPT → PPTX** as the [PPT reader](#ppt-reader) translates it |
+| **ODP writer** | built in | **PPTX (+ PPTM/POTX/POTM/PPSX), PPT → ODP, OTP, FODP** with masters, shapes, pictures, tables, lists and speaker notes; **Markdown, DOCX (+ variants), DOC (+ DOT, WPS), ODT (+ OTT, FODT), HWPX, HWP, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), TXT, RTF, XLSX, XLS, ODS, CSV → ODP slides** laid out as the PPTX writer lays them out (see [ODP writer](#odp-writer)); a deck with what the slide model leaves out (charts without a picture, effects, 3D) keeps LibreOffice's route |
| PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) |
| PDF slides | built in (PdfPig, PDFium) | **PDF → PPTX**: each page rebuilt as an editable slide (text boxes with the PDF's fonts, pictures, shapes, ruled tables); or, as a preset option, a picture of each page with its text in the speaker notes |
| PDF tables | built in (PdfPig) | **PDF → XLSX, ODS, CSV** (#267): each table drawn with lines on its own sheet, numbers and dates as real values, merged cells and column widths kept |
| **PostScript writer** | built in | **PDF → PS (LanguageLevel 3), EPS** (one per page) without Ghostscript: vectors, text with its embedded fonts, pictures, shadings, patterns; pages with transparency as pictures (see [PDF → PostScript and EPS](#pdf--postscript-and-eps)) |
-| Document tables | built in | **DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT/WPS), ODT, RTF, HWP, HWPX, HTML, MHTML → XLSX, ODS, CSV** (#1016): each table on its own sheet, numbers and dates as real values, merged cells, borders, fill, alignment and column widths kept |
+| Document tables | built in | **DOCX (+ DOCM/DOTX/DOTM), DOC (+ DOT/WPS), ODT (+ OTT, FODT), RTF, HWP, HWPX, HTML, MHTML → XLSX, ODS, CSV** (#1016): each table on its own sheet, numbers and dates as real values, merged cells, borders, fill, alignment and column widths kept |
| E-mail | built in (MimeKit, MsgReader) | **EML, Outlook MSG → HTML** (headers + body, inline pictures), **TXT**, **ZIP** (the attachments); **MSG → EML**; **MHTML → HTML** (the saved page in one file, pictures inlined; on to PDF, DOCX, HWPX, TXT, Markdown, EPUB from there) |
| Signed files | built in (System.Security.Cryptography.Pkcs) | **P7M → the signed file inside** (CMS / PKCS #7, CAdES: Italian e-invoices `*.xml.p7m`, signed PDFs `*.pdf.p7m`), then on from its format (P7M → PDF → JPG); the signature isn't checked |
| Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard, iCalendar ↔ CSV**; **property lists (.plist, XML and binary) → each of them and TXT**; FreeMASTER oscilloscope TXT → CSV; spreadsheets, contacts and events reach JSON / YAML / TOML / XML through CSV |
| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ, CHM, PDB, PML, TCR, RB, SNB, OEB → EPUB, AZW3, MOBI, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/AZW3/MOBI/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) |
-| **Drawings** | built in | **Visio VSDX, ODG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); **XPS, OpenXPS → PDF, SVG, PNG** with Filee's own XPS reader ([XPS reader](#xps-and-openxps-reader)); **Excel chart templates (CRTX) → PDF, SVG, PNG** with the [chart drawer](#charts); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route |
+| **Drawings** | built in | **Visio VSDX, ODG, OTG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); **XPS, OpenXPS → PDF, SVG, PNG** with Filee's own XPS reader ([XPS reader](#xps-and-openxps-reader)); **Excel chart templates (CRTX) → PDF, SVG, PNG** with the [chart drawer](#charts); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route |
+| **DjVu** | built in | **DjVu (.djvu, .djv; one page or bundled) → PDF** (the layers kept: background JPEG, 1-bit masks; the hidden text searchable) and **PNG, JPG, TIFF** pictures of the pages (#346; see [DjVu](#djvu)) |
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| G-code | built in | **G-code (3D printers, CNC machines) → PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, …: the toolpath from above or isometric, or the preview the slicer saved in the file |
| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KuGou KRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, TXT**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |
| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX → each of them; → PNG, JPG, … (an isometric preview) |
| Pictures to 3D relief | built in | **PNG, JPG, WEBP, … (every picture ImageMagick reads) → GLB, glTF, STL, OBJ, 3MF, PLY**: a relief, brighter areas higher |
| **Geospatial vector data** | built in | **GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV** (longitude / latitude or WKT); Garmin FIT (activities) and OpenStreetMap XML (`.osm`), both read only, → each of them and CSV; projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted to WGS 84; through CSV to XLSX, JSON, … (see below) |
-| **Filee renderer** | built in, on by default (Settings → Engines → *Use the Filee renderer*) | **HWPX, HWP, Word documents (DOCX and DOC), ODT, RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats), mind maps as outlines → PDF** with Filee's own layout engine; **PPTX, PPTM, POTX, POTM, PPSX, PPT ([PPT reader](#ppt-reader)), ODP, OTP, FODP ([ODP / ODG reader](#odp--odg-reader)) → PDF, PNG, JPG** with its slide renderer; files with what it doesn't draw yet take the HWPX writer and rhwp (see [Filee renderer: PDF output](#filee-renderer-pdf-output) and [slides](#filee-renderer-slides)) |
+| **Filee renderer** | built in, on by default (Settings → Engines → *Use the Filee renderer*) | **HWPX, HWP, Word documents (DOCX and DOC), ODT (+ OTT, FODT), RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats), mind maps as outlines → PDF** with Filee's own layout engine; **PPTX, PPTM, POTX, POTM, PPSX, PPT ([PPT reader](#ppt-reader)), ODP, OTP, FODP ([ODP / ODG reader](#odp--odg-reader)) → PDF, PNG, JPG** with its slide renderer; files with what it doesn't draw yet take the HWPX writer and rhwp (see [Filee renderer: PDF output](#filee-renderer-pdf-output) and [slides](#filee-renderer-slides)) |
| rhwp | bundled with the installer (`engines/rhwp`, with the Microsoft C++ runtime, see below) | HWP/HWPX → PDF when the Filee renderer is off or can't draw a file yet, **HWPX → HWP** (HWP → HWPX too, ranked below the built-in HWP reader) |
| Archives | built in (SharpCompress, DiscUtils, .NET and Filee's own readers and writers); 7-Zip optional (Settings → *Engines*, ~2 MB download) | **in-process**: ZIP (including ANSYS Workbench WBPZ and Adobe ZXP, and Windows app packages MSIX / APPX), Minecraft and Modrinth packs, Garry's Mod addons (GMA), Valve paks (VPK), the files packed into Source maps (BSP), 7Z (solid ones too), RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ/ZST), GZ, BZ2, XZ, LZMA, Z, ZST, lzip, CPIO, DEB, RPM, ISO (UDF discs too), IMG and DMG disk images, split (.001), ALZ, EGG, CAB, LHA, ARJ; **7-Zip, when installed**: the rare variants the in-process readers leave to it (see [Archives](#archives)) **→ folder, ZIP, 7Z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, BZ2, XZ, the packs, GMA** (in-process); "Compress into one archive" for any files |
-| LibreOffice | **optional download** (~370 MB, 1.1 GB on disk) | older and rare formats only: Word 6.0 / 95 and Works documents, PowerPoint 95 and older PPT, binary Visio (`.vsd`), and ODP / ODG with what Filee doesn't draw yet (charts, OLE objects, 3D) → PDF; XLS, PPT, RTF and OpenDocument to each other, output as DOCX/ODT/ODS, and ODP for what the [ODP writer](#odp-writer) doesn't take (OpenDocument presentations themselves, Keynote, decks with charts, effects or 3D); read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
-| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (LaTeX, AsciiDoc, Typst, man; and RTF / EPUB from the built-in ones) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT); their AST feeds the built-in PPTX writer (Pandoc's own slides only where Filee assumes a Pandoc that isn't installed) |
-| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PostScript-based AI → PDF (images through PDF and PDFium), EPS/PS → PNG; PDF → EPS/PS only when moved above the built-in PostScript writer; smaller PDFs when a preset asks for it; PDF/A-2b for PDF/A presets; renders CMYK PDF/AI pages for CMYK JPG/TIFF |
+| LibreOffice | **optional download** (~370 MB, 1.1 GB on disk) | older and rare formats only: Word 6.0 / 95 and Works documents, PowerPoint 95 and older PPT, binary Visio (`.vsd`), and ODP / ODG with what Filee doesn't draw yet (charts, OLE objects, 3D) → PDF; XLS, PPT, RTF and OpenDocument to each other, output as DOCX/ODT/ODS, and ODP for what the [ODP writer](#odp-writer) doesn't take (OpenDocument presentations themselves, Keynote, decks with charts, effects or 3D); read-only formats (see below) → PDF and their kind's editable formats; XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
+| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (LaTeX, AsciiDoc, Typst, man; and RTF / EPUB from the built-in ones) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT); their AST feeds the built-in PPTX writer (Pandoc's own slides only where Filee assumes a Pandoc that isn't installed) |
+| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PostScript-based AI → PDF (images through PDF and PDFium), EPS/PS → PNG; PDF → EPS/PS only when moved above the built-in PostScript writer; smaller PDFs when a preset asks for it; PDF/A-2b for what the built-in PDF/A writer refuses; renders CMYK PDF/AI pages for CMYK JPG/TIFF |
| Tesseract | **optional download** (~50 MB, 160 MB on disk; each language 0.4–10 MB when first used) | **text recognition (OCR)**: scans and pictures → searchable PDF, and their text into DOCX, TXT, Markdown and HWPX ("Recognize text" in the preset, see below) |
| Apple Vision | part of macOS (Mac only) | **text recognition (OCR) on a Mac**, the same step as Tesseract without a download; Tesseract reads the languages Vision doesn't (see "Apple Vision on macOS") |
| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF / APNG / WebP, a still frame or every frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF, APNG and photos → MP4/WEBM/MOV, Live / Motion Photos → their video, a clip of a video → an iPhone Live Photo or Android Motion Photo (experimental), images → HEIC, clips or audio files joined into one, pictures → a slideshow MP4, a video split into parts every so often or into equal parts (copied, not encoded), copies without metadata (see "Media tools") |
@@ -774,11 +777,15 @@ those shapes, which `Read` leaves out as before; it also takes an OLE object as
- **RTF** (`RtfReader.cs`, no Pandoc needed) as Word, WordPad, LibreOffice and 한글 write it: text in the code page
of its font (`\fcharset`, `\cpg`) or the document's (`\ansicpg`, so Korean, Chinese and Japanese RTF reads right)
and `\uN` characters; bold, italic, underline, strike-through, raised / lowered, size, font, colour and highlight;
- alignment, indents, spacing, line spacing and keep options; the style sheet (headings by `heading N` or
+ alignment, indents, spacing, line spacing, keep options and tab stops (`\tx` with their kind and leader, measured
+ from the indent as the model has them); the font table's other names (`{\*\falt …}`, used like Word's
+ `w:altName` where a font is not installed) and the default tab interval (`\deftab`, Word's 720 twips when the file
+ gives none, from the margin); the style sheet (headings by `heading N` or
`\outlinelevel`); lists from `\listtable` / `\listoverridetable`; tables (`\trowd` … `\row`, merged and shaded
cells, borders as a grid or none, nested tables flattened into their cell); PNG, JPEG, EMF and WMF pictures sized
- by `\picwgoal`; footnotes and endnotes; hyperlink, page and page count fields; bookmarks; headers and footers
- (first-page ones are left out); sections with their paper, margins, orientation and columns. Unknown `\*`
+ by `\picwgoal`; footnotes and endnotes (the space after a note's own number is dropped, as in the DOCX reader);
+ hyperlink, page and page count fields; bookmarks; headers and footers (`\header` / `\footer` for every page,
+ `\headerr` / `\headerl` for odd and even ones; first-page ones are left out); sections with their paper, margins, orientation and columns. Unknown `\*`
destinations, index entries, comments and object data are skipped; group depth, paragraphs and pictures count
against the reader limits.
- Markdown, HTML and Pandoc keep structure only, so page setup comes from the built-in template (A4).
@@ -1737,7 +1744,10 @@ specification, so ODT → DOCX / HWPX / PDF / Markdown / HTML and anything → O
text boxes, as characters or floating with position, relation, wrap, outer margins, border and padding; rectangles,
rounded rectangles, ellipses (also LibreOffice's custom shapes of those kinds) and lines, with fill and stroke;
shapes with text become text boxes; formulas (embedded Math objects) become their StarMath text;
-- footnotes and endnotes with their numbering (`text:notes-configuration`).
+- footnotes and endnotes with their numbering (`text:notes-configuration`);
+- default tab stops as LibreOffice sets them: every `style:tab-stop-distance` of the default paragraph style, else
+ LibreOffice's 1.25 cm, counted from the paragraph's indent unless `settings.xml` has `TabsRelativeToIndent` false
+ (documents that came from Word); the layout engine then puts a tab after the text at the next of them.
The package is read within DocumentLimits (see **Limits** under *HWPX reader*): `DocumentPackage` counts every part, SafeXml
reads the XML, `DocumentBudget` counts paragraphs, objects and nesting (tables, notes, frames, groups and lists);
@@ -1760,7 +1770,68 @@ so it wins over Pandoc and LibreOffice. ODT → PDF goes through the Filee rende
Not yet: numbering restarts in the middle of a list (only an item's start value on the first item counts), outline numbering
of headings (`text:outline-style`), different first-page headers with content, gradients (a gradient fills with its
start colour), rotated or cropped pictures, charts and other OLE objects, drop caps, change tracking, fields other
-than page number / count (their text is kept), flat ODT (`.fodt`) and templates (`.ott`, still LibreOffice's).
+than page number / count (their text is kept).
+
+Templates (`.ott`) and flat files (`.fodt`) are read by the same reader and written from its ODT, see
+[OpenDocument templates and flat files](#opendocument-templates-and-flat-files).
+
+## RTF writer
+
+`Hwp/Hwpx/RtfWriter*.cs` writes Rich Text Format from the document model, by hand from the RTF 1.9 specification, so
+anything Filee reads becomes an RTF file without LibreOffice or Pandoc. `RtfWriterConverter` (engine `rtf-writer`)
+offers every built-in reader's format → RTF at cost 8 (PDF at 14), like the DOCX and ODT writers, so it wins over
+Pandoc (Markdown and the markup languages → RTF) and LibreOffice (Word, ODT, HWP → RTF).
+
+- **The file:** `{\rtf1\ansi\ansicpg1252\deff0\uc1` with the font table (each font with its `\fcharset` and, where
+ one is known, its other name in `{\*\falt …}`: the document's own (DOCX `w:altName`), the Korean or English name
+ of a Korean font, a font of the same widths), the colour table, Normal and `heading 1`..`heading 9` with outline
+ levels, `\listtable` / `\listoverridetable`, `\info` (title, authors), the first section's page, `\deftab` (the
+ model's default tab interval, else 한글's 40 pt) and note numbering. The body is written first into a temporary
+ file beside the output (the tables fill as it is written), then the header and the body go into the output through
+ a temporary file of their own.
+- **Text:** ASCII only. Other characters are `\uN` (negative past 32767, surrogate pairs as two) followed by the
+ same character in the code page of its font's `\fcharset`, with `\ucN` saying how many bytes that is (two for
+ Korean in CP949), or `?` where the code page has none. Text is split where its script changes: Hangul, kana and
+ Chinese characters in the East Asian font with an East Asian `\fcharset` (which Word and Filee's reader take as
+ the East Asian font), Greek, Cyrillic, Hebrew, Arabic and Thai in the Latin font with their own `\fcharset`;
+ spaces and punctuation stay with the text around them. Arabic and Hebrew pieces are `\rtlch`.
+- **Paragraphs** repeat their style's formatting after `\pard\plain` (RTF paragraphs carry it themselves), then
+ alignment, indents (`\lin` / `\rin` too, for right-to-left paragraphs), spacing, line spacing (as the DOCX writer
+ converts it), keeps, widow control, page breaks, tab stops (measured from the margin), borders and shading, and the
+ list (`\ls`, `\ilvl`; continuation paragraphs indented to the item's text). Runs are groups with only the
+ control words that differ from the paragraph mark's formatting.
+- **Links, fields, notes:** HYPERLINK fields (`\l` for a bookmark), bookmarks, PAGE / NUMPAGES fields with a result,
+ footnotes and endnotes (`\footnote`, `\ftnalt`) after their reference mark; a note outside the body text and
+ its tables (in a header, note or text box) stays in place in brackets, as in the DOCX writer. Equations are their
+ text (TeX source or linear form).
+- **Tables:** `\trowd` with the row's padding, indent, alignment, height, header and keep, a cell definition per
+ grid column (`\clmgf` / `\clmrg` across columns, `\clvmgf` / `\clvmrg` down rows, vertical alignment, borders,
+ shading, padding, width, `\cellx` at its right edge), the cells' paragraphs (`\intbl`, each cell ending with
+ `\cell`) and `\row`. Tables in cells are nested tables (`\itapN`, `\nestcell`, `\nesttableprops` with
+ `\nestrow`). Column widths come from the model as in the DOCX writer, and the cell grid goes through
+ `HwpxWriter.PlaceCells` with its limits.
+- **Pictures:** `\pict` groups, PNG and JPEG as they are (`\pngblip`, `\jpegblip`), EMF as `\emfblip`, WMF as
+ `\wmetafile8` (without the placeable header), any other picture converted to PNG; sized by `\picwgoal` /
+ `\pichgoal`, in the text like a character. **Text boxes and shapes** are Word drawing objects (`\shp` with their
+ placement, wrap, fill and outline); a text box's paragraphs are in `\shptxt`, and its text in `\shprslt` too,
+ for programs (Filee's reader among them) that don't draw shapes.
+- **Sections:** `\sectd` with the paper, margins (the model's Top / Header become `\margtsxn` and `\headery`),
+ gutter, orientation, columns (own widths, separator, right to left), page number restarts, headers and footers
+ (`\header`, or `\headerr` / `\headerl` with facing pages; `\titlepg` with `\headerf` for a first page that
+ hides or has its own); columns that change in a section start a section without a page break (`\sbknone`).
+- **Limits:** the model is opened up past 32 levels of nesting (`Nesting.Limit`); a file that would pass
+ `DocumentLimits.MaxPackageBytes` (what the RTF reader takes), tables past the cell limit and font, colour or list
+ tables past `MaxObjects` are refused (`error.document_too_complex`) and leave no file; pictures past
+ `MaxPartBytes` or claiming more than `MaxPicturePixels` are left out before anything decodes them; cancelling stops
+ the write and removes its temporary files.
+- Tests: `RtfWriterTests` builds models in code, writes them and reads them back with the RTF reader into the same
+ model (`HDocumentAssert.Similar`), checks the file is valid RTF (one balanced `{\rtf1` group, ASCII only), the
+ Unicode fallbacks, the fonts and their other names, the routes, and the refusals.
+
+Not yet: floating pictures stay in the text (no `\shp` with a picture), picture crops and rotation, first-page
+headers' own content when the model has none (`\headerf` repeats the others), paragraph styles other than Normal
+and the headings, table and paragraph borders other than solid lines on all sides, comments and tracked changes.
+Checked by reading the files back with Filee's RTF reader, not with Word or LibreOffice.
## DOC reader
@@ -1909,7 +1980,7 @@ Checked against decks built from the specification, not against files PowerPoint
## ODP / ODG reader
-OpenDocument presentations (`.odp`, templates `.otp`, flat `.fodp`) and drawings (`.odg`, flat `.fodg`) are read
+OpenDocument presentations (`.odp`, templates `.otp`, flat `.fodp`) and drawings (`.odg`, templates `.otg`, flat `.fodg`) are read
in-process into the slide model, written from OpenDocument 1.3 Part 3 (`Odf/Draw`), without LibreOffice:
presentations to PDF, PNG and JPG through the [slide renderer](#filee-renderer-slides) (the Filee renderer,
`Slides/SlideFormats.cs`), drawings to PDF, SVG and PNG through the [drawing engine](#drawings-visio-odg).
@@ -2065,8 +2136,10 @@ same model, which the tests check shape by shape and as pictures.
columns and turned text (`draw:text-rotate-angle`).
- **Routes.** Its edges cost 8, as the PPTX writer's, below LibreOffice's fallback (25), and are `DirectOnly`. Deck
edges are checked with the renderer's capability check (charts without a picture, effects, 3D, WordArt, …), so such
- a deck keeps LibreOffice's route where it is installed. OpenDocument presentations (ODP, OTP, FODP) are not
- sources: ODP → PPTX and the template formats stay with LibreOffice.
+ a deck keeps LibreOffice's route where it is installed. Every source also goes to OTP and FODP: the writer
+ writes the ODP and turns it into the template or the flat file (`Odf/OdfVariants.cs`), since a `DirectOnly`
+ edge can't lead on. OpenDocument presentations (ODP, OTP, FODP) are not sources: they become each other through
+ the [forms engine](#opendocument-templates-and-flat-files), and ODP → PPTX stays with LibreOffice.
- **Hostile input:** the model comes from the bounded readers; the writer caps the XML it makes (512 million
characters), group nesting (`MaxNestingDepth`) and the pictures' bytes (`MaxPackageBytes`), refused with
`error.document_too_complex`; non-finite boxes and turns are left out, coordinates cut at ±10 km, characters XML
@@ -2077,7 +2150,7 @@ same model, which the tests check shape by shape and as pictures.
Not yet: shapes as placeholders (`presentation:class`; the model doesn't say which shapes were), the preset name and
adjust handles of a shape (its outline is written, not the formula), shadows and other effects, charts, SmartArt as
-anything but its drawing, animations and transitions, compound lines, ODG output, OTP and FODP output. Checked against
+anything but its drawing, animations and transitions, compound lines, ODG output. Checked against
Filee's own reader; not yet opened in LibreOffice by the tests.
## PDF reader
@@ -2612,20 +2685,111 @@ wrote it (PDFsharp, rhwp, LibreOffice, Ghostscript …), and once on a merged PD
## PDF/A
A preset with *PDF/A (archival)* ticked (`DocumentOptions.PdfA`; the built-in "PDF/A" preset, #1367) makes every PDF
-it writes a PDF/A-2b, PDF → PDF too. `JobQueue` runs `IPdfArchiver` (Ghostscript) after the finishing, on each PDF a
-file became and once on a merged PDF, so the box means the same whichever engine wrote the PDF.
-
-- **Already PDF/A**: LibreOffice (`SelectPdfVersion` 2) and SVG → PDF (Skia) write PDF/A themselves. A PDF whose
- catalog XMP has `pdfaid:part` is kept as it is, unless a watermark or page numbers were added since: then it is
- rewritten like any other.
-- **Ghostscript** (`GhostscriptConverter.ConvertToPdfAAsync`): `pdfwrite` with `-dPDFA=2 -dPDFACompatibilityPolicy=1
- -sColorConversionStrategy=RGB`, after a small PostScript prelude (as Ghostscript's `PDFA_def.ps`) that adds the sRGB
- output intent; the profile is Magick.NET's sRGB, written into the prelude as a hex string so safe mode needn't read
- a file. Colours become RGB, fonts are embedded, what PDF/A forbids is left out (policy 1), and a tagged PDF loses its
- tags (part B doesn't need them).
-- **Without Ghostscript**: a preset whose files are all PDFs is greyed out with the usual engine reason. Other files
- are converted and the PDF is left as it is, with `notice.pdfa_needs_ghostscript` in the result, unless LibreOffice
- made it PDF/A.
+it writes a PDF/A-2b, PDF → PDF too. `JobQueue` runs the `IPdfArchiver`s after the finishing, on each PDF a file
+became and once on a merged PDF, so the box means the same whichever engine wrote the PDF. They are tried in engine
+order (PDFsharp before Ghostscript by default): one that refuses a PDF (`ConversionRefusedException`) hands it to the
+next.
+
+- **Already PDF/A**: the Filee renderer (below), LibreOffice (`SelectPdfVersion` 2) and SVG → PDF (Skia) write PDF/A
+ themselves. A PDF whose catalog XMP has `pdfaid:part` is kept as it is, unless a watermark or page numbers were
+ added since: then it is rewritten like any other.
+- **Built in** (`PdfSharpConverter.ArchiveAsync` → `Pdf/PdfAConformance.cs`, `PdfAMetadata.cs`): the PDF is opened with
+ PDFsharp and changed in place to keep the PDF/A-2b rules (ISO 19005-2), form fields staying fields:
+ - one `GTS_PDFA1` output intent: a CMYK or RGB PDF/A intent the PDF already has for the device colours it draws in
+ (a PDF/X file keeps its CMYK profile), else **sRGB made in code** (`SrgbProfile`, below); PDFsharp's page
+ transparency groups get the intent's colour space;
+ - no encryption, no LZW (unpacked and deflated), no external stream data; graphics states lose `TR`, `TR2` (but
+ `/Default`), `HT`, `HTO`, unknown `RI` and blend modes; pictures lose `Alternates`, `OPI`, `Interpolate`; forms
+ lose `OPI`, `PS`, `Ref`;
+ - annotations: 3D, sound, screen, movie, rich media, file attachments and hidden ones go; the rest print and keep
+ only their normal appearance (a button's single stream becomes its one state, a state set outside buttons the
+ state shown); popups lose flags PDF/A forbids;
+ - JavaScript, launch and the other forbidden actions (also in `/Next` chains, open actions, outlines), every `AA`,
+ the actions of fields and widgets, XFA, `NeedAppearances`, embedded files, alternate presentations, `PresSteps`,
+ `Requirements`, `Collection`, other `Perms` than UR3/DocMDP, XMP of pages and pictures; optional-content
+ configurations get unique names, no `AS`, and an `Order` that lists every group; CIDFontType2 gets
+ `CIDToGIDMap /Identity` when it has none; PDF 2.0 is written as 1.7.
+
+ Saving: PDFsharp always replaces `/Metadata` with an XMP packet of its own (no `pdfaid`, dates that don't always
+ match) and puts its name in the producer, and it can't be told not to (`SetPdfA` claims PDF/A-1a). So the PDF is
+ saved by PDFsharp, then an **incremental update** (which PDF/A allows) writes the document information and the XMP
+ packet again under their own object numbers: `pdfaid:part 2`, `conformance B`, title, author, subject, keywords,
+ creator tool, producer and dates the same in both (text cleaned of what XML can't carry, so both always match),
+ the trailer's `/ID` kept, `/Prev` to PDFsharp's table. Custom information entries and `Trapped` are dropped.
+
+ It **refuses** (`pdfa.reason.*`, the PDF left as it is) a font drawn with that isn't embedded (any font listed in a
+ `/Resources` dictionary; a form's `/DR` doesn't count), device CMYK without a CMYK intent or CMYK and RGB together,
+ an annotation or field without its own appearance (but links, popups, zero-size ones), XFA-only forms, PostScript
+ XObjects, external stream data, LZW mixed with filters PDFsharp can't unpack, inline pictures with LZW or
+ interpolation, content streams it can't read, a password-protected PDF, and (`error.document_too_complex`) more
+ than `MaxObjects` objects or more content than `PdfFontUses` reads.
+
+ **Not checked**: that embedded fonts hold every glyph drawn and their widths match the dictionary, TrueType
+ symbolic/non-symbolic encodings and cmaps, the document's own ICC-based colour spaces, JPEG 2000 specifics, halftone
+ details beyond dropping `HT`, the implementation limits (string, name and number sizes, `q` nesting), page-level
+ colour spaces through `DefaultCMYK`, and content stream operators outside ISO 32000-1. Conformance is tested by a
+ structural check of the rules above (`tests/Filee.Engines.Tests/PdfA2bChecks.cs`); veraPDF isn't run.
+- **sRGB profile** (`Pdf/SrgbProfile.cs`): built from the numbers of IEC 61966-2-1 rather than shipped: primaries
+ and D65 adapted to D50 with the Bradford transform, the sRGB curve sampled at 1024 points shared by the three
+ channels, an ICC version 2.1 display profile of about 2.3 KB with the description "sRGB IEC61966-2.1" and the
+ copyright "No copyright, use freely". No one's profile file is copied, so there is no licence to carry; skcms
+ (Skia) reads it as sRGB's gamut and curve.
+- **Filee renderer** (`PdfPageWriter`, `PdfDocumentInfo.PdfA`): DOCX, HWP/HWPX, sheets, slides and drawings drawn by
+ the renderer are written as PDF/A-2b directly: Skia's PDF/A mode, then the PDFsharp pass with `PdfAConformance` and
+ `PdfAMetadata`, creator and producer "Filee". Fonts are already embedded and subset with ToUnicode maps, links get
+ the print flag. Should the pass refuse, the plain PDF is written and the job queue's archivers try again.
+- **Ghostscript** (`GhostscriptConverter.ConvertToPdfAAsync`), for what the built-in one refuses: `pdfwrite` with
+ `-dPDFA=2 -dPDFACompatibilityPolicy=1 -sColorConversionStrategy=RGB`, after a small PostScript prelude (as
+ Ghostscript's `PDFA_def.ps`) that adds the sRGB output intent; the profile is Magick.NET's sRGB, written into the
+ prelude as a hex string so safe mode needn't read a file. Colours become RGB, fonts are embedded, what PDF/A forbids
+ is left out (policy 1), form fields become page content, and a tagged PDF loses its tags (part B doesn't need them).
+- **When none makes it PDF/A**: the PDF is left as it is, with `notice.pdfa_needs_ghostscript` and the built-in one's
+ reason in brackets. A preset whose files are all PDFs is greyed out only when neither PDFsharp nor Ghostscript is
+ among the engines.
+
+## OpenDocument templates and flat files
+
+An OpenDocument type comes in three forms (OpenDocument 1.3 Part 2 and Part 3): the package (`.odt`, `.ods`, `.odp`,
+`.odg`), the template (`.ott`, `.ots`, `.otp`, `.otg`: the same package with the `-template` media type) and the flat
+XML file (`.fodt`, `.fods`, `.fodp`, `.fodg`: one `office:document` with meta, settings, scripts, font faces, styles,
+automatic styles, master styles and body, pictures as base64 `office:binary-data` and embedded objects as
+`office:document`s inside `draw:object`). `OdfVariantConverter` (engine `odf-variants`, cost 2) turns each form into
+the others of its type without LibreOffice and without reading the document into a model (`Odf/OdfVariants.cs`,
+`Odf/OdfFlat.cs`), so macros, settings, thumbnails and everything the readers don't know stay:
+
+- **Package ↔ template:** every part copied as it is through `DocumentPackage`, with the new media type in `mimetype`
+ (first, stored) and on the manifest's root entry.
+- **Package → flat file:** the parts put together; the automatic styles of `styles.xml` that have the name of one in
+ `content.xml` are renamed (with the references in its automatic and master styles) so both fit in one element; each
+ picture and OLE object an `xlink:href` names inside the package becomes `office:binary-data`, each object folder
+ (`Object 1/`, a chart) an `office:document` with the media type from the manifest.
+- **Flat file → package:** the reverse: `content.xml`, `styles.xml` (both with the automatic styles and font faces),
+ `meta.xml`, `settings.xml`, a part under `Pictures/` per picture (one for a picture stored more than once, named by
+ its signature: PNG, JPEG, GIF, BMP, TIFF, WebP, EMF, WMF, SVG), an `Object N/` folder per embedded document, and the
+ manifest. Pictures that aren't base64 are left out, as the readers leave them out.
+
+The readers read every form: the ODT reader takes `.ott`, the spreadsheet reader `.ots`, the ODP / ODG reader the
+templates and flat files itself; a `.fodt` or `.fods` is read as the package it splits into, in a temporary file
+(`OdfVariants.AsPackage`), so FODT / OTT go to PDF through the Filee renderer, to DOCX, HWPX, PPTX, ODP and tables
+through the writers, and FODS / OTS to PDF through sheet printing and to XLSX / CSV / TSV. The renderer and sheet
+printing check a flat file as that package. Out: DOCX → ODT (ODT writer) → OTT / FODT, XLSX → ODS (spreadsheet engine)
+→ OTS / FODS; the ODP writer writes OTP and FODP itself. All of it costs far less than LibreOffice's fallback, whose
+FODT and template edges stay for the formats only it reads.
+
+- **Hostile input:** a flat file is read through `SafeXml` within `DocumentLimits`' XML depth and element counts and
+ at most four times what a package part may hold (256 MB, as the ODP / ODG reader reads one); a picture decodes to at
+ most a part (64 MB), all pictures to at most the package size, in at most as many parts as a package may have,
+ objects at most `MaxObjects` and eight deep. A package is read through `DocumentPackage` (part, package and inflate
+ limits); the flat file made from it may hold at most what a flat file may be read with, so a picture used again and
+ again can't make it grow without end. Each refusal is `error.document_too_complex`; another type's media type,
+ damaged XML and encrypted packages are refused with their reason.
+- Tests: `OdfVariantTests` (packages built in code by `OdtBuilder` / `OdpBuilder` / the ODS writer: round trips with
+ text, pictures, styles and a chart object, the readers, routes, DOCX and PPTX conversions, hostile flat files and
+ packages) and `OdfVariantFuzzTests` (mutated flat texts and spreadsheets, mutated packages turned flat).
+
+Not yet: a flat file's `office:binary-data` in elements other than pictures, fill images, background images, list
+images and OLE objects is dropped; a flat file is read as its document even when it says it is a template. Checked
+against Filee's own readers; not yet opened in LibreOffice by the tests.
## Office Open XML variants
@@ -2857,7 +3021,7 @@ its reader, one line in `Drawings/DrawingFormats.cs`:
rows, groups, connectors (the geometry they carry) and pictures (Foreign shapes: PNG, JPEG, GIF, BMP, TIFF, EMF,
WMF). Cells, geometry and text are inherited from master shapes and style sheets; colours by index come from the
document's colour table, fonts from its face names. Only stored values (`V`) are read; formulas aren't calculated.
-- **ODG and FODG** (OpenDocument drawings, packaged and flat): the [ODP / ODG reader](#odp--odg-reader).
+- **ODG, OTG and FODG** (OpenDocument drawings, packaged, templates and flat): the [ODP / ODG reader](#odp--odg-reader).
- **XPS and OpenXPS** (`.xps`, `.oxps`, format id `xps`): not slides; the [XPS reader](#xps-and-openxps-reader) draws
its pages straight into the page model (`DrawingFormat.ReadPages`, `IFixedPages`).
- **Excel chart templates** (`.crtx`, format id `crtx`, #1354): `ChartTemplate`, one page of Excel's default chart size
@@ -3933,9 +4097,8 @@ all expected bytes have been written; failures and cancellation preserve any pre
- Each parallel worker gets its own profile under `%APPDATA%\Filee\libreoffice-profiles` (LibreOffice silently
fails when two conversions share a profile).
- LibreOffice doesn't open HWP or HWPX: Filee reads them itself ([HWP reader](#hwp-reader), [HWPX
- reader](#hwpx-reader)) and writes DOCX, ODT, HWPX, TXT, Markdown, HTML and EPUB with its own writers; PDF is the
- Filee renderer's (rhwp's with it off). Only HWP → RTF still takes an optional engine, as there is no built-in RTF writer: Filee
- writes Markdown that Pandoc turns into RTF, or, without Pandoc, DOCX or ODT that LibreOffice does. Until settings
+ reader](#hwpx-reader)) and writes DOCX, ODT, RTF, HWPX, TXT, Markdown, HTML and EPUB with its own writers; PDF is the
+ Filee renderer's (rhwp's with it off), and RTF with the [RTF writer](#rtf-writer). Until settings
schema 101 LibreOffice opened HWP with the H2Orestart extension (GPL, Java) and a Java runtime downloaded with it
(about 50 MB, 130 MB on disk); Filee removes the copies an earlier version installed (`EngineInstaller.RemoveRetired`,
at start-up), and whoever had *Use LibreOffice for HWP·HWPX → PDF* on gets the Filee renderer instead.
@@ -3959,19 +4122,19 @@ all expected bytes have been written; failures and cancellation preserve any pre
- It is the only reader of rarer formats, converted to PDF and to the editable formats of their kind: Word 6.0 / 95
and Microsoft Works documents (a `.doc`, `.dot` or `.wps` the [DOC reader](#doc-reader) names as such), WordPerfect,
Lotus Word Pro, AbiWord, Apple Pages, StarWriter, ClarisWorks / AppleWorks (`.cwk`), MacWrite (`.mcw`), T602
- (`.602`) and Pocket Word (`.psw`) (→ DOCX, ODT, FODT, OTT, DOC, RTF, TXT, HTML); WPS Spreadsheets (ET), Apple Numbers, StarCalc and flat ODS (`.fods`) (→ XLSX, ODS, OTS, XLS, XLT, CSV, HTML); XLSB too, where the built-in reader has no route (→ XLS, XLT, OTS) and for a workbook with what the print engine doesn't draw; Apple
+ (`.602`) and Pocket Word (`.psw`) (→ DOCX, ODT, DOC, RTF, TXT, HTML, and on to OTT and FODT); WPS Spreadsheets (ET), Apple Numbers and StarCalc (→ XLSX, ODS, XLS, XLT, CSV, HTML, and on to OTS and FODS); XLSB too, where the built-in reader has no route (→ XLS, XLT) and for a workbook with what the print engine doesn't draw; Apple
Keynote, WPS Presentation (DPS), StarImpress / StarDraw and PowerPoint 95 and older PPT (→ PPTX, ODP, OTP, PPT);
- Publisher, CorelDRAW, binary Visio (`.vsd`) and CGM (→ ODG, SVG, PNG, EMF, WMF). VSDX, ODP, FODP, ODG and FODG
- are read by Filee itself ([Drawings](#drawings-visio-odg), [ODP / ODG reader](#odp--odg-reader)); LibreOffice keeps
+ Publisher, CorelDRAW, binary Visio (`.vsd`) and CGM (→ ODG, SVG, PNG, EMF, WMF). VSDX, ODP, OTP, FODP, ODG, OTG and FODG
+ are read by Filee itself (FODT, OTT, FODS and OTS too, by the text and spreadsheet readers) ([Drawings](#drawings-visio-odg), [ODP / ODG reader](#odp--odg-reader)); LibreOffice keeps
them when their check names what Filee doesn't draw yet (charts, OLE objects, 3D), and converts them to the editable
formats (ODP → PPTX, ODG → EMF, …). The `--convert-to`
filter follows the application that opens the file (checked against LibreOffice's filter registry): Publisher,
CorelDRAW and Visio open in Draw, CGM in Impress, and "SDA" files in Draw (.sda) or Impress (.sdd). ClarisWorks
files can also be spreadsheets or drawings; Filee treats them as text documents, the common case. SVG, PNG, EMF
and WMF export the first page.
-- Written only by LibreOffice: FODT (`OpenDocument Text Flat XML`), the OpenDocument templates OTT / OTS / OTP
- (`writer8_template`, `calc8_template`, `impress8_template`) and XLT (`MS Excel 97 Vorlage/Template`). XLT is read
- by the built-in spreadsheet engine like XLS.
+- Written only by LibreOffice: XLT (`MS Excel 97 Vorlage/Template`), read by the built-in spreadsheet engine like
+ XLS. Its FODT and template filters (`OpenDocument Text Flat XML`, `writer8_template`, `calc8_template`,
+ `impress8_template`) stay as edges, but the [forms engine](#opendocument-templates-and-flat-files) costs less.
- SVG opens in Draw only for EMF, WMF and ODG; the vector engine keeps SVG → PDF and images. PDF opens in Draw
(`draw_pdf_import`) only for SVG and ODG: Draw's SVG export draws every page of a PDF on top of each other, so Filee
first copies the first page of the preset's page range into a PDF of its own (PDFsharp). EPS and PS reach SVG
@@ -4238,11 +4401,44 @@ SRT or SAMI file in CP949 comes out as UTF-8).
## DjVu
-Not supported: DjVuLibre (GPL) has no pinned, redistributable Windows build in an archive the installer can unpack.
-The official Windows release is an NSIS installer (`DjVuLibre-3.5.29_DjView-4.12_Setup.exe` on SourceForge), which
-would have to be run (a system install) or unpacked with 7-Zip; MSYS2's packages are `.pkg.tar.zst` archives with
-five dependency packages. A DjVu engine needs a zip of `ddjvu.exe` / `djvutxt.exe` and their DLLs published for
-Filee (with the GPL source offer), then an `engines.json` component and an optional package.
+Built in (#346), in `Djvu/`, written from the DjVu v3 specification (engine id `djvu`, format id `djvu` for `.djvu`
+and `.djv`, documents donut). `DjvuConverter` turns a DjVu document into **PDF** (every page) and into **PNG, JPG and
+TIFF** pictures of its pages (the PDF options' page range, each page at its own resolution, then the image options;
+TIFF holds every page in one file). Other targets (DOCX, TXT, …) go on from the PDF.
+
+- **Container:** IFF85 (`AT&T`, then a FORM chunk). One page (`FORM:DJVU`) or a bundled document (`FORM:DJVM`): the
+ `DIRM` directory (versions 0 and 1, its BZZ tables of sizes, flags and names) gives the components at their offsets
+ — pages, included files (`FORM:DJVI`) and thumbnails (skipped). An **indirect** document (pages in separate files)
+ is refused with `error.djvu_indirect`, which says to bundle it in a DjVu viewer first. A file cut short keeps the
+ chunks it still holds.
+- **Page:** `INFO` (size, resolution 25–6000 dpi, else 300; rotation → the PDF page's `/Rotate`, the picture turned),
+ `INCL` (followed depth first, each file once, so include loops end), the mask `Sjbz` with its shared dictionary
+ `Djbz` (in the page or an included file; a dictionary may build on another; decoded once per file and kept for the
+ next pages), the background `BG44` (or `BGjp`), foreground colours `FG44` (or `FGjp`) or the palette `FGbz`
+ (colours and a colour per shape), hidden text `TXTz` / `TXTa`.
+- **Decoders:** the ZP-coder (the specification's probability table), BZZ (block sort transform, move-to-front with
+ the specification's rank estimator), JB2 (all record types: new shapes coded directly, refinements against library
+ shapes, copies, non-mark data, comments, dictionary requests and number-coder resets) and IW44 (luminance and
+ chrominance maps of 32 × 32 blocks, all bands and slices over several chunks, chrominance at half resolution or
+ starting late, the backward lifting transform, the YCbCr transform; grey pictures).
+- **Composition:** the background scaled up to the page (bilinear, by the reduction its size gives), then each mask
+ pixel in its foreground colour (the FG44 picture, the shape's palette colour, or black); white without a background.
+- **PDF:** the layers stay layers (`DjvuPdfWriter`), so a scanned book stays small: the background as a JPEG at its
+ own resolution, the mask as 1-bit image masks (Flate) painted in their colour — one per palette colour, or the FG44
+ picture shown through the mask (explicit masking). A page with more than 64 palette colours is one JPEG. The hidden
+ text's lines and words become an invisible text layer (the OCR layer's glyphless font, `Ocr/OcrTextLayer.cs`), so
+ the PDF can be searched and its text copied in any script.
+- **Limits** (`DjvuLimits`, refusals with `error.document_too_complex`): 20,000 pages and 40,000 components; 64 MB per
+ chunk and per BZZ stream; 150 million pixels per page; 64 million pixels per IW44 picture and 10,000 slices;
+ 2 million shapes, 4 million placed shapes and 400 million shape pixels per mask (counted before a shape is
+ allocated); 20 million number-coder cells; 2 million text zones; 65,535 palette colours. Decoding is iterative (no
+ recursion over files or zones) and checks cancellation.
+- **Left out:** `Smmr` masks (G4), JPEG 2000 layers (`BG2k`, `FG2k`) and JPEG layers Skia can't decode are counted as
+ pictures left out in the file's result. Not read: annotations (`ANTa`/`ANTz`: hyperlinks, highlights, background
+ colour), bookmarks (`NAVM`), thumbnails, standalone IW44 files (`FORM:PM44`/`BM44`), and hidden text of a page with
+ no zones below the page.
+- Tests (`DjvuTests.cs`, `DjvuFuzzTests.cs`) build every file in code: `DjvuBuilder.cs` has encoders for each piece
+ (ZP-coder, BZZ, JB2, IW44 with the forward transform, text zones, palettes, the bundled directory).
## FFmpeg
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 111ab5f92..2ad6de781 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "الملف داخل ملف .p7m هذا من نوع لا يحوّله Filee",
"error.udf_not_uyap": "ملف .udf هذا ليس مستند UYAP. إذا كان صورة قرص (Universal Disk Format)، فافتحه باستخدام «استخراج»",
"error.chart_template_unsupported": "لا يرسم Filee هذا النوع من المخططات بعد (راداري، فقاعي، أسهم، سطحي، شريط من دائري، أو نوع أحدث مثل الشلال أو الخريطة الشجرية)",
+ "error.djvu_indirect": "هذا مستند DjVu غير مباشر: صفحاته ملفات منفصلة. اجمعه في ملف واحد باستخدام عارض DjVu (مثل DjView: الحفظ كملف مجمّع)، ثم حوّل ذلك الملف",
"error.p7m_too_large": "الملف الموقّع أكبر من أن يُفتح",
"error.document_too_large": "يتوسّع هذا المستند إلى بيانات أكثر من اللازم أو أنه متداخل بعمق شديد بحيث لا يمكن فتحه بأمان",
"format_request.request": "طلب دعم هذه الصيغة",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "هذا الملف بنظام CMYK لكنه حُفظ بنظام RGB: ثبّت Ghostscript من الإعدادات ← المحركات للإبقاء على CMYK",
"notice.pdfa_needs_ghostscript": "هذا الملف ليس PDF/A: ثبّت Ghostscript من الإعدادات ← المحركات لإنشاء PDF/A",
"notice.pdfa_form_fields": "تم إنشاء PDF/A: لم يعد بالإمكان تعبئة حقول النموذج",
+ "pdfa.reason.font_not_embedded": "خط مستخدم غير مضمّن",
+ "pdfa.reason.cmyk": "يجب تحويل ألوان CMYK فيه",
+ "pdfa.reason.no_appearance": "تعليق توضيحي أو حقل نموذج بلا مظهر خاص به",
+ "pdfa.reason.unsupported": "فيه محتوى لا يسمح به PDF/A ولا يستطيع Filee إزالته",
+ "pdfa.reason.unreadable": "تعذّر على Filee قراءته",
+ "pdfa.reason.locked": "محمي بكلمة مرور",
"notice.cmyk_render_failed": "هذا الملف بنظام CMYK، لكن Ghostscript لم يتمكن من رسمه، لذلك حُفظ بنظام RGB",
"notice.original_kept": "تم الاحتفاظ بالأصل وحُفظت النتيجة كنسخة",
"notice.original_in_trash": "الأصل في سلة المحذوفات، واحتفظت النتيجة باسمها",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "إنشاء مستندات Word (DOCX) من PDF وOFD وHWP/HWPX وMarkdown وHTML وجداول البيانات والعروض والكتب الإلكترونية.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "إنشاء مستندات نصية OpenDocument (ODT) من مستندات Word وPDF وOFD وHWP/HWPX وMarkdown وHTML وجداول البيانات والعروض والكتب الإلكترونية.",
+ "engine.rtf-writer.name": "كاتب RTF (مدمج)",
+ "engine.rtf-writer.description": "إنشاء ملفات نص منسق (RTF، لبرنامجَي Word وWordPad) من مستندات Word وODT وPDF وOFD وHWP/HWPX وMarkdown وHTML وجداول البيانات والعروض والكتب الإلكترونية.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "دفاتر Jupyter وOPML وTextile وMediaWiki وreStructuredText وOrg وDocBook دون Pandoc.\nتحويل المستندات إلى هذه الصيغ، وتحويلها إلى Markdown وHTML ونص وDOCX وHWPX وPDF.\nوأيضًا خرائط FreeMind / Freeplane وXMind الذهنية، تُقرأ كمخططات تفصيلية.",
"engine.pptx-writer.name": "كاتب PPTX (مدمج)",
"engine.pptx-writer.description": "ينشئ شرائح PowerPoint (PPTX) من ملفات Markdown ولغات الترميز ومستندات Word وODT وHWP/HWPX وHTML وجداول البيانات والكتب الإلكترونية: شريحة لكل عنوان، مع القوائم والجداول والصور والتعليمات البرمجية.",
"engine.odp-writer.name": "كاتب ODP (مدمج)",
"engine.odp-writer.description": "ينشئ عروض OpenDocument التقديمية (ODP) دون LibreOffice: شرائح PowerPoint (PPTX وPPT) مع أشكالها وصورها وجداولها وملاحظات المتحدث، وملفات Markdown ولغات الترميز ومستندات Word وODT وHWP/HWPX وHTML وجداول البيانات والكتب الإلكترونية بشريحة لكل عنوان.",
+ "engine.odf-variants.name": "قوالب OpenDocument وملفات XML المسطحة (مدمج)",
+ "engine.odf-variants.description": "يحوّل ملفات OpenDocument إلى قوالبها (OTT وOTS وOTP وOTG) وملفات XML المسطحة (FODT وFODS وFODP وFODG) والعكس دون LibreOffice، مع الحفاظ على المستند كاملًا.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "استخراج نصوص PDF بترتيب القراءة، بما في ذلك الصفحات ذات العمودين (دون تعرّف ضوئي OCR للمستندات الممسوحة).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "مسارات الطابعات ثلاثية الأبعاد وآلات CNC (G-code) إلى PDF وSVG وصور، أو معاينة برنامج التقطيع.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "تحويل رسومات Visio (VSDX) ورسومات OpenDocument (ODG وFODG) إلى PDF وSVG وPNG دون Visio أو LibreOffice.\nوكذلك مستندات XPS وOpenXPS (.xps و.oxps).\nوكذلك قوالب مخططات Excel (.crtx).\nلا تزال ملفات Visio الثنائية القديمة (.vsd) تحتاج إلى LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "كتب ومستندات DjVu الممسوحة ضوئيًا (.djvu، .djv) إلى PDF مع إمكانية البحث في نصها المخفي، وإلى صور PNG وJPG وTIFF للصفحات.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "التحويل بين النماذج ثلاثية الأبعاد: GLB وglTF وSTL وOBJ و3MF وPLY، وتحويل FBX إلى أي منها، وإنشاء معاينة PNG.",
"engine.image3d.name": "صور إلى نقش بارز ثلاثي الأبعاد (مدمج)",
diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json
index 11ea3129b..0985adb2c 100644
--- a/src/Filee.App/Assets/i18n/bn-BD.json
+++ b/src/Filee.App/Assets/i18n/bn-BD.json
@@ -126,6 +126,7 @@
"error.p7m_unknown_content": "এই .p7m-এর ভেতরের ফাইলটি এমন ধরনের যা ফাইলি রূপান্তর করে না",
"error.udf_not_uyap": "এই .udf ফাইলটি UYAP ডকুমেন্ট নয়। এটি ডিস্ক ইমেজ (Universal Disk Format) হলে «নিষ্কাশন করুন» দিয়ে খুলুন",
"error.chart_template_unsupported": "Filee এখনও এই ধরনের চার্ট আঁকে না (রাডার, বাবল, স্টক, সারফেস, পাই-এর বার, বা ওয়াটারফল বা ট্রিম্যাপের মতো নতুন ধরন)",
+ "error.djvu_indirect": "এটি একটি পরোক্ষ DjVu নথি: এর পাতাগুলো আলাদা ফাইল। একটি DjVu ভিউয়ারে এটিকে এক ফাইলে জুড়ে নিন (যেমন DjView: বান্ডেল হিসেবে সংরক্ষণ), তারপর সেই ফাইলটি রূপান্তর করুন",
"error.p7m_too_large": "স্বাক্ষরিত ফাইলটি খোলার জন্য অতিরিক্ত বড়",
"error.document_too_large": "এই নথিটি খুললে অতিরিক্ত ডেটা তৈরি হয় বা এটি অতিরিক্ত গভীরভাবে নেস্ট করা, তাই নিরাপদে খোলা যাচ্ছে না",
"format_request.request": "এই ফরম্যাটের অনুরোধ করুন",
@@ -217,6 +218,12 @@
"notice.cmyk_needs_ghostscript": "এই ফাইলটি CMYK হলেও RGB হিসেবে সংরক্ষণ করা হয়েছে: CMYK রাখতে সেটিংস → ইঞ্জিন-এ Ghostscript ইনস্টল করুন",
"notice.pdfa_needs_ghostscript": "এই পিডিএফটি PDF/A নয়: PDF/A বানাতে সেটিংস → ইঞ্জিন-এ Ghostscript ইনস্টল করুন",
"notice.pdfa_form_fields": "PDF/A তৈরি হয়েছে: ফর্মের ঘরগুলো আর পূরণ করা যাবে না",
+ "pdfa.reason.font_not_embedded": "ব্যবহৃত একটি ফন্ট এমবেড করা নেই",
+ "pdfa.reason.cmyk": "এর CMYK রং রূপান্তর করতে হবে",
+ "pdfa.reason.no_appearance": "কোনো টীকা বা ফর্ম ফিল্ডের নিজস্ব চেহারা নেই",
+ "pdfa.reason.unsupported": "এতে এমন বিষয়বস্তু আছে যা PDF/A অনুমতি দেয় না এবং Filee সরাতে পারে না",
+ "pdfa.reason.unreadable": "Filee এটি পড়তে পারেনি",
+ "pdfa.reason.locked": "এটি পাসওয়ার্ড দিয়ে লক করা",
"notice.cmyk_render_failed": "এই ফাইলটি CMYK, কিন্তু Ghostscript এটি আঁকতে পারেনি, তাই RGB হিসেবে সংরক্ষণ করা হয়েছে",
"notice.original_kept": "মূল ফাইলটি রাখা হয়েছে, ফলাফলটি একটি কপি হিসেবে সংরক্ষণ করা হয়েছে",
"notice.original_in_trash": "মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে রয়েছে, ফলাফলটি নিজস্ব নাম বজায় রেখেছে",
@@ -301,12 +308,16 @@
"engine.docx-writer.description": "পিডিএফ, OFD, HWP/HWPX, মার্কডাউন , এইচটিএমএল, স্প্রেডশিট, স্লাইড এবং ই-বুক থেকে ওয়ার্ড ডকুমেন্ট (DOCX) তৈরি করে।",
"engine.odt-writer.name": "ODT রাইটার (বিল্ট-ইন)",
"engine.odt-writer.description": "ওয়ার্ড ডকুমেন্ট, পিডিএফ, OFD, HWP/HWPX, মার্কডাউন, এইচটিএমএল, স্প্রেডশিট, স্লাইড এবং ই-বুক থেকে OpenDocument টেক্সট (ODT, LibreOffice Writer) তৈরি করে।",
+ "engine.rtf-writer.name": "RTF রাইটার (বিল্ট-ইন)",
+ "engine.rtf-writer.description": "ওয়ার্ড ডকুমেন্ট, ODT, পিডিএফ, OFD, HWP/HWPX, মার্কডাউন, এইচটিএমএল, স্প্রেডশিট, স্লাইড এবং ই-বুক থেকে রিচ টেক্সট ফরম্যাট (RTF, Word ও WordPad-এর জন্য) তৈরি করে।",
"engine.markup.name": "মার্কআপ ভাষা (বিল্ট-ইন)",
"engine.markup.description": "Pandoc ছাড়াই Jupyter নোটবুক, OPML, Textile, MediaWiki, reStructuredText, Org এবং DocBook।\nডকুমেন্ট থেকে এই ফরম্যাটগুলোতে, এবং এগুলো থেকে মার্কডাউন, এইচটিএমএল, টেক্সট, DOCX, HWPX ও পিডিএফ-এ।\nএছাড়া FreeMind / Freeplane ও XMind মাইন্ড ম্যাপ, আউটলাইন হিসেবে পড়া হয়।",
"engine.pptx-writer.name": "PPTX রাইটার (বিল্ট-ইন)",
"engine.pptx-writer.description": "মার্কডাউন ও মার্কআপ ফাইল, ওয়ার্ড ডকুমেন্ট, ODT, HWP/HWPX, এইচটিএমএল, স্প্রেডশিট এবং ই-বুক থেকে পাওয়ারপয়েন্ট স্লাইড (PPTX) তৈরি করে: প্রতিটি শিরোনামের জন্য একটি স্লাইড, তালিকা, সারণি, ছবি ও কোডসহ।",
"engine.odp-writer.name": "ODP রাইটার (বিল্ট-ইন)",
"engine.odp-writer.description": "লিব্রেঅফিস ছাড়াই ওপেনডকুমেন্ট উপস্থাপনা (ODP) তৈরি করে: পাওয়ারপয়েন্ট স্লাইড (PPTX, PPT) তাদের আকৃতি, ছবি, সারণি ও বক্তার নোটসহ, এবং মার্কডাউন ও মার্কআপ ফাইল, ওয়ার্ড ডকুমেন্ট, ODT, HWP/HWPX, এইচটিএমএল, স্প্রেডশিট ও ই-বুক থেকে প্রতিটি শিরোনামের জন্য একটি স্লাইড।",
+ "engine.odf-variants.name": "ওপেনডকুমেন্ট টেমপ্লেট ও ফ্ল্যাট XML ফাইল (বিল্ট-ইন)",
+ "engine.odf-variants.description": "লিব্রেঅফিস ছাড়াই ওপেনডকুমেন্ট ফাইলকে তার টেমপ্লেট (OTT, OTS, OTP, OTG) ও ফ্ল্যাট XML ফাইলে (FODT, FODS, FODP, FODG) এবং আবার আগের রূপে বদলায়, পুরো ডকুমেন্ট অক্ষত রেখে।",
"engine.pdf-text.name": "পিডিএফ টেক্সট (বিল্ট-ইন)",
"engine.pdf-text.description": "পড়ার ক্রম অনুযায়ী পিডিএফ-এর টেক্সট নিষ্কাশন করে, দুই কলামের পৃষ্ঠা থেকেও (স্ক্যান করা ফাইলের জন্য OCR নয়)।",
"engine.pdf-slides.name": "পিডিএফ স্লাইড (বিল্ট-ইন)",
@@ -335,6 +346,8 @@
"engine.gcode.description": "3D প্রিন্টার ও CNC মেশিনের টুলপাথ (G-code) PDF, SVG ও ছবিতে, অথবা স্লাইসারের নিজের প্রিভিউ।",
"engine.drawing.name": "ড্রয়িং (বিল্ট-ইন)",
"engine.drawing.description": "Visio ড্রয়িং (VSDX) ও OpenDocument ড্রয়িং (ODG, FODG) থেকে পিডিএফ, SVG ও PNG, Visio বা LibreOffice ছাড়াই।\nXPS ও OpenXPS ডকুমেন্টও (.xps, .oxps)।\nExcel চার্ট টেমপ্লেটও (.crtx)।\nপুরোনো বাইনারি Visio ফাইলের (.vsd) জন্য এখনও LibreOffice লাগে।",
+ "engine.djvu.name": "DjVu (বিল্ট-ইন)",
+ "engine.djvu.description": "DjVu স্ক্যান করা বই ও নথি (.djvu, .djv) লুকানো লেখা খোঁজা যায় এমন PDF-এ, এবং পাতার PNG, JPG ও TIFF ছবিতে।",
"engine.model3d.name": "3D মডেল (বিল্ট-ইন)",
"engine.model3d.description": "3D মডেল: GLB, glTF, STL, OBJ, 3MF এবং PLY একে অপরে রূপান্তর, যেকোনোটিতে FBX রূপান্তর এবং একটি PNG প্রিভিউ।",
"engine.image3d.name": "ছবি থেকে 3D রিলিফ (বিল্ট-ইন)",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index 31d8f9826..055e2fd3a 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "Die Datei in dieser .p7m hat ein Format, das Filee nicht konvertiert",
"error.udf_not_uyap": "Diese .udf-Datei ist kein UYAP-Dokument. Ist sie ein Disk-Image (Universal Disk Format), öffnen Sie sie mit „Entpacken“",
"error.chart_template_unsupported": "Diese Diagrammart zeichnet Filee noch nicht (Netz, Blase, Kurs, Oberfläche, Balken aus Kreis oder ein neuerer Typ wie Wasserfall oder Treemap)",
+ "error.djvu_indirect": "Dies ist ein indirektes DjVu-Dokument: Seine Seiten sind einzelne Dateien. Fassen Sie es in einem DjVu-Viewer zu einer Datei zusammen (z. B. DjView: als gebündelt speichern) und konvertieren Sie dann diese Datei",
"error.p7m_too_large": "Die signierte Datei ist zu groß zum Öffnen",
"error.document_too_large": "Dieses Dokument entpackt sich zu zu vielen Daten oder ist zu tief verschachtelt, um es sicher zu öffnen",
"format_request.request": "Dieses Format vorschlagen",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "Diese Datei ist CMYK, wurde aber als RGB gespeichert: Installiere Ghostscript unter Einstellungen → Module, um CMYK zu behalten",
"notice.pdfa_needs_ghostscript": "Diese PDF ist kein PDF/A: Installiere Ghostscript unter Einstellungen → Module, um PDF/A zu erstellen",
"notice.pdfa_form_fields": "PDF/A erstellt: Die Formularfelder können nicht mehr ausgefüllt werden",
+ "pdfa.reason.font_not_embedded": "eine verwendete Schrift ist nicht eingebettet",
+ "pdfa.reason.cmyk": "die CMYK-Farben müssten umgewandelt werden",
+ "pdfa.reason.no_appearance": "eine Anmerkung oder ein Formularfeld hat kein eigenes Aussehen",
+ "pdfa.reason.unsupported": "sie enthält Inhalte, die PDF/A nicht erlaubt und die Filee nicht entfernen kann",
+ "pdfa.reason.unreadable": "Filee konnte sie nicht lesen",
+ "pdfa.reason.locked": "sie ist mit einem Passwort geschützt",
"notice.cmyk_render_failed": "Diese Datei ist CMYK, aber Ghostscript konnte sie nicht zeichnen, daher wurde sie als RGB gespeichert",
"notice.original_kept": "Das Original wurde beibehalten und das Ergebnis als Kopie gespeichert",
"notice.original_in_trash": "Das Original liegt im Papierkorb. Das Ergebnis hat seinen eigenen Namen behalten",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "Erstellt Word-Dokumente (DOCX) aus PDF, OFD, HWP/HWPX, Markdown, HTML, Tabellen, Folien und E-Books.",
"engine.odt-writer.name": "ODT-Writer (integriert)",
"engine.odt-writer.description": "Erstellt OpenDocument-Textdokumente (ODT) aus Word-Dokumenten, PDF, OFD, HWP/HWPX, Markdown, HTML, Tabellen, Folien und E-Books.",
+ "engine.rtf-writer.name": "RTF-Writer (integriert)",
+ "engine.rtf-writer.description": "Erstellt Rich-Text-Dateien (RTF, für Word und WordPad) aus Word-Dokumenten, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, Tabellen, Folien und E-Books.",
"engine.markup.name": "Auszeichnungssprachen (integriert)",
"engine.markup.description": "Jupyter-Notebooks, OPML, Textile, MediaWiki, reStructuredText, Org und DocBook ohne Pandoc.\nDokumente in diese Formate und diese in Markdown, HTML, Text, DOCX, HWPX und PDF.\nAußerdem Mindmaps aus FreeMind / Freeplane und XMind, als Gliederung gelesen.",
"engine.pptx-writer.name": "PPTX-Writer (integriert)",
"engine.pptx-writer.description": "Erstellt PowerPoint-Folien (PPTX) aus Markdown- und Markup-Dateien, Word-Dokumenten, ODT, HWP/HWPX, HTML, Tabellen und E-Books: eine Folie pro Überschrift, mit Listen, Tabellen, Bildern und Code.",
"engine.odp-writer.name": "ODP-Writer (integriert)",
"engine.odp-writer.description": "Erstellt OpenDocument-Präsentationen (ODP) ohne LibreOffice: PowerPoint-Folien (PPTX, PPT) mit Formen, Bildern, Tabellen und Notizen sowie Markdown- und Markup-Dateien, Word-Dokumente, ODT, HWP/HWPX, HTML, Tabellen und E-Books mit einer Folie pro Überschrift.",
+ "engine.odf-variants.name": "OpenDocument-Vorlagen und Flat-XML-Dateien (integriert)",
+ "engine.odf-variants.description": "Wandelt OpenDocument-Dateien ohne LibreOffice in ihre Vorlagen (OTT, OTS, OTP, OTG) und Flat-XML-Dateien (FODT, FODS, FODP, FODG) um und zurück; das ganze Dokument bleibt erhalten.",
"engine.pdf-text.name": "PDF-Text (integriert)",
"engine.pdf-text.description": "Extrahiert PDF-Text in Lesereihenfolge, auch aus zweispaltigen Seiten (keine Texterkennung für Scans).",
"engine.pdf-slides.name": "PDF-Folien (integriert)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "Werkzeugwege von 3D-Druckern und CNC-Maschinen (G-Code) als PDF, SVG und Bild, oder die Vorschau des Slicers.",
"engine.drawing.name": "Zeichnungen (integriert)",
"engine.drawing.description": "Visio-Zeichnungen (VSDX) und OpenDocument-Zeichnungen (ODG, FODG) in PDF, SVG und PNG, ohne Visio oder LibreOffice.\nAuch XPS- und OpenXPS-Dokumente (.xps, .oxps).\nAuch Excel-Diagrammvorlagen (.crtx).\nFür alte binäre Visio-Dateien (.vsd) ist weiterhin LibreOffice nötig.",
+ "engine.djvu.name": "DjVu (integriert)",
+ "engine.djvu.description": "Gescannte DjVu-Bücher und -Dokumente (.djvu, .djv) in PDF mit durchsuchbarem verborgenem Text sowie in PNG-, JPG- und TIFF-Bilder der Seiten.",
"engine.model3d.name": "3D-Modelle (integriert)",
"engine.model3d.description": "3D-Modelle: Konvertiert GLB, glTF, STL, OBJ, 3MF und PLY untereinander, FBX in jedes dieser Formate und erstellt eine PNG-Vorschau.",
"engine.image3d.name": "Bilder zu 3D-Relief (integriert)",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 98fb4b38c..0b625d423 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "The file inside this .p7m is of a type Filee doesn't convert",
"error.udf_not_uyap": "This .udf file isn't a UYAP document. If it's a disc image (Universal Disk Format), use Extract to unpack it",
"error.chart_template_unsupported": "Filee doesn't draw this kind of chart yet (radar, bubble, stock, surface, bar of pie, or a newer type such as waterfall or treemap)",
+ "error.djvu_indirect": "This is an indirect DjVu document: its pages are separate files. Bundle it into one file in a DjVu viewer (for example DjView: Save as bundled), then convert that file",
"error.p7m_too_large": "The signed file is too large to open",
"error.document_too_large": "This document unpacks to too much data or is nested too deeply to open safely",
"format_request.request": "Request this format",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "This file is CMYK but was saved as RGB: install Ghostscript in Settings → Engines to keep CMYK",
"notice.pdfa_needs_ghostscript": "This PDF isn't PDF/A: install Ghostscript in Settings → Engines to make it PDF/A",
"notice.pdfa_form_fields": "Made PDF/A: its form fields can no longer be filled in",
+ "pdfa.reason.font_not_embedded": "a font it uses isn't embedded",
+ "pdfa.reason.cmyk": "its CMYK colours have to be converted",
+ "pdfa.reason.no_appearance": "an annotation or form field has no appearance of its own",
+ "pdfa.reason.unsupported": "it has content PDF/A doesn't allow that Filee can't take out",
+ "pdfa.reason.unreadable": "Filee couldn't read it",
+ "pdfa.reason.locked": "it is locked with a password",
"notice.cmyk_render_failed": "This file is CMYK, but Ghostscript couldn't draw it, so it was saved as RGB",
"notice.original_kept": "The original was kept, the result was saved as a copy",
"notice.original_in_trash": "The original is in the Recycle Bin / Trash, the result kept its own name",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Writes Word documents (DOCX) from PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Writes OpenDocument text (ODT, LibreOffice Writer) from Word documents, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",
+ "engine.rtf-writer.name": "RTF writer (built-in)",
+ "engine.rtf-writer.description": "Writes Rich Text Format (RTF, for Word and WordPad) from Word documents, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheets, slides and e-books.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Jupyter notebooks, OPML, Textile, MediaWiki, reStructuredText, Org and DocBook without Pandoc.\nDocuments to these formats, and these to Markdown, HTML, text, DOCX, HWPX and PDF.\nAlso FreeMind / Freeplane and XMind mind maps, read as outlines.",
"engine.pptx-writer.name": "PPTX writer (built-in)",
"engine.pptx-writer.description": "Makes PowerPoint slides (PPTX) from Markdown and markup files, Word documents, ODT, HWP/HWPX, HTML, spreadsheets and e-books: a slide per heading, with lists, tables, pictures and code.",
"engine.odp-writer.name": "ODP writer (built-in)",
"engine.odp-writer.description": "Makes OpenDocument presentations (ODP) without LibreOffice: PowerPoint decks (PPTX, PPT) with their shapes, pictures, tables and speaker notes, and Markdown and markup files, Word documents, ODT, HWP/HWPX, HTML, spreadsheets and e-books with a slide per heading.",
+ "engine.odf-variants.name": "OpenDocument templates and flat files (built-in)",
+ "engine.odf-variants.description": "Turns OpenDocument files into their templates (OTT, OTS, OTP, OTG) and flat XML files (FODT, FODS, FODP, FODG) and back without LibreOffice, keeping the whole document.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "Extracts the text of PDFs in reading order, also from two-column pages (no OCR for scans).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Toolpaths of 3D printers and CNC machines (G-code) to PDF, SVG and pictures, or the slicer's own preview.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Visio drawings (VSDX) and OpenDocument drawings (ODG, FODG) to PDF, SVG and PNG, without Visio or LibreOffice.\nAlso XPS and OpenXPS documents (.xps, .oxps).\nAlso Excel chart templates (.crtx).\nOld binary Visio files (.vsd) still need LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "DjVu scanned books and documents (.djvu, .djv) to PDF with their hidden text searchable, and to PNG, JPG and TIFF pictures of the pages.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, FBX into any of them, and a PNG preview.",
"engine.image3d.name": "Pictures to 3D relief (built-in)",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index f52142523..0a206d060 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "El archivo dentro de este .p7m es de un tipo que Filee no convierte",
"error.udf_not_uyap": "Este archivo .udf no es un documento de UYAP. Si es una imagen de disco (Universal Disk Format), ábrelo con «Extraer»",
"error.chart_template_unsupported": "Filee aún no dibuja este tipo de gráfico (radial, de burbujas, de cotizaciones, de superficie, barra de gráfico circular o un tipo nuevo como cascada o rectángulos)",
+ "error.djvu_indirect": "Es un documento DjVu indirecto: sus páginas son archivos separados. Agrúpelo en un solo archivo en un visor DjVu (por ejemplo DjView: guardar como agrupado) y convierta ese archivo",
"error.p7m_too_large": "El archivo firmado es demasiado grande para abrirlo",
"error.document_too_large": "Este documento se descomprime en demasiados datos o está anidado a demasiada profundidad para abrirlo de forma segura",
"format_request.request": "Solicitar este formato",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "Este archivo es CMYK, pero se guardó en RGB: instala Ghostscript en Ajustes → Motores para mantener CMYK",
"notice.pdfa_needs_ghostscript": "Este PDF no es PDF/A: instala Ghostscript en Ajustes → Motores para crear PDF/A",
"notice.pdfa_form_fields": "Se creó un PDF/A: los campos del formulario ya no se pueden rellenar",
+ "pdfa.reason.font_not_embedded": "una fuente que usa no está incrustada",
+ "pdfa.reason.cmyk": "habría que convertir sus colores CMYK",
+ "pdfa.reason.no_appearance": "una anotación o un campo de formulario no tiene apariencia propia",
+ "pdfa.reason.unsupported": "tiene contenido que PDF/A no permite y que Filee no puede quitar",
+ "pdfa.reason.unreadable": "Filee no pudo leerlo",
+ "pdfa.reason.locked": "está protegido con contraseña",
"notice.cmyk_render_failed": "Este archivo es CMYK, pero Ghostscript no pudo dibujarlo, así que se guardó en RGB",
"notice.original_kept": "Se conservó el original, el resultado se guardó como copia",
"notice.original_in_trash": "El original está en la Papelera, el resultado conservó su propio nombre",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "Escribe documentos de Word (DOCX) desde PDF, OFD, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Escribe documentos de texto OpenDocument (ODT) desde documentos de Word, PDF, OFD, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.",
+ "engine.rtf-writer.name": "Escritor RTF (integrado)",
+ "engine.rtf-writer.description": "Escribe documentos de texto enriquecido (RTF, para Word y WordPad) desde documentos de Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, hojas de cálculo, diapositivas y libros electrónicos.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Cuadernos de Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org y DocBook sin Pandoc.\nDocumentos a estos formatos, y estos a Markdown, HTML, texto, DOCX, HWPX y PDF.\nTambién mapas mentales de FreeMind / Freeplane y XMind, leídos como esquemas.",
"engine.pptx-writer.name": "Generador PPTX (integrado)",
"engine.pptx-writer.description": "Crea diapositivas de PowerPoint (PPTX) a partir de archivos Markdown y de marcado, documentos de Word, ODT, HWP/HWPX, HTML, hojas de cálculo y libros electrónicos: una diapositiva por encabezado, con listas, tablas, imágenes y código.",
"engine.odp-writer.name": "Generador ODP (integrado)",
"engine.odp-writer.description": "Crea presentaciones OpenDocument (ODP) sin LibreOffice: diapositivas de PowerPoint (PPTX, PPT) con sus formas, imágenes, tablas y notas, y archivos Markdown y de marcado, documentos de Word, ODT, HWP/HWPX, HTML, hojas de cálculo y libros electrónicos, una diapositiva por encabezado.",
+ "engine.odf-variants.name": "Plantillas y archivos XML planos de OpenDocument (integrado)",
+ "engine.odf-variants.description": "Convierte archivos OpenDocument en sus plantillas (OTT, OTS, OTP, OTG) y archivos XML planos (FODT, FODS, FODP, FODG), y viceversa, sin LibreOffice y conservando todo el documento.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "Extrae el texto de los PDF en orden de lectura, también de páginas en dos columnas (sin OCR para escaneos).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "Trayectorias de impresoras 3D y máquinas CNC (G-code) a PDF, SVG e imágenes, o la vista previa del laminador.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Dibujos de Visio (VSDX) y de OpenDocument (ODG, FODG) a PDF, SVG y PNG, sin Visio ni LibreOffice.\nTambién documentos XPS y OpenXPS (.xps, .oxps).\nTambién plantillas de gráficos de Excel (.crtx).\nLos archivos binarios antiguos de Visio (.vsd) siguen necesitando LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "Libros y documentos escaneados DjVu (.djvu, .djv) a PDF con su texto oculto buscable, y a imágenes PNG, JPG y TIFF de las páginas.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, FBX a cualquiera de ellos, además de una vista previa en PNG.",
"engine.image3d.name": "Imágenes a relieve 3D (integrado)",
diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json
index 8de6630ad..b205c41c1 100644
--- a/src/Filee.App/Assets/i18n/fa.json
+++ b/src/Filee.App/Assets/i18n/fa.json
@@ -126,6 +126,7 @@
"error.p7m_unknown_content": "فایل داخل این .p7m از نوعی است که Filee تبدیل نمیکند",
"error.udf_not_uyap": "این فایل .udf سند UYAP نیست. اگر ایمیج دیسک (Universal Disk Format) است، آن را با «استخراج» باز کنید",
"error.chart_template_unsupported": "Filee هنوز این نوع نمودار را نمیکشد (راداری، حبابی، سهام، سطحی، میلهای از دایرهای یا نوعی تازهتر مانند آبشاری یا نقشهٔ درختی)",
+ "error.djvu_indirect": "این یک سند DjVu غیرمستقیم است: صفحههایش فایلهای جداگانهاند. آن را در یک نمایشگر DjVu در یک فایل جمع کنید (مثلاً DjView: ذخیره بهصورت بستهای) و سپس همان فایل را تبدیل کنید",
"error.p7m_too_large": "فایل امضاشده برای باز شدن بیش از حد بزرگ است",
"error.document_too_large": "دادههای استخراجشده از این سند بیش از حد مجاز است یا ساختار آن برای باز شدن ایمن بیش از حد تودرتو است",
"format_request.request": "درخواست این فرمت",
@@ -217,6 +218,12 @@
"notice.cmyk_needs_ghostscript": "این فایل CMYK است اما به صورت RGB ذخیره شد: برای حفظ CMYK، نرمافزار Ghostscript را در تنظیمات ← موتورها نصب کنید",
"notice.pdfa_needs_ghostscript": "این PDF از نوع PDF/A نیست: برای ساخت PDF/A، نرمافزار Ghostscript را در تنظیمات ← موتورها نصب کنید",
"notice.pdfa_form_fields": "PDF/A ساخته شد: دیگر نمیتوان فیلدهای فرم را پر کرد",
+ "pdfa.reason.font_not_embedded": "فونتی که به کار رفته جاسازی نشده است",
+ "pdfa.reason.cmyk": "رنگهای CMYK آن باید تبدیل شوند",
+ "pdfa.reason.no_appearance": "یک یادداشت یا فیلد فرم ظاهر خودش را ندارد",
+ "pdfa.reason.unsupported": "محتوایی دارد که PDF/A اجازه نمیدهد و Filee نمیتواند حذفش کند",
+ "pdfa.reason.unreadable": "Filee نتوانست آن را بخواند",
+ "pdfa.reason.locked": "با گذرواژه قفل شده است",
"notice.cmyk_render_failed": "این فایل CMYK است، اما Ghostscript نتوانست آن را رسم کند، بنابراین به صورت RGB ذخیره شد",
"notice.original_kept": "فایل اصلی حفظ شد و نتیجه به عنوان نسخه کپی ذخیره گردید",
"notice.original_in_trash": "فایل اصلی در سطل زباله است، نتیجه نام خود را حفظ کرد",
@@ -301,12 +308,16 @@
"engine.docx-writer.description": "نوشتن اسناد Word (DOCX) از PDF، OFD، HWP/HWPX، مارکداون، HTML، صفحهگستردهها، اسلایدها و کتابهای الکترونیکی.",
"engine.odt-writer.name": "نویسنده ODT (داخلی)",
"engine.odt-writer.description": "نوشتن متن OpenDocument (ODT، LibreOffice Writer) از اسناد Word، PDF، OFD، HWP/HWPX، مارکداون، HTML، صفحهگستردهها، اسلایدها و کتابهای الکترونیکی.",
+ "engine.rtf-writer.name": "نویسنده RTF (داخلی)",
+ "engine.rtf-writer.description": "نوشتن متن قالبدار (RTF، برای Word و WordPad) از اسناد Word، ODT، PDF، OFD، HWP/HWPX، مارکداون، HTML، صفحهگستردهها، اسلایدها و کتابهای الکترونیکی.",
"engine.markup.name": "زبانهای نشانهگذاری (داخلی)",
"engine.markup.description": "دفترچههای Jupyter، OPML، Textile، MediaWiki، reStructuredText، Org و DocBook بدون Pandoc.\nاسناد به این قالبها، و این قالبها به مارکداون، HTML، متن، DOCX، HWPX و PDF.\nهمچنین نقشههای ذهنی FreeMind / Freeplane و XMind که بهصورت طرح کلی خوانده میشوند.",
"engine.pptx-writer.name": "نویسنده PPTX (داخلی)",
"engine.pptx-writer.description": "ساخت اسلایدهای PowerPoint (PPTX) از فایلهای مارکداون و نشانهگذاری، اسناد Word، ODT، HWP/HWPX، HTML، صفحهگستردهها و کتابهای الکترونیکی: یک اسلاید برای هر عنوان، با فهرستها، جدولها، تصاویر و کد.",
"engine.odp-writer.name": "نویسنده ODP (داخلی)",
"engine.odp-writer.description": "ساخت ارائههای OpenDocument (ODP) بدون LibreOffice: اسلایدهای PowerPoint (PPTX، PPT) با شکلها، تصاویر، جدولها و یادداشتهای سخنران، و فایلهای مارکداون و نشانهگذاری، اسناد Word، ODT، HWP/HWPX، HTML، صفحهگستردهها و کتابهای الکترونیکی با یک اسلاید برای هر عنوان.",
+ "engine.odf-variants.name": "قالبها و فایلهای XML تخت OpenDocument (داخلی)",
+ "engine.odf-variants.description": "فایلهای OpenDocument را بدون LibreOffice به قالبها (OTT، OTS، OTP، OTG) و فایلهای XML تخت (FODT، FODS، FODP، FODG) و برعکس تبدیل میکند و کل سند را حفظ میکند.",
"engine.pdf-text.name": "متن PDF (داخلی)",
"engine.pdf-text.description": "استخراج متن PDF به ترتیب خواندن، همچنین از صفحات دو ستونه (بدون OCR برای اسکنها).",
"engine.pdf-slides.name": "اسلایدهای PDF (داخلی)",
@@ -335,6 +346,8 @@
"engine.gcode.description": "مسیرهای چاپگرهای سهبعدی و دستگاههای CNC (G-code) به PDF، SVG و تصویر، یا پیشنمایش خود اسلایسر.",
"engine.drawing.name": "نمودارها و نقشهها (داخلی)",
"engine.drawing.description": "نمودارهای Visio (VSDX) و نقشههای OpenDocument (ODG، FODG) به PDF، SVG و PNG، بدون Visio یا LibreOffice.\nهمچنین سندهای XPS و OpenXPS (.xps، .oxps).\nهمچنین الگوهای نمودار Excel (.crtx).\nفایلهای باینری قدیمی Visio (.vsd) همچنان به LibreOffice نیاز دارند.",
+ "engine.djvu.name": "DjVu (داخلی)",
+ "engine.djvu.description": "کتابها و اسناد اسکنشدهٔ DjVu (.djvu، .djv) به PDF با متن پنهانِ قابل جستوجو، و به تصاویر PNG، JPG و TIFF صفحهها.",
"engine.model3d.name": "مدلهای سهبعدی (داخلی)",
"engine.model3d.description": "مدلهای سهبعدی: GLB، glTF، STL، OBJ، 3MF و PLY به یکدیگر، FBX به هر یک از آنها، همراه با پیشنمایش PNG.",
"engine.image3d.name": "تبدیل تصاویر به برجستهسازی سهبعدی (داخلی)",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 8ba6306ca..193db5aec 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "Le fichier contenu dans ce .p7m est d'un type que Filee ne convertit pas",
"error.udf_not_uyap": "Ce fichier .udf n'est pas un document UYAP. S'il s'agit d'une image disque (Universal Disk Format), ouvrez-le avec « Extraire »",
"error.chart_template_unsupported": "Filee ne dessine pas encore ce type de graphique (radar, bulles, boursier, surface, barres de secteurs ou un type récent comme cascade ou compartimentage)",
+ "error.djvu_indirect": "Ce document DjVu est indirect : ses pages sont des fichiers séparés. Regroupez-le en un seul fichier dans une visionneuse DjVu (par exemple DjView : enregistrer en groupé), puis convertissez ce fichier",
"error.p7m_too_large": "Le fichier signé est trop volumineux pour être ouvert",
"error.document_too_large": "Ce document se décompresse en trop de données ou est imbriqué trop profondément pour être ouvert en toute sécurité",
"format_request.request": "Demander ce format",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Ce fichier est en CMJN mais a été enregistré en RVB : installez Ghostscript dans Paramètres → Moteurs pour garder le CMJN",
"notice.pdfa_needs_ghostscript": "Ce PDF n'est pas un PDF/A : installez Ghostscript dans Paramètres → Moteurs pour créer du PDF/A",
"notice.pdfa_form_fields": "PDF/A créé : les champs du formulaire ne peuvent plus être remplis",
+ "pdfa.reason.font_not_embedded": "une police utilisée n'est pas incorporée",
+ "pdfa.reason.cmyk": "ses couleurs CMJN devraient être converties",
+ "pdfa.reason.no_appearance": "une annotation ou un champ de formulaire n'a pas d'apparence propre",
+ "pdfa.reason.unsupported": "il contient des éléments interdits en PDF/A que Filee ne peut pas retirer",
+ "pdfa.reason.unreadable": "Filee n'a pas pu le lire",
+ "pdfa.reason.locked": "il est protégé par un mot de passe",
"notice.cmyk_render_failed": "Ce fichier est en CMJN, mais Ghostscript n'a pas pu le dessiner : il a été enregistré en RVB",
"notice.original_kept": "L'original a été conservé, le résultat a été enregistré en copie",
"notice.original_in_trash": "L'original est dans la Corbeille, le résultat a gardé son propre nom",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Écrit des documents Word (DOCX) à partir de PDF, OFD, HWP/HWPX, Markdown, HTML, feuilles de calcul, diapositives et livres numériques.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Écrit des documents texte OpenDocument (ODT) à partir de documents Word, PDF, OFD, HWP/HWPX, Markdown, HTML, feuilles de calcul, diapositives et livres numériques.",
+ "engine.rtf-writer.name": "Écrivain RTF (intégré)",
+ "engine.rtf-writer.description": "Écrit du texte enrichi (RTF, pour Word et WordPad) à partir de documents Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, feuilles de calcul, diapositives et livres numériques.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org et DocBook sans Pandoc.\nDes documents vers ces formats, et ceux-ci en Markdown, HTML, texte, DOCX, HWPX et PDF.\nAussi les cartes mentales FreeMind / Freeplane et XMind, lues comme des plans.",
"engine.pptx-writer.name": "Générateur PPTX (intégré)",
"engine.pptx-writer.description": "Crée des diapositives PowerPoint (PPTX) à partir de fichiers Markdown et de balisage, de documents Word, ODT, HWP/HWPX, HTML, de feuilles de calcul et de livres numériques : une diapositive par titre, avec listes, tableaux, images et code.",
"engine.odp-writer.name": "Générateur ODP (intégré)",
"engine.odp-writer.description": "Crée des présentations OpenDocument (ODP) sans LibreOffice : diapositives PowerPoint (PPTX, PPT) avec leurs formes, images, tableaux et notes, ainsi que fichiers Markdown et de balisage, documents Word, ODT, HWP/HWPX, HTML, feuilles de calcul et livres numériques, une diapositive par titre.",
+ "engine.odf-variants.name": "Modèles et fichiers XML plats OpenDocument (intégré)",
+ "engine.odf-variants.description": "Convertit les fichiers OpenDocument en modèles (OTT, OTS, OTP, OTG) et en fichiers XML plats (FODT, FODS, FODP, FODG), et inversement, sans LibreOffice, en gardant tout le document.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "Extrait le texte des PDF dans l'ordre de lecture, y compris sur deux colonnes (pas d'OCR pour les numérisations).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Parcours d'imprimantes 3D et de machines CNC (G-code) en PDF, SVG et images, ou l'aperçu du slicer.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Dessins Visio (VSDX) et OpenDocument (ODG, FODG) en PDF, SVG et PNG, sans Visio ni LibreOffice.\nAussi les documents XPS et OpenXPS (.xps, .oxps).\nAussi les modèles de graphiques Excel (.crtx).\nLes anciens fichiers Visio binaires (.vsd) nécessitent toujours LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "Livres et documents numérisés DjVu (.djvu, .djv) en PDF avec leur texte caché consultable, et en images PNG, JPG et TIFF des pages.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modèles 3D : GLB, glTF, STL, OBJ, 3MF et PLY entre eux, FBX vers chacun d'eux, et un aperçu PNG.",
"engine.image3d.name": "Images vers relief 3D (intégré)",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index f6965d2f9..a8afe6d55 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "इस .p7m के अंदर की फ़ाइल ऐसे प्रकार की है जिसे Filee नहीं बदलता",
"error.udf_not_uyap": "यह .udf फ़ाइल UYAP दस्तावेज़ नहीं है। अगर यह डिस्क इमेज (Universal Disk Format) है, तो इसे «निकालें» से खोलें",
"error.chart_template_unsupported": "Filee अभी इस तरह का चार्ट नहीं बनाता (रडार, बबल, स्टॉक, सरफ़ेस, पाई का बार, या वॉटरफ़ॉल या ट्रीमैप जैसा नया प्रकार)",
+ "error.djvu_indirect": "यह एक अप्रत्यक्ष DjVu दस्तावेज़ है: इसके पेज अलग-अलग फ़ाइलें हैं। इसे किसी DjVu व्यूअर में एक फ़ाइल में जोड़ें (जैसे DjView: बंडल के रूप में सहेजें), फिर उस फ़ाइल को बदलें",
"error.p7m_too_large": "साइन की गई फ़ाइल खोलने के लिए बहुत बड़ी है",
"error.document_too_large": "यह दस्तावेज़ खोलने पर बहुत ज़्यादा डेटा बनता है या बहुत गहराई तक नेस्टेड है, इसलिए इसे सुरक्षित रूप से नहीं खोला जा सकता",
"format_request.request": "इस फ़ॉर्मैट का अनुरोध करें",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "यह फ़ाइल CMYK है, लेकिन RGB में सेव हुई: CMYK बनाए रखने के लिए सेटिंग्स → इंजन में Ghostscript इंस्टॉल करें",
"notice.pdfa_needs_ghostscript": "यह PDF, PDF/A नहीं है: PDF/A बनाने के लिए सेटिंग्स → इंजन में Ghostscript इंस्टॉल करें",
"notice.pdfa_form_fields": "PDF/A बनाया गया: फ़ॉर्म के फ़ील्ड अब भरे नहीं जा सकते",
+ "pdfa.reason.font_not_embedded": "इस्तेमाल किया गया एक फ़ॉन्ट एम्बेड नहीं है",
+ "pdfa.reason.cmyk": "इसके CMYK रंगों को बदलना होगा",
+ "pdfa.reason.no_appearance": "किसी टिप्पणी या फ़ॉर्म फ़ील्ड का अपना रूप नहीं है",
+ "pdfa.reason.unsupported": "इसमें ऐसी सामग्री है जिसकी PDF/A अनुमति नहीं देता और Filee उसे हटा नहीं सकता",
+ "pdfa.reason.unreadable": "Filee इसे पढ़ नहीं सका",
+ "pdfa.reason.locked": "यह पासवर्ड से सुरक्षित है",
"notice.cmyk_render_failed": "यह फ़ाइल CMYK है, लेकिन Ghostscript इसे नहीं बना सका, इसलिए यह RGB में सेव हुई",
"notice.original_kept": "मूल फ़ाइल रखी गई, परिणाम कॉपी के रूप में सहेजा गया",
"notice.original_in_trash": "मूल फ़ाइल रीसायकल बिन / ट्रैश में है, परिणाम ने अपना नाम रखा",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से Word दस्तावेज़ (DOCX) लिखता है।",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Word दस्तावेज़, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से OpenDocument टेक्स्ट (ODT) लिखता है।",
+ "engine.rtf-writer.name": "RTF writer (built-in)",
+ "engine.rtf-writer.description": "Word दस्तावेज़, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडशीट, स्लाइड और ई-बुक से रिच टेक्स्ट फ़ॉर्मेट (RTF, Word और WordPad के लिए) लिखता है।",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Pandoc के बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org और DocBook।\nदस्तावेज़ों से ये फ़ॉर्मैट, और इनसे Markdown, HTML, टेक्स्ट, DOCX, HWPX और PDF।\nसाथ ही FreeMind / Freeplane और XMind माइंड मैप, आउटलाइन के रूप में पढ़े जाते हैं।",
"engine.pptx-writer.name": "PPTX लेखक (अंतर्निहित)",
"engine.pptx-writer.description": "Markdown और मार्कअप फ़ाइलों, Word दस्तावेज़, ODT, HWP/HWPX, HTML, स्प्रेडशीट और ई-बुक से PowerPoint स्लाइड (PPTX) बनाता है: हर शीर्षक के लिए एक स्लाइड, सूचियों, तालिकाओं, चित्रों और कोड के साथ।",
"engine.odp-writer.name": "ODP लेखक (अंतर्निहित)",
"engine.odp-writer.description": "LibreOffice के बिना OpenDocument प्रस्तुतियाँ (ODP) बनाता है: PowerPoint स्लाइड (PPTX, PPT) उनकी आकृतियों, चित्रों, तालिकाओं और वक्ता नोट्स के साथ, और Markdown व मार्कअप फ़ाइलें, Word दस्तावेज़, ODT, HWP/HWPX, HTML, स्प्रेडशीट और ई-बुक, हर शीर्षक के लिए एक स्लाइड।",
+ "engine.odf-variants.name": "OpenDocument टेम्पलेट और फ़्लैट XML फ़ाइलें (अंतर्निहित)",
+ "engine.odf-variants.description": "LibreOffice के बिना OpenDocument फ़ाइलों को उनके टेम्पलेट (OTT, OTS, OTP, OTG) और फ़्लैट XML फ़ाइलों (FODT, FODS, FODP, FODG) में और वापस बदलता है, पूरा दस्तावेज़ जैसा का तैसा रखते हुए।",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "PDF का टेक्स्ट पढ़ने के क्रम में निकालता है, दो-कॉलम वाले पेजों से भी (स्कैन के लिए OCR नहीं)।",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "3D प्रिंटर और CNC मशीनों के टूलपाथ (G-code) को PDF, SVG और चित्र में, या स्लाइसर का अपना प्रीव्यू।",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Visio ड्रॉइंग (VSDX) और OpenDocument ड्रॉइंग (ODG, FODG) से PDF, SVG और PNG, बिना Visio या LibreOffice के।\nXPS और OpenXPS दस्तावेज़ (.xps, .oxps) भी।\nExcel चार्ट टेम्पलेट (.crtx) भी।\nपुरानी बाइनरी Visio फ़ाइलों (.vsd) के लिए अब भी LibreOffice चाहिए।",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "DjVu स्कैन की गई किताबें और दस्तावेज़ (.djvu, .djv) को खोजे जा सकने वाले छिपे टेक्स्ट सहित PDF में, और पेजों की PNG, JPG व TIFF तस्वीरों में।",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D मॉडल: GLB, glTF, STL, OBJ, 3MF और PLY एक-दूसरे में, FBX इनमें से किसी में भी, और PNG प्रीव्यू।",
"engine.image3d.name": "चित्र से 3D रिलीफ़ (बिल्ट-इन)",
diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json
index 9030c5343..33775b48c 100644
--- a/src/Filee.App/Assets/i18n/id.json
+++ b/src/Filee.App/Assets/i18n/id.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "File di dalam .p7m ini berjenis yang tidak dikonversi Filee",
"error.udf_not_uyap": "File .udf ini bukan dokumen UYAP. Jika ini image disk (Universal Disk Format), buka dengan “Ekstrak”",
"error.chart_template_unsupported": "Filee belum dapat menggambar jenis bagan ini (radar, gelembung, saham, permukaan, batang dari pai, atau jenis baru seperti air terjun atau peta pohon)",
+ "error.djvu_indirect": "Ini dokumen DjVu tidak langsung: halamannya berupa file terpisah. Gabungkan menjadi satu file di penampil DjVu (misalnya DjView: simpan sebagai bundel), lalu konversi file tersebut",
"error.p7m_too_large": "File bertanda tangan terlalu besar untuk dibuka",
"error.document_too_large": "Dokumen ini terurai menjadi data yang terlalu besar atau bersarang terlalu dalam untuk dibuka dengan aman",
"format_request.request": "Minta format ini",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "File ini CMYK, tetapi disimpan sebagai RGB: pasang Ghostscript di Pengaturan → Engine agar tetap CMYK",
"notice.pdfa_needs_ghostscript": "PDF ini bukan PDF/A: pasang Ghostscript di Pengaturan → Engine untuk membuat PDF/A",
"notice.pdfa_form_fields": "PDF/A dibuat: kolom formulir tidak lagi bisa diisi",
+ "pdfa.reason.font_not_embedded": "font yang dipakai tidak disematkan",
+ "pdfa.reason.cmyk": "warna CMYK-nya perlu dikonversi",
+ "pdfa.reason.no_appearance": "anotasi atau kolom formulir tidak punya tampilan sendiri",
+ "pdfa.reason.unsupported": "ada konten yang tidak diizinkan PDF/A dan tidak bisa dihapus Filee",
+ "pdfa.reason.unreadable": "Filee tidak bisa membacanya",
+ "pdfa.reason.locked": "dikunci dengan kata sandi",
"notice.cmyk_render_failed": "File ini CMYK, tetapi Ghostscript tidak bisa menggambarnya, jadi disimpan sebagai RGB",
"notice.original_kept": "File asli dipertahankan, hasil konversi disimpan sebagai salinan",
"notice.original_in_trash": "File asli ada di Tong Sampah, hasil konversi mempertahankan namanya sendiri",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "Menulis dokumen Word (DOCX) dari PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheet, slide, dan e-book.",
"engine.odt-writer.name": "Penulis ODT (bawaan)",
"engine.odt-writer.description": "Menulis dokumen teks OpenDocument (ODT) dari dokumen Word, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheet, slide, dan e-book.",
+ "engine.rtf-writer.name": "Penulis RTF (bawaan)",
+ "engine.rtf-writer.description": "Menulis dokumen Rich Text Format (RTF, untuk Word dan WordPad) dari dokumen Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, spreadsheet, slide, dan e-book.",
"engine.markup.name": "Bahasa markup (bawaan)",
"engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org, dan DocBook tanpa Pandoc.\nDokumen ke format ini, dan format ini ke Markdown, HTML, teks, DOCX, HWPX, dan PDF.\nJuga peta pikiran FreeMind / Freeplane dan XMind, dibaca sebagai kerangka.",
"engine.pptx-writer.name": "Penulis PPTX (bawaan)",
"engine.pptx-writer.description": "Membuat slide PowerPoint (PPTX) dari file Markdown dan markup, dokumen Word, ODT, HWP/HWPX, HTML, spreadsheet, dan e-book: satu slide per judul, dengan daftar, tabel, gambar, dan kode.",
"engine.odp-writer.name": "Penulis ODP (bawaan)",
"engine.odp-writer.description": "Membuat presentasi OpenDocument (ODP) tanpa LibreOffice: slide PowerPoint (PPTX, PPT) beserta bentuk, gambar, tabel, dan catatan pembicara, serta file Markdown dan markup, dokumen Word, ODT, HWP/HWPX, HTML, spreadsheet, dan e-book dengan satu slide per judul.",
+ "engine.odf-variants.name": "Templat dan file XML datar OpenDocument (bawaan)",
+ "engine.odf-variants.description": "Mengubah file OpenDocument menjadi templatnya (OTT, OTS, OTP, OTG) dan file XML datar (FODT, FODS, FODP, FODG) serta sebaliknya tanpa LibreOffice, dengan seluruh dokumen tetap utuh.",
"engine.pdf-text.name": "Teks PDF (bawaan)",
"engine.pdf-text.description": "Mengekstrak teks PDF sesuai urutan baca, termasuk halaman dua kolom (tanpa OCR untuk dokumen pindai).",
"engine.pdf-slides.name": "Slide PDF (bawaan)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "Jalur printer 3D dan mesin CNC (G-code) ke PDF, SVG, dan gambar, atau pratinjau dari slicer.",
"engine.drawing.name": "Diagram (bawaan)",
"engine.drawing.description": "Diagram Visio (VSDX) dan gambar OpenDocument (ODG, FODG) ke PDF, SVG, dan PNG, tanpa Visio atau LibreOffice.\nJuga dokumen XPS dan OpenXPS (.xps, .oxps).\nJuga templat bagan Excel (.crtx).\nFile Visio biner lama (.vsd) masih memerlukan LibreOffice.",
+ "engine.djvu.name": "DjVu (bawaan)",
+ "engine.djvu.description": "Buku dan dokumen pindaian DjVu (.djvu, .djv) ke PDF dengan teks tersembunyi yang bisa dicari, serta ke gambar halaman PNG, JPG, dan TIFF.",
"engine.model3d.name": "Model 3D (bawaan)",
"engine.model3d.description": "Model 3D: GLB, glTF, STL, OBJ, 3MF, dan PLY saling konversi, FBX ke format mana pun, serta pratinjau gambar PNG.",
"engine.image3d.name": "Gambar ke relief 3D (bawaan)",
diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json
index 3d900fcd2..83404b65c 100644
--- a/src/Filee.App/Assets/i18n/it.json
+++ b/src/Filee.App/Assets/i18n/it.json
@@ -111,6 +111,7 @@
"error.p7m_unknown_content": "Il file dentro questo .p7m è di un tipo che Filee non converte",
"error.udf_not_uyap": "Questo file .udf non è un documento UYAP. Se è un'immagine disco (Universal Disk Format), aprilo con «Estrai»",
"error.chart_template_unsupported": "Filee non disegna ancora questo tipo di grafico (radar, a bolle, azionario, a superficie, barra di torta o un tipo più recente come a cascata o treemap)",
+ "error.djvu_indirect": "È un documento DjVu indiretto: le sue pagine sono file separati. Riuniscilo in un unico file con un visualizzatore DjVu (ad esempio DjView: salva come raggruppato), poi converti quel file",
"error.p7m_too_large": "Il file firmato è troppo grande da aprire",
"error.document_too_large": "Questo documento si decomprime in troppi dati o è annidato troppo in profondità per essere aperto in sicurezza",
"format_request.request": "Richiedi questo formato",
@@ -202,6 +203,12 @@
"notice.cmyk_needs_ghostscript": "Questo file è CMYK ma è stato salvato in RGB: installa Ghostscript in Impostazioni → Motori per mantenere il CMYK",
"notice.pdfa_needs_ghostscript": "Questo PDF non è PDF/A: installa Ghostscript in Impostazioni → Motori per creare PDF/A",
"notice.pdfa_form_fields": "PDF/A creato: i campi del modulo non possono più essere compilati",
+"pdfa.reason.font_not_embedded": "un font usato non è incorporato",
+"pdfa.reason.cmyk": "i suoi colori CMYK andrebbero convertiti",
+"pdfa.reason.no_appearance": "un'annotazione o un campo modulo non ha un aspetto proprio",
+"pdfa.reason.unsupported": "contiene elementi non ammessi in PDF/A che Filee non può rimuovere",
+"pdfa.reason.unreadable": "Filee non è riuscito a leggerlo",
+"pdfa.reason.locked": "è protetto da password",
"notice.cmyk_render_failed": "Questo file è CMYK, ma Ghostscript non è riuscito a disegnarlo, quindi è stato salvato in RGB",
"notice.original_kept": "L'originale è stato conservato, il risultato è stato salvato come copia",
"notice.original_in_trash": "L'originale è nel Cestino, il risultato ha mantenuto il proprio nome",
@@ -286,12 +293,16 @@
"engine.docx-writer.description": "Scrive documenti Word (DOCX) da PDF, OFD, HWP/HWPX, Markdown, HTML, fogli di calcolo, presentazioni ed e-book.",
"engine.odt-writer.name": "Writer ODT (integrato)",
"engine.odt-writer.description": "Scrive documenti di testo OpenDocument (ODT) da documenti Word, PDF, OFD, HWP/HWPX, Markdown, HTML, fogli di calcolo, presentazioni ed e-book.",
+"engine.rtf-writer.name": "Writer RTF (integrato)",
+"engine.rtf-writer.description": "Scrive documenti Rich Text Format (RTF, per Word e WordPad) da documenti Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, fogli di calcolo, presentazioni ed e-book.",
"engine.markup.name": "Linguaggi di markup (integrato)",
"engine.markup.description": "Notebook Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook senza Pandoc.\nDocumenti in questi formati e questi in Markdown, HTML, testo, DOCX, HWPX e PDF.\nAnche mappe mentali FreeMind / Freeplane e XMind, lette come schemi.",
"engine.pptx-writer.name": "Writer PPTX (integrato)",
"engine.pptx-writer.description": "Crea diapositive PowerPoint (PPTX) da file Markdown e di markup, documenti Word, ODT, HWP/HWPX, HTML, fogli di calcolo ed e-book: una diapositiva per titolo, con elenchi, tabelle, immagini e codice.",
"engine.odp-writer.name": "Writer ODP (integrato)",
"engine.odp-writer.description": "Crea presentazioni OpenDocument (ODP) senza LibreOffice: diapositive PowerPoint (PPTX, PPT) con forme, immagini, tabelle e note, e file Markdown e di markup, documenti Word, ODT, HWP/HWPX, HTML, fogli di calcolo ed e-book, una diapositiva per titolo.",
+"engine.odf-variants.name": "Modelli e file XML flat OpenDocument (integrato)",
+"engine.odf-variants.description": "Converte i file OpenDocument nei loro modelli (OTT, OTS, OTP, OTG) e in file XML flat (FODT, FODS, FODP, FODG) e viceversa senza LibreOffice, mantenendo tutto il documento.",
"engine.pdf-text.name": "Testo PDF (integrato)",
"engine.pdf-text.description": "Estrae il testo dei PDF nell'ordine di lettura, anche dalle pagine a due colonne (niente OCR per le scansioni).",
"engine.pdf-slides.name": "Slide PDF (integrato)",
@@ -320,6 +331,8 @@
"engine.gcode.description": "Percorsi di stampanti 3D e macchine CNC (G-code) in PDF, SVG e immagini, o l'anteprima dello slicer.",
"engine.drawing.name": "Disegni (integrato)",
"engine.drawing.description": "Disegni Visio (VSDX) e OpenDocument (ODG, FODG) in PDF, SVG e PNG, senza Visio né LibreOffice.\nAnche documenti XPS e OpenXPS (.xps, .oxps).\nAnche modelli di grafico di Excel (.crtx).\nI vecchi file binari di Visio (.vsd) richiedono ancora LibreOffice.",
+ "engine.djvu.name": "DjVu (integrato)",
+ "engine.djvu.description": "Libri e documenti scansionati DjVu (.djvu, .djv) in PDF con il testo nascosto ricercabile, e in immagini PNG, JPG e TIFF delle pagine.",
"engine.model3d.name": "Modelli 3D (integrato)",
"engine.model3d.description": "Modelli 3D: GLB, glTF, STL, OBJ, 3MF e PLY convertibili tra loro, FBX in uno qualsiasi di essi, e un'anteprima PNG.",
"engine.image3d.name": "Immagini in rilievo 3D (integrato)",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 890ee52c3..45ec349e5 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "この .p7m の中のファイルは、Filee が変換できない形式です",
"error.udf_not_uyap": "この .udf ファイルは UYAP 文書ではありません。ディスクイメージ (Universal Disk Format) なら「展開」で開いてください",
"error.chart_template_unsupported": "この種類のグラフはまだ描画できません(レーダー、バブル、株価、等高線、補助縦棒付き円、ウォーターフォールやツリーマップなどの新しいグラフ)",
+ "error.djvu_indirect": "ページが別々のファイルになった間接形式のDjVu文書です。DjVuビューアー(例:DjViewの「バンドル形式で保存」)で1つのファイルにまとめてから変換してください",
"error.p7m_too_large": "署名付きファイルが大きすぎて開けません",
"error.document_too_large": "この文書は展開するとデータが大きすぎるか、入れ子が深すぎるため、安全に開けません",
"format_request.request": "この形式への対応をリクエスト",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "CMYK のファイルですが RGB で保存しました。CMYK のまま保存するには「設定」→「変換エンジン」で Ghostscript をインストールしてください",
"notice.pdfa_needs_ghostscript": "この PDF は PDF/A ではありません。PDF/A にするには「設定」→「変換エンジン」で Ghostscript をインストールしてください",
"notice.pdfa_form_fields": "PDF/A に変換しました。フォームの入力欄には入力できなくなりました",
+ "pdfa.reason.font_not_embedded": "使われているフォントが埋め込まれていません",
+ "pdfa.reason.cmyk": "CMYK の色を変換する必要があります",
+ "pdfa.reason.no_appearance": "注釈かフォームフィールドに外観がありません",
+ "pdfa.reason.unsupported": "PDF/A で使えない内容を Filee が取り除けません",
+ "pdfa.reason.unreadable": "Filee がファイルを読み込めませんでした",
+ "pdfa.reason.locked": "パスワードで保護されています",
"notice.cmyk_render_failed": "CMYK のファイルですが、Ghostscript で描画できなかったため RGB で保存しました",
"notice.original_kept": "元のファイルを残し、結果をコピーとして保存しました",
"notice.original_in_trash": "元のファイルはごみ箱にあります。結果は別の名前のままです",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "PDF、OFD、HWP/HWPX、Markdown、HTML、表計算ファイル、スライド、電子書籍からWord文書(DOCX)を作成します。",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Word文書、PDF、OFD、HWP/HWPX、Markdown、HTML、表計算ファイル、スライド、電子書籍からOpenDocumentテキスト(ODT)を作成します。",
+ "engine.rtf-writer.name": "RTF writer (built-in)",
+ "engine.rtf-writer.description": "Word 文書、ODT、PDF、OFD、HWP/HWPX、Markdown、HTML、スプレッドシート、スライド、電子書籍からリッチテキスト形式 (RTF、Word・ワードパッド用) を作成します。",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Pandocなしで Jupyter ノートブック、OPML、Textile、MediaWiki、reStructuredText、Org、DocBook を読み書きします。\n文書をこれらの形式に、これらをMarkdown、HTML、テキスト、DOCX、HWPX、PDFに変換します。\nFreeMind / Freeplane と XMind のマインドマップもアウトラインとして読み込みます。",
"engine.pptx-writer.name": "PPTX ライター(組み込み)",
"engine.pptx-writer.description": "Markdown やマークアップ、Word 文書、ODT、HWP/HWPX、HTML、表計算ファイル、電子書籍から PowerPoint スライド(PPTX)を作成します。見出しごとに 1 枚のスライドで、リスト・表・画像・コードも入ります。",
"engine.odp-writer.name": "ODP ライター(組み込み)",
"engine.odp-writer.description": "LibreOffice なしで OpenDocument プレゼンテーション(ODP)を作成します。PowerPoint スライド(PPTX、PPT)は図形・画像・表・発表者ノートごと移し、Markdown やマークアップ、Word 文書、ODT、HWP/HWPX、HTML、表計算ファイル、電子書籍は見出しごとに 1 枚のスライドにします。",
+ "engine.odf-variants.name": "OpenDocument テンプレート・フラット XML(内蔵)",
+ "engine.odf-variants.description": "LibreOffice なしで OpenDocument ファイルをテンプレート(OTT、OTS、OTP、OTG)やフラット XML ファイル(FODT、FODS、FODP、FODG)に、またその逆に変換します。文書の内容はそのまま保たれます。",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "PDFのテキストを読み順に抽出します。2段組みのページにも対応します(スキャン画像のOCRには非対応)。",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "3D プリンターと CNC マシンのツールパス (G-code) を PDF、SVG、画像に。スライサーのプレビューも使えます。",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Visio図面(VSDX)とOpenDocument図面(ODG、FODG)を、VisioやLibreOfficeなしでPDF、SVG、PNGに変換します。\nXPS・OpenXPS文書(.xps、.oxps)にも対応しています。\nExcel のグラフ テンプレート(.crtx)にも対応しています。\n古いバイナリ形式のVisioファイル(.vsd)には引き続きLibreOfficeが必要です。",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "DjVuのスキャン本や文書(.djvu、.djv)を、隠しテキストを検索できるPDFに、またページのPNG・JPG・TIFF画像に変換します。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3Dモデル(GLB、glTF、STL、OBJ、3MF、PLY)を相互変換します。FBXから各形式への変換と、PNGプレビューの作成にも対応します。",
"engine.image3d.name": "画像から3Dレリーフ(内蔵)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index e1dae63ca..63f705dc9 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "이 .p7m 안의 파일은 Filee가 변환하지 않는 형식이에요",
"error.udf_not_uyap": "이 .udf 파일은 UYAP 문서가 아니에요. 디스크 이미지(Universal Disk Format)라면 압축 풀기로 열어 주세요",
"error.chart_template_unsupported": "이 종류의 차트는 아직 그리지 못해요(방사형, 거품형, 주식형, 표면형, 원형 대 막대형, 폭포·트리맵 같은 새 차트)",
+ "error.djvu_indirect": "페이지가 따로따로 된 간접(indirect) DjVu 문서예요. DjVu 뷰어(예: DjView의 '묶음으로 저장')에서 한 파일로 묶은 다음 그 파일을 변환하세요",
"error.p7m_too_large": "서명 파일이 너무 커서 열 수 없어요",
"error.document_too_large": "이 문서는 풀면 데이터가 너무 크거나 너무 깊이 중첩되어 있어서 안전하게 열 수 없어요",
"format_request.request": "이 형식 요청하기",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "CMYK 파일인데 RGB로 저장했어요. CMYK로 받으려면 설정 → 변환 엔진에서 Ghostscript를 설치하세요",
"notice.pdfa_needs_ghostscript": "이 PDF는 PDF/A가 아니에요. PDF/A로 받으려면 설정 → 변환 엔진에서 Ghostscript를 설치하세요",
"notice.pdfa_form_fields": "PDF/A로 만들면서 양식 입력 칸은 더 이상 채울 수 없게 됐어요",
+ "pdfa.reason.font_not_embedded": "사용한 글꼴이 파일에 들어 있지 않아요",
+ "pdfa.reason.cmyk": "CMYK 색을 변환해야 해요",
+ "pdfa.reason.no_appearance": "주석이나 양식 필드에 자체 모양이 없어요",
+ "pdfa.reason.unsupported": "PDF/A에서 허용하지 않는 내용을 Filee가 뺄 수 없어요",
+ "pdfa.reason.unreadable": "Filee가 파일을 읽지 못했어요",
+ "pdfa.reason.locked": "암호로 잠겨 있어요",
"notice.cmyk_render_failed": "CMYK 파일인데 Ghostscript가 그리지 못해서 RGB로 저장했어요",
"notice.original_kept": "원본은 그대로 두고 결과를 사본으로 저장했어요",
"notice.original_in_trash": "원본은 휴지통으로 옮겼고, 결과는 저장된 이름 그대로예요",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "PDF, OFD, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 워드 문서(DOCX)를 만들어요.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "워드 문서, PDF, OFD, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 오픈문서 텍스트(ODT, LibreOffice Writer)를 만들어요.",
+ "engine.rtf-writer.name": "RTF writer (built-in)",
+ "engine.rtf-writer.description": "워드 문서, ODT, PDF, OFD, HWP/HWPX, 마크다운, HTML, 스프레드시트, 슬라이드, 전자책으로 서식 있는 텍스트(RTF, 워드·워드패드용)를 만들어요.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Pandoc 없이 주피터 노트북, OPML, Textile, MediaWiki, reStructuredText, Org, DocBook을 읽고 써요.\n문서를 이 형식으로, 이 형식을 마크다운, HTML, 텍스트, DOCX, HWPX, PDF로 바꿔요.\nFreeMind / Freeplane, XMind 마인드맵도 개요로 읽어요.",
"engine.pptx-writer.name": "PPTX 작성기 (내장)",
"engine.pptx-writer.description": "마크다운과 마크업 파일, 워드 문서, ODT, HWP/HWPX, HTML, 스프레드시트, 전자책으로 파워포인트 슬라이드(PPTX)를 만들어요. 제목마다 슬라이드 한 장이고, 목록·표·그림·코드도 들어가요.",
"engine.odp-writer.name": "ODP 작성기 (내장)",
"engine.odp-writer.description": "LibreOffice 없이 오픈도큐먼트 프레젠테이션(ODP)을 만들어요. 파워포인트 슬라이드(PPTX, PPT)는 도형·그림·표·발표자 노트까지 옮기고, 마크다운과 마크업 파일, 워드 문서, ODT, HWP/HWPX, HTML, 스프레드시트, 전자책은 제목마다 슬라이드 한 장으로 만들어요.",
+ "engine.odf-variants.name": "오픈도큐먼트 서식 파일·단일 XML 파일 (내장)",
+ "engine.odf-variants.description": "LibreOffice 없이 오픈도큐먼트 파일을 서식 파일(OTT, OTS, OTP, OTG)과 단일 XML 파일(FODT, FODS, FODP, FODG)로, 또 그 반대로 바꿔요. 문서 내용은 그대로 유지돼요.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "PDF의 글자를 읽는 순서대로 뽑아내요.\n2단 편집도 순서대로 읽어요(스캔 이미지 글자 인식은 안 해요).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "3D 프린터와 CNC 기계의 툴패스(G-code)를 PDF, SVG, 그림으로 바꿔요. 슬라이서가 저장한 미리보기도 쓸 수 있어요.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Visio 도면(VSDX)과 오픈도큐먼트 도면(ODG, FODG)을 Visio나 LibreOffice 없이 PDF, SVG, PNG로 바꿔요.\nXPS·OpenXPS 문서(.xps, .oxps)도 바꿔요.\nExcel 차트 서식 파일(.crtx)도 바꿔요.\n오래된 바이너리 Visio 파일(.vsd)은 여전히 LibreOffice가 필요해요.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "DjVu 스캔 책·문서(.djvu, .djv)를 숨은 텍스트까지 검색되는 PDF로, 페이지를 PNG·JPG·TIFF 그림으로 바꿔요.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고, FBX도 이 형식들로 바꾸고, PNG 미리보기도 만들어요.",
"engine.image3d.name": "이미지를 3D 부조로 (내장)",
diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json
index f3d78b428..1915a225b 100644
--- a/src/Filee.App/Assets/i18n/mn.json
+++ b/src/Filee.App/Assets/i18n/mn.json
@@ -111,6 +111,7 @@
"error.p7m_unknown_content": "Энэ .p7m доторх файл нь Filee хөрвүүлдэггүй төрлийн файл байна",
"error.udf_not_uyap": "Энэ .udf файл UYAP баримт биш. Хэрэв дискний дүрс (Universal Disk Format) бол «Задлах»-аар нээнэ үү",
"error.chart_template_unsupported": "Filee энэ төрлийн диаграмыг одоогоор зурахгүй (радар, бөмбөлөг, хувьцаа, гадаргуу, бялуугийн багана эсвэл хүрхрээ, модон зураглал зэрэг шинэ төрөл)",
+ "error.djvu_indirect": "Энэ бол шууд бус DjVu баримт: хуудсууд нь тусдаа файлууд. DjVu үзэгч дээр нэг файл болгон нэгтгээд (жишээ нь DjView: багцаар хадгалах), дараа нь тэр файлыг хөрвүүлнэ үү",
"error.p7m_too_large": "Гарын үсэгтэй файл нээхэд хэт том байна",
"error.document_too_large": "Энэ баримт нь задлахад хэт их өгөгдөлтэй эсвэл аюулгүй нээхэд хэт гүн давхарлагдсан байна",
"format_request.request": "Энэ форматыг хүсэх",
@@ -202,6 +203,12 @@
"notice.cmyk_needs_ghostscript": "Энэ файл CMYK боловч RGB хэлбэрээр хадгалагдлаа: CMYK хэвээр хадгалахын тулд Тохиргоо → Хөдөлгүүрүүд хэсгээс Ghostscript суулгана уу",
"notice.pdfa_needs_ghostscript": "Энэ PDF нь PDF/A биш байна: PDF/A болгохын тулд Тохиргоо → Хөдөлгүүрүүд хэсгээс Ghostscript суулгана уу",
"notice.pdfa_form_fields": "PDF/A болголоо: маягтын талбаруудыг цаашид бөглөх боломжгүй",
+ "pdfa.reason.font_not_embedded": "ашигласан фонт шингээгдээгүй байна",
+ "pdfa.reason.cmyk": "CMYK өнгийг хөрвүүлэх шаардлагатай",
+ "pdfa.reason.no_appearance": "тайлбар эсвэл маягтын талбарт өөрийн дүр төрх алга",
+ "pdfa.reason.unsupported": "PDF/A зөвшөөрдөггүй, Filee хасаж чадахгүй агуулга байна",
+ "pdfa.reason.unreadable": "Filee уншиж чадсангүй",
+ "pdfa.reason.locked": "нууц үгээр түгжигдсэн байна",
"notice.cmyk_render_failed": "Энэ файл CMYK боловч Ghostscript зурж чадсангүй тул RGB хэлбэрээр хадгаллаа",
"notice.original_kept": "Эх файлыг хэвээр үлдээж, үр дүнг хуулбар болгон хадгаллаа",
"notice.original_in_trash": "Эх файл Хогийн саванд орж, үр дүнгийн файл нэрийг нь авлаа",
@@ -286,12 +293,16 @@
"engine.docx-writer.description": "PDF, OFD, HWP/HWPX, Markdown, HTML, хүснэгт, слайд болон цахим номноос Word баримт (DOCX) бичнэ.",
"engine.odt-writer.name": "ODT бичигч (суурилагдсан)",
"engine.odt-writer.description": "Word баримт, PDF, OFD, HWP/HWPX, Markdown, HTML, хүснэгт, слайд болон цахим номноос OpenDocument текст (ODT, LibreOffice Writer) бичнэ.",
+ "engine.rtf-writer.name": "RTF бичигч (суурилуулсан)",
+ "engine.rtf-writer.description": "Word баримт, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, хүснэгт, слайд, цахим номоос Rich Text Format (RTF, Word болон WordPad-д) файл бичнэ.",
"engine.markup.name": "Тэмдэглэгээний хэлүүд (суурилагдсан)",
"engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org болон DocBook-ийг Pandoc-гүйгээр.\nБаримтыг эдгээр формат руу, эдгээрийг Markdown, HTML, текст, DOCX, HWPX болон PDF руу.\nМөн FreeMind / Freeplane болон XMind оюун ухааны газрын зургийг тойм хэлбэрээр уншина.",
"engine.pptx-writer.name": "PPTX бичигч (суурилагдсан)",
"engine.pptx-writer.description": "Markdown болон тэмдэглэгээний файл, Word баримт, ODT, HWP/HWPX, HTML, хүснэгт болон цахим номноос PowerPoint слайд (PPTX) үүсгэнэ: гарчиг бүрт нэг слайд, жагсаалт, хүснэгт, зураг болон кодтой.",
"engine.odp-writer.name": "ODP бичигч (суурилагдсан)",
"engine.odp-writer.description": "LibreOffice-гүйгээр OpenDocument үзүүлэн (ODP) үүсгэнэ: PowerPoint үзүүлэнг (PPTX, PPT) дүрс, зураг, хүснэгт болон илтгэгчийн тэмдэглэлтэй нь, мөн Markdown болон тэмдэглэгээний файл, Word баримт, ODT, HWP/HWPX, HTML, хүснэгт болон цахим номыг гарчиг бүрт нэг слайдтайгаар.",
+ "engine.odf-variants.name": "OpenDocument загвар ба хавтгай XML файл (суурилагдсан)",
+ "engine.odf-variants.description": "LibreOffice-гүйгээр OpenDocument файлыг загвар (OTT, OTS, OTP, OTG) болон хавтгай XML файл (FODT, FODS, FODP, FODG) болгож, мөн буцааж хөрвүүлнэ; баримт бичиг бүтнээрээ хадгалагдана.",
"engine.pdf-text.name": "PDF текст (суурилагдсан)",
"engine.pdf-text.description": "PDF-ийн текстийг унших дарааллаар нь, мөн хоёр баганатай хуудаснаас гаргаж авна (сканнердсан файлд OCR хийхгүй).",
"engine.pdf-slides.name": "PDF слайд (суурилагдсан)",
@@ -320,6 +331,8 @@
"engine.gcode.description": "3D принтер болон CNC машины замыг (G-code) PDF, SVG, зураг руу, эсвэл слайсерын өөрийн урьдчилан харах зураг руу.",
"engine.drawing.name": "Зураг төсөл (суурилагдсан)",
"engine.drawing.description": "Visio зураг (VSDX) болон OpenDocument зургийг (ODG, FODG) Visio эсвэл LibreOffice-гүйгээр PDF, SVG болон PNG болгоно.\nМөн XPS болон OpenXPS баримт бичиг (.xps, .oxps).\nМөн Excel диаграмын загвар (.crtx).\nХуучин хоёртын Visio файлд (.vsd) LibreOffice хэрэгтэй хэвээр.",
+ "engine.djvu.name": "DjVu (суурилагдсан)",
+ "engine.djvu.description": "DjVu скан хийсэн ном, баримтыг (.djvu, .djv) далд текстээр нь хайж болох PDF болон хуудсуудын PNG, JPG, TIFF зураг болгоно.",
"engine.model3d.name": "3D загвар (суурилагдсан)",
"engine.model3d.description": "3D загварууд: GLB, glTF, STL, OBJ, 3MF болон PLY хоорондоо, FBX-ийг эдгээрийн аль руу ч хөрвүүлэх ба PNG урьдчилж харах зураг үүсгэнэ.",
"engine.image3d.name": "Зургийг 3D рельеф болгох (суурилагдсан)",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 14b2c4002..6c5b817cc 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "यो .p7m भित्रको फाइल Filee ले रूपान्तरण नगर्ने प्रकारको हो",
"error.udf_not_uyap": "यो .udf फाइल UYAP कागजात होइन। यो डिस्क इमेज (Universal Disk Format) हो भने «निकाल्नुहोस्» ले खोल्नुहोस्",
"error.chart_template_unsupported": "Filee ले अझै यस्तो चार्ट कोर्दैन (राडार, बबल, स्टक, सतह, पाईको बार, वा वाटरफल वा ट्रीम्याप जस्ता नयाँ प्रकार)",
+ "error.djvu_indirect": "यो अप्रत्यक्ष DjVu कागजात हो: यसका पानाहरू छुट्टाछुट्टै फाइल हुन्। यसलाई कुनै DjVu भ्युअरमा एउटै फाइलमा जोड्नुहोस् (जस्तै DjView: बन्डलको रूपमा सेभ), त्यसपछि त्यो फाइल रूपान्तरण गर्नुहोस्",
"error.p7m_too_large": "हस्ताक्षरित फाइल खोल्न धेरै ठूलो छ",
"error.document_too_large": "यो कागजात खोल्दा धेरै ठूलो डेटा बन्छ वा धेरै गहिरोसम्म नेस्ट गरिएको छ, त्यसैले सुरक्षित रूपमा खोल्न सकिँदैन",
"error.merge_paper_geometry": "पृष्ठको आकार, घुमाइ वा एकाइ मान्य छैन, त्यसैले यसलाई छानिएको कागजमा मिलाउन सकिँदैन",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "यो फाइल CMYK हो, तर RGB मा सेभ भयो: CMYK राख्न सेटिङहरू → इन्जिनहरूमा Ghostscript स्थापना गर्नुहोस्",
"notice.pdfa_needs_ghostscript": "यो PDF, PDF/A होइन: PDF/A बनाउन सेटिङहरू → इन्जिनहरूमा Ghostscript स्थापना गर्नुहोस्",
"notice.pdfa_form_fields": "PDF/A बनाइयो: फारमका फिल्डहरू अब भर्न सकिँदैन",
+ "pdfa.reason.font_not_embedded": "प्रयोग गरिएको एउटा फन्ट इम्बेड गरिएको छैन",
+ "pdfa.reason.cmyk": "यसका CMYK रङहरू रूपान्तरण गर्नुपर्छ",
+ "pdfa.reason.no_appearance": "कुनै टिप्पणी वा फारम फिल्डको आफ्नै रूप छैन",
+ "pdfa.reason.unsupported": "यसमा PDF/A ले अनुमति नदिने र Filee ले हटाउन नसक्ने सामग्री छ",
+ "pdfa.reason.unreadable": "Filee ले यसलाई पढ्न सकेन",
+ "pdfa.reason.locked": "यो पासवर्डले लक गरिएको छ",
"notice.cmyk_render_failed": "यो फाइल CMYK हो, तर Ghostscript ले यसलाई कोर्न सकेन, त्यसैले RGB मा सेभ भयो",
"notice.original_kept": "मूल फाइल राखियो, नतिजा प्रतिलिपिको रूपमा सुरक्षित भयो",
"notice.original_in_trash": "मूल फाइल रिसाइकल बिन / ट्र्यासमा छ, नतिजाले आफ्नै नाम राख्यो",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडसिट, स्लाइड र इ-पुस्तकबाट Word कागजातहरू (DOCX) लेख्छ।",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Word कागजात, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडसिट, स्लाइड र इ-पुस्तकबाट OpenDocument पाठ (ODT) लेख्छ।",
+ "engine.rtf-writer.name": "RTF लेखक (बिल्ट-इन)",
+ "engine.rtf-writer.description": "Word कागजात, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, स्प्रेडसिट, स्लाइड र ई-पुस्तकबाट रिच टेक्स्ट फर्म्याट (RTF, Word र WordPad का लागि) लेख्छ।",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Pandoc बिना Jupyter नोटबुक, OPML, Textile, MediaWiki, reStructuredText, Org र DocBook पढ्छ र लेख्छ।\nकागजातलाई यी ढाँचामा, र यिनलाई Markdown, HTML, पाठ, DOCX, HWPX र PDF मा रूपान्तरण गर्दछ।\nसाथै FreeMind / Freeplane र XMind माइन्ड म्याप, रूपरेखाका रूपमा पढिन्छ।",
"engine.pptx-writer.name": "PPTX लेखक (भित्री)",
"engine.pptx-writer.description": "Markdown र मार्कअप फाइल, Word कागजात, ODT, HWP/HWPX, HTML, स्प्रेडसिट र इ-पुस्तकबाट PowerPoint स्लाइड (PPTX) बनाउँछ: हरेक शीर्षकका लागि एउटा स्लाइड, सूची, तालिका, चित्र र कोडसहित।",
"engine.odp-writer.name": "ODP लेखक (भित्री)",
"engine.odp-writer.description": "LibreOffice बिना OpenDocument प्रस्तुतीकरण (ODP) बनाउँछ: PowerPoint स्लाइड (PPTX, PPT) तिनका आकृति, चित्र, तालिका र वक्ता टिप्पणीसहित, र Markdown तथा मार्कअप फाइल, Word कागजात, ODT, HWP/HWPX, HTML, स्प्रेडसिट र इ-पुस्तक, हरेक शीर्षकका लागि एउटा स्लाइड।",
+ "engine.odf-variants.name": "OpenDocument टेम्प्लेट र फ्ल्याट XML फाइलहरू (बिल्ट-इन)",
+ "engine.odf-variants.description": "LibreOffice बिना OpenDocument फाइलहरूलाई तिनका टेम्प्लेट (OTT, OTS, OTP, OTG) र फ्ल्याट XML फाइल (FODT, FODS, FODP, FODG) मा र फेरि उल्टो बदल्छ, पूरै कागजात जस्ताको तस्तै राख्दै।",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "पढ्ने क्रममा PDF को पाठ निकाल्छ, दुई-स्तम्भ पृष्ठहरूबाट पनि (स्क्यानका लागि OCR होइन)।",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "3D प्रिन्टर र CNC मेसिनका टूलपाथ (G-code) लाई PDF, SVG र चित्रमा, वा स्लाइसरकै पूर्वावलोकन।",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Visio रेखाचित्र (VSDX) र OpenDocument रेखाचित्र (ODG, FODG) बाट PDF, SVG र PNG, Visio वा LibreOffice बिना।\nXPS र OpenXPS कागजातहरू (.xps, .oxps) पनि।\nExcel चार्ट टेम्प्लेटहरू (.crtx) पनि।\nपुराना बाइनरी Visio फाइलहरू (.vsd) का लागि अझै LibreOffice चाहिन्छ।",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "DjVu स्क्यान गरिएका किताब र कागजात (.djvu, .djv) लाई लुकेको पाठ खोज्न मिल्ने PDF मा, र पानाहरूको PNG, JPG र TIFF तस्बिरमा।",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "थ्रीडी मोडलहरू: GLB, glTF, STL, OBJ, 3MF र PLY एकअर्कामा, FBX यीमध्ये कुनैमा पनि, र PNG पूर्वावलोकन।",
"engine.image3d.name": "चित्रबाट थ्रीडी रिलिफ (बिल्ट-इन)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 658fb1946..c36bb9c59 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "Plik w tym .p7m jest typu, którego Filee nie konwertuje",
"error.udf_not_uyap": "Ten plik .udf nie jest dokumentem UYAP. Jeśli to obraz dysku (Universal Disk Format), otwórz go poleceniem „Rozpakuj”",
"error.chart_template_unsupported": "Filee nie rysuje jeszcze tego rodzaju wykresu (radarowy, bąbelkowy, giełdowy, powierzchniowy, słupkowy kołowego lub nowszy typ, np. kaskadowy czy mapa drzewa)",
+ "error.djvu_indirect": "To pośredni dokument DjVu: jego strony są osobnymi plikami. Połącz go w jeden plik w przeglądarce DjVu (np. DjView: zapisz jako pakiet), a potem przekonwertuj ten plik",
"error.p7m_too_large": "Podpisany plik jest za duży, by go otworzyć",
"error.document_too_large": "Ten dokument rozpakowuje się do zbyt dużej ilości danych lub jest zagnieżdżony zbyt głęboko, by bezpiecznie go otworzyć",
"error.merge_paper_geometry": "Strona ma nieprawidłowy rozmiar, obrót lub jednostki i nie można jej dopasować do wybranego papieru",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Ten plik jest w CMYK, ale zapisano go w RGB: zainstaluj Ghostscript w Ustawienia → Silniki, aby zachować CMYK",
"notice.pdfa_needs_ghostscript": "Ten PDF nie jest w formacie PDF/A: zainstaluj Ghostscript w Ustawienia → Silniki, aby tworzyć PDF/A",
"notice.pdfa_form_fields": "Utworzono PDF/A: pól formularza nie można już wypełniać",
+ "pdfa.reason.font_not_embedded": "użyta czcionka nie jest osadzona",
+ "pdfa.reason.cmyk": "jego kolory CMYK trzeba by przekonwertować",
+ "pdfa.reason.no_appearance": "adnotacja lub pole formularza nie ma własnego wyglądu",
+ "pdfa.reason.unsupported": "zawiera treść niedozwoloną w PDF/A, której Filee nie może usunąć",
+ "pdfa.reason.unreadable": "Filee nie mógł go odczytać",
+ "pdfa.reason.locked": "jest chroniony hasłem",
"notice.cmyk_render_failed": "Ten plik jest w CMYK, ale Ghostscript nie mógł go narysować, więc zapisano go w RGB",
"notice.original_kept": "Oryginał został zachowany, wynik zapisano jako kopię",
"notice.original_in_trash": "Oryginał jest w Koszu, wynik zachował własną nazwę",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Zapisuje dokumenty Word (DOCX) z PDF, OFD, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Zapisuje dokumenty tekstowe OpenDocument (ODT) z dokumentów Word, PDF, OFD, HWP/HWPX, Markdown, HTML, arkuszy, slajdów i e-booków.",
+ "engine.rtf-writer.name": "Zapis RTF (wbudowany)",
+ "engine.rtf-writer.description": "Zapisuje pliki Rich Text Format (RTF, dla Worda i WordPada) z dokumentów Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, arkuszy kalkulacyjnych, slajdów i e-booków.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Notatniki Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org i DocBook bez Pandoc.\nDokumenty do tych formatów, a te do Markdown, HTML, tekstu, DOCX, HWPX i PDF.\nTakże mapy myśli FreeMind / Freeplane i XMind, czytane jako konspekt.",
"engine.pptx-writer.name": "Generator PPTX (wbudowany)",
"engine.pptx-writer.description": "Tworzy slajdy PowerPoint (PPTX) z plików Markdown i języków znaczników, dokumentów Word, ODT, HWP/HWPX, HTML, arkuszy i e-booków: slajd na każdy nagłówek, z listami, tabelami, obrazami i kodem.",
"engine.odp-writer.name": "Generator ODP (wbudowany)",
"engine.odp-writer.description": "Tworzy prezentacje OpenDocument (ODP) bez LibreOffice: slajdy PowerPoint (PPTX, PPT) z kształtami, obrazami, tabelami i notatkami oraz pliki Markdown i języków znaczników, dokumenty Word, ODT, HWP/HWPX, HTML, arkusze i e-booki, slajd na każdy nagłówek.",
+ "engine.odf-variants.name": "Szablony i płaskie pliki XML OpenDocument (wbudowane)",
+ "engine.odf-variants.description": "Zamienia pliki OpenDocument na ich szablony (OTT, OTS, OTP, OTG) i płaskie pliki XML (FODT, FODS, FODP, FODG) oraz z powrotem bez LibreOffice, zachowując cały dokument.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "Wyodrębnia tekst z PDF w kolejności czytania, także ze stron dwukolumnowych (bez OCR skanów).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Ścieżki drukarek 3D i maszyn CNC (G-code) do PDF, SVG i obrazów albo podgląd zapisany przez slicer.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Rysunki Visio (VSDX) i OpenDocument (ODG, FODG) do PDF, SVG i PNG, bez Visio i LibreOffice.\nTakże dokumenty XPS i OpenXPS (.xps, .oxps).\nTakże szablony wykresów Excela (.crtx).\nStare binarne pliki Visio (.vsd) nadal wymagają LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "Zeskanowane książki i dokumenty DjVu (.djvu, .djv) do PDF z przeszukiwalnym ukrytym tekstem oraz do obrazów stron PNG, JPG i TIFF.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą, FBX do każdego z nich oraz podgląd PNG.",
"engine.image3d.name": "Obrazy na płaskorzeźbę 3D (wbudowany)",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index 628fade4a..5fba661da 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "O arquivo dentro deste .p7m é de um tipo que o Filee não converte",
"error.udf_not_uyap": "Este arquivo .udf não é um documento do UYAP. Se for uma imagem de disco (Universal Disk Format), abra-o com “Extrair”",
"error.chart_template_unsupported": "O Filee ainda não desenha este tipo de gráfico (radar, bolhas, ações, superfície, barra de pizza ou um tipo mais novo como cascata ou mapa de árvore)",
+ "error.djvu_indirect": "Este é um documento DjVu indireto: as páginas são arquivos separados. Junte-o em um único arquivo em um visualizador DjVu (por exemplo DjView: salvar como agrupado) e converta esse arquivo",
"error.p7m_too_large": "O arquivo assinado é grande demais para abrir",
"error.document_too_large": "Este documento se descompacta em dados demais ou está aninhado fundo demais para ser aberto com segurança",
"error.merge_paper_geometry": "A página tem tamanho, rotação ou unidades inválidos e não pode ser ajustada ao papel selecionado",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Este arquivo é CMYK, mas foi salvo em RGB: instale o Ghostscript em Configurações → Motores para manter o CMYK",
"notice.pdfa_needs_ghostscript": "Este PDF não é PDF/A: instale o Ghostscript em Configurações → Motores para criar PDF/A",
"notice.pdfa_form_fields": "PDF/A criado: os campos do formulário não podem mais ser preenchidos",
+ "pdfa.reason.font_not_embedded": "uma fonte usada não está incorporada",
+ "pdfa.reason.cmyk": "as cores CMYK precisariam ser convertidas",
+ "pdfa.reason.no_appearance": "uma anotação ou campo de formulário não tem aparência própria",
+ "pdfa.reason.unsupported": "tem conteúdo que o PDF/A não permite e que o Filee não consegue remover",
+ "pdfa.reason.unreadable": "o Filee não conseguiu lê-lo",
+ "pdfa.reason.locked": "está protegido por senha",
"notice.cmyk_render_failed": "Este arquivo é CMYK, mas o Ghostscript não conseguiu desenhá-lo, então foi salvo em RGB",
"notice.original_kept": "O original foi mantido, o resultado foi salvo como cópia",
"notice.original_in_trash": "O original está na Lixeira, o resultado manteve o próprio nome",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Grava documentos do Word (DOCX) a partir de PDF, OFD, HWP/HWPX, Markdown, HTML, planilhas, slides e e-books.",
"engine.odt-writer.name": "Gerador ODT (mecanismo integrado)",
"engine.odt-writer.description": "Grava documentos de texto OpenDocument (ODT) a partir de documentos do Word, PDF, OFD, HWP/HWPX, Markdown, HTML, planilhas, slides e e-books.",
+ "engine.rtf-writer.name": "Gravador RTF (integrado)",
+ "engine.rtf-writer.description": "Grava documentos Rich Text Format (RTF, para Word e WordPad) a partir de documentos do Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, planilhas, slides e e-books.",
"engine.markup.name": "Linguagens de marcação (mecanismo integrado)",
"engine.markup.description": "Notebooks Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para esses formatos e eles para Markdown, HTML, texto, DOCX, HWPX e PDF.\nTambém mapas mentais do FreeMind / Freeplane e do XMind, lidos como tópicos.",
"engine.pptx-writer.name": "Gerador PPTX (mecanismo integrado)",
"engine.pptx-writer.description": "Cria slides do PowerPoint (PPTX) a partir de arquivos Markdown e de marcação, documentos do Word, ODT, HWP/HWPX, HTML, planilhas e e-books: um slide por título, com listas, tabelas, imagens e código.",
"engine.odp-writer.name": "Gerador ODP (mecanismo integrado)",
"engine.odp-writer.description": "Cria apresentações OpenDocument (ODP) sem o LibreOffice: slides do PowerPoint (PPTX, PPT) com formas, imagens, tabelas e anotações, e arquivos Markdown e de marcação, documentos do Word, ODT, HWP/HWPX, HTML, planilhas e e-books, um slide por título.",
+ "engine.odf-variants.name": "Modelos e arquivos XML planos do OpenDocument (integrado)",
+ "engine.odf-variants.description": "Converte arquivos OpenDocument em seus modelos (OTT, OTS, OTP, OTG) e arquivos XML planos (FODT, FODS, FODP, FODG), e vice-versa, sem LibreOffice, mantendo o documento inteiro.",
"engine.pdf-text.name": "Texto de PDF (mecanismo integrado)",
"engine.pdf-text.description": "Extrai o texto de PDFs na ordem de leitura, também de páginas em duas colunas (sem OCR para digitalizações).",
"engine.pdf-slides.name": "Slides de PDF (mecanismo integrado)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a prévia do fatiador.",
"engine.drawing.name": "Desenhos (mecanismo integrado)",
"engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nTambém modelos de gráfico do Excel (.crtx).\nArquivos binários antigos do Visio (.vsd) ainda precisam do LibreOffice.",
+ "engine.djvu.name": "DjVu (mecanismo integrado)",
+ "engine.djvu.description": "Livros e documentos digitalizados DjVu (.djvu, .djv) para PDF com o texto oculto pesquisável, e para imagens PNG, JPG e TIFF das páginas.",
"engine.model3d.name": "Modelos 3D (mecanismo integrado)",
"engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF e PLY entre si, FBX para qualquer um deles, e uma prévia em PNG.",
"engine.image3d.name": "Imagens para relevo 3D (mecanismo integrado)",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index 09302ed56..f1daab0c8 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "O ficheiro dentro deste .p7m é de um tipo que o Filee não converte",
"error.udf_not_uyap": "Este ficheiro .udf não é um documento do UYAP. Se for uma imagem de disco (Universal Disk Format), abra-o com «Extrair»",
"error.chart_template_unsupported": "O Filee ainda não desenha este tipo de gráfico (radar, bolhas, cotações, superfície, barra de circular ou um tipo mais recente como cascata ou mapa de árvore)",
+ "error.djvu_indirect": "Este é um documento DjVu indireto: as páginas são ficheiros separados. Junte-o num único ficheiro num visualizador DjVu (por exemplo DjView: guardar como agrupado) e converta esse ficheiro",
"error.p7m_too_large": "O ficheiro assinado é demasiado grande para abrir",
"error.document_too_large": "Este documento descomprime-se em demasiados dados ou está aninhado demasiado fundo para ser aberto em segurança",
"error.merge_paper_geometry": "A página tem um tamanho, uma rotação ou unidades inválidos e não pode ser ajustada ao papel selecionado",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Este ficheiro é CMYK, mas foi guardado em RGB: instala o Ghostscript em Definições → Motores para manter o CMYK",
"notice.pdfa_needs_ghostscript": "Este PDF não é PDF/A: instala o Ghostscript em Definições → Motores para criar PDF/A",
"notice.pdfa_form_fields": "PDF/A criado: os campos do formulário já não podem ser preenchidos",
+ "pdfa.reason.font_not_embedded": "um tipo de letra usado não está incorporado",
+ "pdfa.reason.cmyk": "as cores CMYK teriam de ser convertidas",
+ "pdfa.reason.no_appearance": "uma anotação ou campo de formulário não tem aparência própria",
+ "pdfa.reason.unsupported": "tem conteúdo que o PDF/A não permite e que o Filee não consegue remover",
+ "pdfa.reason.unreadable": "o Filee não o conseguiu ler",
+ "pdfa.reason.locked": "está protegido por palavra-passe",
"notice.cmyk_render_failed": "Este ficheiro é CMYK, mas o Ghostscript não o conseguiu desenhar, por isso foi guardado em RGB",
"notice.original_kept": "O original foi mantido e o resultado foi guardado como cópia",
"notice.original_in_trash": "O original está na Reciclagem ou no Lixo; o resultado manteve o seu próprio nome",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Cria documentos Word (DOCX) a partir de PDF, OFD, HWP/HWPX, Markdown, HTML, folhas de cálculo, diapositivos e livros digitais.",
"engine.odt-writer.name": "Gerador ODT (motor integrado)",
"engine.odt-writer.description": "Cria documentos de texto OpenDocument (ODT) a partir de documentos Word, PDF, OFD, HWP/HWPX, Markdown, HTML, folhas de cálculo, diapositivos e livros digitais.",
+ "engine.rtf-writer.name": "Escritor RTF (integrado)",
+ "engine.rtf-writer.description": "Escreve documentos Rich Text Format (RTF, para Word e WordPad) a partir de documentos do Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, folhas de cálculo, diapositivos e livros eletrónicos.",
"engine.markup.name": "Linguagens de marcação (motor integrado)",
"engine.markup.description": "Blocos de notas Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org e DocBook sem Pandoc.\nDocumentos para estes formatos e estes para Markdown, HTML, texto, DOCX, HWPX e PDF.\nTambém mapas mentais do FreeMind / Freeplane e do XMind, lidos como esquemas.",
"engine.pptx-writer.name": "Gerador PPTX (motor integrado)",
"engine.pptx-writer.description": "Cria diapositivos do PowerPoint (PPTX) a partir de ficheiros Markdown e de marcação, documentos Word, ODT, HWP/HWPX, HTML, folhas de cálculo e livros digitais: um diapositivo por título, com listas, tabelas, imagens e código.",
"engine.odp-writer.name": "Gerador ODP (motor integrado)",
"engine.odp-writer.description": "Cria apresentações OpenDocument (ODP) sem o LibreOffice: diapositivos do PowerPoint (PPTX, PPT) com formas, imagens, tabelas e notas, e ficheiros Markdown e de marcação, documentos Word, ODT, HWP/HWPX, HTML, folhas de cálculo e livros digitais, um diapositivo por título.",
+ "engine.odf-variants.name": "Modelos e ficheiros XML planos OpenDocument (integrado)",
+ "engine.odf-variants.description": "Converte ficheiros OpenDocument nos seus modelos (OTT, OTS, OTP, OTG) e em ficheiros XML planos (FODT, FODS, FODP, FODG), e vice-versa, sem LibreOffice, mantendo o documento inteiro.",
"engine.pdf-text.name": "Texto de PDF (motor integrado)",
"engine.pdf-text.description": "Extrai o texto de PDF pela ordem de leitura, incluindo páginas com duas colunas (sem OCR para digitalizações).",
"engine.pdf-slides.name": "Diapositivos de PDF (motor integrado)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a pré-visualização do fatiador.",
"engine.drawing.name": "Desenhos (motor integrado)",
"engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nTambém modelos de gráfico do Excel (.crtx).\nOs ficheiros binários antigos do Visio (.vsd) continuam a precisar do LibreOffice.",
+ "engine.djvu.name": "DjVu (motor integrado)",
+ "engine.djvu.description": "Livros e documentos digitalizados DjVu (.djvu, .djv) para PDF com o texto oculto pesquisável, e para imagens PNG, JPG e TIFF das páginas.",
"engine.model3d.name": "Modelos 3D (motor integrado)",
"engine.model3d.description": "Converte modelos 3D entre GLB, glTF, STL, OBJ, 3MF e PLY, de FBX para qualquer um destes formatos e para uma pré-visualização PNG.",
"engine.image3d.name": "Imagens para relevo 3D (motor integrado)",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index d74ffafdf..e681dc765 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "Файл внутри этого .p7m имеет тип, который Filee не конвертирует",
"error.udf_not_uyap": "Этот файл .udf не является документом UYAP. Если это образ диска (Universal Disk Format), откройте его командой «Распаковать»",
"error.chart_template_unsupported": "Filee пока не рисует такие диаграммы (лепестковые, пузырьковые, биржевые, поверхностные, вторичные линейчатые или новые типы, например каскадные и древовидные)",
+ "error.djvu_indirect": "Это непрямой (indirect) документ DjVu: его страницы — отдельные файлы. Соберите его в один файл в просмотрщике DjVu (например, DjView: «Сохранить как пакетный»), затем конвертируйте этот файл",
"error.p7m_too_large": "Подписанный файл слишком большой, чтобы его открыть",
"error.document_too_large": "Этот документ распаковывается в слишком большой объём данных или вложен слишком глубоко, чтобы его можно было безопасно открыть",
"error.merge_paper_geometry": "У страницы неверный размер, поворот или единицы измерения — её нельзя вписать в выбранный формат бумаги",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Это файл CMYK, но он сохранён в RGB: чтобы сохранить CMYK, установите Ghostscript в разделе Настройки → Движки",
"notice.pdfa_needs_ghostscript": "Этот PDF не в формате PDF/A: чтобы создавать PDF/A, установите Ghostscript в разделе Настройки → Движки",
"notice.pdfa_form_fields": "Создан PDF/A: поля формы больше нельзя заполнять",
+ "pdfa.reason.font_not_embedded": "использованный шрифт не встроен",
+ "pdfa.reason.cmyk": "его цвета CMYK нужно преобразовать",
+ "pdfa.reason.no_appearance": "у аннотации или поля формы нет собственного вида",
+ "pdfa.reason.unsupported": "в нём есть содержимое, запрещённое в PDF/A, которое Filee не может убрать",
+ "pdfa.reason.unreadable": "Filee не удалось его прочитать",
+ "pdfa.reason.locked": "он защищён паролем",
"notice.cmyk_render_failed": "Это файл CMYK, но Ghostscript не смог его отрисовать, поэтому он сохранён в RGB",
"notice.original_kept": "Оригинал оставлен, результат сохранён как копия",
"notice.original_in_trash": "Оригинал в Корзине, результат сохранил своё имя",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Создаёт документы Word (DOCX) из PDF, OFD, HWP/HWPX, Markdown, HTML, таблиц, презентаций и электронных книг.",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "Создаёт текстовые документы OpenDocument (ODT) из документов Word, PDF, OFD, HWP/HWPX, Markdown, HTML, таблиц, презентаций и электронных книг.",
+ "engine.rtf-writer.name": "Запись RTF (встроенная)",
+ "engine.rtf-writer.description": "Создаёт файлы Rich Text Format (RTF, для Word и WordPad) из документов Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, таблиц, слайдов и электронных книг.",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Блокноты Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org и DocBook без Pandoc.\nДокументы — в эти форматы, а их — в Markdown, HTML, текст, DOCX, HWPX и PDF.\nА также интеллект-карты FreeMind / Freeplane и XMind, читаемые как план.",
"engine.pptx-writer.name": "Генератор PPTX (встроенный)",
"engine.pptx-writer.description": "Создаёт слайды PowerPoint (PPTX) из файлов Markdown и разметки, документов Word, ODT, HWP/HWPX, HTML, таблиц и электронных книг: по слайду на каждый заголовок, со списками, таблицами, рисунками и кодом.",
"engine.odp-writer.name": "Генератор ODP (встроенный)",
"engine.odp-writer.description": "Создаёт презентации OpenDocument (ODP) без LibreOffice: слайды PowerPoint (PPTX, PPT) с фигурами, рисунками, таблицами и заметками, а также файлы Markdown и разметки, документы Word, ODT, HWP/HWPX, HTML, таблицы и электронные книги — по слайду на каждый заголовок.",
+ "engine.odf-variants.name": "Шаблоны и плоские XML-файлы OpenDocument (встроено)",
+ "engine.odf-variants.description": "Превращает файлы OpenDocument в шаблоны (OTT, OTS, OTP, OTG) и плоские XML-файлы (FODT, FODS, FODP, FODG) и обратно без LibreOffice, сохраняя документ целиком.",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "Достаёт текст из PDF в порядке чтения, в том числе со страниц в две колонки (сканы не распознаются).",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Траектории 3D-принтеров и станков с ЧПУ (G-code) в PDF, SVG и изображения или превью слайсера.",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "Схемы Visio (VSDX) и рисунки OpenDocument (ODG, FODG) — в PDF, SVG и PNG без Visio и LibreOffice.\nА также документы XPS и OpenXPS (.xps, .oxps).\nА также шаблоны диаграмм Excel (.crtx).\nДля старых двоичных файлов Visio (.vsd) по-прежнему нужен LibreOffice.",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "Отсканированные книги и документы DjVu (.djvu, .djv) в PDF с поиском по скрытому тексту, а также в изображения страниц PNG, JPG и TIFF.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D-модели: GLB, glTF, STL, OBJ, 3MF и PLY друг в друга, FBX — в любой из них, плюс превью в PNG.",
"engine.image3d.name": "Изображения в 3D-рельеф (встроенный)",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index 338a98ec3..a7afef2bf 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "ไฟล์ใน .p7m นี้เป็นชนิดที่ Filee ไม่แปลง",
"error.udf_not_uyap": "ไฟล์ .udf นี้ไม่ใช่เอกสาร UYAP หากเป็นอิมเมจดิสก์ (Universal Disk Format) ให้เปิดด้วย “แตกไฟล์”",
"error.chart_template_unsupported": "Filee ยังวาดแผนภูมิชนิดนี้ไม่ได้ (เรดาร์ ฟอง หุ้น พื้นผิว แท่งของวงกลม หรือชนิดใหม่อย่างน้ำตกหรือทรีแมป)",
+ "error.djvu_indirect": "นี่คือเอกสาร DjVu แบบแยกไฟล์ (indirect): แต่ละหน้าเป็นไฟล์แยกกัน โปรดรวมเป็นไฟล์เดียวในโปรแกรมดู DjVu (เช่น DjView: บันทึกแบบรวม) แล้วจึงแปลงไฟล์นั้น",
"error.p7m_too_large": "ไฟล์ที่ลงนามใหญ่เกินกว่าจะเปิดได้",
"error.document_too_large": "เอกสารนี้แตกออกเป็นข้อมูลมากเกินไปหรือซ้อนกันลึกเกินไป จึงเปิดอย่างปลอดภัยไม่ได้",
"format_request.request": "ขอให้รองรับฟอร์แมตนี้",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "ไฟล์นี้เป็น CMYK แต่บันทึกเป็น RGB: ติดตั้ง Ghostscript ในการตั้งค่า → เครื่องมือแปลงไฟล์ เพื่อคง CMYK ไว้",
"notice.pdfa_needs_ghostscript": "PDF นี้ไม่ใช่ PDF/A: ติดตั้ง Ghostscript ในการตั้งค่า → เครื่องมือแปลงไฟล์ เพื่อสร้าง PDF/A",
"notice.pdfa_form_fields": "สร้าง PDF/A แล้ว: ไม่สามารถกรอกช่องแบบฟอร์มได้อีก",
+ "pdfa.reason.font_not_embedded": "ฟอนต์ที่ใช้ไม่ได้ฝังอยู่ในไฟล์",
+ "pdfa.reason.cmyk": "ต้องแปลงสี CMYK ในไฟล์",
+ "pdfa.reason.no_appearance": "คำอธิบายประกอบหรือช่องฟอร์มไม่มีลักษณะที่แสดงของตัวเอง",
+ "pdfa.reason.unsupported": "มีเนื้อหาที่ PDF/A ไม่อนุญาตและ Filee เอาออกไม่ได้",
+ "pdfa.reason.unreadable": "Filee อ่านไฟล์นี้ไม่ได้",
+ "pdfa.reason.locked": "ไฟล์ถูกล็อกด้วยรหัสผ่าน",
"notice.cmyk_render_failed": "ไฟล์นี้เป็น CMYK แต่ Ghostscript วาดไม่ได้ จึงบันทึกเป็น RGB",
"notice.original_kept": "เก็บไฟล์ต้นฉบับไว้ และบันทึกผลลัพธ์เป็นสำเนา",
"notice.original_in_trash": "ไฟล์ต้นฉบับอยู่ในถังขยะ ผลลัพธ์ยังใช้ชื่อของตัวเอง",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "เขียนเอกสาร Word (DOCX) จาก PDF, OFD, HWP/HWPX, Markdown, HTML, สเปรดชีต, สไลด์ และอีบุ๊ก",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "เขียนเอกสารข้อความ OpenDocument (ODT) จากเอกสาร Word, PDF, OFD, HWP/HWPX, Markdown, HTML, สเปรดชีต, สไลด์ และอีบุ๊ก",
+ "engine.rtf-writer.name": "ตัวเขียน RTF (ในตัว)",
+ "engine.rtf-writer.description": "เขียนไฟล์ Rich Text Format (RTF สำหรับ Word และ WordPad) จากเอกสาร Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, สเปรดชีต, สไลด์ และอีบุ๊ก",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "Jupyter notebook, OPML, Textile, MediaWiki, reStructuredText, Org และ DocBook โดยไม่ต้องใช้ Pandoc\nแปลงเอกสารเป็นรูปแบบเหล่านี้ และแปลงรูปแบบเหล่านี้เป็น Markdown, HTML, ข้อความ, DOCX, HWPX และ PDF\nรวมถึงแผนผังความคิดของ FreeMind / Freeplane และ XMind ซึ่งอ่านเป็นโครงร่าง",
"engine.pptx-writer.name": "ตัวเขียน PPTX (ในตัว)",
"engine.pptx-writer.description": "สร้างสไลด์ PowerPoint (PPTX) จากไฟล์ Markdown และภาษามาร์กอัป เอกสาร Word, ODT, HWP/HWPX, HTML, สเปรดชีต และอีบุ๊ก: หนึ่งสไลด์ต่อหนึ่งหัวข้อ พร้อมรายการ ตาราง รูปภาพ และโค้ด",
"engine.odp-writer.name": "ตัวเขียน ODP (ในตัว)",
"engine.odp-writer.description": "สร้างงานนำเสนอ OpenDocument (ODP) โดยไม่ต้องใช้ LibreOffice: สไลด์ PowerPoint (PPTX, PPT) พร้อมรูปร่าง รูปภาพ ตาราง และบันทึกผู้บรรยาย รวมถึงไฟล์ Markdown และภาษามาร์กอัป เอกสาร Word, ODT, HWP/HWPX, HTML, สเปรดชีต และอีบุ๊ก โดยหนึ่งสไลด์ต่อหนึ่งหัวข้อ",
+ "engine.odf-variants.name": "เทมเพลตและไฟล์ XML แบบแบน OpenDocument (ในตัว)",
+ "engine.odf-variants.description": "แปลงไฟล์ OpenDocument เป็นเทมเพลต (OTT, OTS, OTP, OTG) และไฟล์ XML แบบแบน (FODT, FODS, FODP, FODG) และแปลงกลับได้โดยไม่ต้องใช้ LibreOffice โดยเก็บเอกสารไว้ครบถ้วน",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "แยกข้อความของ PDF ตามลำดับการอ่าน รวมถึงหน้าที่มีสองคอลัมน์ (ไม่มี OCR สำหรับเอกสารสแกน)",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "เส้นทางของเครื่องพิมพ์ 3 มิติและเครื่อง CNC (G-code) เป็น PDF, SVG และรูปภาพ หรือภาพตัวอย่างของสไลเซอร์",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "แปลงไดอะแกรม Visio (VSDX) และภาพวาด OpenDocument (ODG, FODG) เป็น PDF, SVG และ PNG โดยไม่ต้องใช้ Visio หรือ LibreOffice\nรวมถึงเอกสาร XPS และ OpenXPS (.xps, .oxps)\nรวมถึงเทมเพลตแผนภูมิ Excel (.crtx)\nไฟล์ Visio แบบไบนารีรุ่นเก่า (.vsd) ยังต้องใช้ LibreOffice",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "แปลงหนังสือและเอกสารสแกน DjVu (.djvu, .djv) เป็น PDF ที่ค้นหาข้อความแฝงได้ และเป็นภาพ PNG, JPG, TIFF ของแต่ละหน้า",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "โมเดล 3D: GLB, glTF, STL, OBJ, 3MF และ PLY สลับกันได้ FBX เป็นฟอร์แมตใดก็ได้ และแสดงตัวอย่างเป็น PNG",
"engine.image3d.name": "รูปภาพเป็นภาพนูน 3D (ในตัว)",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 999ce28b5..1ef2abbd7 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -112,6 +112,7 @@
"error.p7m_unknown_content": "Bu .p7m içindeki dosya, Filee'nin dönüştürmediği bir türde",
"error.udf_not_uyap": "Bu .udf dosyası bir UYAP belgesi değil. Bir disk görüntüsüyse (Universal Disk Format), açmak için Arşivi aç'ı kullanın",
"error.chart_template_unsupported": "Filee bu tür grafiği henüz çizmiyor (radar, kabarcık, hisse senedi, yüzey, pastanın çubuğu ya da şelale veya ağaç haritası gibi yeni bir tür)",
+ "error.djvu_indirect": "Bu dolaylı bir DjVu belgesi: sayfaları ayrı dosyalar. Bir DjVu görüntüleyicide tek dosyada birleştirin (örneğin DjView: paketlenmiş olarak kaydet), ardından o dosyayı dönüştürün",
"error.p7m_too_large": "İmzalı dosya açılamayacak kadar büyük",
"error.document_too_large": "Bu belge açıldığında çok fazla veriye dönüşüyor ya da çok derin iç içe geçmiş, güvenle açılamıyor",
"format_request.request": "Bu biçimi talep et",
@@ -203,6 +204,12 @@
"notice.cmyk_needs_ghostscript": "Bu dosya CMYK ama RGB olarak kaydedildi: CMYK'yı korumak için Ayarlar → Dönüştürme motorları'ndan Ghostscript'i yükleyin",
"notice.pdfa_needs_ghostscript": "Bu PDF, PDF/A değil: PDF/A oluşturmak için Ayarlar → Dönüştürme motorları'ndan Ghostscript'i yükleyin",
"notice.pdfa_form_fields": "PDF/A oluşturuldu: form alanları artık doldurulamaz",
+ "pdfa.reason.font_not_embedded": "kullanılan bir yazı tipi gömülü değil",
+ "pdfa.reason.cmyk": "CMYK renklerinin dönüştürülmesi gerekiyor",
+ "pdfa.reason.no_appearance": "bir açıklamanın ya da form alanının kendi görünümü yok",
+ "pdfa.reason.unsupported": "PDF/A'nın izin vermediği ve Filee'nin çıkaramadığı içerik var",
+ "pdfa.reason.unreadable": "Filee dosyayı okuyamadı",
+ "pdfa.reason.locked": "parolayla korunuyor",
"notice.cmyk_render_failed": "Bu dosya CMYK ama Ghostscript onu çizemedi, bu yüzden RGB olarak kaydedildi",
"notice.original_kept": "Özgün dosya korundu, sonuç kopya olarak kaydedildi",
"notice.original_in_trash": "Özgün dosya Geri Dönüşüm Kutusu'nda / Çöp Sepeti'nde; sonuç kendi adını korudu",
@@ -287,12 +294,16 @@
"engine.docx-writer.description": "PDF, OFD, HWP/HWPX, Markdown, HTML, elektronik tablo, slayt ve e-kitaplardan Word belgesi (DOCX) oluşturur.",
"engine.odt-writer.name": "ODT oluşturucu (yerleşik)",
"engine.odt-writer.description": "Word belgeleri, PDF, OFD, HWP/HWPX, Markdown, HTML, elektronik tablo, slayt ve e-kitaplardan OpenDocument metin belgesi (ODT) oluşturur.",
+ "engine.rtf-writer.name": "RTF yazıcı (yerleşik)",
+ "engine.rtf-writer.description": "Word belgeleri, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, elektronik tablolar, slaytlar ve e-kitaplardan Zengin Metin Biçimi (RTF, Word ve WordPad için) yazar.",
"engine.markup.name": "İşaretleme dilleri (yerleşik)",
"engine.markup.description": "Pandoc olmadan Jupyter not defterleri, OPML, Textile, MediaWiki, reStructuredText, Org ve DocBook.\nBelgeleri bu biçimlere, bunları da Markdown, HTML, metin, DOCX, HWPX ve PDF'ye dönüştürür.\nAyrıca FreeMind / Freeplane ve XMind zihin haritaları, ana hat olarak okunur.",
"engine.pptx-writer.name": "PPTX oluşturucu (yerleşik)",
"engine.pptx-writer.description": "Markdown ve işaretleme dosyaları, Word belgeleri, ODT, HWP/HWPX, HTML, elektronik tablolar ve e-kitaplardan PowerPoint slaytları (PPTX) oluşturur: her başlık için bir slayt; listeler, tablolar, resimler ve kod dahil.",
"engine.odp-writer.name": "ODP oluşturucu (yerleşik)",
"engine.odp-writer.description": "LibreOffice olmadan OpenDocument sunuları (ODP) oluşturur: PowerPoint slaytlarını (PPTX, PPT) şekilleri, resimleri, tabloları ve konuşmacı notlarıyla; Markdown ve işaretleme dosyalarını, Word belgelerini, ODT, HWP/HWPX, HTML, elektronik tabloları ve e-kitapları her başlık için bir slaytla.",
+ "engine.odf-variants.name": "OpenDocument şablonları ve düz XML dosyaları (yerleşik)",
+ "engine.odf-variants.description": "OpenDocument dosyalarını LibreOffice olmadan şablonlarına (OTT, OTS, OTP, OTG) ve düz XML dosyalarına (FODT, FODS, FODP, FODG) dönüştürür ve geri çevirir; belgenin tamamı korunur.",
"engine.pdf-text.name": "PDF metin (yerleşik)",
"engine.pdf-text.description": "İki sütunlu sayfalar dahil PDF metnini okuma sırasıyla çıkarır (taramalar için OCR yoktur).",
"engine.pdf-slides.name": "PDF slayt (yerleşik)",
@@ -321,6 +332,8 @@
"engine.gcode.description": "3B yazıcıların ve CNC makinelerinin takım yolları (G-code) PDF, SVG ve resme, ya da dilimleyicinin kendi önizlemesi.",
"engine.drawing.name": "Çizimler (yerleşik)",
"engine.drawing.description": "Visio çizimleri (VSDX) ve OpenDocument çizimleri (ODG, FODG) → PDF, SVG ve PNG; Visio veya LibreOffice gerekmez.\nXPS ve OpenXPS belgeleri (.xps, .oxps) de.\nExcel grafik şablonları (.crtx) da.\nEski ikili Visio dosyaları (.vsd) için hâlâ LibreOffice gerekir.",
+ "engine.djvu.name": "DjVu (yerleşik)",
+ "engine.djvu.description": "Taranmış DjVu kitap ve belgelerini (.djvu, .djv) gizli metni aranabilir PDF'ye ve sayfaların PNG, JPG ve TIFF resimlerine dönüştürür.",
"engine.model3d.name": "3B modeller (yerleşik)",
"engine.model3d.description": "3B modeller: GLB, glTF, STL, OBJ, 3MF ve PLY arasında dönüştürme; FBX'ten bunların tümüne ve PNG önizlemesine dönüştürme.",
"engine.image3d.name": "Resimden 3B kabartma (yerleşik)",
diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json
index 360b5f07d..3d90a3359 100644
--- a/src/Filee.App/Assets/i18n/vi.json
+++ b/src/Filee.App/Assets/i18n/vi.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "Tệp bên trong .p7m này thuộc loại Filee không chuyển đổi",
"error.udf_not_uyap": "Tệp .udf này không phải tài liệu UYAP. Nếu đây là ảnh đĩa (Universal Disk Format), hãy mở bằng “Giải nén”",
"error.chart_template_unsupported": "Filee chưa vẽ được loại biểu đồ này (radar, bong bóng, chứng khoán, bề mặt, thanh của hình tròn hoặc loại mới như thác nước hay bản đồ dạng cây)",
+ "error.djvu_indirect": "Đây là tài liệu DjVu gián tiếp: các trang là những tệp riêng. Hãy gộp thành một tệp trong trình xem DjVu (ví dụ DjView: lưu dạng gộp), rồi chuyển đổi tệp đó",
"error.p7m_too_large": "Tệp đã ký quá lớn để mở",
"error.document_too_large": "Tài liệu này giải nén ra quá nhiều dữ liệu hoặc lồng nhau quá sâu nên không thể mở an toàn",
"format_request.request": "Yêu cầu định dạng này",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "Tệp này là CMYK nhưng đã được lưu dưới dạng RGB: hãy cài Ghostscript trong Cài đặt → Bộ xử lý để giữ CMYK",
"notice.pdfa_needs_ghostscript": "Tệp PDF này không phải PDF/A: hãy cài Ghostscript trong Cài đặt → Bộ xử lý để tạo PDF/A",
"notice.pdfa_form_fields": "Đã tạo PDF/A: không thể điền các trường biểu mẫu nữa",
+ "pdfa.reason.font_not_embedded": "một phông chữ được dùng chưa được nhúng",
+ "pdfa.reason.cmyk": "cần chuyển đổi màu CMYK của tệp",
+ "pdfa.reason.no_appearance": "một chú thích hoặc trường biểu mẫu không có hình thức riêng",
+ "pdfa.reason.unsupported": "tệp có nội dung PDF/A không cho phép mà Filee không thể gỡ bỏ",
+ "pdfa.reason.unreadable": "Filee không đọc được tệp",
+ "pdfa.reason.locked": "tệp được khóa bằng mật khẩu",
"notice.cmyk_render_failed": "Tệp này là CMYK, nhưng Ghostscript không vẽ được nên đã lưu dưới dạng RGB",
"notice.original_kept": "Bản gốc được giữ lại, kết quả được lưu thành bản sao",
"notice.original_in_trash": "Bản gốc đã ở trong Thùng rác, kết quả giữ tên riêng của nó",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "Ghi tài liệu Word (DOCX) từ PDF, OFD, HWP/HWPX, Markdown, HTML, bảng tính, trang chiếu và sách điện tử.",
"engine.odt-writer.name": "Trình ghi ODT (tích hợp)",
"engine.odt-writer.description": "Ghi văn bản OpenDocument (ODT, LibreOffice Writer) từ tài liệu Word, PDF, OFD, HWP/HWPX, Markdown, HTML, bảng tính, trang chiếu và sách điện tử.",
+ "engine.rtf-writer.name": "Trình ghi RTF (tích hợp)",
+ "engine.rtf-writer.description": "Ghi tệp Rich Text Format (RTF, cho Word và WordPad) từ tài liệu Word, ODT, PDF, OFD, HWP/HWPX, Markdown, HTML, bảng tính, trang chiếu và sách điện tử.",
"engine.markup.name": "Ngôn ngữ đánh dấu (tích hợp)",
"engine.markup.description": "Sổ tay Jupyter, OPML, Textile, MediaWiki, reStructuredText, Org và DocBook mà không cần Pandoc.\nTài liệu sang các định dạng này, và các định dạng này sang Markdown, HTML, văn bản, DOCX, HWPX và PDF.\nCả sơ đồ tư duy FreeMind / Freeplane và XMind, được đọc dưới dạng dàn ý.",
"engine.pptx-writer.name": "Trình ghi PPTX (tích hợp)",
"engine.pptx-writer.description": "Tạo trang chiếu PowerPoint (PPTX) từ tệp Markdown và tệp đánh dấu, tài liệu Word, ODT, HWP/HWPX, HTML, bảng tính và sách điện tử: mỗi tiêu đề một trang chiếu, kèm danh sách, bảng, hình ảnh và mã.",
"engine.odp-writer.name": "Trình ghi ODP (tích hợp)",
"engine.odp-writer.description": "Tạo bản trình bày OpenDocument (ODP) không cần LibreOffice: trang chiếu PowerPoint (PPTX, PPT) kèm hình vẽ, hình ảnh, bảng và ghi chú, cùng tệp Markdown và tệp đánh dấu, tài liệu Word, ODT, HWP/HWPX, HTML, bảng tính và sách điện tử với mỗi tiêu đề một trang chiếu.",
+ "engine.odf-variants.name": "Mẫu và tệp XML phẳng OpenDocument (tích hợp)",
+ "engine.odf-variants.description": "Chuyển tệp OpenDocument thành mẫu (OTT, OTS, OTP, OTG) và tệp XML phẳng (FODT, FODS, FODP, FODG) và ngược lại mà không cần LibreOffice, giữ nguyên toàn bộ tài liệu.",
"engine.pdf-text.name": "Văn bản PDF (tích hợp)",
"engine.pdf-text.description": "Trích xuất văn bản của PDF theo thứ tự đọc, kể cả trang hai cột (không OCR cho bản quét).",
"engine.pdf-slides.name": "Trang chiếu PDF (tích hợp)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "Đường chạy của máy in 3D và máy CNC (G-code) sang PDF, SVG và ảnh, hoặc ảnh xem trước của slicer.",
"engine.drawing.name": "Bản vẽ (tích hợp)",
"engine.drawing.description": "Bản vẽ Visio (VSDX) và bản vẽ OpenDocument (ODG, FODG) sang PDF, SVG và PNG, không cần Visio hay LibreOffice.\nCả tài liệu XPS và OpenXPS (.xps, .oxps).\nCả mẫu biểu đồ Excel (.crtx).\nTệp Visio nhị phân cũ (.vsd) vẫn cần LibreOffice.",
+ "engine.djvu.name": "DjVu (tích hợp)",
+ "engine.djvu.description": "Sách và tài liệu quét DjVu (.djvu, .djv) sang PDF tìm kiếm được văn bản ẩn, và sang ảnh PNG, JPG, TIFF của từng trang.",
"engine.model3d.name": "Mô hình 3D (tích hợp)",
"engine.model3d.description": "Mô hình 3D: GLB, glTF, STL, OBJ, 3MF và PLY chuyển đổi qua lại, FBX sang bất kỳ định dạng nào trong số đó, và ảnh xem trước PNG.",
"engine.image3d.name": "Ảnh sang phù điêu 3D (tích hợp)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index ecfbb5bd7..7f88f735c 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "这个 .p7m 中的文件是 Filee 不转换的类型",
"error.udf_not_uyap": "这个 .udf 文件不是 UYAP 文档。如果它是光盘映像(Universal Disk Format),请用“解压”打开",
"error.chart_template_unsupported": "暂不支持绘制此类图表(雷达图、气泡图、股价图、曲面图、复合条饼图,或瀑布图、树状图等新图表类型)",
+ "error.djvu_indirect": "这是间接 DjVu 文档:各页是单独的文件。请先在 DjVu 阅读器中将其合并为一个文件(例如 DjView:另存为捆绑文档),再转换该文件",
"error.p7m_too_large": "已签名的文件太大,无法打开",
"error.document_too_large": "此文档解压后数据过多或嵌套过深,无法安全打开",
"format_request.request": "请求支持此格式",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "这是 CMYK 文件,但保存成了 RGB:要保留 CMYK,请在 设置 → 转换引擎 中安装 Ghostscript",
"notice.pdfa_needs_ghostscript": "这个 PDF 不是 PDF/A:要生成 PDF/A,请在 设置 → 转换引擎 中安装 Ghostscript",
"notice.pdfa_form_fields": "已生成 PDF/A:表单字段不能再填写",
+ "pdfa.reason.font_not_embedded": "使用的字体没有嵌入",
+ "pdfa.reason.cmyk": "需要转换其中的 CMYK 颜色",
+ "pdfa.reason.no_appearance": "某个注释或表单域没有自己的外观",
+ "pdfa.reason.unsupported": "其中有 PDF/A 不允许、Filee 又无法去掉的内容",
+ "pdfa.reason.unreadable": "Filee 无法读取该文件",
+ "pdfa.reason.locked": "该文件受密码保护",
"notice.cmyk_render_failed": "这是 CMYK 文件,但 Ghostscript 无法绘制,所以保存成了 RGB",
"notice.original_kept": "已保留原文件,结果另存为副本",
"notice.original_in_trash": "原文件已在回收站/废纸篓中,结果保留了自己的名称",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "用 PDF、OFD、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 Word 文档(DOCX)。",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "用 Word 文档、PDF、OFD、HWP/HWPX、Markdown、HTML、表格、幻灯片和电子书生成 OpenDocument 文本(ODT)。",
+ "engine.rtf-writer.name": "RTF 写入器(内置)",
+ "engine.rtf-writer.description": "从 Word 文档、ODT、PDF、OFD、HWP/HWPX、Markdown、HTML、电子表格、幻灯片和电子书写出 RTF 富文本(供 Word 和写字板使用)。",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "无需 Pandoc 即可读写 Jupyter 笔记本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文档转为这些格式,也把它们转为 Markdown、HTML、文本、DOCX、HWPX 和 PDF。\n还可把 FreeMind / Freeplane 和 XMind 思维导图读成大纲。",
"engine.pptx-writer.name": "PPTX 生成器(内置)",
"engine.pptx-writer.description": "用 Markdown 和标记语言文件、Word 文档、ODT、HWP/HWPX、HTML、表格和电子书生成 PowerPoint 幻灯片(PPTX):每个标题一张幻灯片,包含列表、表格、图片和代码。",
"engine.odp-writer.name": "ODP 生成器(内置)",
"engine.odp-writer.description": "无需 LibreOffice 即可生成 OpenDocument 演示文稿(ODP):PowerPoint 幻灯片(PPTX、PPT)连同形状、图片、表格和演讲者备注一并转换;Markdown 和标记语言文件、Word 文档、ODT、HWP/HWPX、HTML、表格和电子书则每个标题一张幻灯片。",
+ "engine.odf-variants.name": "OpenDocument 模板和平面 XML 文件(内置)",
+ "engine.odf-variants.description": "无需 LibreOffice,即可将 OpenDocument 文件转换为模板(OTT、OTS、OTP、OTG)和平面 XML 文件(FODT、FODS、FODP、FODG),也可反向转换,文档内容完整保留。",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "按阅读顺序提取 PDF 中的文字,双栏页面也能正确排序(不对扫描件做文字识别)。",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "将 3D 打印机和 CNC 机床的刀路 (G-code) 转为 PDF、SVG 和图片,或使用切片软件保存的预览图。",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "将 Visio 图表(VSDX)和 OpenDocument 绘图(ODG、FODG)转为 PDF、SVG 和 PNG,无需 Visio 或 LibreOffice。\n也支持 XPS 和 OpenXPS 文档(.xps、.oxps)。\n也支持 Excel 图表模板(.crtx)。\n旧的二进制 Visio 文件(.vsd)仍需 LibreOffice。",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "将 DjVu 扫描书籍和文档(.djvu、.djv)转换为可搜索隐藏文字的 PDF,以及页面的 PNG、JPG、TIFF 图片。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,FBX 可转换为其中任意格式,并可生成 PNG 预览。",
"engine.image3d.name": "图片转 3D 浮雕(内置)",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index d53a7df1e..9ba5feda1 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -118,6 +118,7 @@
"error.p7m_unknown_content": "這個 .p7m 中的檔案是 Filee 不轉換的類型",
"error.udf_not_uyap": "這個 .udf 檔案不是 UYAP 文件。如果它是光碟映像(Universal Disk Format),請用「解壓縮」開啟",
"error.chart_template_unsupported": "暫不支援繪製此類圖表(雷達圖、泡泡圖、股票圖、曲面圖、子母長條圖,或瀑布圖、矩形式樹狀結構圖等新圖表類型)",
+ "error.djvu_indirect": "這是間接 DjVu 文件:各頁是個別的檔案。請先在 DjVu 檢視器中將其合併為一個檔案(例如 DjView:另存為綑綁文件),再轉換該檔案",
"error.p7m_too_large": "已簽署的檔案太大,無法開啟",
"error.document_too_large": "此文件解壓縮後資料過多或巢狀層級過深,無法安全開啟",
"format_request.request": "請求支援此格式",
@@ -209,6 +210,12 @@
"notice.cmyk_needs_ghostscript": "這是 CMYK 檔案,但儲存成了 RGB:要保留 CMYK,請在「設定 → 轉換引擎」中安裝 Ghostscript",
"notice.pdfa_needs_ghostscript": "這個 PDF 不是 PDF/A:要產生 PDF/A,請在「設定 → 轉換引擎」中安裝 Ghostscript",
"notice.pdfa_form_fields": "已產生 PDF/A:表單欄位無法再填寫",
+ "pdfa.reason.font_not_embedded": "使用的字型沒有內嵌",
+ "pdfa.reason.cmyk": "需要轉換其中的 CMYK 色彩",
+ "pdfa.reason.no_appearance": "某個註解或表單欄位沒有自己的外觀",
+ "pdfa.reason.unsupported": "其中有 PDF/A 不允許、Filee 又無法移除的內容",
+ "pdfa.reason.unreadable": "Filee 無法讀取這個檔案",
+ "pdfa.reason.locked": "這個檔案受密碼保護",
"notice.cmyk_render_failed": "這是 CMYK 檔案,但 Ghostscript 無法繪製,所以儲存成了 RGB",
"notice.original_kept": "已保留原始檔案,結果另存為副本",
"notice.original_in_trash": "原始檔案已在資源回收筒/垃圾桶中,結果保留了自己的名稱",
@@ -294,12 +301,16 @@
"engine.docx-writer.description": "用 PDF、OFD、HWP/HWPX、Markdown、HTML、表格、投影片和電子書產生 Word 文件(DOCX)。",
"engine.odt-writer.name": "ODT writer (built-in)",
"engine.odt-writer.description": "用 Word 文件、PDF、OFD、HWP/HWPX、Markdown、HTML、表格、投影片和電子書產生 OpenDocument 文字文件(ODT)。",
+ "engine.rtf-writer.name": "RTF 寫入器(內建)",
+ "engine.rtf-writer.description": "從 Word 文件、ODT、PDF、OFD、HWP/HWPX、Markdown、HTML、試算表、投影片和電子書寫出 RTF 豐富文字(供 Word 和 WordPad 使用)。",
"engine.markup.name": "Markup languages (built-in)",
"engine.markup.description": "不需 Pandoc 即可讀寫 Jupyter 筆記本、OPML、Textile、MediaWiki、reStructuredText、Org 和 DocBook。\n把文件轉為這些格式,也把它們轉為 Markdown、HTML、文字、DOCX、HWPX 和 PDF。\n也能把 FreeMind / Freeplane 和 XMind 心智圖讀成大綱。",
"engine.pptx-writer.name": "PPTX 產生器(內建)",
"engine.pptx-writer.description": "用 Markdown 和標記語言檔案、Word 文件、ODT、HWP/HWPX、HTML、表格和電子書產生 PowerPoint 投影片(PPTX):每個標題一張投影片,包含清單、表格、圖片和程式碼。",
"engine.odp-writer.name": "ODP 產生器(內建)",
"engine.odp-writer.description": "不需 LibreOffice 即可產生 OpenDocument 簡報(ODP):PowerPoint 投影片(PPTX、PPT)連同圖形、圖片、表格和演講者備忘稿一併轉換;Markdown 和標記語言檔案、Word 文件、ODT、HWP/HWPX、HTML、表格和電子書則每個標題一張投影片。",
+ "engine.odf-variants.name": "OpenDocument 範本與平面 XML 檔案(內建)",
+ "engine.odf-variants.description": "不需 LibreOffice,即可將 OpenDocument 檔案轉換為範本(OTT、OTS、OTP、OTG)與平面 XML 檔案(FODT、FODS、FODP、FODG),也能反向轉換,文件內容完整保留。",
"engine.pdf-text.name": "PDF text (built-in)",
"engine.pdf-text.description": "按閱讀順序擷取 PDF 中的文字,雙欄頁面也能正確排序(不對掃描檔做文字辨識)。",
"engine.pdf-slides.name": "PDF slides (built-in)",
@@ -328,6 +339,8 @@
"engine.gcode.description": "將 3D 印表機和 CNC 機台的刀具路徑 (G-code) 轉為 PDF、SVG 和圖片,或使用切片軟體儲存的預覽圖。",
"engine.drawing.name": "Drawings (built-in)",
"engine.drawing.description": "將 Visio 圖表(VSDX)和 OpenDocument 繪圖(ODG、FODG)轉為 PDF、SVG 和 PNG,不需 Visio 或 LibreOffice。\n也支援 XPS 和 OpenXPS 文件(.xps、.oxps)。\n也支援 Excel 圖表範本(.crtx)。\n舊的二進位 Visio 檔案(.vsd)仍需 LibreOffice。",
+ "engine.djvu.name": "DjVu (built-in)",
+ "engine.djvu.description": "將 DjVu 掃描書籍與文件(.djvu、.djv)轉換為可搜尋隱藏文字的 PDF,以及頁面的 PNG、JPG、TIFF 圖片。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相轉換,FBX 可轉換為其中任意格式,並可產生 PNG 預覽。",
"engine.image3d.name": "圖片轉 3D 浮雕(內建)",
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
index 4558bd8d7..8133a62ee 100644
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -314,9 +314,10 @@ bool Joinable(RoutePlanner planner) => formats.Any(f => preset.Media.Slideshow
: new(PresetUse.Unusable, _loc["error.no_route"]);
}
- // PDF/A of PDFs is Ghostscript's (the job queue's IPdfArchiver): without it they would only be copied. Other files
- // may get it from LibreOffice, or are converted with a notice that the PDF isn't PDF/A.
- static bool Archives(RoutePlanner planner) => planner.Includes("ghostscript");
+ // PDF/A of PDFs is the job queue's IPdfArchiver: the PDF engine's own, with Ghostscript for what that one can't
+ // make conform. With neither they would only be copied. Other files may get it from their engine (the Filee
+ // renderer, LibreOffice), or are converted with a notice that the PDF isn't PDF/A.
+ static bool Archives(RoutePlanner planner) => planner.Includes("pdfsharp") || planner.Includes("ghostscript");
if (preset.TargetFormat == "pdf" && preset.Document.PdfA && formats.All(f => f.Id == "pdf") && !Archives(installedPlanner()))
{
return packageEnabling(Archives) is { } archiver
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 30f3c877b..2049abc72 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -334,9 +334,10 @@ public interface IPdfFinisher
}
///
-/// Makes a finished PDF a PDF/A (). Implemented by the Ghostscript engine;
-/// runs it after the finishing on every PDF a job writes, whichever engine made it, and on a
-/// merged PDF once, so the box means the same for every route.
+/// Makes a finished PDF a PDF/A (). Implemented by the PDF engine (built in)
+/// and the Ghostscript engine; runs them after the finishing on every PDF a job writes,
+/// whichever engine made it, and on a merged PDF once, so the box means the same for every route. They are tried in
+/// engine order until one makes the PDF PDF/A.
///
public interface IPdfArchiver
{
@@ -346,6 +347,8 @@ public interface IPdfArchiver
///
/// What it did; when it can't (Ghostscript isn't installed):
/// the PDF is left as it is.
+ /// This PDF can't be made to conform here (its error key says why);
+ /// the PDF is left as it is and the next archiver gets it.
Task ArchiveAsync(string path, bool changed, string workDirectory, CancellationToken cancellationToken);
}
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 78321a207..d7da9750e 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -274,8 +274,10 @@ private async Task FinishPdfsAsync(Preset preset, IReadOnlyList outputs,
///
/// Makes the PDFs among PDF/A when the preset asks for it (),
- /// after the finishing, which would undo it. Without Ghostscript they stay as they are and the file says so, rather
- /// than pass for PDF/A. Otherwise the file says when form fields were made page content, which can't be filled in.
+ /// after the finishing, which would undo it. The archivers are tried in engine order (the built-in one before
+ /// Ghostscript): one that refuses a PDF hands it to the next. A PDF none made PDF/A stays as it is and the file says
+ /// so, with why the built-in one refused it, rather than pass for PDF/A. Otherwise the file says when form fields
+ /// were made page content, which can't be filled in.
///
/// Rewritten since the engine wrote it: a PDF/A from LibreOffice no longer is one.
private async Task ArchivePdfsAsync(Preset preset, IReadOnlyList outputs, FileResult file, string workDir, bool changed,
@@ -283,18 +285,42 @@ private async Task ArchivePdfsAsync(Preset preset, IReadOnlyList outputs
{
if (!preset.Document.PdfA)
return;
- var archiver = _catalog.All.OfType().FirstOrDefault();
+ var archivers = _catalog.Ordered.OfType().ToList();
var notArchived = false;
+ string? refusal = null;
var withoutFormFields = false;
foreach (var pdf in outputs.Where(o => FormatRegistry.Detect(o)?.Id == "pdf"))
{
- var outcome = archiver is null ? PdfArchiveOutcome.NotArchived : await archiver.ArchiveAsync(pdf, changed, workDir, ct);
- notArchived |= outcome == PdfArchiveOutcome.NotArchived;
+ var outcome = PdfArchiveOutcome.NotArchived;
+ string? why = null;
+ foreach (var archiver in archivers)
+ {
+ try
+ {
+ outcome = await archiver.ArchiveAsync(pdf, changed, workDir, ct);
+ }
+ catch (ConversionRefusedException refused)
+ {
+ why ??= refused.ErrorKey;
+ continue;
+ }
+ if (outcome != PdfArchiveOutcome.NotArchived)
+ break;
+ }
+ if (outcome == PdfArchiveOutcome.NotArchived)
+ {
+ notArchived = true;
+ refusal ??= why;
+ }
withoutFormFields |= outcome == PdfArchiveOutcome.ArchivedWithoutFormFields;
}
// A PDF that didn't become PDF/A matters more than fields that can't be filled in any more.
if (notArchived)
+ {
file.NoticeKey = "notice.pdfa_needs_ghostscript";
+ file.NoticeReasonKey = refusal;
+ file.NoticeDetail = null;
+ }
else if (withoutFormFields)
{
file.NoticeKey = "notice.pdfa_form_fields";
diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs
index dcff6d3e5..738903f4e 100644
--- a/src/Filee.Core/Formats/FormatFields.cs
+++ b/src/Filee.Core/Formats/FormatFields.cs
@@ -64,8 +64,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow
]),
(FormatGrade.General,
[
- "tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "canvas", "crtx",
- "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "mm", "xmind", "abw", "pages", "pub", "eml", "msg",
+ "tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "otg", "canvas", "crtx",
+ "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "djvu", "mm", "xmind", "abw", "pages", "pub", "eml", "msg",
"p7m", "xlsm", "xltx", "xlsb", "xls", "ods", "ots", "tsv", "et", "numbers", "pptm", "potx", "potm", "ppsx", "ppt",
"odp", "otp", "key", "dps", "md", "html", "mhtml", "opml", "json", "xml", "vcf", "ics", "epub", "kepub",
"azw3", "fb2", "cbz", "cbr", "cb7", "cbt", "cbc", "m4v", "mkv", "webm", "avi", "wmv", "mpg", "ts",
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index 5f21d3c48..15a129b32 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -94,10 +94,12 @@ public static class FormatRegistry
// Tajima embroidery designs: the stitches drawn as lines (issue #397).
new("dst", "DST", FormatCategory.Vector, ["dst"], Writable: false),
new("odg", "ODG", FormatCategory.Vector, ["odg"]),
+ // OpenDocument drawing templates: the ODG package with the template media type.
+ new("otg", "OTG", FormatCategory.Vector, ["otg"]),
// Obsidian's visual boards (JSON Canvas 1.0): cards, groups and the lines between them, read by Filee itself and
// drawn as SVG (then PDF and pictures), or their text as Markdown. A .canvas that isn't one is refused.
new("canvas", "Obsidian Canvas", FormatCategory.Vector, ["canvas"], Writable: false),
- new("fodg", "FODG", FormatCategory.Vector, ["fodg"], Writable: false),
+ new("fodg", "FODG", FormatCategory.Vector, ["fodg"]),
// Excel chart templates (#1354): the chart drawn by the drawing engine (PDF, SVG, PNG), sample values where the
// template holds none, as Excel's template preview shows it.
new("crtx", "CRTX", FormatCategory.Vector, ["crtx"], Writable: false),
@@ -124,6 +126,8 @@ public static class FormatRegistry
new("udf", "UYAP (UDF)", FormatCategory.Document, ["udf"], Writable: false),
// XPS and OpenXPS (ECMA-388) fixed-layout documents (#613), read by the built-in XPS reader (drawing engine).
new("xps", "XPS", FormatCategory.Document, ["xps", "oxps"], Writable: false),
+ // DjVu scanned books and documents (#346), one page or bundled, read by the built-in DjVu reader.
+ new("djvu", "DjVu", FormatCategory.Document, ["djvu", "djv"], Writable: false),
// Mind maps (#1543, #1004), read by Filee itself as an outline: topics as headings and lists, notes under them (the
// map isn't drawn). A .mm that isn't XML is Objective-C++ source, read as plain text.
new("mm", "FreeMind / Freeplane (MM)", FormatCategory.Document, ["mm"], Writable: false),
@@ -158,7 +162,7 @@ public static class FormatRegistry
new("xlt", "XLT", FormatCategory.Spreadsheet, ["xlt"]),
new("ods", "ODS", FormatCategory.Spreadsheet, ["ods"]),
new("ots", "OTS", FormatCategory.Spreadsheet, ["ots"]),
- new("fods", "FODS", FormatCategory.Spreadsheet, ["fods"], Writable: false),
+ new("fods", "FODS", FormatCategory.Spreadsheet, ["fods"]),
new("csv", "CSV", FormatCategory.Spreadsheet, ["csv"]),
new("tsv", "TSV", FormatCategory.Spreadsheet, ["tsv", "tab"]),
new("et", "ET", FormatCategory.Spreadsheet, ["et"], Writable: false),
@@ -174,7 +178,7 @@ public static class FormatRegistry
new("ppt", "PPT", FormatCategory.Presentation, ["ppt", "pps", "pot"]),
new("odp", "ODP", FormatCategory.Presentation, ["odp"]),
new("otp", "OTP", FormatCategory.Presentation, ["otp"]),
- new("fodp", "FODP", FormatCategory.Presentation, ["fodp"], Writable: false),
+ new("fodp", "FODP", FormatCategory.Presentation, ["fodp"]),
new("key", "Keynote", FormatCategory.Presentation, ["key"], Writable: false),
new("dps", "DPS", FormatCategory.Presentation, ["dps"], Writable: false),
new("sda", "SDA", FormatCategory.Presentation, ["sda", "sdd"], Writable: false),
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 1984d1bb1..e149598b2 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -170,7 +170,7 @@ public static bool IsFlipKeyAllowed(string key, IEnumerable gest
public sealed class AppSettings
{
/// Current schema version. Increase when the format changes and add a migration.
- public const int CurrentSchemaVersion = 109;
+ public const int CurrentSchemaVersion = 112;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 51cd46eaa..ebd85355a 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -1236,6 +1236,12 @@ public static bool ApplyToLibrary(int from, List presets, ListUnpacks BZZ streams.
+internal static class BzzDecoder
+{
+ /// Largest block the format allows.
+ private const int MaxBlock = 4096 * 1024;
+
+ private const int FrequencyCount = 4;
+ private const int ContextIds = 3;
+
+ /// Unpacks ; refuses one that unpacks to more than .
+ public static byte[] Decode(byte[] data, long maxBytes, CancellationToken cancellationToken = default) =>
+ Decode(data, 0, data.Length, maxBytes, cancellationToken);
+
+ public static byte[] Decode(byte[] data, int offset, int count, long maxBytes, CancellationToken cancellationToken = default)
+ {
+ var zp = new ZpDecoder(data, offset, count);
+ var contexts = new byte[300];
+ using var output = new MemoryStream();
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var size = DecodeRaw(zp, 24);
+ if (size == 0)
+ break;
+ if (size > MaxBlock)
+ throw new InvalidDataException("A BZZ block is larger than the format allows.");
+ if (output.Length + size - 1 > maxBytes)
+ throw Documents.DocumentLimits.Exceeded($"A compressed part of the DjVu file unpacks to more than {Documents.DocumentLimits.Megabytes(maxBytes)}.");
+ var block = DecodeBlock(zp, contexts, size, cancellationToken);
+ output.Write(block);
+ }
+ return output.ToArray();
+ }
+
+ private static int DecodeRaw(ZpDecoder zp, int bits)
+ {
+ var n = 1;
+ var m = 1 << bits;
+ while (n < m)
+ n = (n << 1) | zp.DecodeRaw();
+ return n - m;
+ }
+
+ /// A binary number of bits, a context per node of its tree from .
+ private static int DecodeBinary(ZpDecoder zp, byte[] contexts, int first, int bits)
+ {
+ var n = 1;
+ var m = 1 << bits;
+ while (n < m)
+ n = (n << 1) | zp.Decode(ref contexts[first + n - 1]);
+ return n - m;
+ }
+
+ /// One block, its marker removed and the transform undone.
+ private static byte[] DecodeBlock(ZpDecoder zp, byte[] contexts, int size, CancellationToken cancellationToken)
+ {
+ var data = new byte[size];
+ var fshift = 0;
+ if (zp.DecodeRaw() != 0)
+ {
+ fshift++;
+ if (zp.DecodeRaw() != 0)
+ fshift++;
+ }
+ var mtf = new byte[256];
+ for (var i = 0; i < 256; i++)
+ mtf[i] = (byte)i;
+ var freq = new uint[FrequencyCount];
+ uint fadd = 4;
+ var mtfno = 3;
+ var marker = -1;
+ for (var i = 0; i < size; i++)
+ {
+ if ((i & 0xFFFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var ctxid = Math.Min(ContextIds - 1, mtfno);
+ if (zp.Decode(ref contexts[ctxid]) != 0)
+ mtfno = 0;
+ else if (zp.Decode(ref contexts[ContextIds + ctxid]) != 0)
+ mtfno = 1;
+ else
+ {
+ mtfno = -1;
+ // Ranks 2-3, 4-7, ... 128-255: a flag, then the rank's low bits as a binary number.
+ var at = 2 * ContextIds;
+ for (var bits = 1; bits <= 7; bits++)
+ {
+ if (zp.Decode(ref contexts[at]) != 0)
+ {
+ mtfno = (1 << bits) + DecodeBinary(zp, contexts, at + 1, bits);
+ break;
+ }
+ at += 1 << bits;
+ }
+ if (mtfno < 0)
+ {
+ mtfno = 256;
+ if (marker >= 0)
+ throw new InvalidDataException("A BZZ block has two end markers.");
+ marker = i;
+ continue;
+ }
+ }
+ var c = mtf[mtfno];
+ data[i] = c;
+ // The rank list is ordered by how often each byte came lately, not strictly move-to-front.
+ fadd += fadd >> fshift;
+ if (fadd > 0x10000000)
+ {
+ fadd >>= 24;
+ for (var k = 0; k < FrequencyCount; k++)
+ freq[k] >>= 24;
+ }
+ var fc = fadd;
+ if (mtfno < FrequencyCount)
+ fc += freq[mtfno];
+ int at2;
+ for (at2 = mtfno; at2 >= FrequencyCount; at2--)
+ mtf[at2] = mtf[at2 - 1];
+ for (; at2 > 0 && fc >= freq[at2 - 1]; at2--)
+ {
+ mtf[at2] = mtf[at2 - 1];
+ freq[at2] = freq[at2 - 1];
+ }
+ mtf[at2] = c;
+ freq[at2] = fc;
+ }
+ if (marker < 1 || marker >= size)
+ throw new InvalidDataException("A BZZ block's end marker is missing or misplaced.");
+ return Untransform(data, size, marker);
+ }
+
+ /// Undoes the Burrows-Wheeler transform of a block whose marker is at .
+ private static byte[] Untransform(byte[] data, int size, int marker)
+ {
+ var position = new int[size];
+ var count = new int[256];
+ for (var i = 0; i < size; i++)
+ {
+ if (i == marker)
+ continue;
+ var c = data[i];
+ position[i] = (c << 24) | (count[c] & 0xFFFFFF);
+ count[c]++;
+ }
+ // Row 0 is the rotation that starts with the marker, which sorts before every byte.
+ var last = 1;
+ for (var i = 0; i < 256; i++)
+ {
+ var n = count[i];
+ count[i] = last;
+ last += n;
+ }
+ var result = new byte[size - 1];
+ var row = 0;
+ for (var at = size - 2; at >= 0; at--)
+ {
+ var n = position[row];
+ var c = (byte)((uint)n >> 24);
+ result[at] = c;
+ row = count[c] + (n & 0xFFFFFF);
+ if ((uint)row >= (uint)size)
+ throw new InvalidDataException("A BZZ block is damaged.");
+ }
+ if (row != marker)
+ throw new InvalidDataException("A BZZ block is damaged.");
+ return result;
+ }
+}
diff --git a/src/Filee.Engines/Djvu/DjvuConverter.cs b/src/Filee.Engines/Djvu/DjvuConverter.cs
new file mode 100644
index 000000000..fcdf0ebfa
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuConverter.cs
@@ -0,0 +1,135 @@
+// Filee's own DjVu reader (engine id "djvu", #346): DjVu documents (.djvu, .djv; one page or bundled) to PDF — every
+// page at its size, the layers kept (DjvuPdfWriter), the hidden text searchable — and pictures of the pages (PNG, JPEG,
+// TIFF; the PDF options' page range, the pages' own resolution, then the image options; TIFF holds all pages in one
+// file). Layers Filee doesn't decode are named in the file's result (ConversionStep.LeftOut).
+
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Magick;
+using Filee.Engines.Ocr;
+using ImageMagick;
+
+namespace Filee.Engines.Djvu;
+
+/// DjVu → PDF and pictures.
+public sealed class DjvuConverter : IConverter, IImageTransformer
+{
+ /// The picture formats pages are written to.
+ internal static readonly string[] PictureTargets = ["png", "jpg", "tiff"];
+
+ public string Id => "djvu";
+ public string DisplayName => "DjVu (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList Edges { get; } =
+ [
+ new ConversionEdge("djvu", "pdf"),
+ .. PictureTargets.Select(target => ImageEncoder.Edge("djvu", target)),
+ ];
+
+ /// Pictures of pages are written here, with the image options (turn, mirror, size) applied.
+ public bool Transforms(string from, string to) => to != "pdf";
+
+ public EngineStatus GetStatus() => EngineStatus.Available(version: EngineVersions.BuiltIn);
+
+ public Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) =>
+ Task.Run>(() =>
+ {
+ using var document = DjvuDocument.Open(step.InputPath, cancellationToken: cancellationToken);
+ var written = step.To == "pdf"
+ ? WritePdf(step, document, progress, cancellationToken)
+ : WritePictures(step, document, progress, cancellationToken);
+ if (document.LeftOut > 0)
+ step.LeftOut?.Invoke(new LeftOutNotice("notice.renderer_left_out", [new LeftOutPart("notice.renderer_left_out.pictures", document.LeftOut)]));
+ return written;
+ }, cancellationToken);
+
+ private static List WritePdf(ConversionStep step, DjvuDocument document, IProgress? progress, CancellationToken cancellationToken)
+ {
+ using var writer = new OcrPdfWriter();
+ for (var i = 0; i < document.Count; i++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ DjvuPdfWriter.AddPage(writer, document.ReadPage(i, cancellationToken), cancellationToken);
+ progress?.Report(0.95 * (i + 1) / document.Count);
+ }
+ if (step.Output.Allocate("pdf") is not { } target)
+ return [];
+ writer.Save(target);
+ progress?.Report(1);
+ return [target];
+ }
+
+ private static List WritePictures(ConversionStep step, DjvuDocument document, IProgress? progress, CancellationToken cancellationToken)
+ {
+ var pages = PageRange.Parse(step.Preset.Pdf.PageRange, document.Count);
+ var (_, extension) = ImageEncoder.OutputFormat(step.To, step.Preset.Image);
+ var written = new List();
+ var collected = new List>();
+ try
+ {
+ var done = 0;
+ foreach (var index in pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var image = Picture(document.ReadPage(index, cancellationToken), cancellationToken);
+ ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);
+ if (step.To == "tiff")
+ {
+ collected.Add(image);
+ }
+ else
+ {
+ using (image)
+ {
+ if (step.Output.Allocate(extension, pages.Count > 1 ? $"_p{index + 1}" : null) is { } path)
+ {
+ ImageEncoder.WriteImage(image, path, step.To);
+ written.Add(path);
+ }
+ }
+ }
+ done++;
+ progress?.Report(0.95 * done / pages.Count);
+ }
+ if (collected.Count > 0)
+ written.AddRange(ImageEncoder.Write(collected, step.To, step.Output, step.Preset.Image));
+ }
+ finally
+ {
+ foreach (var image in collected)
+ image.Dispose();
+ }
+ progress?.Report(1);
+ return written;
+ }
+
+ /// A page drawn at its own resolution, turned as its INFO says; grey when it has no colour.
+ internal static MagickImage Picture(DjvuPage page, CancellationToken cancellationToken)
+ {
+ var rgb = DjvuRenderer.Compose(page, cancellationToken);
+ var grey = true;
+ for (var i = 0; i < rgb.Length && grey; i += 3)
+ grey = rgb[i] == rgb[i + 1] && rgb[i] == rgb[i + 2];
+ MagickImage image;
+ if (grey)
+ {
+ // One channel, read as a PGM: a third of the memory of a colour picture.
+ var header = System.Text.Encoding.ASCII.GetBytes($"P5\n{page.Width} {page.Height}\n255\n");
+ var pgm = new byte[header.Length + (long)page.Width * page.Height];
+ header.CopyTo(pgm, 0);
+ for (long i = 0, o = header.Length; o < pgm.Length; i += 3, o++)
+ pgm[o] = rgb[i];
+ image = new MagickImage(pgm, MagickFormat.Pgm);
+ }
+ else
+ {
+ image = new MagickImage();
+ image.ReadPixels(rgb, new PixelReadSettings((uint)page.Width, (uint)page.Height, StorageType.Char, PixelMapping.RGB));
+ }
+ image.Density = new Density(page.Dpi, page.Dpi, DensityUnit.PixelsPerInch);
+ if (page.Rotation != 0)
+ image.Rotate(-90 * page.Rotation);
+ return image;
+ }
+}
diff --git a/src/Filee.Engines/Djvu/DjvuDocument.cs b/src/Filee.Engines/Djvu/DjvuDocument.cs
new file mode 100644
index 000000000..e7faeaab6
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuDocument.cs
@@ -0,0 +1,460 @@
+// A DjVu document (DjVu v3 specification): an IFF85 file ("AT&T" then a FORM chunk) holding one page (FORM:DJVU) or a
+// bundled document (FORM:DJVM): a directory (DIRM) of components at offsets in the file — pages (FORM:DJVU), files
+// pages include (FORM:DJVI: shared shape dictionaries, annotations) and thumbnails (FORM:THUM). An indirect document,
+// whose directory names separate files, is refused with error.djvu_indirect.
+//
+// A page is read when asked for: INFO (size, resolution, rotation), the mask (Sjbz, with the shape dictionary Djbz of
+// the page or of a file it includes with INCL), the background (BG44 chunks, or BGjp), the foreground colours (FG44 or
+// FGjp, or the palette FGbz) and the hidden text (TXTz / TXTa). Layers Filee doesn't decode (Smmr masks, JPEG 2000
+// BG2k / FG2k) are counted as pictures left out. Chunks are read one at a time, never more than DjvuLimits.MaxChunkBytes.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Engines.Documents;
+using SkiaSharp;
+
+namespace Filee.Engines.Djvu;
+
+/// A page's foreground palette: its colours and the colour of each blit of the mask.
+internal sealed record DjvuPalette(SKColor[] Colors, int[]? BlitColors);
+
+/// One decoded page.
+internal sealed class DjvuPage
+{
+ public required int Width { get; init; }
+ public required int Height { get; init; }
+ public required int Dpi { get; init; }
+
+ /// Quarter turns counter-clockwise the page is shown with (INFO's orientation).
+ public int Rotation { get; init; }
+
+ public Jb2Image? Mask { get; init; }
+ public DjvuPixmap? Background { get; init; }
+ public DjvuPixmap? Foreground { get; init; }
+ public DjvuPalette? Palette { get; init; }
+ public IReadOnlyList Text { get; init; } = [];
+
+ /// Layers of the page Filee couldn't decode.
+ public int LeftOut { get; init; }
+}
+
+/// An open DjVu file.
+internal sealed class DjvuDocument : IDisposable
+{
+ /// The error key of an indirect document (pages in separate files).
+ public const string IndirectKey = "error.djvu_indirect";
+
+ private sealed record Chunk(string Id, long Offset, int Size);
+
+ private sealed class Component(string id, long offset, long end, string kind)
+ {
+ public string Id { get; } = id;
+ public long Offset { get; } = offset;
+ public long End { get; } = end;
+ public string Kind { get; } = kind;
+ public List? Chunks { get; set; }
+ }
+
+ private readonly FileStream _file;
+ private readonly DjvuLimits _limits;
+ private readonly List _pages = [];
+ private readonly Dictionary _byId = new(StringComparer.Ordinal);
+ private readonly Dictionary _dictionaries = new(StringComparer.Ordinal);
+ private int _leftOut;
+
+ private DjvuDocument(FileStream file, DjvuLimits limits)
+ {
+ _file = file;
+ _limits = limits;
+ }
+
+ public int Count => _pages.Count;
+
+ /// Layers left out of the pages read so far.
+ public int LeftOut => _leftOut;
+
+ /// Opens ; refuses a file that isn't a DjVu document Filee reads.
+ public static DjvuDocument Open(string path, DjvuLimits? limits = null, CancellationToken cancellationToken = default)
+ {
+ var file = File.OpenRead(path);
+ var document = new DjvuDocument(file, limits ?? DjvuLimits.Default);
+ try
+ {
+ document.ReadStructure(cancellationToken);
+ return document;
+ }
+ catch
+ {
+ document.Dispose();
+ throw;
+ }
+ }
+
+ public void Dispose() => _file.Dispose();
+
+ private void ReadStructure(CancellationToken cancellationToken)
+ {
+ var start = 0L;
+ var magic = ReadBytes(0, Math.Min(4, (int)_file.Length));
+ if (magic.Length == 4 && magic.AsSpan().SequenceEqual("AT&T"u8))
+ start = 4;
+ var (kind, end) = ReadForm(start) ?? throw new InvalidDataException("The file isn't a DjVu document.");
+ switch (kind)
+ {
+ case "DJVU":
+ _pages.Add(new Component("", start, end, kind));
+ break;
+ case "DJVM":
+ ReadBundle(start, end, cancellationToken);
+ break;
+ case "DJVI":
+ throw new InvalidDataException("The file is a part DjVu pages include, not a document.");
+ default:
+ throw new InvalidDataException($"The DjVu file holds a {kind} form, not pages Filee reads.");
+ }
+ if (_pages.Count == 0)
+ throw new InvalidDataException("The DjVu document has no pages.");
+ }
+
+ /// The kind and end of a FORM chunk at , or null when there is none.
+ private (string Kind, long End)? ReadForm(long offset)
+ {
+ if (offset < 0 || offset + 12 > _file.Length)
+ return null;
+ var header = ReadBytes(offset, 12);
+ if (!header.AsSpan(0, 4).SequenceEqual("FORM"u8))
+ return null;
+ var size = ((long)header[4] << 24) | ((long)header[5] << 16) | ((long)header[6] << 8) | header[7];
+ if (size < 4)
+ return null;
+ // A file cut short keeps the pages it still holds.
+ var end = Math.Min(offset + 8 + size, _file.Length);
+ return (Encoding.ASCII.GetString(header, 8, 4), end);
+ }
+
+ /// The chunks inside a form (from its data after the kind to its end).
+ private List ListChunks(long offset, long end, CancellationToken cancellationToken)
+ {
+ var chunks = new List();
+ var at = offset + 12;
+ var header = new byte[8];
+ while (at + 8 <= end)
+ {
+ if ((chunks.Count & 0xFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ _file.Position = at;
+ _file.ReadExactly(header);
+ var size = ((long)header[4] << 24) | ((long)header[5] << 16) | ((long)header[6] << 8) | header[7];
+ var data = at + 8;
+ if (data + size > end)
+ break; // a cut-short last chunk is left out
+ chunks.Add(new Chunk(Encoding.ASCII.GetString(header, 0, 4), data, (int)Math.Min(size, int.MaxValue)));
+ if (chunks.Count > 1_000_000)
+ throw DocumentLimits.Exceeded("A DjVu form has more than 1,000,000 chunks.");
+ at = data + size;
+ if ((at & 1) != 0)
+ at++;
+ }
+ return chunks;
+ }
+
+ private byte[] ReadChunk(Chunk chunk)
+ {
+ if (chunk.Size > _limits.MaxChunkBytes)
+ throw DocumentLimits.Exceeded($"A DjVu chunk is larger than {DocumentLimits.Megabytes(_limits.MaxChunkBytes)}.");
+ return ReadBytes(chunk.Offset, chunk.Size);
+ }
+
+ private byte[] ReadBytes(long offset, int count)
+ {
+ var data = new byte[count];
+ _file.Position = offset;
+ _file.ReadExactly(data);
+ return data;
+ }
+
+ private void ReadBundle(long start, long end, CancellationToken cancellationToken)
+ {
+ var chunks = ListChunks(start, end, cancellationToken);
+ var dirm = chunks.FirstOrDefault(c => c.Id == "DIRM") ?? throw new InvalidDataException("The DjVu document has no directory.");
+ var data = ReadChunk(dirm);
+ var reader = new DjvuBytes(data);
+ var version = reader.U8();
+ if ((version & 0x80) == 0)
+ throw new ConversionRefusedException(IndirectKey, "The DjVu document's pages are separate files (an indirect document).");
+ version &= 0x7F;
+ if (version > 1)
+ throw new InvalidDataException("The DjVu directory has a version Filee doesn't know.");
+ var count = reader.U16();
+ if (count > _limits.MaxComponents)
+ throw DocumentLimits.Exceeded($"The DjVu document has more than {DocumentLimits.Count(_limits.MaxComponents)} parts.");
+ var offsets = new long[count];
+ var sizes = new int[count];
+ for (var i = 0; i < count; i++)
+ {
+ offsets[i] = reader.U32();
+ if (version == 0)
+ sizes[i] = reader.U24();
+ }
+ var table = BzzDecoder.Decode(data, reader.Position, data.Length - reader.Position, _limits.MaxUnpackedBytes, cancellationToken);
+ var packed = new DjvuBytes(table);
+ if (version > 0)
+ {
+ for (var i = 0; i < count; i++)
+ sizes[i] = packed.U24();
+ }
+ var flags = new int[count];
+ for (var i = 0; i < count; i++)
+ {
+ flags[i] = packed.U8();
+ if (version == 0)
+ flags[i] = ((flags[i] & 1) != 0 ? 1 : 0) | ((flags[i] & 2) != 0 ? 0x80 : 0) | ((flags[i] & 4) != 0 ? 0x40 : 0);
+ }
+ for (var i = 0; i < count; i++)
+ {
+ var id = packed.CString();
+ if ((flags[i] & 0x80) != 0)
+ packed.CString();
+ if ((flags[i] & 0x40) != 0)
+ packed.CString();
+ if (ReadForm(offsets[i]) is not { } form)
+ throw new InvalidDataException("A part of the DjVu document isn't where its directory says.");
+ var component = new Component(id, offsets[i], form.End, form.Kind);
+ _byId.TryAdd(id, component);
+ if ((flags[i] & 0x3F) == 1)
+ {
+ if (form.Kind != "DJVU")
+ throw new InvalidDataException("A page of the DjVu document isn't a page.");
+ if (_pages.Count >= _limits.MaxPages)
+ throw DocumentLimits.Exceeded($"The DjVu document has more than {DocumentLimits.Count(_limits.MaxPages)} pages.");
+ _pages.Add(component);
+ }
+ }
+ }
+
+ private List ChunksOf(Component component, CancellationToken cancellationToken) =>
+ component.Chunks ??= ListChunks(component.Offset, component.End, cancellationToken);
+
+ /// Page decoded.
+ public DjvuPage ReadPage(int index, CancellationToken cancellationToken = default)
+ {
+ var component = _pages[index];
+ var own = ChunksOf(component, cancellationToken);
+ var info = own.FirstOrDefault(c => c.Id == "INFO") ?? throw new InvalidDataException("A DjVu page has no INFO chunk.");
+ var (width, height, dpi, rotation) = ReadInfo(ReadChunk(info));
+
+ var leftOut = 0;
+ Jb2Image? mask = null;
+ DjvuPalette? palette = null;
+ var background = new Iw44Decoder(_limits);
+ var foreground = new Iw44Decoder(_limits);
+ DjvuPixmap? backgroundJpeg = null, foregroundJpeg = null;
+ List text = [];
+ foreach (var chunk in own)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ switch (chunk.Id)
+ {
+ case "Sjbz":
+ mask = Jb2Decoder.DecodeImage(ReadChunk(chunk), Dictionary(component, cancellationToken), _limits, cancellationToken);
+ break;
+ case "BG44":
+ background.Decode(ReadChunk(chunk), cancellationToken);
+ break;
+ case "FG44":
+ foreground.Decode(ReadChunk(chunk), cancellationToken);
+ break;
+ case "BGjp":
+ backgroundJpeg = DecodeJpeg(ReadChunk(chunk));
+ if (backgroundJpeg is null)
+ leftOut++;
+ break;
+ case "FGjp":
+ foregroundJpeg = DecodeJpeg(ReadChunk(chunk));
+ if (foregroundJpeg is null)
+ leftOut++;
+ break;
+ case "FGbz":
+ palette = ReadPalette(ReadChunk(chunk), cancellationToken);
+ break;
+ case "TXTz":
+ text = ReadText(BzzDecoder.Decode(ReadChunk(chunk), _limits.MaxUnpackedBytes, cancellationToken));
+ break;
+ case "TXTa":
+ text = ReadText(ReadChunk(chunk));
+ break;
+ case "Smmr" or "BG2k" or "FG2k":
+ leftOut++;
+ break;
+ }
+ }
+ if (mask is not null && (mask.Width != width || mask.Height != height))
+ throw new InvalidDataException("A DjVu page's mask has another size than the page.");
+ _leftOut += leftOut;
+ return new DjvuPage
+ {
+ Width = width,
+ Height = height,
+ Dpi = dpi,
+ Rotation = rotation,
+ Mask = mask,
+ Background = background.HasData ? background.ToPixmap(cancellationToken) : backgroundJpeg,
+ Foreground = foreground.HasData ? foreground.ToPixmap(cancellationToken) : foregroundJpeg,
+ Palette = palette,
+ Text = text,
+ LeftOut = leftOut,
+ };
+ }
+
+ private (int Width, int Height, int Dpi, int Rotation) ReadInfo(byte[] data)
+ {
+ if (data.Length < 5)
+ throw new InvalidDataException("A DjVu page's INFO chunk is damaged.");
+ var width = (data[0] << 8) | data[1];
+ var height = (data[2] << 8) | data[3];
+ var dpi = data.Length >= 8 && data[7] != 0xFF ? (data[7] << 8) | data[6] : 300;
+ if (dpi is < 25 or > 6000)
+ dpi = 300;
+ var flags = data.Length >= 10 ? data[9] : 0;
+ var rotation = (flags & 7) switch { 6 => 1, 2 => 2, 5 => 3, _ => 0 };
+ if (width == 0 || height == 0)
+ throw new InvalidDataException("A DjVu page has no size.");
+ if ((long)width * height > _limits.MaxPagePixels)
+ throw DocumentLimits.Exceeded($"A DjVu page has more than {DocumentLimits.Count(_limits.MaxPagePixels)} pixels.");
+ return (width, height, dpi, rotation);
+ }
+
+ private List ReadText(byte[] data)
+ {
+ try
+ {
+ return DjvuText.Read(data, _limits);
+ }
+ catch (InvalidDataException)
+ {
+ // Damaged hidden text leaves the page without its text layer; the picture is still the page.
+ return [];
+ }
+ }
+
+ private DjvuPalette ReadPalette(byte[] data, CancellationToken cancellationToken)
+ {
+ var reader = new DjvuBytes(data);
+ var version = reader.U8();
+ if ((version & 0x7F) != 0)
+ throw new InvalidDataException("A DjVu palette has a version Filee doesn't know.");
+ var size = reader.U16();
+ if (size > _limits.MaxPaletteColors)
+ throw DocumentLimits.Exceeded("A DjVu palette has too many colours.");
+ var colors = new SKColor[size];
+ for (var i = 0; i < size; i++)
+ {
+ // Stored blue, green, red.
+ var b = (byte)reader.U8();
+ var g = (byte)reader.U8();
+ var r = (byte)reader.U8();
+ colors[i] = new SKColor(r, g, b);
+ }
+ int[]? indices = null;
+ if ((version & 0x80) != 0)
+ {
+ var count = reader.U24();
+ if (count > _limits.MaxBlits)
+ throw DocumentLimits.Exceeded($"A DjVu palette colours more than {DocumentLimits.Count(_limits.MaxBlits)} shapes.");
+ var packed = BzzDecoder.Decode(data, reader.Position, data.Length - reader.Position, Math.Min(_limits.MaxUnpackedBytes, 2L * count), cancellationToken);
+ if (packed.Length < 2L * count)
+ throw new InvalidDataException("A DjVu palette's colour indices are cut short.");
+ indices = new int[count];
+ for (var i = 0; i < count; i++)
+ {
+ var index = (short)((packed[2 * i] << 8) | packed[2 * i + 1]);
+ if (index < 0 || index >= size)
+ throw new InvalidDataException("A DjVu palette's colour index is out of range.");
+ indices[i] = index;
+ }
+ }
+ return new DjvuPalette(colors, indices);
+ }
+
+ ///
+ /// The first file with a Djbz chunk among (when ) and the
+ /// files it includes, depth first in the order of its INCL chunks, skipping files already .
+ ///
+ private Component? FindDictionary(Component start, bool includeSelf, HashSet seen, CancellationToken cancellationToken)
+ {
+ var pending = new Stack<(Component Component, bool Check)>();
+ pending.Push((start, includeSelf));
+ seen.Add(start);
+ while (pending.Count > 0)
+ {
+ var (component, check) = pending.Pop();
+ var chunks = ChunksOf(component, cancellationToken);
+ if (check && chunks.Any(c => c.Id == "Djbz"))
+ return component;
+ var included = new List();
+ foreach (var include in chunks.Where(c => c.Id == "INCL"))
+ {
+ var id = Encoding.UTF8.GetString(ReadChunk(include)).Trim('\0', ' ', '\n', '\r');
+ if (_byId.TryGetValue(id, out var target) && seen.Add(target))
+ included.Add(target);
+ }
+ for (var i = included.Count - 1; i >= 0; i--)
+ pending.Push((included[i], true));
+ }
+ return null;
+ }
+
+ /// A JPEG layer (BGjp, FGjp), or null when Skia can't decode it or it is too large.
+ private DjvuPixmap? DecodeJpeg(byte[] data)
+ {
+ using var codec = SKCodec.Create(new MemoryStream(data));
+ if (codec is null || (long)codec.Info.Width * codec.Info.Height > _limits.MaxIw44Pixels)
+ return null;
+ using var bitmap = SKBitmap.Decode(codec, new SKImageInfo(codec.Info.Width, codec.Info.Height, SKColorType.Rgba8888, SKAlphaType.Opaque));
+ if (bitmap is null)
+ return null;
+ var pixels = bitmap.GetPixelSpan();
+ var rgb = new byte[(long)bitmap.Width * bitmap.Height * 3];
+ for (int i = 0, o = 0; o < rgb.Length; i += 4, o += 3)
+ {
+ rgb[o] = pixels[i];
+ rgb[o + 1] = pixels[i + 1];
+ rgb[o + 2] = pixels[i + 2];
+ }
+ return new DjvuPixmap(bitmap.Width, bitmap.Height, rgb);
+ }
+
+ ///
+ /// The shape dictionary a page's mask may build on: the page's own Djbz, or that of the first file it includes
+ /// (directly or through other includes) that has one. Decoded once per file.
+ ///
+ private Jb2Dictionary? Dictionary(Component page, CancellationToken cancellationToken)
+ {
+ // The chain of files whose dictionaries build on each other, each file looked at once.
+ var chain = new List();
+ var seen = new HashSet();
+ var holder = FindDictionary(page, includeSelf: true, seen, cancellationToken);
+ while (holder is not null)
+ {
+ chain.Add(holder);
+ holder = FindDictionary(holder, includeSelf: false, seen, cancellationToken);
+ }
+ Jb2Dictionary? dictionary = null;
+ for (var i = chain.Count - 1; i >= 0; i--)
+ {
+ var component = chain[i];
+ var key = component.Id + "@" + component.Offset;
+ if (!_dictionaries.TryGetValue(key, out var decoded))
+ {
+ var djbz = ChunksOf(component, cancellationToken).First(c => c.Id == "Djbz");
+ decoded = Jb2Decoder.DecodeDictionary(ReadChunk(djbz), dictionary, _limits, cancellationToken);
+ // A few shared dictionaries serve a whole book; keep only the latest ones.
+ if (_dictionaries.Count >= 8)
+ _dictionaries.Clear();
+ _dictionaries[key] = decoded;
+ }
+ dictionary = decoded;
+ }
+ return dictionary;
+ }
+}
diff --git a/src/Filee.Engines/Djvu/DjvuLimits.cs b/src/Filee.Engines/Djvu/DjvuLimits.cs
new file mode 100644
index 000000000..016872aa9
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuLimits.cs
@@ -0,0 +1,56 @@
+// What one DjVu document may make Filee read and build: pages, chunk sizes, decompressed (BZZ) bytes, page pixels,
+// JB2 shapes, blits and their pixels, IW44 slices and coefficient blocks, text zones. Every limit is far beyond what
+// scanners and DjVu encoders write (a 600 dpi A3 scan is 70 million pixels); a document past one is refused with
+// error.document_too_complex, naming the limit.
+
+using Filee.Engines.Documents;
+
+namespace Filee.Engines.Djvu;
+
+/// Limits of the DjVu reader.
+internal sealed record DjvuLimits
+{
+ public static DjvuLimits Default { get; } = new();
+
+ /// Pages of one document.
+ public int MaxPages { get; init; } = DocumentLimits.Default.MaxPages;
+
+ /// Components (pages, shared dictionaries, thumbnails) of a bundled document.
+ public int MaxComponents { get; init; } = 2 * DocumentLimits.Default.MaxPages;
+
+ /// Bytes of one chunk read into memory (a page's mask, background or text).
+ public long MaxChunkBytes { get; init; } = DocumentLimits.Default.MaxPartBytes;
+
+ /// Bytes one BZZ stream (text, palette indices, the directory) may unpack to.
+ public long MaxUnpackedBytes { get; init; } = DocumentLimits.Default.MaxPartBytes;
+
+ /// Pixels of one page (its INFO size), and of one IW44 picture.
+ public long MaxPagePixels { get; init; } = 150_000_000;
+
+ ///
+ /// Pixels of one IW44 picture (a background or foreground layer; encoders store them at a third of the page's
+ /// resolution or less, photographs at full size). Three maps of two bytes per pixel are decoded.
+ ///
+ public long MaxIw44Pixels { get; init; } = 64_000_000;
+
+ /// Shapes of one JB2 image or dictionary.
+ public int MaxShapes { get; init; } = 2_000_000;
+
+ /// Blits (placed shapes) of one JB2 image.
+ public int MaxBlits { get; init; } = 4_000_000;
+
+ /// Pixels of all shapes of one JB2 image or dictionary together (each costs a byte while decoded).
+ public long MaxShapePixels { get; init; } = 400_000_000;
+
+ /// Cells of the JB2 number coder between two resets (each costs 9 bytes).
+ public int MaxNumberCells { get; init; } = 20_000_000;
+
+ /// Coding slices of one IW44 picture (all its chunks together; real files have 100 or fewer).
+ public int MaxSlices { get; init; } = 10_000;
+
+ /// Text zones of one page.
+ public int MaxTextZones { get; init; } = 2_000_000;
+
+ /// Colours of a foreground palette.
+ public int MaxPaletteColors { get; init; } = 65_535;
+}
diff --git a/src/Filee.Engines/Djvu/DjvuPdfWriter.cs b/src/Filee.Engines/Djvu/DjvuPdfWriter.cs
new file mode 100644
index 000000000..75bedafc9
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuPdfWriter.cs
@@ -0,0 +1,236 @@
+// DjVu pages as PDF pages, each at its size at the page's resolution (INFO), its turn as the page's /Rotate. The
+// layers stay layers, so a scanned book stays small: the background as a JPEG at its own (reduced) resolution, the
+// mask as 1-bit image masks (Flate) painted in the foreground colour — one per palette colour, or the FG44 picture
+// (a JPEG) shown through the mask (explicit masking). A page with more than MaxStencils palette colours is drawn
+// whole as one JPEG instead. The hidden text becomes an invisible text layer (OcrPdfWriter's glyphless font), so the
+// PDF can be searched and its text copied.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using Filee.Engines.Ocr;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using SkiaSharp;
+
+namespace Filee.Engines.Djvu;
+
+internal static class DjvuPdfWriter
+{
+ /// Palette colours drawn as separate masks at most; a page with more is drawn as one picture.
+ internal const int MaxStencils = 64;
+
+ /// Largest page side in points (PDF's own limit, 200 inches).
+ private const double MaxSide = 14_400;
+
+ private const int JpegQuality = 85;
+
+ /// Adds to 's document.
+ public static void AddPage(OcrPdfWriter writer, DjvuPage page, CancellationToken cancellationToken = default)
+ {
+ var document = writer.Document;
+ var scale = 72.0 / page.Dpi;
+ scale = Math.Min(scale, MaxSide / Math.Max(page.Width, page.Height));
+ var width = page.Width * scale;
+ var height = page.Height * scale;
+ var pdfPage = document.AddPage();
+ pdfPage.Width = XUnit.FromPoint(width);
+ pdfPage.Height = XUnit.FromPoint(height);
+ if (page.Rotation != 0)
+ pdfPage.Elements.SetInteger("/Rotate", page.Rotation switch { 1 => 270, 2 => 180, _ => 90 });
+
+ var content = new StringBuilder();
+ var images = new List<(string Name, PdfDictionary Image)>();
+ void Draw(PdfDictionary image, string? fill = null)
+ {
+ var name = "/Im" + images.Count.ToString(CultureInfo.InvariantCulture);
+ images.Add((name, image));
+ content.Append("q ");
+ if (fill is not null)
+ content.Append(fill).Append(' ');
+ content.Append(CultureInfo.InvariantCulture, $"{N(width)} 0 0 {N(height)} 0 0 cm {name} Do Q\n");
+ }
+
+ var mask = page.Mask is { Blits.Count: > 0 } ? page.Mask : null;
+ var palette = page.Palette is { Colors.Length: > 0 } p ? p : null;
+ var used = mask is null || palette is null || page.Foreground is not null ? null : UsedColors(mask, palette);
+ if (used is { Count: > MaxStencils })
+ {
+ // Too many colours to draw one mask each: the page as it looks.
+ Draw(Jpeg(document, new DjvuPixmap(page.Width, page.Height, DjvuRenderer.Compose(page, cancellationToken))));
+ }
+ else
+ {
+ if (page.Background is { } background)
+ Draw(Jpeg(document, background));
+ if (mask is not null)
+ {
+ if (page.Foreground is { } foreground)
+ {
+ var image = Jpeg(document, foreground);
+ image.Elements["/Mask"] = Stencil(document, page, null, cancellationToken).Reference;
+ Draw(image);
+ }
+ else if (used is not null)
+ {
+ foreach (var color in used)
+ {
+ var c = palette!.Colors[color];
+ Draw(Stencil(document, page, color, cancellationToken), $"{N(c.Red / 255.0)} {N(c.Green / 255.0)} {N(c.Blue / 255.0)} rg");
+ }
+ }
+ else
+ {
+ Draw(Stencil(document, page, null, cancellationToken), "0 g");
+ }
+ }
+ }
+
+ if (images.Count > 0)
+ {
+ if (pdfPage.Resources.Elements.GetDictionary("/XObject") is not { } objects)
+ {
+ objects = new PdfDictionary(document);
+ pdfPage.Resources.Elements["/XObject"] = objects;
+ }
+ foreach (var (name, image) in images)
+ objects.Elements.SetReference(name, image);
+ pdfPage.Contents.AppendContent().CreateStream(Encoding.ASCII.GetBytes(content.ToString()));
+ }
+ writer.AddText(pdfPage, Lines(page), width, height);
+ }
+
+ /// The palette colours the mask's shapes use, in the order first used.
+ private static List UsedColors(Jb2Image mask, DjvuPalette palette)
+ {
+ var used = new List();
+ var seen = new HashSet();
+ for (var b = 0; b < mask.Blits.Count; b++)
+ {
+ var color = DjvuRenderer.ColorOf(palette.BlitColors, b, mask.Blits.Count);
+ if (seen.Add(color))
+ {
+ used.Add(color);
+ if (used.Count > MaxStencils)
+ break;
+ }
+ }
+ return used;
+ }
+
+ /// The page's text lines as fractions of the page, as the OCR layer takes them.
+ internal static List Lines(DjvuPage page)
+ {
+ double w = page.Width, h = page.Height;
+ var lines = new List();
+ foreach (var line in page.Text)
+ {
+ var box = line.Box;
+ if (line.Words.Count == 0 || !LaidOut(line.Words))
+ {
+ lines.Add(OcrLine.Estimate(line.Text, box.Left / w, box.Bottom / h, box.Width / w, box.Height / h));
+ continue;
+ }
+ var words = line.Words.Select(word => new OcrWord(word.Text, word.Box.Left / w, word.Box.Width / w)).ToList();
+ lines.Add(new OcrLine(box.Left / w, box.Bottom / h, box.Width / w, box.Height / h, words));
+ }
+ return lines;
+ }
+
+ ///
+ /// Whether a line's word boxes follow each other left to right. Some files give every word the box of its whole
+ /// line; their words are spread over the line by their length instead, so they don't overlap in the PDF.
+ ///
+ private static bool LaidOut(IReadOnlyList words)
+ {
+ for (var i = 1; i < words.Count; i++)
+ {
+ var previous = words[i - 1].Box;
+ var word = words[i].Box;
+ if (previous.Left + previous.Width - word.Left > Math.Min(previous.Width, word.Width) / 2)
+ return false;
+ }
+ return true;
+ }
+
+ /// An image mask of the page's shapes (one palette colour's, or all), a set sample painted.
+ private static PdfDictionary Stencil(PdfDocument document, DjvuPage page, int? color, CancellationToken cancellationToken)
+ {
+ var bits = DjvuRenderer.MaskBits(page, color, cancellationToken);
+ var image = Stream(document, Deflate(bits), "/FlateDecode");
+ image.Elements.SetName("/Type", "/XObject");
+ image.Elements.SetName("/Subtype", "/Image");
+ image.Elements.SetInteger("/Width", page.Width);
+ image.Elements.SetInteger("/Height", page.Height);
+ image.Elements.SetBoolean("/ImageMask", true);
+ image.Elements.SetInteger("/BitsPerComponent", 1);
+ var decode = new PdfArray(document);
+ decode.Elements.Add(new PdfInteger(1));
+ decode.Elements.Add(new PdfInteger(0));
+ image.Elements["/Decode"] = decode;
+ return image;
+ }
+
+ /// A JPEG image of , in grey when every pixel is grey.
+ private static PdfDictionary Jpeg(PdfDocument document, DjvuPixmap pixmap)
+ {
+ var rgb = pixmap.Rgb;
+ var grey = true;
+ for (var i = 0; i < rgb.Length && grey; i += 3)
+ grey = rgb[i] == rgb[i + 1] && rgb[i] == rgb[i + 2];
+ byte[] jpeg;
+ if (grey)
+ {
+ var pixels = new byte[(long)pixmap.Width * pixmap.Height];
+ for (int i = 0, o = 0; o < pixels.Length; i += 3, o++)
+ pixels[o] = rgb[i];
+ jpeg = Encode(pixels, new SKImageInfo(pixmap.Width, pixmap.Height, SKColorType.Gray8, SKAlphaType.Opaque));
+ }
+ else
+ {
+ var pixels = new byte[(long)pixmap.Width * pixmap.Height * 4];
+ for (int i = 0, o = 0; o < pixels.Length; i += 3, o += 4)
+ {
+ pixels[o] = rgb[i];
+ pixels[o + 1] = rgb[i + 1];
+ pixels[o + 2] = rgb[i + 2];
+ pixels[o + 3] = 255;
+ }
+ jpeg = Encode(pixels, new SKImageInfo(pixmap.Width, pixmap.Height, SKColorType.Rgba8888, SKAlphaType.Opaque));
+ }
+ var image = Stream(document, jpeg, "/DCTDecode");
+ image.Elements.SetName("/Type", "/XObject");
+ image.Elements.SetName("/Subtype", "/Image");
+ image.Elements.SetInteger("/Width", pixmap.Width);
+ image.Elements.SetInteger("/Height", pixmap.Height);
+ image.Elements.SetName("/ColorSpace", grey ? "/DeviceGray" : "/DeviceRGB");
+ image.Elements.SetInteger("/BitsPerComponent", 8);
+ return image;
+ }
+
+ private static byte[] Encode(byte[] pixels, SKImageInfo info)
+ {
+ using var image = SKImage.FromPixelCopy(info, pixels, info.RowBytes) ?? throw new InvalidOperationException("Skia can't hold the picture.");
+ using var data = image.Encode(SKEncodedImageFormat.Jpeg, JpegQuality) ?? throw new InvalidOperationException("Skia can't write the JPEG.");
+ return data.ToArray();
+ }
+
+ private static byte[] Deflate(byte[] data)
+ {
+ using var buffer = new MemoryStream();
+ using (var zlib = new ZLibStream(buffer, CompressionLevel.Optimal, leaveOpen: true))
+ zlib.Write(data);
+ return buffer.ToArray();
+ }
+
+ private static PdfDictionary Stream(PdfDocument document, byte[] data, string filter)
+ {
+ var dictionary = new PdfDictionary(document);
+ document.Internals.AddObject(dictionary);
+ dictionary.CreateStream(data);
+ dictionary.Elements.SetName("/Filter", filter);
+ return dictionary;
+ }
+
+ private static string N(double value) => Math.Round(value, 4).ToString("0.####", CultureInfo.InvariantCulture);
+}
diff --git a/src/Filee.Engines/Djvu/DjvuRenderer.cs b/src/Filee.Engines/Djvu/DjvuRenderer.cs
new file mode 100644
index 000000000..9da34912e
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuRenderer.cs
@@ -0,0 +1,185 @@
+// Draws a decoded DjVu page as DjVu viewers compose it: the background scaled up to the page (it is stored at a
+// fraction of the page's resolution: the reduction is the smallest whole factor that gives its size), then every
+// pixel the mask covers in the foreground colour: the FG44 / FGjp picture at that point (scaled the same way), the
+// palette colour of the shape that covers it, or black. A page without a background is white.
+//
+// The mask is also given as 1-bit rows for the PDF writer, all shapes or only those of one palette colour.
+
+namespace Filee.Engines.Djvu;
+
+internal static class DjvuRenderer
+{
+ /// The reduction of a layer of × on the page.
+ public static int Reduction(int width, int height, int layerWidth, int layerHeight)
+ {
+ for (var red = 1; red < 16; red++)
+ {
+ if ((width + red - 1) / red == layerWidth && (height + red - 1) / red == layerHeight)
+ return red;
+ }
+ return 16;
+ }
+
+ ///
+ /// The page's mask as 1-bit rows, top row first, a set bit for a black pixel, each row padded to a byte;
+ /// keeps only the shapes of that palette colour.
+ ///
+ public static byte[] MaskBits(DjvuPage page, int? color = null, CancellationToken cancellationToken = default)
+ {
+ int width = page.Width, height = page.Height;
+ var stride = (width + 7) / 8;
+ var bits = new byte[(long)stride * height];
+ if (page.Mask is not { } mask)
+ return bits;
+ var blitColors = page.Palette?.BlitColors;
+ for (var b = 0; b < mask.Blits.Count; b++)
+ {
+ if ((b & 0x3FF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ if (color is { } wanted && ColorOf(blitColors, b, mask.Blits.Count) != wanted)
+ continue;
+ var blit = mask.Blits[b];
+ var shape = mask.Shapes[blit.Shape];
+ for (var y = 0; y < shape.Height; y++)
+ {
+ var pageY = height - 1 - (blit.Bottom + y);
+ if ((uint)pageY >= (uint)height)
+ continue;
+ var row = (long)pageY * stride;
+ var source = y * shape.Width;
+ for (var x = 0; x < shape.Width; x++)
+ {
+ if (shape.Bits[source + x] == 0)
+ continue;
+ var pageX = blit.Left + x;
+ if ((uint)pageX < (uint)width)
+ bits[row + (pageX >> 3)] |= (byte)(0x80 >> (pageX & 7));
+ }
+ }
+ }
+ return bits;
+ }
+
+ /// The palette colour of blit (the first colour when the file has no indices).
+ public static int ColorOf(int[]? blitColors, int blit, int blits) =>
+ blitColors is not null && blitColors.Length == blits ? blitColors[blit] : 0;
+
+ /// The page drawn as RGB bytes, three per pixel, top row first.
+ public static byte[] Compose(DjvuPage page, CancellationToken cancellationToken = default)
+ {
+ int width = page.Width, height = page.Height;
+ var rgb = new byte[(long)width * height * 3];
+ if (page.Background is { } background)
+ Upscale(background, rgb, width, height, cancellationToken);
+ else
+ Array.Fill(rgb, (byte)255);
+ if (page.Mask is not { } mask)
+ return rgb;
+
+ if (page.Foreground is null && page.Palette is { Colors.Length: > 0 } palette)
+ {
+ // Each shape in its own colour, in the order they are placed.
+ for (var b = 0; b < mask.Blits.Count; b++)
+ {
+ if ((b & 0x3FF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var c = palette.Colors[ColorOf(palette.BlitColors, b, mask.Blits.Count)];
+ Paint(mask, b, rgb, width, height, c.Red, c.Green, c.Blue);
+ }
+ return rgb;
+ }
+
+ var bits = MaskBits(page, null, cancellationToken);
+ var stride = (width + 7) / 8;
+ var foreground = page.Foreground;
+ var red = foreground is null ? 1 : Reduction(width, height, foreground.Width, foreground.Height);
+ for (var y = 0; y < height; y++)
+ {
+ if ((y & 0xFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var row = (long)y * stride;
+ var o = (long)y * width * 3;
+ var fy = foreground is null ? 0 : Math.Min(y / red, foreground.Height - 1);
+ for (var x = 0; x < width; x++, o += 3)
+ {
+ if ((bits[row + (x >> 3)] & (0x80 >> (x & 7))) == 0)
+ continue;
+ if (foreground is null)
+ {
+ rgb[o] = rgb[o + 1] = rgb[o + 2] = 0;
+ continue;
+ }
+ var f = ((long)fy * foreground.Width + Math.Min(x / red, foreground.Width - 1)) * 3;
+ rgb[o] = foreground.Rgb[f];
+ rgb[o + 1] = foreground.Rgb[f + 1];
+ rgb[o + 2] = foreground.Rgb[f + 2];
+ }
+ }
+ return rgb;
+ }
+
+ private static void Paint(Jb2Image mask, int b, byte[] rgb, int width, int height, byte r, byte g, byte bl)
+ {
+ var blit = mask.Blits[b];
+ var shape = mask.Shapes[blit.Shape];
+ for (var y = 0; y < shape.Height; y++)
+ {
+ var pageY = height - 1 - (blit.Bottom + y);
+ if ((uint)pageY >= (uint)height)
+ continue;
+ var source = y * shape.Width;
+ for (var x = 0; x < shape.Width; x++)
+ {
+ var pageX = blit.Left + x;
+ if (shape.Bits[source + x] == 0 || (uint)pageX >= (uint)width)
+ continue;
+ var o = ((long)pageY * width + pageX) * 3;
+ rgb[o] = r;
+ rgb[o + 1] = g;
+ rgb[o + 2] = bl;
+ }
+ }
+ }
+
+ /// Scales up to the page, bilinear, each layer pixel centred on its block of page pixels.
+ public static void Upscale(DjvuPixmap layer, byte[] rgb, int width, int height, CancellationToken cancellationToken)
+ {
+ var red = Reduction(width, height, layer.Width, layer.Height);
+ int lw = layer.Width, lh = layer.Height;
+ var source = layer.Rgb;
+ var xs = new int[width];
+ var xf = new int[width];
+ for (var x = 0; x < width; x++)
+ {
+ var sx = Math.Clamp((x + 0.5) / red - 0.5, 0, lw - 1);
+ xs[x] = (int)sx;
+ xf[x] = (int)((sx - xs[x]) * 256);
+ }
+ for (var y = 0; y < height; y++)
+ {
+ if ((y & 0xFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ var sy = Math.Clamp((y + 0.5) / red - 0.5, 0, lh - 1);
+ var y0 = (int)sy;
+ var y1 = Math.Min(y0 + 1, lh - 1);
+ var fy = (int)((sy - y0) * 256);
+ var row0 = (long)y0 * lw * 3;
+ var row1 = (long)y1 * lw * 3;
+ var o = (long)y * width * 3;
+ for (var x = 0; x < width; x++, o += 3)
+ {
+ var x0 = xs[x];
+ var x1 = Math.Min(x0 + 1, lw - 1);
+ var fx = xf[x];
+ for (var c = 0; c < 3; c++)
+ {
+ int a = source[row0 + x0 * 3 + c], b = source[row0 + x1 * 3 + c];
+ int d = source[row1 + x0 * 3 + c], e = source[row1 + x1 * 3 + c];
+ var top = a * 256 + (b - a) * fx;
+ var bottom = d * 256 + (e - d) * fx;
+ rgb[o + c] = (byte)((top * 256 + (bottom - top) * fy + 32768) >> 16);
+ }
+ }
+ }
+ }
+}
diff --git a/src/Filee.Engines/Djvu/DjvuText.cs b/src/Filee.Engines/Djvu/DjvuText.cs
new file mode 100644
index 000000000..f1670ef6b
--- /dev/null
+++ b/src/Filee.Engines/Djvu/DjvuText.cs
@@ -0,0 +1,239 @@
+// The hidden text of a DjVu page (DjVu v3 specification, "Text Chunk": TXTa, or TXTz which is TXTa packed with BZZ):
+// the page's text in UTF-8, then a tree of zones (page, column, region, paragraph, line, word, character), each with
+// its box in page pixels (row 0 at the bottom) and the range of the text it covers. A zone's box is coded relative to
+// the previous zone at its level or to its parent. The lines and words become the invisible text layer of the PDF.
+
+using System.Text;
+using Filee.Engines.Documents;
+
+namespace Filee.Engines.Djvu;
+
+/// A box in page pixels, row 0 at the bottom.
+internal readonly record struct DjvuRect(int Left, int Bottom, int Width, int Height);
+
+/// A word of a text line and its box.
+internal sealed record DjvuWord(string Text, DjvuRect Box);
+
+/// A line of text: its box and words (one estimated word per run of text when the file has no word zones).
+internal sealed record DjvuLine(DjvuRect Box, IReadOnlyList Words, string Text);
+
+/// Reads TXTa data.
+internal static class DjvuText
+{
+ private const int Line = 5, Word = 6;
+
+ private sealed class Zone(int type, DjvuRect box, int textStart, int textLength)
+ {
+ public int Type { get; } = type;
+ public DjvuRect Box { get; } = box;
+ public int TextStart { get; } = textStart;
+ public int TextLength { get; } = textLength;
+ public List Children { get; } = [];
+ }
+
+ /// The lines of a page's text; empty when it has no zones. Damaged text throws InvalidDataException.
+ public static List Read(byte[] data, DjvuLimits limits)
+ {
+ var reader = new DjvuBytes(data);
+ var size = reader.U24();
+ if (size <= 0 || size > data.Length - 3)
+ throw new InvalidDataException("A DjVu text chunk is damaged.");
+ var text = reader.Bytes(size);
+ if (reader.Remaining == 0)
+ return [];
+ if (reader.U8() != 1)
+ throw new InvalidDataException("A DjVu text chunk has a version Filee doesn't know.");
+ var root = ReadZones(reader, size, limits);
+ return Lines(root, text);
+ }
+
+ /// The zone tree, read without recursion.
+ private static Zone ReadZones(DjvuBytes reader, int textSize, DjvuLimits limits)
+ {
+ var zones = 0;
+ // Each open zone with how many children it still has and its last child read.
+ var stack = new Stack<(Zone Zone, int Remaining, Zone? Last)>();
+ Zone? root = null;
+ Zone? parent = null;
+ Zone? previous = null;
+ while (true)
+ {
+ if (++zones > limits.MaxTextZones)
+ throw DocumentLimits.Exceeded($"A DjVu page's text has more than {DocumentLimits.Count(limits.MaxTextZones)} zones.");
+ var type = reader.U8();
+ if (type is < 1 or > 7 || (parent is not null && type <= parent.Type))
+ throw new InvalidDataException("A DjVu text zone is damaged.");
+ var x = reader.U16() - 0x8000;
+ var y = reader.U16() - 0x8000;
+ var width = reader.U16() - 0x8000;
+ var height = reader.U16() - 0x8000;
+ var start = reader.U16() - 0x8000;
+ var length = reader.U24();
+ if (previous is not null)
+ {
+ if (type is 1 or 4 or 5)
+ {
+ x += previous.Box.Left;
+ y = previous.Box.Bottom - (y + height);
+ }
+ else
+ {
+ x += previous.Box.Left + previous.Box.Width;
+ y += previous.Box.Bottom;
+ }
+ start += previous.TextStart + previous.TextLength;
+ }
+ else if (parent is not null)
+ {
+ x += parent.Box.Left;
+ y = parent.Box.Bottom + parent.Box.Height - (y + height);
+ start += parent.TextStart;
+ }
+ var children = reader.U24();
+ if (start < 0 || length < 0 || (long)start + length > textSize)
+ throw new InvalidDataException("A DjVu text zone points outside the text.");
+ var zone = new Zone(type, new DjvuRect(x, y, width, height), start, length);
+ if (parent is null)
+ root = zone;
+ else
+ parent.Children.Add(zone);
+ if (stack.Count > 0)
+ {
+ var top = stack.Pop();
+ stack.Push((top.Zone, top.Remaining - 1, zone));
+ }
+ if (children > 0)
+ {
+ stack.Push((zone, children, null));
+ parent = zone;
+ previous = null;
+ continue;
+ }
+ // Closes the zones whose children are all read.
+ while (stack.Count > 0 && stack.Peek().Remaining == 0)
+ stack.Pop();
+ if (stack.Count == 0)
+ return root!;
+ (parent, _, previous) = stack.Peek();
+ }
+ }
+
+ private static List Lines(Zone root, byte[] text)
+ {
+ var lines = new List();
+ var pending = new Stack();
+ pending.Push(root);
+ while (pending.Count > 0)
+ {
+ var zone = pending.Pop();
+ if (zone.Type == Line || zone.Type >= Word || (zone.Children.Count == 0 && zone.Type > 1))
+ {
+ var line = MakeLine(zone, text);
+ if (line is not null)
+ lines.Add(line);
+ continue;
+ }
+ for (var i = zone.Children.Count - 1; i >= 0; i--)
+ pending.Push(zone.Children[i]);
+ }
+ return lines;
+ }
+
+ private static DjvuLine? MakeLine(Zone zone, byte[] text)
+ {
+ if (zone.Box.Width <= 0 || zone.Box.Height <= 0)
+ return null;
+ var whole = Text(text, zone.TextStart, zone.TextLength);
+ if (whole.Length == 0)
+ return null;
+ var words = new List();
+ if (zone.Type == Line)
+ {
+ foreach (var child in zone.Children)
+ {
+ if (child.Type != Word || child.Box.Width <= 0)
+ continue;
+ var word = Text(text, child.TextStart, child.TextLength);
+ if (word.Length > 0)
+ words.Add(new DjvuWord(word, child.Box));
+ }
+ }
+ else if (zone.Type >= Word)
+ {
+ words.Add(new DjvuWord(whole, zone.Box));
+ }
+ return new DjvuLine(zone.Box, words, whole);
+ }
+
+ /// A zone's text without the separators DjVu ends zones with (space, line feed, 0x0B, 0x1D, 0x1F).
+ private static string Text(byte[] text, int start, int length)
+ {
+ var value = Encoding.UTF8.GetString(text, start, length);
+ return value.Trim().Trim('\v', '\u001d', '\u001f', '\0').Trim();
+ }
+}
+
+/// Big-endian reading of a chunk's bytes; reading past the end is damage.
+internal sealed class DjvuBytes(byte[] data, int offset = 0)
+{
+ private int _at = offset;
+
+ public int Remaining => data.Length - _at;
+
+ public int Position => _at;
+
+ public int U8()
+ {
+ Need(1);
+ return data[_at++];
+ }
+
+ public int U16()
+ {
+ Need(2);
+ var value = (data[_at] << 8) | data[_at + 1];
+ _at += 2;
+ return value;
+ }
+
+ public int U24()
+ {
+ Need(3);
+ var value = (data[_at] << 16) | (data[_at + 1] << 8) | data[_at + 2];
+ _at += 3;
+ return value;
+ }
+
+ public long U32()
+ {
+ Need(4);
+ var value = ((long)data[_at] << 24) | ((long)data[_at + 1] << 16) | ((long)data[_at + 2] << 8) | data[_at + 3];
+ _at += 4;
+ return value;
+ }
+
+ /// A zero-terminated UTF-8 string.
+ public string CString()
+ {
+ var end = Array.IndexOf(data, (byte)0, _at);
+ if (end < 0)
+ throw new InvalidDataException("A DjVu chunk ends early.");
+ var value = Encoding.UTF8.GetString(data, _at, end - _at);
+ _at = end + 1;
+ return value;
+ }
+
+ public byte[] Bytes(int count)
+ {
+ Need(count);
+ var value = data.AsSpan(_at, count).ToArray();
+ _at += count;
+ return value;
+ }
+
+ private void Need(int count)
+ {
+ if (count < 0 || count > data.Length - _at)
+ throw new InvalidDataException("A DjVu chunk ends early.");
+ }
+}
diff --git a/src/Filee.Engines/Djvu/Iw44Decoder.cs b/src/Filee.Engines/Djvu/Iw44Decoder.cs
new file mode 100644
index 000000000..467e1081c
--- /dev/null
+++ b/src/Filee.Engines/Djvu/Iw44Decoder.cs
@@ -0,0 +1,700 @@
+// IW44, DjVu's wavelet picture coding (DjVu v3 specification, "IW44"): the background (BG44) and foreground colours
+// (FG44) of a page. A picture is a luminance map and, in colour, two chrominance maps (YCbCr, chrominance optionally at
+// half resolution and starting a few slices late), each in blocks of 32 × 32 wavelet coefficients. The coefficients
+// arrive in slices, from the coarsest band and the highest bit down: each slice tells which coefficients become
+// significant at the current threshold, their signs, and one more bit of those already known. A picture may come in
+// several chunks, each adding slices.
+//
+// Reconstruction: the coefficients of all blocks in one array, the lifting transform run backwards from scale 16 to 1
+// (scale 2 for half-resolution chrominance, then each value repeated over 2 × 2), each value rounded (six fraction
+// bits) to −128..127, then the "Pigeon" YCbCr → RGB transform, or 127 − Y for a grey picture.
+
+using Filee.Engines.Documents;
+
+namespace Filee.Engines.Djvu;
+
+/// A decoded picture: RGB bytes, three per pixel, top row first.
+internal sealed class DjvuPixmap(int width, int height, byte[] rgb)
+{
+ public int Width { get; } = width;
+ public int Height { get; } = height;
+ public byte[] Rgb { get; } = rgb;
+}
+
+/// Decodes the chunks of one IW44 picture, in order.
+internal sealed class Iw44Decoder(DjvuLimits limits)
+{
+ private Iw44Map? _y, _cb, _cr;
+ private Iw44Codec? _yCodec, _cbCodec, _crCodec;
+ private int _serial;
+ private int _slices;
+ private int _chromaDelay;
+ private bool _chromaHalf;
+
+ public bool HasData => _y is not null;
+
+ /// Adds one chunk (BG44, FG44, PM44, BM44).
+ public void Decode(byte[] chunk, CancellationToken cancellationToken = default)
+ {
+ if (chunk.Length < 2)
+ throw new InvalidDataException("An IW44 chunk is too short.");
+ var serial = chunk[0];
+ var slices = chunk[1];
+ if (serial != _serial)
+ throw new InvalidDataException("IW44 chunks are out of order.");
+ var at = 2;
+ if (serial == 0)
+ {
+ if (chunk.Length < 9)
+ throw new InvalidDataException("An IW44 chunk is too short.");
+ var major = chunk[2];
+ var minor = chunk[3];
+ if ((major & 0x7F) != 1)
+ throw new InvalidDataException("An IW44 picture uses a coder version Filee doesn't know.");
+ if (minor > 2)
+ throw new InvalidDataException("An IW44 picture uses a newer coder version than Filee knows.");
+ var width = (chunk[4] << 8) | chunk[5];
+ var height = (chunk[6] << 8) | chunk[7];
+ at = 8;
+ _chromaDelay = 0;
+ _chromaHalf = false;
+ if (minor >= 2)
+ {
+ var delay = chunk[at++];
+ _chromaDelay = delay & 0x7F;
+ _chromaHalf = (delay & 0x80) == 0;
+ }
+ if ((major & 0x80) != 0)
+ _chromaDelay = -1;
+ if (width == 0 || height == 0)
+ throw new InvalidDataException("An IW44 picture has no size.");
+ if ((long)width * height > limits.MaxIw44Pixels)
+ throw DocumentLimits.Exceeded($"A DjVu picture has more than {DocumentLimits.Count(limits.MaxIw44Pixels)} pixels.");
+ _y = new Iw44Map(width, height);
+ _yCodec = new Iw44Codec(_y);
+ if (_chromaDelay >= 0)
+ {
+ _cb = new Iw44Map(width, height);
+ _cr = new Iw44Map(width, height);
+ _cbCodec = new Iw44Codec(_cb);
+ _crCodec = new Iw44Codec(_cr);
+ }
+ }
+ if (_yCodec is null)
+ throw new InvalidDataException("An IW44 picture is missing its first chunk.");
+ var total = _slices + slices;
+ if (total > limits.MaxSlices)
+ throw DocumentLimits.Exceeded($"A DjVu picture has more than {DocumentLimits.Count(limits.MaxSlices)} slices.");
+ var zp = new ZpDecoder(chunk, at, chunk.Length - at);
+ var more = true;
+ while (more && _slices < total)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ more = _yCodec.DecodeSlice(zp);
+ if (_cbCodec is not null && _crCodec is not null && _chromaDelay <= _slices)
+ {
+ more |= _cbCodec.DecodeSlice(zp);
+ more |= _crCodec.DecodeSlice(zp);
+ }
+ _slices++;
+ }
+ _serial++;
+ }
+
+ /// The picture so far.
+ public DjvuPixmap ToPixmap(CancellationToken cancellationToken = default)
+ {
+ var y = _y ?? throw new InvalidDataException("An IW44 picture has no data.");
+ int w = y.Width, h = y.Height;
+ var luma = y.Reconstruct(half: false, cancellationToken);
+ var rgb = new byte[(long)w * h * 3];
+ var color = _cb is not null && _cr is not null && _chromaDelay >= 0;
+ var cb = color ? _cb!.Reconstruct(_chromaHalf, cancellationToken) : null;
+ var cr = color ? _cr!.Reconstruct(_chromaHalf, cancellationToken) : null;
+ // The maps' row 0 is the bottom of the picture (as DjVu draws everything); the pixmap's is the top.
+ for (var row = 0; row < h; row++)
+ {
+ var i = row * w;
+ var o = (h - 1 - row) * w * 3;
+ for (var x = 0; x < w; x++, i++, o += 3)
+ {
+ int yy = luma[i];
+ if (!color)
+ {
+ rgb[o] = rgb[o + 1] = rgb[o + 2] = (byte)(127 - yy);
+ continue;
+ }
+ int b = cb![i], r = cr![i];
+ var t1 = b >> 2;
+ var t2 = r + (r >> 1);
+ var t3 = yy + 128 - t1;
+ rgb[o] = Clamp(yy + 128 + t2);
+ rgb[o + 1] = Clamp(t3 - (t2 >> 1));
+ rgb[o + 2] = Clamp(t3 + (b << 1));
+ }
+ }
+ return new DjvuPixmap(w, h, rgb);
+ }
+
+ private static byte Clamp(int value) => (byte)Math.Clamp(value, 0, 255);
+}
+
+/// The coefficients of one IW44 component, block by block, each bucket allocated when first coded.
+internal sealed class Iw44Map
+{
+ public Iw44Map(int width, int height)
+ {
+ Width = width;
+ Height = height;
+ BlockWidth = (width + 31) & ~31;
+ BlockHeight = (height + 31) & ~31;
+ Blocks = new Iw44Block[BlockWidth / 32 * (BlockHeight / 32)];
+ }
+
+ public int Width { get; }
+ public int Height { get; }
+ public int BlockWidth { get; }
+ public int BlockHeight { get; }
+ public Iw44Block[] Blocks { get; }
+
+ /// The component's values (−128..127), row 0 at the bottom of the picture.
+ public sbyte[] Reconstruct(bool half, CancellationToken cancellationToken)
+ {
+ int bw = BlockWidth, bh = BlockHeight;
+ var data = new short[(long)bw * bh];
+ var index = 0;
+ for (var i = 0; i < bh; i += 32)
+ {
+ for (var j = 0; j < bw; j += 32)
+ {
+ var block = Blocks[index++];
+ if (block.Coefficients is not { } coefficients)
+ continue;
+ for (var n = 0; n < 1024; n++)
+ {
+ if (!block.Has(n >> 4))
+ {
+ n |= 15;
+ continue;
+ }
+ var at = ZigZag[n];
+ data[(i + (at >> 5)) * bw + j + (at & 31)] = coefficients[n];
+ }
+ }
+ }
+ cancellationToken.ThrowIfCancellationRequested();
+ Iw44Transform.Backward(data, Width, Height, bw, 32, half ? 2 : 1);
+ if (half)
+ {
+ for (var i = 0; i < bh; i += 2)
+ {
+ var row = i * bw;
+ for (var j = 0; j < bw; j += 2)
+ {
+ var v = data[row + j];
+ data[row + j + 1] = v;
+ if (i + 1 < bh)
+ data[row + bw + j] = data[row + bw + j + 1] = v;
+ }
+ }
+ }
+ var result = new sbyte[(long)Width * Height];
+ for (var i = 0; i < Height; i++)
+ {
+ var row = i * bw;
+ var o = i * Width;
+ for (var j = 0; j < Width; j++)
+ result[o + j] = (sbyte)Math.Clamp((data[row + j] + 32) >> 6, -128, 127);
+ }
+ return result;
+ }
+
+ ///
+ /// Where coefficient n of a block lies in its 32 × 32 square (row × 32 + column): n's bits, from the lowest, are
+ /// alternately the column's and the row's, from their highest bit down.
+ ///
+ internal static readonly int[] ZigZag = BuildZigZag();
+
+ private static int[] BuildZigZag()
+ {
+ var table = new int[1024];
+ for (var n = 0; n < 1024; n++)
+ {
+ int x = 0, y = 0;
+ for (var bit = 0; bit < 5; bit++)
+ {
+ x |= ((n >> (2 * bit)) & 1) << (4 - bit);
+ y |= ((n >> (2 * bit + 1)) & 1) << (4 - bit);
+ }
+ table[n] = y * 32 + x;
+ }
+ return table;
+ }
+}
+
+/// A block's 64 buckets of 16 coefficients; a bucket not yet coded is absent.
+internal struct Iw44Block
+{
+ private ulong _present;
+
+ public short[]? Coefficients { get; private set; }
+
+ public readonly bool Has(int bucket) => (_present & (1UL << bucket)) != 0;
+
+ /// Allocates bucket (zeroes) when it is absent.
+ public void Allocate(int bucket)
+ {
+ Coefficients ??= new short[1024];
+ _present |= 1UL << bucket;
+ }
+}
+
+/// Decodes slices into one component's coefficients.
+internal sealed class Iw44Codec
+{
+ private const int Zero = 1, Active = 2, New = 4, Unknown = 8;
+
+ internal static readonly int[] Quantization =
+ [
+ 0x004000, 0x008000, 0x008000, 0x010000, 0x010000, 0x010000, 0x020000, 0x020000,
+ 0x020000, 0x040000, 0x040000, 0x040000, 0x080000, 0x040000, 0x040000, 0x080000,
+ ];
+
+ /// The first bucket and the number of buckets of each band.
+ internal static readonly (int Start, int Size)[] Bands =
+ [(0, 1), (1, 1), (2, 1), (3, 1), (4, 4), (8, 4), (12, 4), (16, 16), (32, 16), (48, 16)];
+
+ private readonly Iw44Map _map;
+ private readonly int[] _quantLow = new int[16];
+ private readonly int[] _quantHigh = new int[10];
+ private readonly byte[] _coefficientState = new byte[256];
+ private readonly byte[] _bucketState = new byte[16];
+ private readonly byte[] _contextStart = new byte[32];
+ private readonly byte[,] _contextBucket = new byte[10, 8];
+ private byte _contextMantissa;
+ private byte _contextRoot;
+ private int _band;
+ private int _bit = 1;
+
+ public Iw44Codec(Iw44Map map)
+ {
+ _map = map;
+ var i = 0;
+ var q = 0;
+ for (; i < 4; i++)
+ _quantLow[i] = Quantization[q++];
+ for (var group = 0; group < 3; group++, q++)
+ {
+ for (var j = 0; j < 4; j++)
+ _quantLow[i++] = Quantization[q];
+ }
+ _quantHigh[0] = 0;
+ for (var j = 1; j < 10; j++)
+ _quantHigh[j] = Quantization[q++];
+ }
+
+ /// Decodes one slice; false once the component has no more.
+ public bool DecodeSlice(ZpDecoder zp)
+ {
+ if (_bit < 0)
+ return false;
+ if (!IsNullSlice())
+ {
+ var (start, size) = Bands[_band];
+ var blocks = _map.Blocks;
+ for (var b = 0; b < blocks.Length; b++)
+ DecodeBuckets(zp, _band, ref blocks[b], start, size);
+ }
+ return FinishSlice();
+ }
+
+ private bool IsNullSlice()
+ {
+ if (_band == 0)
+ {
+ var isNull = true;
+ for (var i = 0; i < 16; i++)
+ {
+ var threshold = _quantLow[i];
+ _coefficientState[i] = Zero;
+ if (threshold is > 0 and < 0x8000)
+ {
+ _coefficientState[i] = Unknown;
+ isNull = false;
+ }
+ }
+ return isNull;
+ }
+ var high = _quantHigh[_band];
+ return !(high is > 0 and < 0x8000);
+ }
+
+ private bool FinishSlice()
+ {
+ _quantHigh[_band] >>= 1;
+ if (_band == 0)
+ {
+ for (var i = 0; i < 16; i++)
+ _quantLow[i] >>= 1;
+ }
+ if (++_band >= Bands.Length)
+ {
+ _band = 0;
+ _bit++;
+ if (_quantHigh[Bands.Length - 1] == 0)
+ {
+ _bit = -1;
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /// The states of the band's buckets and coefficients before a slice; their union.
+ private int Prepare(int first, int count, ref Iw44Block block)
+ {
+ var all = 0;
+ var coefficients = block.Coefficients;
+ if (first != 0)
+ {
+ for (var bucket = 0; bucket < count; bucket++)
+ {
+ var state = 0;
+ if (!block.Has(first + bucket))
+ {
+ state = Unknown;
+ }
+ else
+ {
+ var at = (first + bucket) << 4;
+ for (var i = 0; i < 16; i++)
+ {
+ var c = coefficients![at + i] != 0 ? Active : Unknown;
+ _coefficientState[(bucket << 4) + i] = (byte)c;
+ state |= c;
+ }
+ }
+ _bucketState[bucket] = (byte)state;
+ all |= state;
+ }
+ }
+ else
+ {
+ if (!block.Has(0))
+ {
+ all = Unknown;
+ }
+ else
+ {
+ for (var i = 0; i < 16; i++)
+ {
+ int c = _coefficientState[i];
+ if (c != Zero)
+ c = coefficients![i] != 0 ? Active : Unknown;
+ _coefficientState[i] = (byte)c;
+ all |= c;
+ }
+ }
+ _bucketState[0] = (byte)all;
+ }
+ return all;
+ }
+
+ private void DecodeBuckets(ZpDecoder zp, int band, ref Iw44Block block, int first, int count)
+ {
+ var all = Prepare(first, count, ref block);
+ if (count < 16 || (all & Active) != 0)
+ all |= New;
+ else if ((all & Unknown) != 0 && zp.Decode(ref _contextRoot) != 0)
+ all |= New;
+
+ if ((all & New) != 0)
+ {
+ for (var bucket = 0; bucket < count; bucket++)
+ {
+ if ((_bucketState[bucket] & Unknown) == 0)
+ continue;
+ var ctx = 0;
+ if (band > 0)
+ {
+ // How many of the four coefficients of the parent bucket are significant.
+ var k = (first + bucket) << 2;
+ if (block.Has(k >> 4))
+ {
+ var c = block.Coefficients!;
+ var at = ((k >> 4) << 4) + (k & 15);
+ if (c[at] != 0)
+ ctx++;
+ if (c[at + 1] != 0)
+ ctx++;
+ if (c[at + 2] != 0)
+ ctx++;
+ if (ctx < 3 && c[at + 3] != 0)
+ ctx++;
+ }
+ }
+ if ((all & Active) != 0)
+ ctx |= 4;
+ if (zp.Decode(ref _contextBucket[band, ctx]) != 0)
+ _bucketState[bucket] |= New;
+ }
+
+ var threshold = _quantHigh[band];
+ for (var bucket = 0; bucket < count; bucket++)
+ {
+ if ((_bucketState[bucket] & New) == 0)
+ continue;
+ var state = bucket << 4;
+ if (!block.Has(first + bucket))
+ {
+ block.Allocate(first + bucket);
+ for (var i = 0; i < 16; i++)
+ {
+ if (first != 0 || _coefficientState[state + i] != Zero)
+ _coefficientState[state + i] = Unknown;
+ }
+ }
+ var coefficients = block.Coefficients!;
+ var at = (first + bucket) << 4;
+ var gotcha = 0;
+ for (var i = 0; i < 16; i++)
+ {
+ if ((_coefficientState[state + i] & Unknown) != 0)
+ gotcha++;
+ }
+ for (var i = 0; i < 16; i++)
+ {
+ if ((_coefficientState[state + i] & Unknown) == 0)
+ continue;
+ if (band == 0)
+ threshold = _quantLow[i];
+ var ctx = Math.Min(gotcha, 7);
+ if ((_bucketState[bucket] & Active) != 0)
+ ctx |= 8;
+ if (zp.Decode(ref _contextStart[ctx]) != 0)
+ {
+ _coefficientState[state + i] |= New;
+ var half = threshold >> 1;
+ var value = threshold + half - (half >> 2);
+ coefficients[at + i] = (short)(zp.DecodeIw() != 0 ? -value : value);
+ }
+ if ((_coefficientState[state + i] & New) != 0)
+ gotcha = 0;
+ else if (gotcha > 0)
+ gotcha--;
+ }
+ }
+ }
+
+ if ((all & Active) != 0)
+ {
+ var threshold = _quantHigh[band];
+ var coefficients = block.Coefficients!;
+ for (var bucket = 0; bucket < count; bucket++)
+ {
+ if ((_bucketState[bucket] & Active) == 0)
+ continue;
+ var state = bucket << 4;
+ var at = (first + bucket) << 4;
+ for (var i = 0; i < 16; i++)
+ {
+ if ((_coefficientState[state + i] & Active) == 0)
+ continue;
+ int value = coefficients[at + i];
+ var magnitude = Math.Abs(value);
+ if (band == 0)
+ threshold = _quantLow[i];
+ if (magnitude <= 3 * threshold)
+ {
+ magnitude += threshold >> 2;
+ magnitude += zp.Decode(ref _contextMantissa) != 0 ? threshold >> 1 : -threshold + (threshold >> 1);
+ }
+ else
+ {
+ magnitude += zp.DecodeIw() != 0 ? threshold >> 1 : -threshold + (threshold >> 1);
+ }
+ coefficients[at + i] = (short)(value > 0 ? magnitude : -magnitude);
+ }
+ }
+ }
+ }
+}
+
+/// The IW44 lifting transform, backwards (coefficients → pixels).
+internal static class Iw44Transform
+{
+ /// Runs scales /2 down to over .
+ public static void Backward(short[] p, int w, int h, int rowsize, int begin, int end)
+ {
+ for (var scale = begin >> 1; scale >= end; scale >>= 1)
+ {
+ Vertical(p, w, h, rowsize, scale);
+ Horizontal(p, w, h, rowsize, scale);
+ }
+ }
+
+ private static void Vertical(short[] d, int w, int h, int rowsize, int scale)
+ {
+ var y = 0;
+ var s = scale * rowsize;
+ var s3 = s + s + s;
+ h = ((h - 1) / scale) + 1;
+ var p = 0;
+ while (y - 3 < h)
+ {
+ // Undoes the prediction of the odd rows.
+ var q = p;
+ var e = q + w;
+ if (y >= 3 && y + 3 < h)
+ {
+ for (; q < e; q += scale)
+ {
+ var a = d[q - s] + d[q + s];
+ var b = d[q - s3] + d[q + s3];
+ d[q] = (short)(d[q] - (((a << 3) + a - b + 16) >> 5));
+ }
+ }
+ else if (y < h)
+ {
+ var q1 = y + 1 < h ? q + s : -1;
+ var q3 = y + 3 < h ? q + s3 : -1;
+ for (; q < e; q += scale)
+ {
+ var below1 = q1 >= 0 ? d[q1] : 0;
+ var below3 = q3 >= 0 ? d[q3] : 0;
+ int a, b;
+ if (y >= 3)
+ {
+ a = d[q - s] + below1;
+ b = d[q - s3] + below3;
+ }
+ else if (y >= 1)
+ {
+ a = d[q - s] + below1;
+ b = below3;
+ }
+ else
+ {
+ a = below1;
+ b = below3;
+ }
+ d[q] = (short)(d[q] - (((a << 3) + a - b + 16) >> 5));
+ if (q1 >= 0)
+ q1 += scale;
+ if (q3 >= 0)
+ q3 += scale;
+ }
+ }
+ // Undoes the update of the even rows three rows up.
+ q = p - s3;
+ e = q + w;
+ if (y >= 6 && y < h)
+ {
+ for (; q < e; q += scale)
+ {
+ var a = d[q - s] + d[q + s];
+ var b = d[q - s3] + d[q + s3];
+ d[q] = (short)(d[q] + (((a << 3) + a - b + 8) >> 4));
+ }
+ }
+ else if (y >= 3)
+ {
+ var q1 = y - 2 < h ? q + s : q - s;
+ for (; q < e; q += scale, q1 += scale)
+ {
+ var a = d[q - s] + d[q1];
+ d[q] = (short)(d[q] + ((a + 1) >> 1));
+ }
+ }
+ y += 2;
+ p += s + s;
+ }
+ }
+
+ private static void Horizontal(short[] d, int w, int h, int rowsize, int scale)
+ {
+ var s = scale;
+ var s3 = s + s + s;
+ rowsize *= scale;
+ var p = 0;
+ for (var y = 0; y < h; y += scale, p += rowsize)
+ {
+ var q = p;
+ var e = p + w;
+ int a0 = 0, a1 = 0, a2 = 0, a3 = 0;
+ int b0 = 0, b1 = 0, b2 = 0, b3 = 0;
+ if (q < e)
+ {
+ if (q + s < e)
+ a2 = d[q + s];
+ if (q + s3 < e)
+ a3 = d[q + s3];
+ b2 = b3 = d[q] - ((((a1 + a2) << 3) + (a1 + a2) - a0 - a3 + 16) >> 5);
+ d[q] = (short)b3;
+ q += s + s;
+ }
+ if (q < e)
+ {
+ a0 = a1;
+ a1 = a2;
+ a2 = a3;
+ if (q + s3 < e)
+ a3 = d[q + s3];
+ b3 = d[q] - ((((a1 + a2) << 3) + (a1 + a2) - a0 - a3 + 16) >> 5);
+ d[q] = (short)b3;
+ q += s + s;
+ }
+ if (q < e)
+ {
+ b1 = b2;
+ b2 = b3;
+ a0 = a1;
+ a1 = a2;
+ a2 = a3;
+ if (q + s3 < e)
+ a3 = d[q + s3];
+ b3 = d[q] - ((((a1 + a2) << 3) + (a1 + a2) - a0 - a3 + 16) >> 5);
+ d[q] = (short)b3;
+ d[q - s3] = (short)(d[q - s3] + ((b1 + b2 + 1) >> 1));
+ q += s + s;
+ }
+ while (q + s3 < e)
+ {
+ a0 = a1;
+ a1 = a2;
+ a2 = a3;
+ a3 = d[q + s3];
+ b0 = b1;
+ b1 = b2;
+ b2 = b3;
+ b3 = d[q] - ((((a1 + a2) << 3) + (a1 + a2) - a0 - a3 + 16) >> 5);
+ d[q] = (short)b3;
+ d[q - s3] = (short)(d[q - s3] + ((((b1 + b2) << 3) + (b1 + b2) - b0 - b3 + 8) >> 4));
+ q += s + s;
+ }
+ while (q < e)
+ {
+ a0 = a1;
+ a1 = a2;
+ a2 = a3;
+ a3 = 0;
+ b0 = b1;
+ b1 = b2;
+ b2 = b3;
+ b3 = d[q] - ((((a1 + a2) << 3) + (a1 + a2) - a0 - a3 + 16) >> 5);
+ d[q] = (short)b3;
+ d[q - s3] = (short)(d[q - s3] + ((((b1 + b2) << 3) + (b1 + b2) - b0 - b3 + 8) >> 4));
+ q += s + s;
+ }
+ while (q - s3 < e)
+ {
+ b0 = b1;
+ b1 = b2;
+ b2 = b3;
+ if (q - s3 >= p)
+ d[q - s3] = (short)(d[q - s3] + ((b1 + b2 + 1) >> 1));
+ q += s + s;
+ }
+ }
+ }
+}
diff --git a/src/Filee.Engines/Djvu/Jb2Decoder.cs b/src/Filee.Engines/Djvu/Jb2Decoder.cs
new file mode 100644
index 000000000..4d54d3ed9
--- /dev/null
+++ b/src/Filee.Engines/Djvu/Jb2Decoder.cs
@@ -0,0 +1,519 @@
+// JB2, DjVu's bilevel picture coding (DjVu v3 specification, "JB2"): the mask of a page (Sjbz) or a dictionary of
+// shapes several pages share (Djbz). A stream is a list of records coded with the ZP-coder: new shapes coded pixel by
+// pixel (a 10-pixel context), shapes coded as refinements of a library shape (an 11-pixel context over both), copies of
+// library shapes, and where each one goes (relative to the shape before it or to the start of its line).
+//
+// Numbers are coded in a binary tree of contexts that grows as values are seen (the "number coder"): its cells are
+// counted against DjvuLimits.MaxNumberCells, the shapes, blits and their pixels against the other JB2 limits.
+//
+// Bitmaps are kept as the specification draws them: one byte per pixel, row 0 at the bottom.
+
+using Filee.Engines.Documents;
+
+namespace Filee.Engines.Djvu;
+
+/// One shape: its pixels (1 = black), row 0 at the bottom, and the box of its black pixels.
+internal sealed class Jb2Shape(int width, int height)
+{
+ public int Width { get; } = width;
+ public int Height { get; } = height;
+ public byte[] Bits { get; } = new byte[(long)width * height];
+
+ /// The black pixels' box (left, bottom, right, top, inclusive); right < left when the shape is empty.
+ public (int Left, int Bottom, int Right, int Top) Box { get; private set; }
+
+ public byte this[int x, int y] => (uint)x < (uint)Width && (uint)y < (uint)Height ? Bits[y * Width + x] : (byte)0;
+
+ public void ComputeBox()
+ {
+ int left = Width, right = -1, bottom = Height, top = -1;
+ for (var y = 0; y < Height; y++)
+ {
+ var row = y * Width;
+ for (var x = 0; x < Width; x++)
+ {
+ if (Bits[row + x] == 0)
+ continue;
+ if (x < left)
+ left = x;
+ if (x > right)
+ right = x;
+ if (y < bottom)
+ bottom = y;
+ top = y;
+ }
+ }
+ // An empty shape gets the box the specification's bounding box search ends with.
+ Box = right < 0 ? (0, 0, -1, -1) : (left, bottom, right, top);
+ }
+}
+
+/// A placed shape: its index and where its bottom-left pixel goes (row 0 at the bottom of the page).
+internal readonly record struct Jb2Blit(int Shape, int Left, int Bottom);
+
+/// Shapes a JB2 dictionary (Djbz) holds, inherited ones first.
+internal sealed class Jb2Dictionary(List shapes)
+{
+ public IReadOnlyList Shapes { get; } = shapes;
+}
+
+/// A decoded JB2 page mask.
+internal sealed class Jb2Image(int width, int height, List shapes, List blits)
+{
+ public int Width { get; } = width;
+ public int Height { get; } = height;
+ public IReadOnlyList Shapes { get; } = shapes;
+ public IReadOnlyList Blits { get; } = blits;
+}
+
+/// Decodes JB2 streams.
+internal sealed class Jb2Decoder
+{
+ private const int StartOfData = 0;
+ private const int NewMark = 1;
+ private const int NewMarkLibraryOnly = 2;
+ private const int NewMarkImageOnly = 3;
+ private const int MatchedRefine = 4;
+ private const int MatchedRefineLibraryOnly = 5;
+ private const int MatchedRefineImageOnly = 6;
+ private const int MatchedCopy = 7;
+ private const int NonMarkData = 8;
+ private const int RequiredDictOrReset = 9;
+ private const int PreservedComment = 10;
+ private const int EndOfData = 11;
+
+ private const int BigPositive = 262142;
+ private const int BigNegative = -262143;
+
+ private readonly ZpDecoder _zp;
+ private readonly DjvuLimits _limits;
+ private readonly Jb2Dictionary? _inherited;
+ private readonly CancellationToken _cancellationToken;
+
+ // The number coder's tree: a bit context per cell and its two children (0 = none yet). Cell 0 is unused.
+ private byte[] _bits = new byte[1024];
+ private int[] _left = new int[1024];
+ private int[] _right = new int[1024];
+ private int _cells = 1;
+
+ private int _recordType, _matchIndex, _commentLength, _commentByte;
+ private int _absLocX, _absLocY, _absSizeX, _absSizeY, _imageSize, _inheritedCount;
+ private int _relLocXCurrent, _relLocXLast, _relLocYCurrent, _relLocYLast, _relSizeX, _relSizeY;
+ private byte _refinementFlag, _offsetType;
+ private readonly byte[] _direct = new byte[1024];
+ private readonly byte[] _cross = new byte[2048];
+
+ private bool _started;
+ private bool _usesInherited;
+ private int _columns, _rows;
+ private int _lastLeft, _lastRight, _lastBottom, _lastRowLeft, _lastRowBottom;
+ private readonly int[] _shortList = new int[3];
+ private int _shortListPosition;
+
+ private readonly List _shapes = [];
+ private readonly List _library = []; // library index → shape index
+ private readonly List _blits = [];
+ private long _shapePixels;
+
+ private Jb2Decoder(byte[] data, Jb2Dictionary? inherited, DjvuLimits limits, CancellationToken cancellationToken)
+ {
+ _zp = new ZpDecoder(data);
+ _inherited = inherited;
+ _limits = limits;
+ _cancellationToken = cancellationToken;
+ }
+
+ ///
+ /// Decodes a page mask (Sjbz); is the shared dictionary it may ask for, or null.
+ ///
+ public static Jb2Image DecodeImage(byte[] data, Jb2Dictionary? dictionary, DjvuLimits limits, CancellationToken cancellationToken = default)
+ {
+ var decoder = new Jb2Decoder(data, dictionary, limits, cancellationToken);
+ decoder.Run(image: true);
+ return new Jb2Image(decoder._columns, decoder._rows, decoder._shapes, decoder._blits);
+ }
+
+ /// Decodes a shared dictionary (Djbz); is a dictionary it may build on.
+ public static Jb2Dictionary DecodeDictionary(byte[] data, Jb2Dictionary? inherited, DjvuLimits limits, CancellationToken cancellationToken = default)
+ {
+ var decoder = new Jb2Decoder(data, inherited, limits, cancellationToken);
+ decoder.Run(image: false);
+ return new Jb2Dictionary(decoder._shapes);
+ }
+
+ private void Run(bool image)
+ {
+ var records = 0;
+ while (true)
+ {
+ if ((++records & 0x3FF) == 0)
+ _cancellationToken.ThrowIfCancellationRequested();
+ var type = DecodeNumber(StartOfData, EndOfData, ref _recordType);
+ if (type == EndOfData)
+ break;
+ if (!image && type is NewMark or NewMarkImageOnly or MatchedRefine or MatchedRefineImageOnly or MatchedCopy or NonMarkData)
+ throw new InvalidDataException("A JB2 dictionary holds a record only a page may hold.");
+ if (type is not (StartOfData or RequiredDictOrReset or PreservedComment) && !_started)
+ throw new InvalidDataException("A JB2 stream places shapes before its start record.");
+ switch (type)
+ {
+ case StartOfData:
+ Start(image);
+ break;
+ case NewMark:
+ AddShape(DecodeDirect(DecodeAbsoluteSize()), library: true, placed: true);
+ break;
+ case NewMarkLibraryOnly:
+ AddShape(DecodeDirect(DecodeAbsoluteSize()), library: true, placed: false);
+ break;
+ case NewMarkImageOnly:
+ AddShape(DecodeDirect(DecodeAbsoluteSize()), library: false, placed: true);
+ break;
+ case MatchedRefine:
+ AddShape(DecodeRefinement(), library: true, placed: true);
+ break;
+ case MatchedRefineLibraryOnly:
+ AddShape(DecodeRefinement(), library: true, placed: false);
+ break;
+ case MatchedRefineImageOnly:
+ AddShape(DecodeRefinement(), library: false, placed: true);
+ break;
+ case MatchedCopy:
+ {
+ var match = DecodeMatch();
+ var shapeIndex = _library[match];
+ var box = _shapes[shapeIndex].Box;
+ var (left, bottom) = DecodeRelativeLocation(box.Top - box.Bottom + 1, box.Right - box.Left + 1);
+ AddBlit(shapeIndex, left - box.Left, bottom - box.Bottom);
+ break;
+ }
+ case NonMarkData:
+ {
+ var shape = DecodeDirect(DecodeAbsoluteSize());
+ var index = Keep(shape, library: false);
+ var left = DecodeNumber(1, _columns, ref _absLocX);
+ var top = DecodeNumber(1, _rows, ref _absLocY);
+ AddBlit(index, left - 1, top - shape.Height);
+ break;
+ }
+ case RequiredDictOrReset:
+ if (!_started)
+ RequireDictionary();
+ else
+ ResetNumbers();
+ break;
+ case PreservedComment:
+ {
+ var length = DecodeNumber(0, BigPositive, ref _commentLength);
+ for (var i = 0; i < length; i++)
+ DecodeNumber(0, 255, ref _commentByte);
+ break;
+ }
+ default:
+ throw new InvalidDataException("A JB2 stream has a record of unknown type.");
+ }
+ }
+ if (!_started)
+ throw new InvalidDataException("A JB2 stream has no start record.");
+ }
+
+ private void Start(bool image)
+ {
+ if (_started)
+ throw new InvalidDataException("A JB2 stream has two start records.");
+ var columns = DecodeNumber(0, BigPositive, ref _imageSize);
+ var rows = DecodeNumber(0, BigPositive, ref _imageSize);
+ if (image)
+ {
+ if (columns == 0 || rows == 0)
+ throw new InvalidDataException("A JB2 page mask has no size.");
+ if ((long)columns * rows > _limits.MaxPagePixels)
+ throw DocumentLimits.Exceeded($"A DjVu page mask has more than {DocumentLimits.Count(_limits.MaxPagePixels)} pixels.");
+ _columns = columns;
+ _rows = rows;
+ _lastLeft = 1 + columns;
+ _lastRowBottom = rows;
+ }
+ else
+ {
+ if (columns != 0 || rows != 0)
+ throw new InvalidDataException("A JB2 dictionary has a page size.");
+ _lastLeft = 1;
+ _lastRowBottom = 0;
+ }
+ _lastRowLeft = 0;
+ _lastRight = 0;
+ FillShortList(_lastRowBottom);
+ _started = true;
+ _zp.Decode(ref _refinementFlag);
+ // The library starts with the inherited dictionary's shapes (all of them were library shapes there).
+ if (_usesInherited && _inherited is not null)
+ {
+ foreach (var shape in _inherited.Shapes)
+ {
+ _library.Add(_shapes.Count);
+ _shapes.Add(shape);
+ }
+ }
+ }
+
+ private void RequireDictionary()
+ {
+ var count = DecodeNumber(0, BigPositive, ref _inheritedCount);
+ if (count == 0)
+ return;
+ if (_inherited is null)
+ throw new InvalidDataException("A DjVu page needs a shared shape dictionary its file doesn't include.");
+ if (_inherited.Shapes.Count != count)
+ throw new InvalidDataException("A DjVu page's shared shape dictionary has another number of shapes than it expects.");
+ _usesInherited = true;
+ }
+
+ private void ResetNumbers()
+ {
+ _recordType = _matchIndex = _commentLength = _commentByte = 0;
+ _absLocX = _absLocY = _absSizeX = _absSizeY = _imageSize = _inheritedCount = 0;
+ _relLocXCurrent = _relLocXLast = _relLocYCurrent = _relLocYLast = _relSizeX = _relSizeY = 0;
+ Array.Clear(_bits, 0, _cells);
+ Array.Clear(_left, 0, _cells);
+ Array.Clear(_right, 0, _cells);
+ _cells = 1;
+ }
+
+ private int DecodeMatch()
+ {
+ if (_library.Count == 0)
+ throw new InvalidDataException("A JB2 stream refers to a library shape before it has any.");
+ return DecodeNumber(0, _library.Count - 1, ref _matchIndex);
+ }
+
+ private (int Width, int Height) DecodeAbsoluteSize()
+ {
+ var width = DecodeNumber(0, BigPositive, ref _absSizeX);
+ var height = DecodeNumber(0, BigPositive, ref _absSizeY);
+ return CheckSize(width, height);
+ }
+
+ private (int Width, int Height) CheckSize(int width, int height)
+ {
+ if (width is < 0 or > ushort.MaxValue || height is < 0 or > ushort.MaxValue)
+ throw new InvalidDataException("A JB2 shape has an impossible size.");
+ _shapePixels += (long)width * height;
+ if (_shapePixels > _limits.MaxShapePixels)
+ throw DocumentLimits.Exceeded($"The shapes of a DjVu mask have more than {DocumentLimits.Count(_limits.MaxShapePixels)} pixels.");
+ if (_shapes.Count >= _limits.MaxShapes)
+ throw DocumentLimits.Exceeded($"A DjVu mask has more than {DocumentLimits.Count(_limits.MaxShapes)} shapes.");
+ return (width, height);
+ }
+
+ /// A new shape coded pixel by pixel, top row first.
+ private Jb2Shape DecodeDirect((int Width, int Height) size)
+ {
+ var shape = new Jb2Shape(size.Width, size.Height);
+ var bits = shape.Bits;
+ var w = size.Width;
+ for (var y = size.Height - 1; y >= 0; y--)
+ {
+ if ((y & 0x3F) == 0)
+ _cancellationToken.ThrowIfCancellationRequested();
+ for (var x = 0; x < w; x++)
+ {
+ var context =
+ (shape[x - 1, y + 2] << 9) | (shape[x, y + 2] << 8) | (shape[x + 1, y + 2] << 7) |
+ (shape[x - 2, y + 1] << 6) | (shape[x - 1, y + 1] << 5) | (shape[x, y + 1] << 4) |
+ (shape[x + 1, y + 1] << 3) | (shape[x + 2, y + 1] << 2) |
+ (shape[x - 2, y] << 1) | shape[x - 1, y];
+ bits[y * w + x] = (byte)_zp.Decode(ref _direct[context]);
+ }
+ }
+ return shape;
+ }
+
+ /// A shape coded as a refinement of a library shape (its size relative to the library shape's box).
+ private Jb2Shape DecodeRefinement()
+ {
+ var match = DecodeMatch();
+ var reference = _shapes[_library[match]];
+ var box = reference.Box;
+ var dx = DecodeNumber(BigNegative, BigPositive, ref _relSizeX);
+ var dy = DecodeNumber(BigNegative, BigPositive, ref _relSizeY);
+ var (w, h) = CheckSize(box.Right - box.Left + 1 + dx, box.Top - box.Bottom + 1 + dy);
+ var shape = new Jb2Shape(w, h);
+ // Aligns the centres of the new shape and the reference's box.
+ var xd2c = (w / 2 - w + 1) - ((box.Right - box.Left + 1) / 2 - box.Right);
+ var yd2c = (h / 2 - h + 1) - ((box.Top - box.Bottom + 1) / 2 - box.Top);
+ if (xd2c is < -15 or > 15 || yd2c is < -15 or > 15)
+ throw new InvalidDataException("A JB2 refinement is too far from its library shape.");
+ var bits = shape.Bits;
+ for (var y = h - 1; y >= 0; y--)
+ {
+ if ((y & 0x3F) == 0)
+ _cancellationToken.ThrowIfCancellationRequested();
+ var cy = y + yd2c;
+ for (var x = 0; x < w; x++)
+ {
+ var cx = x + xd2c;
+ var context =
+ (shape[x - 1, y + 1] << 10) | (shape[x, y + 1] << 9) | (shape[x + 1, y + 1] << 8) |
+ (shape[x - 1, y] << 7) |
+ (reference[cx, cy + 1] << 6) |
+ (reference[cx - 1, cy] << 5) | (reference[cx, cy] << 4) | (reference[cx + 1, cy] << 3) |
+ (reference[cx - 1, cy - 1] << 2) | (reference[cx, cy - 1] << 1) | reference[cx + 1, cy - 1];
+ bits[y * w + x] = (byte)_zp.Decode(ref _cross[context]);
+ }
+ }
+ return shape;
+ }
+
+ private int Keep(Jb2Shape shape, bool library)
+ {
+ shape.ComputeBox();
+ var index = _shapes.Count;
+ _shapes.Add(shape);
+ if (library)
+ _library.Add(index);
+ return index;
+ }
+
+ private void AddShape(Jb2Shape shape, bool library, bool placed)
+ {
+ var index = Keep(shape, library);
+ if (!placed)
+ return;
+ var (left, bottom) = DecodeRelativeLocation(shape.Height, shape.Width);
+ AddBlit(index, left, bottom);
+ }
+
+ private void AddBlit(int shape, int left, int bottom)
+ {
+ if (_blits.Count >= _limits.MaxBlits)
+ throw DocumentLimits.Exceeded($"A DjVu mask places more than {DocumentLimits.Count(_limits.MaxBlits)} shapes.");
+ _blits.Add(new Jb2Blit(shape, left, bottom));
+ }
+
+ /// Where a shape goes: after the one before it on its line, or at the start of a new line.
+ private (int Left, int Bottom) DecodeRelativeLocation(int rows, int columns)
+ {
+ int left, bottom;
+ if (_zp.Decode(ref _offsetType) != 0)
+ {
+ var dx = DecodeNumber(BigNegative, BigPositive, ref _relLocXLast);
+ var dy = DecodeNumber(BigNegative, BigPositive, ref _relLocYLast);
+ left = _lastRowLeft + dx;
+ var top = _lastRowBottom + dy;
+ bottom = top - rows + 1;
+ _lastLeft = _lastRowLeft = left;
+ _lastRight = left + columns - 1;
+ _lastBottom = _lastRowBottom = bottom;
+ FillShortList(bottom);
+ }
+ else
+ {
+ var dx = DecodeNumber(BigNegative, BigPositive, ref _relLocXCurrent);
+ var dy = DecodeNumber(BigNegative, BigPositive, ref _relLocYCurrent);
+ left = _lastRight + dx;
+ bottom = _lastBottom + dy;
+ _lastLeft = left;
+ _lastRight = left + columns - 1;
+ _lastBottom = UpdateShortList(bottom);
+ }
+ return (left - 1, bottom - 1);
+ }
+
+ private void FillShortList(int value)
+ {
+ _shortList[0] = _shortList[1] = _shortList[2] = value;
+ _shortListPosition = 0;
+ }
+
+ /// Adds a bottom to the last three and returns their median.
+ private int UpdateShortList(int value)
+ {
+ if (++_shortListPosition == 3)
+ _shortListPosition = 0;
+ var s = _shortList;
+ s[_shortListPosition] = value;
+ return s[0] >= s[1]
+ ? (s[0] > s[2] ? (s[1] >= s[2] ? s[1] : s[2]) : s[0])
+ : (s[0] < s[2] ? (s[1] >= s[2] ? s[2] : s[1]) : s[0]);
+ }
+
+ /// A number in [, ] from the tree rooted at .
+ private int DecodeNumber(int low, int high, ref int root)
+ {
+ var negative = false;
+ var cutoff = 0;
+ var phase = 1;
+ var range = -1;
+ if (root == 0)
+ root = NewCell();
+ var cell = root;
+ while (true)
+ {
+ var decision = low >= cutoff || (high >= cutoff && _zp.Decode(ref _bits[cell]) != 0);
+ switch (phase)
+ {
+ case 1:
+ negative = !decision;
+ if (negative)
+ {
+ var temp = -low - 1;
+ low = -high - 1;
+ high = temp;
+ }
+ phase = 2;
+ cutoff = 1;
+ break;
+ case 2:
+ if (!decision)
+ {
+ phase = 3;
+ range = (cutoff + 1) / 2;
+ if (range == 1)
+ cutoff = 0;
+ else
+ cutoff -= range / 2;
+ }
+ else
+ {
+ cutoff += cutoff + 1;
+ }
+ break;
+ default:
+ range /= 2;
+ if (range != 1)
+ cutoff += decision ? range / 2 : -(range / 2);
+ else if (!decision)
+ cutoff--;
+ break;
+ }
+ if (range == 1)
+ break;
+ var next = decision ? _right[cell] : _left[cell];
+ if (next == 0)
+ {
+ next = NewCell();
+ if (decision)
+ _right[cell] = next;
+ else
+ _left[cell] = next;
+ }
+ cell = next;
+ }
+ return negative ? -cutoff - 1 : cutoff;
+ }
+
+ private int NewCell()
+ {
+ if (_cells >= _limits.MaxNumberCells)
+ throw DocumentLimits.Exceeded("A DjVu mask codes more numbers than Filee reads.");
+ if (_cells == _bits.Length)
+ {
+ var size = Math.Min((long)_bits.Length * 2, _limits.MaxNumberCells);
+ Array.Resize(ref _bits, (int)size);
+ Array.Resize(ref _left, (int)size);
+ Array.Resize(ref _right, (int)size);
+ }
+ return _cells++;
+ }
+}
diff --git a/src/Filee.Engines/Djvu/ZpDecoder.cs b/src/Filee.Engines/Djvu/ZpDecoder.cs
new file mode 100644
index 000000000..6f1539709
--- /dev/null
+++ b/src/Filee.Engines/Djvu/ZpDecoder.cs
@@ -0,0 +1,218 @@
+// The ZP-coder of DjVu (DjVu v3 specification, appendix: the adaptive binary arithmetic coder every compressed DjVu
+// chunk uses: JB2 masks, IW44 wavelet pictures, BZZ streams). Decoding only. A bit is decoded either with an adaptive
+// context (a byte holding a state of the probability table; its low bit is the more probable value) or without one
+// (the "raw" and IW44 forms, a fixed probability).
+//
+// The table is the specification's (P: probability of the less probable value, M: the threshold above which a more
+// probable value moves the state up, UP and DN: the next states). Past the end of its data the coder reads 0xFF bytes,
+// as the specification says; a stream that asks for 25 bytes more than it has is damaged.
+
+namespace Filee.Engines.Djvu;
+
+/// Decodes bits of one ZP-coded stream.
+internal sealed class ZpDecoder
+{
+ private readonly byte[] _data;
+ private readonly int _end;
+ private int _position;
+ private int _delay = 25;
+
+ private uint _a;
+ private uint _code;
+ private uint _fence;
+ private uint _buffer;
+ private int _scount;
+
+ /// Starts decoding bytes of from .
+ public ZpDecoder(byte[] data, int offset, int count)
+ {
+ _data = data;
+ _position = offset;
+ _end = offset + count;
+ _code = (uint)(NextByte() << 8);
+ _code |= (uint)NextByte();
+ Preload();
+ _fence = _code >= 0x8000 ? 0x7FFF : _code;
+ }
+
+ public ZpDecoder(byte[] data) : this(data, 0, data.Length)
+ {
+ }
+
+ /// Decodes a bit with the adaptive context , which it updates.
+ public int Decode(ref byte context)
+ {
+ var z = _a + P[context];
+ if (z <= _fence)
+ {
+ _a = z;
+ return context & 1;
+ }
+ return DecodeAdaptive(ref context, z);
+ }
+
+ /// A bit of even probability (BZZ's block sizes, JB2 has none).
+ public int DecodeRaw() => DecodeFixed(0x8000 + (_a >> 1));
+
+ /// A bit of IW44's fixed probability (signs and refinement of large coefficients).
+ public int DecodeIw() => DecodeFixed(0x8000 + ((_a + _a + _a) >> 3));
+
+ private int DecodeAdaptive(ref byte context, uint z)
+ {
+ var bit = context & 1;
+ // Keeps the interval from reversing (the P of the ZP-coder).
+ var d = 0x6000 + ((z + _a) >> 2);
+ if (z > d)
+ z = d;
+ if (z > _code)
+ {
+ z = 0x10000 - z;
+ _a += z;
+ _code += z;
+ context = Dn[context];
+ Renormalize();
+ return bit ^ 1;
+ }
+ if (_a >= M[context])
+ context = Up[context];
+ ShiftOne(z);
+ return bit;
+ }
+
+ private int DecodeFixed(uint z)
+ {
+ if (z > _code)
+ {
+ z = 0x10000 - z;
+ _a += z;
+ _code += z;
+ Renormalize();
+ return 1;
+ }
+ ShiftOne(z);
+ return 0;
+ }
+
+ private void ShiftOne(uint z)
+ {
+ _scount--;
+ _a = (z << 1) & 0xFFFF;
+ _code = ((_code << 1) & 0xFFFF) | ((_buffer >> _scount) & 1);
+ if (_scount < 16)
+ Preload();
+ _fence = _code >= 0x8000 ? 0x7FFF : _code;
+ }
+
+ /// After a less probable value: shifts until the interval is back above half.
+ private void Renormalize()
+ {
+ var shift = LeadingOnes(_a);
+ _scount -= shift;
+ _a = (_a << shift) & 0xFFFF;
+ _code = ((_code << shift) & 0xFFFF) | ((_buffer >> _scount) & ((1u << shift) - 1));
+ if (_scount < 16)
+ Preload();
+ _fence = _code >= 0x8000 ? 0x7FFF : _code;
+ }
+
+ /// How many of the top bits of the 16-bit are set.
+ private static int LeadingOnes(uint x) => System.Numerics.BitOperations.LeadingZeroCount(~(x << 16) | 0xFFFF);
+
+ private void Preload()
+ {
+ while (_scount <= 24)
+ {
+ _buffer = (_buffer << 8) | (uint)NextByte();
+ _scount += 8;
+ }
+ }
+
+ private int NextByte()
+ {
+ if (_position < _end)
+ return _data[_position++];
+ if (--_delay < 1)
+ throw new InvalidDataException("A compressed DjVu stream ends early.");
+ return 0xFF;
+ }
+
+ internal static readonly ushort[] P =
+ [
+ 0x8000, 0x8000, 0x8000, 0x6bbd, 0x6bbd, 0x5d45, 0x5d45, 0x51b9, 0x51b9, 0x4813, 0x4813, 0x3fd5,
+ 0x3fd5, 0x38b1, 0x38b1, 0x3275, 0x3275, 0x2cfd, 0x2cfd, 0x2825, 0x2825, 0x23ab, 0x23ab, 0x1f87,
+ 0x1f87, 0x1bbb, 0x1bbb, 0x1845, 0x1845, 0x1523, 0x1523, 0x1253, 0x1253, 0x0fcf, 0x0fcf, 0x0d95,
+ 0x0d95, 0x0b9d, 0x0b9d, 0x09e3, 0x09e3, 0x0861, 0x0861, 0x0711, 0x0711, 0x05f1, 0x05f1, 0x04f9,
+ 0x04f9, 0x0425, 0x0425, 0x0371, 0x0371, 0x02d9, 0x02d9, 0x0259, 0x0259, 0x01ed, 0x01ed, 0x0193,
+ 0x0193, 0x0149, 0x0149, 0x010b, 0x010b, 0x00d5, 0x00d5, 0x00a5, 0x00a5, 0x007b, 0x007b, 0x0057,
+ 0x0057, 0x003b, 0x003b, 0x0023, 0x0023, 0x0013, 0x0013, 0x0007, 0x0007, 0x0001, 0x0001, 0x5695,
+ 0x24ee, 0x8000, 0x0d30, 0x481a, 0x0481, 0x3579, 0x017a, 0x24ef, 0x007b, 0x1978, 0x0028, 0x10ca,
+ 0x000d, 0x0b5d, 0x0034, 0x078a, 0x00a0, 0x050f, 0x0117, 0x0358, 0x01ea, 0x0234, 0x0144, 0x0173,
+ 0x0234, 0x00f5, 0x0353, 0x00a1, 0x05c5, 0x011a, 0x03cf, 0x01aa, 0x0285, 0x0286, 0x01ab, 0x03d3,
+ 0x011a, 0x05c5, 0x00ba, 0x08ad, 0x007a, 0x0ccc, 0x01eb, 0x1302, 0x02e6, 0x1b81, 0x045e, 0x24ef,
+ 0x0690, 0x2865, 0x09de, 0x3987, 0x0dc8, 0x2c99, 0x10ca, 0x3b5f, 0x0b5d, 0x5695, 0x078a, 0x8000,
+ 0x050f, 0x24ee, 0x0358, 0x0d30, 0x0234, 0x0481, 0x0173, 0x017a, 0x00f5, 0x007b, 0x00a1, 0x0028,
+ 0x011a, 0x000d, 0x01aa, 0x0034, 0x0286, 0x00a0, 0x03d3, 0x0117, 0x05c5, 0x01ea, 0x08ad, 0x0144,
+ 0x0ccc, 0x0234, 0x1302, 0x0353, 0x1b81, 0x05c5, 0x24ef, 0x03cf, 0x2b74, 0x0285, 0x201d, 0x01ab,
+ 0x1715, 0x011a, 0x0fb7, 0x00ba, 0x0a67, 0x01eb, 0x06e7, 0x02e6, 0x0496, 0x045e, 0x030d, 0x0690,
+ 0x0206, 0x09de, 0x0155, 0x0dc8, 0x00e1, 0x2b74, 0x0094, 0x201d, 0x0188, 0x1715, 0x0252, 0x0fb7,
+ 0x0383, 0x0a67, 0x0547, 0x06e7, 0x07e2, 0x0496, 0x0bc0, 0x030d, 0x1178, 0x0206, 0x19da, 0x0155,
+ 0x24ef, 0x00e1, 0x320e, 0x0094, 0x432a, 0x0188, 0x447d, 0x0252, 0x5ece, 0x0383, 0x8000, 0x0547,
+ 0x481a, 0x07e2, 0x3579, 0x0bc0, 0x24ef, 0x1178, 0x1978, 0x19da, 0x2865, 0x24ef, 0x3987, 0x320e,
+ 0x2c99, 0x432a, 0x3b5f, 0x447d, 0x5695, 0x5ece, 0x8000, 0x8000, 0x5695, 0x481a, 0x481a,
+ 0, 0, 0, 0, 0,
+ ];
+
+ internal static readonly ushort[] M = Pad(
+ [
+ 0x0000, 0x0000, 0x0000, 0x10a5, 0x10a5, 0x1f28, 0x1f28, 0x2bd3, 0x2bd3, 0x36e3, 0x36e3, 0x408c,
+ 0x408c, 0x48fd, 0x48fd, 0x505d, 0x505d, 0x56d0, 0x56d0, 0x5c71, 0x5c71, 0x615b, 0x615b, 0x65a5,
+ 0x65a5, 0x6962, 0x6962, 0x6ca2, 0x6ca2, 0x6f74, 0x6f74, 0x71e6, 0x71e6, 0x7404, 0x7404, 0x75d6,
+ 0x75d6, 0x7768, 0x7768, 0x78c2, 0x78c2, 0x79ea, 0x79ea, 0x7ae7, 0x7ae7, 0x7bbe, 0x7bbe, 0x7c75,
+ 0x7c75, 0x7d0f, 0x7d0f, 0x7d91, 0x7d91, 0x7dfe, 0x7dfe, 0x7e5a, 0x7e5a, 0x7ea6, 0x7ea6, 0x7ee6,
+ 0x7ee6, 0x7f1a, 0x7f1a, 0x7f45, 0x7f45, 0x7f6b, 0x7f6b, 0x7f8d, 0x7f8d, 0x7faa, 0x7faa, 0x7fc3,
+ 0x7fc3, 0x7fd7, 0x7fd7, 0x7fe7, 0x7fe7, 0x7ff2, 0x7ff2, 0x7ffa, 0x7ffa, 0x7fff, 0x7fff,
+ ]);
+
+ internal static readonly byte[] Up =
+ [
+ 84, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
+ 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
+ 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
+ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
+ 82, 81, 82, 9, 86, 5, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 82, 99, 76, 101,
+ 70, 103, 66, 105, 106, 107, 66, 109, 60, 111, 56, 69, 114, 65, 116, 61, 118, 57, 120, 53,
+ 122, 49, 124, 43, 72, 39, 60, 33, 56, 29, 52, 23, 48, 23, 42, 137, 38, 21, 140, 15,
+ 142, 9, 144, 141, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 70, 157, 66, 81, 62, 75,
+ 58, 69, 54, 65, 50, 167, 44, 65, 40, 59, 34, 55, 30, 175, 24, 177, 178, 179, 180, 181,
+ 182, 183, 184, 69, 186, 59, 188, 55, 190, 51, 192, 47, 194, 41, 196, 37, 198, 199, 72, 201,
+ 62, 203, 58, 205, 54, 207, 50, 209, 46, 211, 40, 213, 36, 215, 30, 217, 26, 219, 20, 71,
+ 14, 61, 14, 57, 8, 53, 228, 49, 230, 45, 232, 39, 234, 35, 138, 29, 24, 25, 240, 19,
+ 22, 13, 16, 13, 10, 7, 244, 249, 10, 89, 230,
+ 0, 0, 0, 0, 0,
+ ];
+
+ internal static readonly byte[] Dn =
+ [
+ 145, 4, 3, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
+ 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
+ 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
+ 78, 79, 80, 85, 226, 6, 176, 143, 138, 141, 112, 135, 104, 133, 100, 129, 98, 127, 72, 125,
+ 102, 123, 60, 121, 110, 119, 108, 117, 54, 115, 48, 113, 134, 59, 132, 55, 130, 51, 128, 47,
+ 126, 41, 62, 37, 66, 31, 54, 25, 50, 131, 46, 17, 40, 15, 136, 7, 32, 139, 172, 9,
+ 170, 85, 168, 248, 166, 247, 164, 197, 162, 95, 160, 173, 158, 165, 156, 161, 60, 159, 56, 71,
+ 52, 163, 48, 59, 42, 171, 38, 169, 32, 53, 26, 47, 174, 193, 18, 191, 222, 189, 218, 187,
+ 216, 185, 214, 61, 212, 53, 210, 49, 208, 45, 206, 39, 204, 195, 202, 31, 200, 243, 64, 239,
+ 56, 237, 52, 235, 48, 233, 44, 231, 38, 229, 34, 227, 28, 225, 22, 223, 16, 221, 220, 63,
+ 8, 55, 224, 51, 2, 47, 87, 43, 246, 37, 244, 33, 238, 27, 236, 21, 16, 15, 8, 241,
+ 242, 7, 10, 245, 2, 1, 83, 250, 2, 143, 246,
+ 0, 0, 0, 0, 0,
+ ];
+
+ private static ushort[] Pad(ushort[] values)
+ {
+ var table = new ushort[256];
+ values.CopyTo(table, 0);
+ return table;
+ }
+}
diff --git a/src/Filee.Engines/Drawings/DrawingConverter.cs b/src/Filee.Engines/Drawings/DrawingConverter.cs
index 2f1746214..707c0c37a 100644
--- a/src/Filee.Engines/Drawings/DrawingConverter.cs
+++ b/src/Filee.Engines/Drawings/DrawingConverter.cs
@@ -77,7 +77,8 @@ public Task> ConvertAsync(ConversionStep step, IProgress(p => progress.Report(0.2 + 0.8 * p)), cancellationToken);
+ var pdf = SlideOutput.ToPdf(deck, progress is null ? null : new Progress(p => progress.Report(0.2 + 0.8 * p)), cancellationToken,
+ step.Preset.Document.PdfA);
if (step.Output.Allocate("pdf") is not { } target)
return [];
File.WriteAllBytes(target, pdf);
@@ -106,7 +107,7 @@ private static List WriteFixed(ConversionStep step, IFixedPages document
return [];
using (var output = File.Create(target))
{
- PdfPageWriter.Write(output, all, new PdfDocumentInfo { Title = document.Title },
+ PdfPageWriter.Write(output, all, new PdfDocumentInfo { Title = document.Title, PdfA = step.Preset.Document.PdfA },
progress is null ? null : new Progress(p => progress.Report(0.5 + 0.5 * p)), cancellationToken);
}
return [target];
diff --git a/src/Filee.Engines/Drawings/DrawingFormats.cs b/src/Filee.Engines/Drawings/DrawingFormats.cs
index 6d5dae793..fb8b881e4 100644
--- a/src/Filee.Engines/Drawings/DrawingFormats.cs
+++ b/src/Filee.Engines/Drawings/DrawingFormats.cs
@@ -2,7 +2,7 @@
// into the slide model (one slide per page, the page's size as the slide's) and, when the reader draws only part of
// what the format can hold, a check that names the first thing it can't draw (once the converter's edges are Checked,
// see DrawingConverter, such a file keeps the route it would take without the converter, LibreOffice Draw). The
-// readers add their line here: VSDX (Visio/), ODG / FODG (Odf/Draw), XPS / OpenXPS (Xps/), chart templates (Charts/).
+// readers add their line here: VSDX (Visio/), ODG / OTG / FODG (Odf/Draw), XPS / OpenXPS (Xps/), chart templates (Charts/).
//
// Fixed-layout documents (XPS) and chart templates are not slides: their reader draws pages straight into the page model (IFixedPages).
@@ -56,8 +56,10 @@ internal static class DrawingFormats
[
// Format id vsd is both .vsdx and binary .vsd: the binary one is left to LibreOffice Draw.
new("vsd", VisioReader.Read, VisioReader.FirstUnsupported),
- // OpenDocument drawings, packaged and flat; charts, OLE objects and 3D scenes are left to LibreOffice Draw.
+ // OpenDocument drawings, packaged, templates and flat; charts, OLE objects and 3D scenes are left to LibreOffice
+ // Draw (a template through the ODG it becomes, OdfVariantConverter).
new("odg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)),
+ new("otg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)),
new("fodg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)),
// XPS and OpenXPS documents (.xps, .oxps): Filee's own reader draws every page.
new("xps", null) { ReadPages = (path, token) => XpsDocument.Open(path, token) },
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index d10d7640f..e7b254d4e 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -63,9 +63,11 @@ public static IReadOnlyList CreateAll(EngineEnvironment env, ILogger
new FontConverter(),
new DocxWriterConverter(),
new OdtWriterConverter(),
+ new RtfWriterConverter(),
new MarkupConverter(),
new PptxWriterConverter(),
new OdpWriterConverter(),
+ new OdfVariantConverter(),
new PdfTextConverter(),
new PdfSlidesConverter(),
new PdfTablesConverter(),
@@ -82,6 +84,7 @@ public static IReadOnlyList CreateAll(EngineEnvironment env, ILogger
new FfmpegConverter(loggers?.CreateLogger()),
new CadConverter(),
new DrawingConverter(),
+ new Djvu.DjvuConverter(),
new Gcode.GcodeConverter(loggers?.CreateLogger()),
new ModelConverter(),
new ImageTo3DConverter(),
diff --git a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
index 8f5dd14ba..5d9f48a3a 100644
--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
@@ -13,6 +13,7 @@
using Filee.Engines.Hwp.Hwpx.Odt;
using Filee.Engines.Hwp.Hwpx.Pptx;
using Filee.Engines.Infrastructure;
+using Filee.Engines.Odf;
using Filee.Engines.Odf.Draw;
using Filee.Engines.Ofd;
using Filee.Engines.Office;
@@ -42,6 +43,10 @@ internal static class DocumentReaders
["dot"] = DocReader.Read,
["wps"] = DocReader.Read,
["odt"] = OdtReader.Read,
+ // OpenDocument text templates are the package with another media type; a flat file is read as the package it
+ // splits into (Odf/OdfVariants), beside the pictures.
+ ["ott"] = OdtReader.Read,
+ ["fodt"] = (path, media) => OdfVariants.Read(path, "fodt", MediaParent(media), package => OdtReader.Read(package, media)),
["txt"] = (path, _) => TextDocument(File.ReadAllBytes(path)),
["rtf"] = RtfReader.Read,
["md"] = (path, _) => MarkdownReader.Read(DecodeText(File.ReadAllBytes(path)), Path.GetDirectoryName(Path.GetFullPath(path))!),
@@ -54,6 +59,8 @@ internal static class DocumentReaders
["xls"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "xls")),
["xlt"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "xlt")),
["ods"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "ods")),
+ ["ots"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "ots")),
+ ["fods"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "fods")),
["pptx"] = PptxReader.Read,
["pptm"] = PptxReader.Read,
["potx"] = PptxReader.Read,
@@ -171,6 +178,9 @@ public static async Task ReadAsync(string path, string format, string
throw new NotSupportedException($"There is no document reader for {format.ToUpperInvariant()} files.");
}
+ /// The job's scratch folder the media folder is in, for files a reader makes on the way.
+ private static string MediaParent(string mediaFolder) => Path.GetDirectoryName(Path.GetFullPath(mediaFolder)) ?? Path.GetTempPath();
+
private static HDocument ReadSlides(string path, string mediaFolder) => SlideDeckText.Build(OdfDrawReader.Read(path), mediaFolder);
// ───────────────────────── Pandoc ─────────────────────────
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 26ae151d5..3ee141b45 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -41,10 +41,18 @@ internal sealed class HDocument
public Dictionary FontAlternates { get; } = new(StringComparer.OrdinalIgnoreCase);
///
- /// Word's distance between default tab stops (settings w:defaultTabStop), in HWPUNIT, measured from the margin;
- /// null: 한글's 40 pt from the paragraph's left indent. Only the layout engine uses it.
+ /// The distance between default tab stops of the source's application (Word's w:defaultTabStop, RTF \deftab,
+ /// ODF style:tab-stop-distance), in HWPUNIT, measured from the margin (or the indent, see
+ /// ); null: 한글's 40 pt from the paragraph's left indent. Only the layout
+ /// engine and the RTF writer use it.
///
public int? DefaultTabStop { get; set; }
+
+ ///
+ /// counts from the paragraph's left indent, as LibreOffice's own documents have it
+ /// (TabsRelativeToIndent), not from the margin as Word's. Only the layout engine uses it.
+ ///
+ public bool DefaultTabStopFromIndent { get; set; }
}
/// A run of pages sharing page setup, headers and footers (한글 "구역").
diff --git a/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.cs b/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.cs
index df857ab3d..589a3dc94 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Odt/OdtReader.cs
@@ -104,6 +104,7 @@ private HDocument ReadDocument()
var styles = Load("styles.xml");
LoadStyles(styles, content);
NotesConfiguration(styles?.Root?.Element(Office + "styles"));
+ DefaultTabs();
_document.Title = Load("meta.xml")?.Root?.Element(Office + "meta")?.Element(Dc + "title")?.Value is { } title && title.Trim().Length > 0 ? title.Trim() : null;
var body = new Sink([], body: true);
@@ -114,6 +115,35 @@ private HDocument ReadDocument()
return _document;
}
+ /// LibreOffice's distance between default tab stops when the default paragraph style gives none: 1.25 cm.
+ private const int LibreOfficeTabStop = 3543;
+
+ ///
+ /// Default tab stops as LibreOffice sets them: every style:tab-stop-distance of the default paragraph style (else
+ /// 1.25 cm), measured from the paragraph's indent unless settings.xml turns TabsRelativeToIndent off (documents
+ /// that came from Word measure from the margin).
+ ///
+ private void DefaultTabs()
+ {
+ var distance = _defaults.TryGetValue("paragraph", out var defaults)
+ ? Odf.Length(Attr(defaults.Element(Style + "paragraph-properties"), Style + "tab-stop-distance"))
+ : null;
+ _document.DefaultTabStop = distance is > 0 and < 7_200_000 ? distance : LibreOfficeTabStop;
+ string? relative;
+ try
+ {
+ relative = Load("settings.xml")?.Descendants(Config + "config-item")
+ .FirstOrDefault(item => Attr(item, Config + "name") == "TabsRelativeToIndent")?.Value.Trim();
+ }
+ catch (InvalidDataException)
+ {
+ relative = null; // damaged view settings don't stop the text from being read
+ }
+ _document.DefaultTabStopFromIndent = !string.Equals(relative, "false", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static readonly XNamespace Config = "urn:oasis:names:tc:opendocument:xmlns:config:1.0";
+
private void NotesConfiguration(XElement? styles)
{
foreach (var configuration in styles?.Elements(Text + "notes-configuration") ?? [])
diff --git a/src/Filee.Engines/Hwp/Hwpx/RtfReader.Tables.cs b/src/Filee.Engines/Hwp/Hwpx/RtfReader.Tables.cs
index 9e0aa8e00..2be0e76c0 100644
--- a/src/Filee.Engines/Hwp/Hwpx/RtfReader.Tables.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/RtfReader.Tables.cs
@@ -258,6 +258,8 @@ private void CloseTable(Story story)
};
var left = def.Left;
HCell? previous = null;
+ // The cell before was below a cell spanning rows (\clvmrg): \clmrg cells after it belong to that cell too.
+ var continuing = false;
for (var i = 0; i < contents.Count; i++)
{
var cellDef = i < def.Cells.Count ? def.Cells[i] : new CellDef { Right = left + 1440 };
@@ -272,12 +274,16 @@ private void CloseTable(Story story)
previous.ColSpan += span;
continue;
}
+ if (cellDef.Horizontal == Merge.Continue && continuing)
+ continue;
if (cellDef.Vertical == Merge.Continue && openVertical.TryGetValue(from, out var above))
{
above.RowSpan++;
previous = null;
+ continuing = true;
continue;
}
+ continuing = false;
var cell = new HCell
{
Column = from,
@@ -429,6 +435,11 @@ private static HNumbering Numbering(ListDef list)
2 => "ROMAN_SMALL",
3 => "LATIN_CAPITAL",
4 => "LATIN_SMALL",
+ 10 => "IDEOGRAPH",
+ 18 => "CIRCLED_DIGIT",
+ 24 => "HANGUL_SYLLABLE",
+ 25 => "HANGUL_JAMO",
+ 40 => "HANGUL_PHONETIC",
_ => "DIGIT",
};
numbering.Levels.Add(new HNumberingLevel(format, level.Text.Length > 0 ? level.Text : $"^{numbering.Levels.Count + 1}.", level.Start, Bullet: false));
diff --git a/src/Filee.Engines/Hwp/Hwpx/RtfReader.cs b/src/Filee.Engines/Hwp/Hwpx/RtfReader.cs
index 0822a6d5d..66bed6bd5 100644
--- a/src/Filee.Engines/Hwp/Hwpx/RtfReader.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/RtfReader.cs
@@ -42,6 +42,9 @@ private enum Dest
Picture,
FieldInstruction,
BookmarkStart,
+
+ /// The other name of the font being defined (\falt).
+ FontAlternate,
}
/// Where text and paragraphs go: the body of a section, a note, a header or a footer.
@@ -79,9 +82,11 @@ private record struct CharProps(bool Bold, bool Italic, bool Underline, bool Str
/// \li and \ri: the left and right side.
/// \lin and \rin: the start and end side (the right and left one in a right-to-left paragraph); they win.
/// \rtlpar.
+ /// Tab stops (\tx, measured from the margin, with their kind and leader), or null.
+ /// The kind and leader the next \tx takes (\tqr, \tldot ...).
private record struct ParaProps(HAlign? Align, int Left, int Right, int FirstLine, int Before, int After, int Line, bool Multiple,
bool KeepNext, bool Keep, bool PageBreakBefore, bool InTable, int Style, int ListOverride, int ListLevel, int Outline,
- int? Start = null, int? End = null, bool RightToLeft = false)
+ int? Start = null, int? End = null, bool RightToLeft = false, TabList? Tabs = null, (HTabKind Kind, string? Leader) TabKind = default)
{
public static ParaProps Default => new() { Style = -1, ListOverride = -1, Outline = -1 };
}
@@ -141,6 +146,7 @@ private sealed class Group
private int _fontCharset = -1;
private int _fontCodePage;
private readonly StringBuilder _collected = new();
+ private readonly StringBuilder _fontAlternate = new();
private int _red, _green, _blue;
private int _styleId = -1;
@@ -262,6 +268,8 @@ private HDocument Run()
foreach (var list in _runs.Keys.ToList())
EndRun(list);
ApplyPage();
+ // Default tab stops every \deftab from the margin, as Word sets them; RTF's default is half an inch.
+ _document.DefaultTabStop ??= HwpxUnits.FromTwips(720);
return _document;
}
@@ -302,6 +310,7 @@ private void Word(string word, int? parameter)
case "pc": _ansiCodePage = 437; return;
case "pca": _ansiCodePage = 850; return;
case "deff": _defaultFont = value; return;
+ case "deftab": _document.DefaultTabStop = parameter is > 0 ? HwpxUnits.FromTwips(Math.Min(parameter.Value, 31680)) : _document.DefaultTabStop; return;
case "uc": _g.Uc = Math.Clamp(value, 0, 16); return;
case "u": Unicode(value); return;
@@ -370,6 +379,15 @@ private void Word(string word, int? parameter)
case "ls": _g.Para = p with { ListOverride = value }; return;
case "ilvl": _g.Para = p with { ListLevel = Math.Clamp(value, 0, 8) }; return;
case "outlinelevel": _g.Para = p with { Outline = value }; return;
+ case "tqr": _g.Para = p with { TabKind = (HTabKind.Right, p.TabKind.Leader) }; return;
+ case "tqc": _g.Para = p with { TabKind = (HTabKind.Center, p.TabKind.Leader) }; return;
+ case "tqdec": _g.Para = p with { TabKind = (HTabKind.Decimal, p.TabKind.Leader) }; return;
+ case "tldot" or "tlmdot": _g.Para = p with { TabKind = (p.TabKind.Kind, "DOT") }; return;
+ case "tlhyph": _g.Para = p with { TabKind = (p.TabKind.Kind, "DASH") }; return;
+ case "tlul" or "tlth" or "tleq": _g.Para = p with { TabKind = (p.TabKind.Kind, "SOLID") }; return;
+ case "tx" or "tb":
+ _g.Para = p with { Tabs = (p.Tabs ?? TabList.Empty).Add(value, p.TabKind.Kind, p.TabKind.Leader ?? "NONE"), TabKind = default };
+ return;
// Text
case "par" or "line" or "tab" or "page" or "emdash" or "endash" or "bullet" or "lquote" or "rquote" or "ldblquote"
@@ -468,6 +486,11 @@ private bool Destination(string word, int? parameter)
AddInline(new HBookmark(name));
};
return true;
+ case "falt" when _g.Dest == Dest.FontTable:
+ // The font's other name, used where the font is not installed (as Word's w:altName).
+ _g.Dest = Dest.FontAlternate;
+ _fontAlternate.Clear();
+ return true;
case "nonshppict" or "listtext" or "pntext" or "xe" or "tc" or "txe" or "rxe" or "bkmkend" or "annotation" or "atnid"
or "atnauthor" or "template" or "comment" or "author" or "operator" or "company" or "manager" or "category"
or "keywords" or "subject" or "doccomm" or "hlinkbase" or "creatim" or "revtim" or "printim" or "buptim"
@@ -589,6 +612,10 @@ private void Decoded(string text)
case Dest.Title or Dest.LevelText or Dest.BookmarkStart:
_collected.Append(text);
break;
+ case Dest.FontAlternate:
+ if (_fontAlternate.Length < 256)
+ _fontAlternate.Append(text);
+ break;
case Dest.FieldInstruction:
_g.Field?.Instruction.Append(text);
break;
@@ -610,8 +637,12 @@ private void FontName(string text)
Definitions(_fonts.Count, "fonts");
var codePage = _fontCodePage > 0 ? _fontCodePage : CharsetCodePage(_fontCharset);
var eastAsian = _fontCharset is 128 or 129 or 130 or 134 or 136;
- _fonts[_fontIndex] = (_collected.ToString().Trim(), codePage, eastAsian);
+ var name = _collected.ToString().Trim();
+ _fonts[_fontIndex] = (name, codePage, eastAsian);
+ if (name.Length > 0 && _fontAlternate.ToString().Trim() is { Length: > 0 } alternate && !alternate.Equals(name, StringComparison.OrdinalIgnoreCase))
+ _document.FontAlternates.TryAdd(name, alternate);
}
+ _fontAlternate.Clear();
_collected.Clear();
_fontIndex = _fontCharset = -1;
_fontCodePage = 0;
@@ -621,7 +652,7 @@ private void FontName(string text)
/// The code page text is decoded with: the font's, else the document's.
private int CodePage()
{
- if (_g.Dest == Dest.FontTable)
+ if (_g.Dest is Dest.FontTable or Dest.FontAlternate)
return _fontCodePage > 0 ? _fontCodePage : CharsetCodePage(_fontCharset) is > 0 and var charset ? charset : _ansiCodePage;
var font = _g.Char.Font >= 0 ? _g.Char.Font : _defaultFont;
return _fonts.TryGetValue(font, out var entry) && entry.CodePage > 0 ? entry.CodePage : _ansiCodePage;
@@ -754,7 +785,48 @@ private HCharFormat Format(CharProps c)
_ => new HLineSpacing(HLineSpacingKind.AtLeast, HwpxUnits.FromTwips(p.Line)),
},
KeepWithNext: p.KeepNext ? true : null,
- KeepLines: p.Keep ? true : null);
+ KeepLines: p.Keep ? true : null,
+ Tabs: TabStops(p));
+
+ ///
+ /// The paragraph's tab stops as the model has them: measured from its start indent (RTF measures from the margin),
+ /// in order; null when it has none.
+ ///
+ private static List? TabStops(ParaProps p)
+ {
+ if (p.Tabs is not { Count: > 0 } tabs)
+ return null;
+ var indent = p.Start ?? (p.RightToLeft ? p.Right : p.Left);
+ return [.. tabs.Stops.OrderBy(t => t.Position).Select(t => t with { Position = Math.Max(0, HwpxUnits.FromTwips(t.Position - indent)) })];
+ }
+
+ ///
+ /// A paragraph's tab stops as read (positions in twips from the margin). It is never changed, so the copies of the
+ /// properties each group makes share it.
+ ///
+ private sealed class TabList
+ {
+ /// Stops a paragraph keeps (Word allows 64); further \tx are ignored.
+ private const int MaxStops = 256;
+
+ public static readonly TabList Empty = new([]);
+
+ private TabList(List stops) => Stops = stops;
+
+ public IReadOnlyList Stops { get; }
+
+ public int Count => Stops.Count;
+
+ /// A list with one more stop (one at the same position is replaced).
+ public TabList Add(int position, HTabKind kind, string leader)
+ {
+ if (Stops.Count >= MaxStops)
+ return this;
+ var stops = Stops.Where(t => t.Position != position).ToList();
+ stops.Add(new HTabStop(position, kind, leader));
+ return new TabList(stops);
+ }
+ }
// ───────────────────────── Paragraphs and sections ─────────────────────────
@@ -832,6 +904,10 @@ private void StartNote()
level.Dispose();
var note = new HNote(group.Endnote);
note.Blocks.AddRange(story.Blocks);
+ // Word's notes start with their number (\chftn) and a space; the layout puts the number there itself.
+ if (note.Blocks.FirstOrDefault() is HParagraph first && first.Inlines.FindIndex(i => i is not HNoteNumber) is var index and > 0
+ && first.Inlines[index] is HText { Text: var leading } text)
+ first.Inlines[index] = new HText(leading.TrimStart(), text.Format);
EndRun(parent);
parent.Add(note);
};
@@ -855,7 +931,7 @@ private void StartHeaderFooter(string word)
// First-page headers and footers have no place in the model: the others apply.
if (word.EndsWith('f'))
return;
- var pages = word.EndsWith('l') ? HPageType.Even : word.EndsWith('r') ? HPageType.Odd : HPageType.Both;
+ var pages = word is "headerl" or "footerl" ? HPageType.Even : word is "headerr" or "footerr" ? HPageType.Odd : HPageType.Both;
var part = new HHeaderFooter(pages);
part.Blocks.AddRange(story.Blocks);
(word.StartsWith("header", StringComparison.Ordinal) ? section.Headers : section.Footers).Add(part);
diff --git a/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Body.cs
new file mode 100644
index 000000000..67125c508
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Body.cs
@@ -0,0 +1,727 @@
+// Document body of an RTF file: paragraphs (\pard ... \par), their character formatting, links, bookmarks, fields,
+// notes and tables.
+//
+// RTF paragraphs carry all of their formatting: after \pard\plain each one repeats what its style has (the heading
+// styles' bold and size, Normal's 10 pt and line spacing), then what the model sets. A run is a group whose control
+// words are only those that differ from the paragraph mark's, so the run's formatting ends with its group. Text is
+// split where it changes from Latin to East Asian script, each part in the font of its slot (RTF has one \f at a time).
+//
+// A table is a run of rows: \trowd with the row's cell definitions (\cellx at each cell's right edge), then the
+// cells' paragraphs (\intbl), each cell ending with \cell and the row with \row. Cells spanning columns are \clmgf
+// with \clmrg cells after them, cells spanning rows \clvmgf with \clvmrg cells below, so every row has a cell at each
+// edge of the grid. Tables in cells are nested tables (\itapN, \nestcell, \nestrow with their \nesttableprops).
+
+using System.Text;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class RtfWriter
+{
+ /// What is being written: notes are only allowed in the body (and its tables).
+ private enum Story
+ {
+ Body,
+ Note,
+ Header,
+ TextBox,
+ }
+
+ /// How the last paragraph of a block list ends: with the story (no mark) or the cell (\cell, \nestcell).
+ private enum BlockEnd
+ {
+ Story,
+ Cell,
+ }
+
+ /// Width (HWPUNIT) available to the content being written: column, table cell or text box.
+ private int _width = DefaultPage.TextWidth;
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ /// Tables around the blocks (0 outside a table, 1 in a cell of a table in the text ...).
+ private void Blocks(IReadOnlyList blocks, Story story, int depth, BlockEnd end)
+ {
+ // A table's caption is its paragraphs after it.
+ if (blocks.Any(b => b is HTable { Caption.Count: > 0 }))
+ blocks = blocks.SelectMany(b => b is HTable { Caption.Count: > 0 } t ? t.Caption.Prepend(b) : [b]).ToList();
+ for (var i = 0; i < blocks.Count; i++)
+ {
+ _token.ThrowIfCancellationRequested();
+ var last = i == blocks.Count - 1;
+ switch (blocks[i])
+ {
+ case HParagraph paragraph:
+ var mark = !last ? "\\par" : end == BlockEnd.Cell ? CellEnd(depth) : "";
+ Paragraph(paragraph, story, depth, mark);
+ break;
+ case HTable table:
+ // Two tables in a row would become one: a paragraph keeps them apart.
+ if (i > 0 && blocks[i - 1] is HTable)
+ EmptyParagraph(depth, "\\par");
+ Table(table, story, depth + 1);
+ if (last)
+ EmptyParagraph(depth, end == BlockEnd.Cell ? CellEnd(depth) : "");
+ break;
+ }
+ }
+ if (blocks.Count == 0 && end == BlockEnd.Cell)
+ EmptyParagraph(depth, CellEnd(depth));
+ }
+
+ private static string CellEnd(int depth) => depth > 1 ? "\\nestcell" : "\\cell";
+
+ /// A paragraph without text (at a table's end it also resets the paragraph properties the table had).
+ private void EmptyParagraph(int depth, string mark)
+ {
+ _out.Control("\\pard\\plain" + InTable(depth) + mark);
+ _out.Line();
+ }
+
+ private static string InTable(int depth) => depth == 0 ? "" : depth == 1 ? "\\intbl" : $"\\intbl\\itap{Number(depth)}";
+
+ // ───────────────────────── Paragraphs ─────────────────────────
+
+ /// The formatting a paragraph's style gives it, which the paragraph repeats.
+ private readonly record struct StyleBase(int Style, bool Bold, int HalfPoints, int Before, int After, HLineSpacing Line, bool Keep,
+ IReadOnlyList? Tabs);
+
+ /// Normal's line spacing: 160 % of the font size in 한글's terms (Word's 1.23 lines, \sl295\slmult1).
+ private static readonly HLineSpacing NormalLine = new(HLineSpacingKind.Percent, 160);
+
+ /// Single lines (headers, footers and notes, as the DOCX writer's styles).
+ private static readonly HLineSpacing SingleLine = new(HLineSpacingKind.Percent, 130);
+
+ /// The tab stops of the DOCX writer's header and footer styles: centre and right of an A4 text width.
+ private static readonly HTabStop[] HeaderTabs = [new(45130, HTabKind.Center, "NONE"), new(90260, HTabKind.Right, "NONE")];
+
+ private static StyleBase BaseOf(HParagraph paragraph, Story story)
+ {
+ if (paragraph.HeadingLevel is >= 1 and <= 9 and var level)
+ return new StyleBase(level, true, HeadingSizes[level - 1], level <= 2 ? 1200 : 800, 400, NormalLine, true, null);
+ return story switch
+ {
+ Story.Note => new StyleBase(0, false, 18, 0, 0, SingleLine, false, null),
+ Story.Header => new StyleBase(0, false, DefaultHalfPoints, 0, 0, SingleLine, false, HeaderTabs),
+ _ => new StyleBase(0, false, DefaultHalfPoints, 0, 0, NormalLine, false, null),
+ };
+ }
+
+ /// What ends the paragraph: \par, \cell, \nestcell, or nothing for the last one of its story.
+ private void Paragraph(HParagraph paragraph, Story story, int depth, string mark)
+ {
+ var o = _out;
+ var style = BaseOf(paragraph, story);
+ o.Control("\\pard\\plain" + ParagraphProperties(paragraph, style, depth));
+
+ // The paragraph mark's formatting is the paragraph's: runs change only what differs from it.
+ var markChars = Resolve(paragraph.MarkFormat, style);
+ o.Control(Difference(PlainChars, markChars) + $"\\f{Number(FontIndex(markChars.Latin, 0))}");
+ var state = new RunState(markChars, FontIndex(markChars.Latin, 0));
+ if (paragraph.ColumnBreakBefore)
+ o.Control("\\column");
+ if (story == Story.Note && _noteNumber)
+ {
+ _noteNumber = false;
+ // The note's own number first (the model's note numbers are where the source had them; they are left out).
+ o.Open();
+ o.Control("\\super\\chftn");
+ o.Close();
+ o.Raw(" ");
+ }
+ Inlines(paragraph.Inlines, state, style, story, depth);
+ o.Control(mark);
+ o.Line();
+ }
+
+ /// The note being written still needs its number (\chftn) in front of its first paragraph.
+ private bool _noteNumber;
+
+ /// Paragraph control words after \pard: style, table, list, alignment, indents, spacing, keeps, tabs, borders.
+ private string ParagraphProperties(HParagraph paragraph, StyleBase style, int depth)
+ {
+ var f = paragraph.Format;
+ var sb = new StringBuilder();
+ if (style.Style > 0)
+ sb.Append($"\\s{Number(style.Style)}\\outlinelevel{Number(style.Style - 1)}");
+ sb.Append(InTable(depth));
+ if (paragraph.List is { Numbered: true } list)
+ sb.Append($"\\ls{Number(ListNumber(list.Numbering))}\\ilvl{Number(Math.Clamp(list.Level, 0, 8))}");
+
+ // Right to left, the model's Align, Left and Right name the start and end side; RTF's \ql, \li ... are the
+ // left and right ones, and \lin / \rin the start and end.
+ var rtl = f.RightToLeft == true;
+ if (rtl)
+ sb.Append("\\rtlpar");
+ var align = f.Align ?? HAlign.Left;
+ if (rtl && align is HAlign.Left or HAlign.Right)
+ align = align == HAlign.Left ? HAlign.Right : HAlign.Left;
+ sb.Append(align switch
+ {
+ HAlign.Center => "\\qc",
+ HAlign.Right => "\\qr",
+ HAlign.Justify => "\\qj",
+ HAlign.Distribute => "\\qd",
+ _ => "\\ql",
+ });
+
+ var (left, firstLine) = (f.Left, f.FirstLine);
+ if (paragraph.List is { } item && left is null)
+ {
+ // List paragraphs take their level's indent; continuation paragraphs line up with the item's text.
+ left = ListIndent(item.Level) * 5;
+ firstLine ??= item.Numbered ? -2000 : 0;
+ }
+ var start = Twips(left ?? 0);
+ var end = Twips(f.Right ?? 0);
+ sb.Append($"\\li{Number(rtl ? end : start)}\\ri{Number(rtl ? start : end)}\\lin{Number(start)}\\rin{Number(end)}\\fi{Number(Twips(firstLine ?? 0))}");
+ sb.Append($"\\sb{Number(Math.Max(0, Twips(f.Before ?? style.Before)))}\\sa{Number(Math.Max(0, Twips(f.After ?? style.After)))}");
+ var line = f.LineSpacing ?? style.Line;
+ sb.Append(line.Kind switch
+ {
+ HLineSpacingKind.Fixed => $"\\sl-{Number(Math.Max(20, Twips(line.Value)))}\\slmult0",
+ HLineSpacingKind.AtLeast => $"\\sl{Number(Math.Max(20, Twips(line.Value)))}\\slmult0",
+ // 한글 percentages are of the font size, RTF's multiples of the font's line (≈ 1.3 em), as in DOCX.
+ _ => $"\\sl{Number(Math.Clamp((int)Math.Round(line.Value * 240 / 130.0), 24, 2400))}\\slmult1",
+ });
+ if (f.KeepWithNext ?? style.Keep)
+ sb.Append("\\keepn");
+ if (f.KeepLines ?? style.Keep)
+ sb.Append("\\keep");
+ sb.Append(f.WidowOrphan == false ? "\\nowidctlpar" : "\\widctlpar");
+ if (paragraph.PageBreakBefore)
+ sb.Append("\\pagebb");
+
+ foreach (var tab in (f.Tabs ?? style.Tabs ?? []).OrderBy(t => t.Position))
+ {
+ sb.Append(tab.Kind switch
+ {
+ HTabKind.Right => "\\tqr",
+ HTabKind.Center => "\\tqc",
+ HTabKind.Decimal => "\\tqdec",
+ _ => "",
+ });
+ sb.Append(tab.Leader switch
+ {
+ "DOT" => "\\tldot",
+ "DASH" => "\\tlhyph",
+ "SOLID" => "\\tlul",
+ _ => "",
+ });
+ // The model measures tab stops from the paragraph's indent, RTF from the margin.
+ sb.Append($"\\tx{Number(Math.Max(0, Twips(tab.Position + (left ?? 0))))}");
+ }
+
+ if (f.Borders is { } borders)
+ {
+ foreach (var (side, border) in new[] { ("t", borders.Top), ("l", borders.Left), ("b", borders.Bottom), ("r", borders.Right) })
+ {
+ if (border.Style != HBorderStyle.None)
+ sb.Append($"\\brdr{side}").Append(Border(border)).Append("\\brsp20");
+ }
+ }
+ else if (f.LeftBar is { } bar && bar.Style != HBorderStyle.None)
+ {
+ sb.Append("\\brdrl").Append(Border(bar)).Append("\\brsp120");
+ }
+ if (ColorIndex(f.Fill) is > 0 and var fill)
+ sb.Append($"\\cbpat{Number(fill)}");
+ return sb.ToString();
+ }
+
+ /// \brdrs\brdrw15\brdrcf1: a border's style, width (twips, at most 75) and colour.
+ private string Border(HBorder border)
+ {
+ var style = border.Style switch
+ {
+ HBorderStyle.Dash => "\\brdrdash",
+ HBorderStyle.Dot => "\\brdrdot",
+ HBorderStyle.DashDot => "\\brdrdashd",
+ HBorderStyle.Double => "\\brdrdb",
+ _ => "\\brdrs",
+ };
+ var width = Math.Clamp((int)Math.Round(border.WidthMm / 25.4 * 1440), 1, 75);
+ var color = ColorIndex(border.Color);
+ return $"{style}\\brdrw{Number(width)}{(color > 0 ? $"\\brdrcf{Number(color)}" : "")}";
+ }
+
+ // ───────────────────────── Character formatting ─────────────────────────
+
+ /// Character formatting with every member decided (the model's null ones from the paragraph's style).
+ /// 0 normal, 1 superscript, 2 subscript.
+ /// Letter spacing in twips (\expndtw).
+ private readonly record struct Chars(bool Bold, bool Italic, bool Underline, bool Strike, int Script, int HalfPoints,
+ string Latin, string EastAsian, int Color, int Shade, int Expand);
+
+ /// What \plain leaves: RTF's 12 pt in the default font, nothing else.
+ private static readonly Chars PlainChars = new(false, false, false, false, 0, 24, DefaultLatinFont, DefaultEastAsianFont, 0, 0, 0);
+
+ private Chars Resolve(HCharFormat f, StyleBase style)
+ {
+ var halfPoints = f.Size is { } size ? Math.Clamp((int)Math.Round(size / 50.0), 2, 3276) : style.HalfPoints;
+ // 한글 letter spacing is a percentage of the font size, RTF's an absolute distance in twips.
+ var expand = f.Spacing is { } spacing and not 0 ? (int)Math.Round(spacing * halfPoints * 10 / 100.0) : 0;
+ return new Chars(
+ f.Bold ?? style.Bold,
+ f.Italic ?? false,
+ f.Underline ?? false,
+ f.Strike ?? false,
+ f.Superscript == true ? 1 : f.Subscript == true ? 2 : 0,
+ halfPoints,
+ f.Font is { Length: > 0 } latin ? latin : DefaultLatinFont,
+ f.EastAsianFont is { Length: > 0 } eastAsian ? eastAsian : f.Font is { Length: > 0 } both ? both : DefaultEastAsianFont,
+ ColorIndex(f.Color),
+ ColorIndex(f.Shade),
+ expand);
+ }
+
+ /// The control words that turn into (fonts are set per piece of text).
+ private static string Difference(Chars from, Chars to)
+ {
+ var sb = new StringBuilder();
+ if (from.Bold != to.Bold)
+ sb.Append(to.Bold ? "\\b" : "\\b0");
+ if (from.Italic != to.Italic)
+ sb.Append(to.Italic ? "\\i" : "\\i0");
+ if (from.Underline != to.Underline)
+ sb.Append(to.Underline ? "\\ul" : "\\ulnone");
+ if (from.Strike != to.Strike)
+ sb.Append(to.Strike ? "\\strike" : "\\strike0");
+ if (from.Script != to.Script)
+ sb.Append(to.Script switch { 1 => "\\super", 2 => "\\sub", _ => "\\nosupersub" });
+ if (from.HalfPoints != to.HalfPoints)
+ sb.Append($"\\fs{Number(to.HalfPoints)}");
+ if (from.Color != to.Color)
+ sb.Append($"\\cf{Number(to.Color)}");
+ if (from.Shade != to.Shade)
+ sb.Append($"\\chshdng0\\chcbpat{Number(to.Shade)}");
+ if (from.Expand != to.Expand)
+ sb.Append($"\\expndtw{Number(to.Expand)}");
+ return sb.ToString();
+ }
+
+ /// The formatting in effect where runs are written (the paragraph mark's), and the \f set there.
+ private sealed record RunState(Chars Chars, int Font);
+
+ private void Inlines(IEnumerable inlines, RunState state, StyleBase style, Story story, int depth)
+ {
+ var o = _out;
+ foreach (var inline in inlines)
+ {
+ switch (inline)
+ {
+ case HText text: // equations too: their TeX source or linear text
+ Run(text.Format, state, style, () => Text(text.Text, Resolve(text.Format, style), state.Font));
+ break;
+ case HLineBreak lineBreak:
+ Run(lineBreak.Format, state, style, () => o.Control("\\line"));
+ break;
+ case HTab tab:
+ Run(tab.Format, state, style, () => o.Control("\\tab"));
+ break;
+ case HLink link:
+ Link(link, state, style, story, depth);
+ break;
+ case HBookmark bookmark:
+ Bookmark(bookmark.Name);
+ break;
+ case HField field:
+ Run(field.Format, state, style, () =>
+ {
+ o.Open();
+ o.Control("\\field");
+ o.Open();
+ o.Control("\\*\\fldinst");
+ o.Raw(field.Kind == HFieldKind.PageNumber ? "PAGE" : "NUMPAGES");
+ o.Close();
+ o.Open();
+ o.Control("\\fldrslt");
+ o.Text(field.Stored is { Length: > 0 } stored ? stored : "1", 1252);
+ o.Close();
+ o.Close();
+ });
+ break;
+ case HNote note:
+ Note(note, state, style, story);
+ break;
+ case HImage image:
+ Picture(image);
+ break;
+ case HTextBox box:
+ TextBox(box, state, style);
+ break;
+ case HShape shape:
+ Shape(shape);
+ break;
+ }
+ }
+ }
+
+ /// A group with the formatting of where it differs from the paragraph mark's.
+ private void Run(HCharFormat format, RunState state, StyleBase style, Action content)
+ {
+ _out.Open();
+ _out.Control(Difference(state.Chars, Resolve(format, style)));
+ content();
+ _out.Close();
+ }
+
+ ///
+ /// Text in pieces of one script: East Asian text in the East Asian font (of an East Asian \fcharset), other text
+ /// in the Latin font of its script's \fcharset; spaces and punctuation stay with the piece around them. Arabic
+ /// and Hebrew pieces are marked right to left (\rtlch), as Word does.
+ ///
+ private void Text(string text, Chars chars, int paragraphFont)
+ {
+ var o = _out;
+ var current = paragraphFont;
+ var start = 0;
+ var kind = Script.Neutral;
+ for (var i = 0; i <= text.Length; i++)
+ {
+ var next = i < text.Length ? ScriptOf(text, i) : Script.Neutral;
+ if (i < text.Length && (next == Script.Neutral || next == kind || kind == Script.Neutral))
+ {
+ if (kind == Script.Neutral)
+ kind = next;
+ if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length)
+ i++;
+ continue;
+ }
+ if (i > start)
+ {
+ var piece = text[start..i];
+ var (font, codePage) = FontFor(kind, chars, piece);
+ if (font != current)
+ {
+ o.Control($"\\f{Number(font)}");
+ current = font;
+ }
+ if (kind is Script.Arabic or Script.Hebrew)
+ o.Control("\\rtlch");
+ o.Text(piece, codePage);
+ if (kind is Script.Arabic or Script.Hebrew)
+ o.Control("\\ltrch");
+ }
+ start = i;
+ kind = next;
+ }
+ }
+
+ /// The scripts text pieces are split by (each has an \fcharset of its own).
+ private enum Script
+ {
+ /// Spaces, digits and punctuation: they go with the text around them.
+ Neutral,
+ Latin,
+ Greek,
+ Cyrillic,
+ Hebrew,
+ Arabic,
+ Thai,
+
+ /// Hangul, kana and Chinese characters, with CJK punctuation and full-width forms.
+ EastAsian,
+ }
+
+ private static Script ScriptOf(string text, int i)
+ {
+ var c = text[i];
+ if (char.IsHighSurrogate(c))
+ return c is >= '\uD840' and <= '\uD87F' ? Script.EastAsian : Script.Latin; // CJK extensions B..F
+ if (char.IsLowSurrogate(c))
+ return Script.Neutral;
+ if (c < '\u0080')
+ return char.IsAsciiLetter(c) ? Script.Latin : Script.Neutral;
+ return c switch
+ {
+ >= '\u0370' and <= '\u03FF' => Script.Greek,
+ >= '\u0400' and <= '\u052F' => Script.Cyrillic,
+ >= '\u0590' and <= '\u05FF' => Script.Hebrew,
+ >= '\u0600' and <= '\u06FF' or >= '\u0750' and <= '\u077F' => Script.Arabic,
+ >= '\u0E00' and <= '\u0E7F' => Script.Thai,
+ >= '\u1100' and <= '\u11FF' or >= '\u3000' and <= '\u4DBF' or >= '\u4E00' and <= '\u9FFF' or >= '\uAC00' and <= '\uD7AF'
+ or >= '\uF900' and <= '\uFAFF' or >= '\uFF00' and <= '\uFFEF' => Script.EastAsian,
+ >= '\u2000' and <= '\u206F' or '\u00A0' => Script.Neutral,
+ _ => Script.Latin,
+ };
+ }
+
+ /// The font index and code page of a piece of text of .
+ private (int Font, int CodePage) FontFor(Script script, Chars chars, string piece)
+ {
+ if (script == Script.EastAsian)
+ {
+ // The text that first uses the font decides its \fcharset: Korean, Japanese, else by the font's name.
+ var charset = piece.Any(c => c is >= '\uAC00' and <= '\uD7AF' or >= '\u1100' and <= '\u11FF' or >= '\u3130' and <= '\u318F') ? 129
+ : piece.Any(c => c is >= '\u3040' and <= '\u30FF' or >= '\u31F0' and <= '\u31FF') ? 128
+ : HanCharset(chars.EastAsian);
+ var index = EastAsianFontIndex(chars.EastAsian, charset);
+ return (index, CodePage(_fonts[index].Charset));
+ }
+ var latin = script switch
+ {
+ Script.Greek => 161,
+ Script.Cyrillic => 204,
+ Script.Hebrew => 177,
+ Script.Arabic => 178,
+ Script.Thai => 222,
+ _ => 0,
+ };
+ return (FontIndex(chars.Latin, latin), CodePage(latin));
+ }
+
+ /// The \fcharset of Chinese characters in a font: Korean, Japanese or Chinese by the font's name.
+ private static int HanCharset(string font)
+ {
+ if (font.Any(c => c is >= '\uAC00' and <= '\uD7AF') || font.Contains("Gothic", StringComparison.OrdinalIgnoreCase) && font.Contains("Malgun", StringComparison.OrdinalIgnoreCase)
+ || font is "Batang" or "BatangChe" or "Gulim" or "GulimChe" or "Dotum" or "DotumChe" or "Gungsuh")
+ return 129;
+ if (font.Any(c => c is >= '\u3040' and <= '\u30FF') || font.StartsWith("MS ", StringComparison.Ordinal) || font.StartsWith("Yu ", StringComparison.Ordinal)
+ || font.StartsWith("Meiryo", StringComparison.Ordinal))
+ return 128;
+ if (font.Contains("Ming", StringComparison.OrdinalIgnoreCase) || font is "新細明體" or "細明體" or "標楷體" or "微軟正黑體" or "Microsoft JhengHei" or "DFKai-SB")
+ return 136;
+ if (font.Any(c => c is >= '\u4E00' and <= '\u9FFF') || font.StartsWith("Sim", StringComparison.Ordinal) || font.Contains("YaHei", StringComparison.Ordinal))
+ return 134;
+ return 129; // the default East Asian font, 맑은 고딕
+ }
+
+ // ───────────────────────── Links, bookmarks, notes ─────────────────────────
+
+ /// A HYPERLINK field: its instruction (\l for a bookmark in the document) and the link's text as its result.
+ private void Link(HLink link, RunState state, StyleBase style, Story story, int depth)
+ {
+ var o = _out;
+ var target = link.Target.Replace("\"", "%22", StringComparison.Ordinal);
+ o.Open();
+ o.Control("\\field");
+ o.Open();
+ o.Control("\\*\\fldinst");
+ o.Raw("HYPERLINK ");
+ if (target.StartsWith('#'))
+ {
+ o.Text("\\l \"" + target[1..] + "\"", 1252);
+ }
+ else
+ {
+ o.Text("\"" + target + "\"", 1252);
+ }
+ o.Close();
+ o.Open();
+ o.Control("\\fldrslt");
+ Inlines(link.Content, state, style, story, depth);
+ o.Close();
+ o.Close();
+ }
+
+ private void Bookmark(string name)
+ {
+ foreach (var kind in new[] { "\\*\\bkmkstart", "\\*\\bkmkend" })
+ {
+ _out.Open();
+ _out.Control(kind);
+ _out.Text(name, 1252);
+ _out.Close();
+ }
+ }
+
+ ///
+ /// A footnote or endnote (\footnote, \ftnalt for an endnote) after its reference mark (\chftn). Notes are only in
+ /// the body text and its tables, as in Word: elsewhere the note's text stays in place, in brackets.
+ ///
+ private void Note(HNote note, RunState state, StyleBase style, Story story)
+ {
+ var o = _out;
+ if (story != Story.Body)
+ {
+ var text = string.Concat(note.Blocks.OfType().SelectMany(p => p.Inlines).OfType().Select(t => t.Text));
+ Run(note.Format ?? default, state, style, () => Text($" ({text})", Resolve(note.Format ?? default, style), state.Font));
+ return;
+ }
+ var reference = Resolve(note.Format ?? default, style) with { Script = 1 };
+ o.Open();
+ o.Control(Difference(state.Chars, reference) + "\\chftn");
+ o.Open();
+ o.Control(note.Endnote ? "\\footnote\\ftnalt" : "\\footnote");
+ var outer = _width;
+ _noteNumber = true;
+ Blocks(note.Blocks.Count > 0 ? note.Blocks : [new HParagraph()], Story.Note, 0, BlockEnd.Story);
+ _width = outer;
+ _noteNumber = false;
+ o.Close();
+ o.Close();
+ }
+
+ // ───────────────────────── Tables ─────────────────────────
+
+ /// Cell padding where neither the cell nor the table gives one: Word's (and the DOCX writer's) 0.19 cm left and right.
+ private static readonly HInsets DefaultCellMargin = new(540, 540, 0, 0);
+
+ /// The table's level: 1 in the text, 2 in a cell of such a table ...
+ private void Table(HTable table, Story story, int depth)
+ {
+ var o = _out;
+ if (table.Rows.Count == 0)
+ return;
+ var (placed, columnCount) = HwpxWriter.PlaceCells(table);
+ var available = Math.Max(4000, _width - (table.Align == HAlign.Left ? table.Indent : 0));
+ var widths = HwpxWriter.ColumnWidths(table, columnCount, available).Select(w => Math.Max(1, w)).ToArray();
+ // Each grid edge in twips from the margin, rounded once so the cells add up.
+ var left = table.Align == HAlign.Left ? table.Indent : 0;
+ var edges = new int[columnCount + 1];
+ long position = left;
+ edges[0] = Twips(left);
+ for (var c = 0; c < columnCount; c++)
+ {
+ position += widths[c];
+ edges[c + 1] = Math.Max(edges[c] + 1, (int)Math.Round(position / 5.0));
+ }
+
+ // Per column: the row a cell written so far covers it to (exclusive), and that cell with its first column.
+ var coveredTo = new int[columnCount];
+ var coveredBy = new (HCell Cell, int Column)[columnCount];
+ var margin = table.CellMargin ?? DefaultCellMargin;
+ var headerRows = table.Rows.TakeWhile(r => r.Header).Count();
+ var outerWidth = _width;
+ for (var r = 0; r < table.Rows.Count; r++)
+ {
+ _token.ThrowIfCancellationRequested();
+ var row = table.Rows[r];
+ var starts = r < placed.Count ? placed[r].GroupBy(p => p.Column).ToDictionary(g => g.Key, g => g.First().Cell) : [];
+
+ // The row's cells: (definition, content, the cell's text width) for each grid position.
+ var cells = new List<(string Definition, HCell? Content, int Width)>();
+ for (var column = 0; column < columnCount;)
+ {
+ if (starts.TryGetValue(column, out var cell))
+ {
+ var span = Math.Clamp(cell.ColSpan, 1, columnCount - column);
+ var rowSpan = Math.Clamp(cell.RowSpan, 1, table.Rows.Count - r);
+ for (var c = column; c < column + span; c++)
+ {
+ coveredTo[c] = r + rowSpan;
+ coveredBy[c] = (cell, column);
+ }
+ var cellMargin = cell.CellMargin ?? margin;
+ var width = Math.Max(1000, widths.Skip(column).Take(span).Sum() - cellMargin.Left - cellMargin.Right);
+ for (var k = 0; k < span; k++)
+ {
+ var merge = (rowSpan > 1 ? "\\clvmgf" : "") + (span > 1 ? k == 0 ? "\\clmgf" : "\\clmrg" : "");
+ cells.Add((CellDefinition(cell, table, merge, edges[column + k + 1], edges[column + k + 1] - edges[column + k]), k == 0 ? cell : null, width));
+ }
+ column += span;
+ }
+ else if (coveredTo[column] > r && coveredBy[column] is (HCell origin, var originColumn) && originColumn == column)
+ {
+ // Below a cell spanning rows: continuation cells, as many columns wide.
+ var span = Math.Clamp(origin.ColSpan, 1, columnCount - column);
+ for (var k = 0; k < span; k++)
+ {
+ var merge = "\\clvmrg" + (span > 1 ? k == 0 ? "\\clmgf" : "\\clmrg" : "");
+ cells.Add((CellDefinition(origin, table, merge, edges[column + k + 1], edges[column + k + 1] - edges[column + k]), null, 0));
+ }
+ column += span;
+ }
+ else
+ {
+ // A gap in a ragged row (or inside a span that started left of it): an empty cell keeps the grid.
+ cells.Add(($"\\cellx{Number(edges[column + 1])}", null, 0));
+ column++;
+ }
+ }
+
+ var definition = RowDefinition(table, row, r < headerRows, margin, edges[0]) + string.Concat(cells.Select(c => c.Definition));
+ if (depth == 1)
+ {
+ o.Control(definition);
+ o.Line();
+ }
+ var firstCell = true;
+ foreach (var (_, content, width) in cells)
+ {
+ if (content is null)
+ {
+ EmptyParagraph(depth, CellEnd(depth));
+ continue;
+ }
+ _width = width;
+ var blocks = content.Blocks.Count > 0 ? content.Blocks : [new HParagraph()];
+ if (firstCell && r == 0 && table.PageBreakBefore && blocks[0] is HParagraph opening)
+ {
+ // The page break goes with the table's first paragraph.
+ var copy = new HParagraph { Format = opening.Format, MarkFormat = opening.MarkFormat, HeadingLevel = opening.HeadingLevel, List = opening.List, PageBreakBefore = true };
+ copy.Inlines.AddRange(opening.Inlines);
+ blocks = [copy, .. blocks.Skip(1)];
+ }
+ firstCell = false;
+ Blocks(blocks, story, depth, BlockEnd.Cell);
+ }
+ _width = outerWidth;
+ if (depth == 1)
+ {
+ o.Control("\\row");
+ }
+ else
+ {
+ // A nested table's row ends with its definition.
+ o.Open();
+ o.Control("\\*\\nesttableprops" + definition + "\\nestrow");
+ o.Close();
+ }
+ o.Line();
+ }
+ }
+
+ /// \trowd and the row's own properties: padding, indent, alignment, height, header and keep.
+ private string RowDefinition(HTable table, HRow row, bool header, HInsets margin, int leftEdge)
+ {
+ var sb = new StringBuilder("\\trowd");
+ sb.Append($"\\trgaph{Number(Twips(margin.Left))}\\trleft{Number(leftEdge)}");
+ sb.Append(table.Align switch
+ {
+ HAlign.Center => "\\trqc",
+ HAlign.Right => "\\trqr",
+ _ => "\\trql",
+ });
+ if (table.RightToLeft)
+ sb.Append("\\rtlrow");
+ if (row.Height is > 0 and var height)
+ sb.Append($"\\trrh{Number(Twips(height))}");
+ if (header)
+ sb.Append("\\trhdr");
+ if (row.CantSplit)
+ sb.Append("\\trkeep");
+ sb.Append($"\\trpaddl{Number(Twips(margin.Left))}\\trpaddr{Number(Twips(margin.Right))}\\trpaddt{Number(Twips(margin.Top))}\\trpaddb{Number(Twips(margin.Bottom))}")
+ .Append("\\trpaddfl3\\trpaddfr3\\trpaddft3\\trpaddfb3");
+ return sb.ToString();
+ }
+
+ /// A cell's definition up to its \cellx: merges, vertical alignment, borders, shading, padding and width.
+ private string CellDefinition(HCell cell, HTable table, string merge, int right, int width)
+ {
+ var sb = new StringBuilder(merge);
+ sb.Append(cell.VerticalAlign switch
+ {
+ HVerticalAlign.Center => "\\clvertalc",
+ HVerticalAlign.Bottom => "\\clvertalb",
+ _ => "\\clvertalt",
+ });
+ var borders = cell.Borders ?? table.Borders ?? HBorders.Grid;
+ foreach (var (side, border) in new[] { ("t", borders.Top), ("l", borders.Left), ("b", borders.Bottom), ("r", borders.Right) })
+ {
+ if (border.Style != HBorderStyle.None)
+ sb.Append($"\\clbrdr{side}").Append(Border(border));
+ }
+ if (ColorIndex(cell.Fill) is > 0 and var fill)
+ sb.Append($"\\clcbpat{Number(fill)}");
+ if (cell.CellMargin is { } m)
+ {
+ // Word reads \clpadl as the top padding and \clpadt as the left one, and writes them so; so does this.
+ sb.Append($"\\clpadt{Number(Twips(m.Left))}\\clpadft3\\clpadr{Number(Twips(m.Right))}\\clpadfr3")
+ .Append($"\\clpadl{Number(Twips(m.Top))}\\clpadfl3\\clpadb{Number(Twips(m.Bottom))}\\clpadfb3");
+ }
+ sb.Append($"\\clftsWidth3\\clwWidth{Number(Math.Max(1, width))}\\cellx{Number(right)}");
+ return sb.ToString();
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Objects.cs
new file mode 100644
index 000000000..151ab689e
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.Objects.cs
@@ -0,0 +1,323 @@
+// Objects in the text of an RTF file: pictures as \pict groups, text boxes and shapes as Word drawing objects (\shp).
+//
+// A picture keeps its PNG or JPEG bytes (\pngblip, \jpegblip), an EMF or WMF stays a metafile (\emfblip, \wmetafile8
+// without the placeable header WMF files start with); any other picture becomes PNG. Its bytes are hex, 64 to a line.
+// Pictures stay in the text like characters (floating ones too, where they were anchored).
+//
+// A text box is a shape (\shp) with its paragraphs in \shptxt, and the same text in \shprslt for programs that don't
+// draw shapes (RtfReader reads it from there); shapes without text have no result.
+
+using Filee.Engines.Documents;
+using Filee.Engines.Magick;
+using ImageMagick;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class RtfWriter
+{
+ // ───────────────────────── Pictures ─────────────────────────
+
+ private void Picture(HImage image)
+ {
+ if (!File.Exists(image.Path) || PictureData(image.Path) is not { } picture)
+ return; // missing or unreadable picture: skip rather than write a broken one
+
+ var (width, height) = (image.Width, image.Height);
+ if ((width is null || height is null) && picture.Pixels is { } pixels && pixels.Width > 0 && pixels.Height > 0)
+ {
+ // Pixels at 96 dpi, like Word and browsers show pictures without a physical size.
+ if (width is null && height is null)
+ (width, height) = ((int)(pixels.Width * HwpxUnits.PerPixel), (int)(pixels.Height * HwpxUnits.PerPixel));
+ else if (width is not null)
+ height = (int)(width.Value * (double)pixels.Height / pixels.Width);
+ else
+ width = (int)(height!.Value * (double)pixels.Width / pixels.Height);
+ }
+ var w = Math.Max(1, width ?? 8504);
+ var h = Math.Max(1, height ?? w);
+ if (image.Anchor is null && w > _width)
+ {
+ // Pictures in the text never overflow its width.
+ h = (int)((long)h * _width / w);
+ w = _width;
+ }
+
+ var o = _out;
+ o.Open();
+ // \picw and \pich: pixels for bitmaps, 0.01 mm for metafiles.
+ var (picW, picH) = picture.Blip is "emfblip" or "wmetafile8"
+ ? ((int)Math.Round(w / HwpxUnits.PerMm * 100), (int)Math.Round(h / HwpxUnits.PerMm * 100))
+ : (picture.Pixels?.Width ?? Math.Max(1, (int)(w / HwpxUnits.PerPixel)), picture.Pixels?.Height ?? Math.Max(1, (int)(h / HwpxUnits.PerPixel)));
+ o.Control($"\\pict\\{picture.Blip}\\picw{Number(picW)}\\pich{Number(picH)}\\picwgoal{Number(Twips(w))}\\pichgoal{Number(Twips(h))}");
+ o.Line();
+ var data = picture.Bytes;
+ const int PerLine = 64;
+ for (var i = 0; i < data.Length; i += PerLine)
+ {
+ _token.ThrowIfCancellationRequested();
+ o.Raw(Convert.ToHexString(data, i, Math.Min(PerLine, data.Length - i)).ToLowerInvariant());
+ o.Line();
+ }
+ o.Close();
+ }
+
+ /// A picture's bytes as RTF takes them, its blip word and its pixel size; null when it can't be written.
+ private sealed record PictureBytes(byte[] Bytes, string Blip, (int Width, int Height)? Pixels);
+
+ private readonly Dictionary _pictures = new(StringComparer.OrdinalIgnoreCase);
+
+ private PictureBytes? PictureData(string path)
+ {
+ if (_pictures.TryGetValue(path, out var known))
+ return known;
+ return _pictures[path] = ReadPicture(path);
+ }
+
+ private PictureBytes? ReadPicture(string path)
+ {
+ // A picture larger than a part of a document may be, or claiming more pixels than any picture has, is left
+ // out before anything decodes it (RtfReader refuses such pictures too).
+ if (new FileInfo(path).Length > _limits.MaxPartBytes)
+ return null;
+ var pixels = PictureSize.Read(path);
+ if (pixels is { } size && (long)size.Width * size.Height > _limits.MaxPicturePixels)
+ return null;
+ var bytes = File.ReadAllBytes(path);
+ if (bytes is [0x89, (byte)'P', (byte)'N', (byte)'G', ..])
+ return new PictureBytes(bytes, "pngblip", pixels);
+ if (bytes is [0xFF, 0xD8, 0xFF, ..])
+ return new PictureBytes(bytes, "jpegblip", pixels);
+ if (bytes.Length > 44 && bytes[0] == 1 && bytes[1] == 0 && bytes[2] == 0 && bytes[3] == 0 && bytes[40] == 0x20 && bytes[41] == 0x45 && bytes[42] == 0x4D && bytes[43] == 0x46)
+ return new PictureBytes(bytes, "emfblip", pixels);
+ if (bytes is [0xD7, 0xCD, 0xC6, 0x9A, ..] && bytes.Length > 22)
+ return new PictureBytes(bytes[22..], "wmetafile8", pixels); // RTF has the metafile without its placeable header
+ if (bytes is [1 or 2, 0, 9, 0, ..])
+ return new PictureBytes(bytes, "wmetafile8", pixels);
+
+ // GIF, BMP, WebP, TIFF ... → PNG, which every RTF reader shows.
+ try
+ {
+ var info = new MagickImageInfo(path);
+ if ((long)info.Width * info.Height > _limits.MaxPicturePixels)
+ return null;
+ using var image = new MagickImage(path);
+ DdsChannelOrder.Correct(path, image);
+ return new PictureBytes(image.ToByteArray(MagickFormat.Png), "pngblip", ((int)image.Width, (int)image.Height));
+ }
+ catch (MagickException)
+ {
+ return null;
+ }
+ }
+
+ // ───────────────────────── Text boxes and shapes ─────────────────────────
+
+ private void TextBox(HTextBox box, RunState state, StyleBase style)
+ {
+ var o = _out;
+ var w = Math.Max(1, box.Width);
+ var h = Math.Max(1, box.Height);
+ o.Open();
+ o.Control("\\shp");
+ o.Open();
+ o.Control("\\*\\shpinst" + ShapePlacement(box.Anchor, w, h, box.ZOrder));
+ var type = box.Shape == HShapeKind.Ellipse ? 3 : box.CornerRatio > 0 ? 2 : 202;
+ Property("shapeType", Number(type));
+ Fill(box.Fill ?? box.Gradient?.Colors.FirstOrDefault());
+ Line(box.Line);
+ Property("dxTextLeft", Number(Emu(box.Padding.Left)));
+ Property("dxTextRight", Number(Emu(box.Padding.Right)));
+ Property("dyTextTop", Number(Emu(box.Padding.Top)));
+ Property("dyTextBottom", Number(Emu(box.Padding.Bottom)));
+ Property("anchorText", box.VerticalAlign switch { HVerticalAlign.Center => "1", HVerticalAlign.Bottom => "2", _ => "0" });
+ if (box.CornerRatio > 0)
+ Property("adjustValue", Number((int)Math.Round(Math.Clamp(box.CornerRatio, 0, 50) / 100.0 * 21600)));
+ Transform(box.Transform);
+
+ var outer = _width;
+ _width = Math.Max(1000, w - box.Padding.Left - box.Padding.Right);
+ o.Open();
+ o.Control("\\shptxt");
+ Blocks(box.Blocks.Count > 0 ? box.Blocks : [new HParagraph()], Story.TextBox, 0, BlockEnd.Story);
+ o.Close();
+ _width = outer;
+ o.Close();
+
+ // The same text, in the paragraph, for programs that don't draw shapes: its paragraphs as lines.
+ o.Open();
+ o.Control("\\shprslt");
+ var first = true;
+ foreach (var paragraph in box.Blocks.OfType())
+ {
+ if (!first)
+ o.Control("\\line");
+ first = false;
+ Inlines(paragraph.Inlines.Where(i => i is HText or HTab or HLineBreak or HLink).ToList(), state, style, Story.TextBox, 0);
+ }
+ o.Close();
+ o.Close();
+ }
+
+ private void Shape(HShape shape)
+ {
+ var type = shape.Kind switch
+ {
+ HShapeKind.Rectangle => shape.CornerRatio > 0 ? 2 : 1,
+ HShapeKind.Ellipse => 3,
+ HShapeKind.Line => 20,
+ _ => 0, // polygons, curves and arcs come only from models read for layout
+ };
+ if (type == 0)
+ return;
+ var o = _out;
+ var w = Math.Max(1, shape.Width);
+ var h = Math.Max(shape.Kind == HShapeKind.Line ? 0 : 1, shape.Height);
+ o.Open();
+ o.Control("\\shp");
+ o.Open();
+ o.Control("\\*\\shpinst" + ShapePlacement(shape.Anchor, w, h, shape.ZOrder));
+ Property("shapeType", Number(type));
+ if (shape.Kind == HShapeKind.Line)
+ Property("fFilled", "0");
+ else
+ Fill(shape.Fill ?? shape.Gradient?.Colors.FirstOrDefault());
+ Line(shape.Line);
+ if (shape.Kind == HShapeKind.Rectangle && shape.CornerRatio > 0)
+ Property("adjustValue", Number((int)Math.Round(Math.Clamp(shape.CornerRatio, 0, 50) / 100.0 * 21600)));
+ if (shape.FlipHorizontal)
+ Property("fFlipH", "1");
+ if (shape.FlipVertical)
+ Property("fFlipV", "1");
+ Transform(shape.Transform);
+ o.Close();
+ o.Close();
+ }
+
+ ///
+ /// \shpleft ... \shpbottom with what they are measured from, the wrap and the stacking order. An object in the
+ /// text (no anchor) is placed at its paragraph, with text above and below it.
+ ///
+ private string ShapePlacement(HAnchor? anchor, int width, int height, int? zOrder)
+ {
+ var x = anchor is null ? 0 : Twips(anchor.HorizontalOffset);
+ var y = anchor is null ? 0 : Twips(anchor.VerticalOffset);
+ var horizontal = anchor?.HorizontalRelativeTo switch
+ {
+ "PAPER" => "\\shpbxpage",
+ "PAGE" => "\\shpbxmargin",
+ _ => "\\shpbxcolumn",
+ };
+ var vertical = anchor?.VerticalRelativeTo switch
+ {
+ "PAPER" => "\\shpbypage",
+ "PAGE" => "\\shpbymargin",
+ _ => "\\shpbypara",
+ };
+ var wrap = anchor?.Wrap switch
+ {
+ null or "TOP_AND_BOTTOM" => "\\shpwr1",
+ "BEHIND_TEXT" => "\\shpwr3\\shpfblwtxt1",
+ "IN_FRONT_OF_TEXT" => "\\shpwr3\\shpfblwtxt0",
+ _ => "\\shpwr2\\shpwrk0",
+ };
+ var id = ++_shapes;
+ return $"\\shpleft{Number(x)}\\shptop{Number(y)}\\shpright{Number(x + Twips(width))}\\shpbottom{Number(y + Twips(height))}" +
+ $"\\shpfhdr0{horizontal}\\shpbxignore{vertical}\\shpbyignore{wrap}\\shpz{Number(Math.Max(0, zOrder ?? id))}\\shplid{Number(1024 + id)}" +
+ PositionProperties(anchor);
+ }
+
+ private int _shapes;
+
+ /// An aligned anchor (centre, right ... without an offset) as Word's posh / posv shape properties.
+ private static string PositionProperties(HAnchor? anchor)
+ {
+ if (anchor is null)
+ return "";
+ var sb = new System.Text.StringBuilder();
+ var posh = anchor.HorizontalOffset != 0 ? 0 : anchor.HorizontalAlign switch
+ {
+ "CENTER" => 2,
+ "RIGHT" => 3,
+ "INSIDE" => 4,
+ "OUTSIDE" => 5,
+ _ => 0,
+ };
+ if (posh > 0)
+ sb.Append($"{{\\sp{{\\sn posh}}{{\\sv {Number(posh)}}}}}");
+ var posv = anchor.VerticalOffset != 0 ? 0 : anchor.VerticalAlign switch
+ {
+ "CENTER" => 2,
+ "BOTTOM" => 3,
+ "INSIDE" => 4,
+ "OUTSIDE" => 5,
+ _ => 0,
+ };
+ if (posv > 0)
+ sb.Append($"{{\\sp{{\\sn posv}}{{\\sv {Number(posv)}}}}}");
+ return sb.ToString();
+ }
+
+ /// A shape property: {\sp{\sn name}{\sv value}}.
+ private void Property(string name, string value)
+ {
+ _out.Control($"{{\\sp{{\\sn {name}}}{{\\sv {value}}}}}");
+ }
+
+ private void Fill(string? color)
+ {
+ if (Odt.Odf.Color(color) is { } fill)
+ {
+ Property("fFilled", "1");
+ Property("fillColor", Number(Bgr(fill)));
+ }
+ else
+ {
+ Property("fFilled", "0");
+ }
+ }
+
+ private void Line(HBorder line)
+ {
+ if (line.Style == HBorderStyle.None)
+ {
+ Property("fLine", "0");
+ return;
+ }
+ Property("fLine", "1");
+ Property("lineColor", Number(Bgr(Odt.Odf.Color(line.Color) ?? "#000000")));
+ Property("lineWidth", Number((int)Math.Round(Math.Max(0, line.WidthMm) * 36000)));
+ var dash = line.Style switch
+ {
+ HBorderStyle.Dash => 1,
+ HBorderStyle.Dot => 2,
+ HBorderStyle.DashDot => 3,
+ _ => 0,
+ };
+ if (dash > 0)
+ Property("lineDashing", Number(dash));
+ if (line.Style == HBorderStyle.Double)
+ Property("lineStyle", "1");
+ }
+
+ private void Transform(HTransform? transform)
+ {
+ if (transform is not { IsIdentity: false } t)
+ return;
+ if (t.Rotation != 0)
+ Property("rotation", Number((int)Math.Round(t.Rotation * 65536)));
+ if (t.FlipHorizontal)
+ Property("fFlipH", "1");
+ if (t.FlipVertical)
+ Property("fFlipV", "1");
+ }
+
+ /// "#RRGGBB" as the BGR number shape properties take.
+ private static int Bgr(string hex)
+ {
+ var value = Convert.ToInt32(hex[1..], 16);
+ return (value >> 16 & 0xFF) | (value & 0xFF00) | (value & 0xFF) << 16;
+ }
+
+ /// HWPUNIT → EMU (shape properties' lengths).
+ private static int Emu(int hwpUnit) => (int)Math.Min(int.MaxValue, Math.Round(hwpUnit * 127.0));
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/RtfWriter.cs b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.cs
new file mode 100644
index 000000000..6b4c9bebb
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/RtfWriter.cs
@@ -0,0 +1,777 @@
+// Writes Rich Text Format from the HDocument model — the counterpart of RtfReader, written by hand from the RTF 1.9
+// specification like the DOCX, ODT and HWPX writers, so anything Filee's readers understand becomes an RTF file that
+// Word, WordPad and LibreOffice open, without LibreOffice or Pandoc.
+//
+// Split over partial files:
+// * RtfWriter.cs the file: its header (fonts with their other names, colours, styles, lists, information,
+// document settings), sections with their page setup, headers and footers; the output and
+// how text is escaped;
+// * RtfWriter.Body.cs paragraphs, character formatting, links, bookmarks, fields, notes and tables;
+// * RtfWriter.Objects.cs pictures (PNG and JPEG as they are, EMF and WMF as metafiles, others as PNG), text boxes
+// and shapes.
+//
+// The body is written first, into a temporary file beside the output, because the font, colour and list tables that
+// come before it fill as the body uses them. The file is ASCII: other characters are \uN followed by the same
+// character in the code page of the font it is in (\ucN says how many bytes that takes), or "?" where that code page
+// has none, so programs without Unicode RTF still show what they can.
+
+using System.Globalization;
+using System.Text;
+using Filee.Engines.Documents;
+using Filee.Engines.Typesetting;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+/// Converts an into an .rtf file.
+internal sealed partial class RtfWriter
+{
+ /// A4 with one-inch margins and headers / footers 1.5 cm from the edge, as the DOCX writer has it.
+ private static readonly HPage DefaultPage = new(59528, 84188, 7200, 7200, 4255, 4255, 2945, 2945, 0);
+
+ /// The fonts the model leaves open: the DOCX writer's Calibri and 맑은 고딕 (font 0 and 1).
+ private const string DefaultLatinFont = "Calibri";
+ private const string DefaultEastAsianFont = "맑은 고딕";
+
+ /// Body text size (half points): 10 pt, the DOCX writer's Normal.
+ private const int DefaultHalfPoints = 20;
+
+ /// Word's distance between default tab stops (twips) when the model gives none: 한글's 40 pt.
+ private const int DefaultTabTwips = 800;
+
+ /// Heading sizes (half points) of "heading 1".."heading 9", as the DOCX writer's.
+ private static readonly int[] HeadingSizes = [32, 28, 26, 24, 22, 20, 20, 20, 20];
+
+ private readonly HDocument _document;
+ private readonly DocumentLimits _limits;
+ private readonly CancellationToken _token;
+ private Output _out = null!;
+
+ private RtfWriter(HDocument document, DocumentLimits limits, CancellationToken token)
+ {
+ _document = document;
+ _limits = limits;
+ _token = token;
+ // Font 0 and 1 are the defaults, whatever the text uses.
+ FontIndex(DefaultLatinFont, 0);
+ EastAsianFontIndex(DefaultEastAsianFont, 129);
+ }
+
+ /// Writes as an .rtf file (replaced atomically, through a temporary file of its own).
+ public static void Write(HDocument document, string outputPath, CancellationToken cancellationToken = default) =>
+ Write(document, outputPath, DocumentLimits.Default, cancellationToken);
+
+ /// Writes within other than (for tests).
+ internal static void Write(HDocument document, string outputPath, DocumentLimits limits, CancellationToken cancellationToken = default)
+ {
+ Nesting.Limit(document); // the writer recurses per table, text box and note level
+ System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ var writer = new RtfWriter(document, limits, cancellationToken);
+
+ // The body goes into a file of its own first: the tables before it are only known once it is written.
+ using var body = WriterTempFile.Create(outputPath, out var bodyPath);
+ try
+ {
+ writer._out = new Output(body, limits.MaxPackageBytes, cancellationToken);
+ writer.Body();
+ writer._out.Flush();
+ var bodyLength = body.Length;
+ WriterTempFile.Write(outputPath, file =>
+ {
+ var header = new Output(file, limits.MaxPackageBytes - bodyLength, cancellationToken);
+ writer._out = header;
+ writer.Header();
+ header.Flush();
+ body.Position = 0;
+ body.CopyTo(file);
+ file.WriteByte((byte)'}');
+ });
+ }
+ finally
+ {
+ body.Dispose();
+ WriterTempFile.Discard(bodyPath);
+ }
+ }
+
+ // ───────────────────────── Output ─────────────────────────
+
+ ///
+ /// The RTF text being written: control words, groups and escaped text. It counts what it writes against the limit
+ /// a file may have (the RTF reader refuses larger ones) and keeps the \uc value of each open group.
+ ///
+ private sealed class Output(Stream stream, long limit, CancellationToken token)
+ {
+ private readonly StreamWriter _writer = new(stream, Encoding.ASCII, 1 << 16, leaveOpen: true);
+ private readonly Stack _ucs = new();
+ private long _written;
+ private long _checked;
+
+ /// A control word was written last: text after it needs a space between.
+ private bool _delimit;
+
+ /// Bytes of fallback after each \uN in the current group.
+ public int Uc { get; private set; } = 1;
+
+ public int Depth => _ucs.Count;
+
+ public void Flush() => _writer.Flush();
+
+ private void Put(string text)
+ {
+ _written += text.Length;
+ if (_written > limit)
+ throw DocumentLimits.Exceeded($"The RTF file would be larger than {limit / (1024 * 1024)} MB.");
+ if (_written - _checked > 1 << 16)
+ {
+ _checked = _written;
+ token.ThrowIfCancellationRequested();
+ }
+ _writer.Write(text);
+ }
+
+ private void Put(char c)
+ {
+ if (++_written > limit)
+ throw DocumentLimits.Exceeded($"The RTF file would be larger than {limit / (1024 * 1024)} MB.");
+ _writer.Write(c);
+ }
+
+ public void Open()
+ {
+ Put('{');
+ _ucs.Push(Uc);
+ _delimit = false;
+ }
+
+ public void Close()
+ {
+ Put('}');
+ if (_ucs.Count > 0)
+ Uc = _ucs.Pop();
+ _delimit = false;
+ }
+
+ /// One or more control words ("\b\fs20"), or a control symbol.
+ public void Control(string words)
+ {
+ Put(words);
+ _delimit = words.Length > 0 && (char.IsAsciiLetterOrDigit(words[^1]) || words[^1] == '-');
+ }
+
+ /// A byte as \'hh (in \leveltext and \levelnumbers).
+ public void Byte(int value)
+ {
+ Put($"\\'{value & 0xFF:x2}");
+ _delimit = false;
+ }
+
+ /// A line end between pieces of the file (RTF ignores it; it keeps lines short for people reading it).
+ public void Line()
+ {
+ Put("\r\n");
+ _delimit = false;
+ }
+
+ /// ASCII text that needs no escaping (hex digits of a picture).
+ public void Raw(string text)
+ {
+ if (_delimit)
+ Put(' ');
+ Put(text);
+ _delimit = false;
+ }
+
+ ///
+ /// Text with RTF's special characters escaped, tabs and line ends as \tab and \line, and characters beyond ASCII
+ /// as \uN with their bytes in (or "?") for programs that don't read \u.
+ ///
+ public void Text(string text, int codePage)
+ {
+ for (var i = 0; i < text.Length; i++)
+ {
+ var c = text[i];
+ switch (c)
+ {
+ case '\\' or '{' or '}':
+ Put('\\');
+ Put(c);
+ _delimit = false;
+ continue;
+ case '\t':
+ Control("\\tab");
+ continue;
+ case '\n':
+ Control("\\line");
+ continue;
+ case '\r':
+ if (i + 1 >= text.Length || text[i + 1] != '\n')
+ Control("\\line");
+ continue;
+ case '\u00A0':
+ Control("\\~");
+ continue;
+ case '\u2011':
+ Control("\\_");
+ continue;
+ case '\u00AD':
+ Control("\\-");
+ continue;
+ }
+ if (c < ' ' || c == '\u007F')
+ continue;
+ if (c < '\u0080')
+ {
+ if (_delimit)
+ Put(' ');
+ _delimit = false;
+ Put(c);
+ continue;
+ }
+ var fallback = Fallback(c, codePage);
+ if (fallback.Length != Uc)
+ {
+ Uc = fallback.Length;
+ Control($"\\uc{Uc}");
+ }
+ Control($"\\u{(short)c}");
+ foreach (var b in fallback)
+ {
+ if (b is >= 0x20 and < 0x7F && b is not ((byte)'\\' or (byte)'{' or (byte)'}'))
+ {
+ // After \uN only a digit or a space would be taken as part of the control word.
+ if (_delimit && (char.IsAsciiDigit((char)b) || b == ' '))
+ Put(' ');
+ Put((char)b);
+ }
+ else
+ {
+ Put($"\\'{b:x2}");
+ }
+ _delimit = false;
+ }
+ }
+ }
+ }
+
+ private static readonly Dictionary Encodings = [];
+
+ /// The bytes of in , or "?" when it has none.
+ private static byte[] Fallback(char c, int codePage)
+ {
+ if (char.IsSurrogate(c))
+ return [(byte)'?'];
+ Encoding encoding;
+ lock (Encodings)
+ {
+ if (!Encodings.TryGetValue(codePage, out encoding!))
+ {
+ try
+ {
+ encoding = System.Text.Encoding.GetEncoding(codePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
+ {
+ encoding = System.Text.Encoding.GetEncoding(1252, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
+ }
+ Encodings[codePage] = encoding;
+ }
+ }
+ try
+ {
+ var bytes = encoding.GetBytes([c]);
+ // Only a character the code page has itself, not a look-alike, and at most a double-byte one.
+ return bytes.Length is 1 or 2 && encoding.GetString(bytes) == c.ToString() ? bytes : [(byte)'?'];
+ }
+ catch (Exception ex) when (ex is EncoderFallbackException or DecoderFallbackException or ArgumentException)
+ {
+ return [(byte)'?'];
+ }
+ }
+
+ // ───────────────────────── Fonts and colours ─────────────────────────
+
+ /// A font table entry: its name, \fcharset and the other name of the font.
+ private sealed record FontEntry(string Name, int Charset, bool EastAsian);
+
+ private readonly List _fonts = [];
+ private readonly Dictionary<(string Name, int Charset), int> _latinFonts = [];
+ private readonly Dictionary _eastAsianFonts = new(StringComparer.Ordinal);
+ private readonly List _colors = [];
+ private readonly Dictionary _colorIndex = new(StringComparer.OrdinalIgnoreCase);
+
+ /// The index of a font for text of , added on first use.
+ private int FontIndex(string name, int charset)
+ {
+ name = CleanFontName(name);
+ if (_latinFonts.TryGetValue((name, charset), out var index))
+ return index;
+ CheckEntries(_fonts.Count, "fonts");
+ _fonts.Add(new FontEntry(name, charset, EastAsian: false));
+ return _latinFonts[(name, charset)] = _fonts.Count - 1;
+ }
+
+ ///
+ /// The index of an East Asian font, added on first use with (the script of the text
+ /// that first used it): RtfReader and Word take a font of an East Asian \fcharset as the East Asian font.
+ ///
+ private int EastAsianFontIndex(string name, int charset)
+ {
+ name = CleanFontName(name);
+ if (_eastAsianFonts.TryGetValue(name, out var index))
+ return index;
+ CheckEntries(_fonts.Count, "fonts");
+ _fonts.Add(new FontEntry(name, charset, EastAsian: true));
+ return _eastAsianFonts[name] = _fonts.Count - 1;
+ }
+
+ /// A font name without the characters that end or open a font table entry.
+ private static string CleanFontName(string name)
+ {
+ var clean = name.Replace(";", "", StringComparison.Ordinal).Trim();
+ return clean.Length == 0 ? DefaultLatinFont : clean;
+ }
+
+ /// The colour table index of "#RRGGBB" (0, the automatic colour, for none).
+ private int ColorIndex(string? color)
+ {
+ if (Odt.Odf.Color(color) is not { } hex)
+ return 0;
+ if (_colorIndex.TryGetValue(hex, out var index))
+ return index;
+ CheckEntries(_colors.Count, "colours");
+ _colors.Add(hex);
+ return _colorIndex[hex] = _colors.Count;
+ }
+
+ private void CheckEntries(int count, string what)
+ {
+ if (count >= _limits.MaxObjects)
+ throw DocumentLimits.Exceeded($"The RTF file would define more than {DocumentLimits.Count(_limits.MaxObjects)} {what}.");
+ }
+
+ /// Windows code page of an \fcharset (the inverse of RtfReader's table), 1252 for ANSI.
+ internal static int CodePage(int charset) => charset switch
+ {
+ 128 => 932,
+ 129 => 949,
+ 134 => 936,
+ 136 => 950,
+ 161 => 1253,
+ 162 => 1254,
+ 163 => 1258,
+ 177 => 1255,
+ 178 => 1256,
+ 186 => 1257,
+ 204 => 1251,
+ 222 => 874,
+ 238 => 1250,
+ _ => 1252,
+ };
+
+ ///
+ /// The other name of a font, which Word and RtfReader use when the font is not installed: the document's own
+ /// (DOCX w:altName), else the font's name in the other language (맑은 고딕 / Malgun Gothic) or a font of the same
+ /// widths (Calibri / Carlito).
+ ///
+ private string? Alternate(string name)
+ {
+ if (_document.FontAlternates.TryGetValue(name, out var known) && !string.IsNullOrWhiteSpace(known))
+ return known;
+ return FontNames.Alternatives(name).FirstOrDefault(other => !other.Equals(name, StringComparison.OrdinalIgnoreCase));
+ }
+
+ // ───────────────────────── Header ─────────────────────────
+
+ /// Everything before the body: the tables the body filled, the document's information and settings.
+ private void Header()
+ {
+ var o = _out;
+ o.Control("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1");
+ o.Line();
+
+ o.Open();
+ o.Control("\\fonttbl");
+ for (var i = 0; i < _fonts.Count; i++)
+ {
+ var font = _fonts[i];
+ o.Line();
+ o.Open();
+ var family = FontNames.IsMonospace(font.Name) ? "\\fmodern" : "\\fnil";
+ o.Control($"\\f{Number(i)}{family}\\fcharset{Number(font.Charset)}\\fprq{(family == "\\fmodern" ? 1 : 2)}");
+ o.Text(font.Name, CodePage(font.Charset));
+ if (Alternate(font.Name) is { } alternate)
+ {
+ o.Open();
+ o.Control("\\*\\falt");
+ o.Text(CleanFontName(alternate), CodePage(font.Charset));
+ o.Close();
+ }
+ o.Raw(";");
+ o.Close();
+ }
+ o.Close();
+ o.Line();
+
+ o.Open();
+ o.Control("\\colortbl");
+ o.Raw(";");
+ foreach (var color in _colors)
+ {
+ var value = int.Parse(color.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+ o.Control($"\\red{Number(value >> 16 & 0xFF)}\\green{Number(value >> 8 & 0xFF)}\\blue{Number(value & 0xFF)}");
+ o.Raw(";");
+ }
+ o.Close();
+ o.Line();
+
+ StyleSheet();
+ ListTables();
+ Information();
+
+ // Document settings: the first section's page, the default tab interval, notes.
+ var first = _document.Sections.FirstOrDefault();
+ var page = first?.Page ?? DefaultPage;
+ o.Control($"\\paperw{Number(Twips(page.Width))}\\paperh{Number(Twips(page.Height))}" +
+ $"\\margl{Number(Twips(page.Left))}\\margr{Number(Twips(page.Right))}" +
+ $"\\margt{Number(Twips(page.Top + page.Header))}\\margb{Number(Twips(page.Bottom + page.Footer))}" +
+ $"\\gutter{Number(Twips(page.Gutter))}{(page.Landscape ? "\\landscape" : "")}");
+ if (_facingPages)
+ o.Control("\\facingp");
+ var tab = _document.DefaultTabStop is > 0 and var interval ? Twips(interval) : DefaultTabTwips;
+ o.Control($"\\deftab{Number(Math.Max(1, tab))}\\widowctrl");
+ o.Control($"\\ftnbj{NoteNumbering("ftn", (first?.Footnotes ?? HNoteShape.Footnote).Format)}\\aenddoc{NoteNumbering("aftn", (first?.Endnotes ?? HNoteShape.Endnote).Format)}\\fet2");
+ o.Line();
+ }
+
+ /// \ftnnar, \aftnnrlc ...: how notes are numbered.
+ private static string NoteNumbering(string prefix, HNoteFormat format) => "\\" + prefix + format.Type switch
+ {
+ "ROMAN_SMALL" => "nrlc",
+ "ROMAN_CAPITAL" => "nruc",
+ "LATIN_SMALL" => "nalc",
+ "LATIN_CAPITAL" => "nauc",
+ "HANGUL_SYLLABLE" => "nganada",
+ "HANGUL_JAMO" => "nchosung",
+ "CIRCLED_DIGIT" => "ncnum",
+ _ => "nar",
+ };
+
+ ///
+ /// Normal and Word's "heading 1".."heading 9" (outline levels, which RtfReader and Word read as headings), with
+ /// the properties paragraphs of those styles repeat (RTF paragraphs carry their formatting themselves).
+ ///
+ private void StyleSheet()
+ {
+ var o = _out;
+ o.Open();
+ o.Control("\\stylesheet");
+ o.Line();
+ o.Open();
+ o.Control($"\\s0\\ql\\widctlpar\\sl295\\slmult1\\f0\\fs{Number(DefaultHalfPoints)}\\snext0");
+ o.Raw("Normal;");
+ o.Close();
+ for (var level = 1; level <= 9; level++)
+ {
+ o.Line();
+ o.Open();
+ o.Control($"\\s{Number(level)}\\ql\\keepn\\keep\\widctlpar\\sb{Number(level <= 2 ? 240 : 160)}\\sa80\\sl295\\slmult1\\outlinelevel{Number(level - 1)}" +
+ $"\\b\\f0\\fs{Number(HeadingSizes[level - 1])}\\sbasedon0\\snext0");
+ o.Raw($"heading {Number(level)};");
+ o.Close();
+ }
+ o.Close();
+ o.Line();
+ }
+
+ private void Information()
+ {
+ var o = _out;
+ if (string.IsNullOrWhiteSpace(_document.Title) && _document.Authors.Count == 0)
+ return;
+ o.Open();
+ o.Control("\\info");
+ if (!string.IsNullOrWhiteSpace(_document.Title))
+ {
+ o.Open();
+ o.Control("\\title");
+ o.Text(_document.Title.Trim(), 1252);
+ o.Close();
+ }
+ if (_document.Authors.Count > 0)
+ {
+ o.Open();
+ o.Control("\\author");
+ o.Text(string.Join("; ", _document.Authors), 1252);
+ o.Close();
+ }
+ o.Close();
+ o.Line();
+ }
+
+ // ───────────────────────── Lists ─────────────────────────
+
+ /// Indent of list level (twips): 400 per level with a 400 hanging number, as the DOCX writer's.
+ private static int ListIndent(int level) => (level + 1) * 400;
+
+ private readonly Dictionary _numberings = new(ReferenceEqualityComparer.Instance);
+
+ /// The \ls number of a list definition, added on first use.
+ private int ListNumber(HNumbering numbering)
+ {
+ if (_numberings.TryGetValue(numbering, out var number))
+ return number;
+ CheckEntries(_numberings.Count, "lists");
+ return _numberings[numbering] = _numberings.Count + 1;
+ }
+
+ /// \listtable with nine levels per list, and \listoverridetable with one \ls per list.
+ private void ListTables()
+ {
+ if (_numberings.Count == 0)
+ return;
+ var o = _out;
+ o.Open();
+ o.Control("\\*\\listtable");
+ foreach (var (numbering, number) in _numberings)
+ {
+ o.Line();
+ o.Open();
+ o.Control($"\\list\\listtemplateid{Number(ListId(number))}\\listhybrid");
+ for (var level = 0; level < 9; level++)
+ {
+ var definition = level < numbering.Levels.Count ? numbering.Levels[level] : new HNumberingLevel("DIGIT", $"^{level + 1}.", 1, Bullet: false);
+ o.Open();
+ var format = definition.Bullet ? 23 : LevelFormat(definition.Format);
+ o.Control($"\\listlevel\\levelnfc{Number(format)}\\levelnfcn{Number(format)}\\leveljc0\\leveljcn0\\levelfollow0\\levelstartat{Number(Math.Max(0, definition.Start))}");
+ var (text, numbers) = LevelText(definition);
+ o.Open();
+ o.Control("\\leveltext");
+ // The length first, then the text with \'00..\'08 for the numbers of those levels.
+ o.Byte(Math.Min(text.Length, 255));
+ foreach (var c in text.Take(255))
+ {
+ if (c < 9)
+ o.Byte(c);
+ else
+ o.Text(c.ToString(), 1252);
+ }
+ o.Raw(";");
+ o.Close();
+ o.Open();
+ o.Control("\\levelnumbers");
+ foreach (var position in numbers)
+ o.Byte(position);
+ o.Raw(";");
+ o.Close();
+ o.Control($"\\fi-400\\li{Number(ListIndent(level))}\\lin{Number(ListIndent(level))}");
+ o.Close();
+ }
+ o.Open();
+ o.Control("\\listname");
+ o.Raw(";");
+ o.Close();
+ o.Control($"\\listid{Number(ListId(number))}");
+ o.Close();
+ }
+ o.Close();
+ o.Line();
+
+ o.Open();
+ o.Control("\\*\\listoverridetable");
+ foreach (var number in _numberings.Values)
+ {
+ o.Line();
+ o.Open();
+ o.Control($"\\listoverride\\listid{Number(ListId(number))}\\listoverridecount0\\ls{Number(number)}");
+ o.Close();
+ }
+ o.Close();
+ o.Line();
+ }
+
+ private static int ListId(int number) => 1000 + number;
+
+ /// OWPML number format → \levelnfc (Word's number formats, the inverse of RtfReader's).
+ internal static int LevelFormat(string owpml) => owpml switch
+ {
+ "ROMAN_CAPITAL" => 1,
+ "ROMAN_SMALL" => 2,
+ "LATIN_CAPITAL" => 3,
+ "LATIN_SMALL" => 4,
+ "IDEOGRAPH" => 10,
+ "CIRCLED_DIGIT" => 18,
+ "HANGUL_SYLLABLE" => 24,
+ "HANGUL_JAMO" => 25,
+ "HANGUL_PHONETIC" => 40,
+ _ => 0,
+ };
+
+ ///
+ /// A level's text with (char)0..(char)8 for the numbers of levels 1..9 ("^1.^2." → "\0.\1."), and the 1-based
+ /// positions of those numbers in it (\levelnumbers). A bullet is its character.
+ ///
+ internal static (string Text, List Numbers) LevelText(HNumberingLevel level)
+ {
+ if (level.Bullet)
+ return (level.Text.Length > 0 ? StringInfo.GetNextTextElement(level.Text) : "•", []);
+ var text = new StringBuilder();
+ var numbers = new List();
+ for (var i = 0; i < level.Text.Length; i++)
+ {
+ if (level.Text[i] == '^' && i + 1 < level.Text.Length && level.Text[i + 1] is >= '1' and <= '9')
+ {
+ text.Append((char)(level.Text[i + 1] - '1'));
+ numbers.Add(text.Length);
+ i++;
+ continue;
+ }
+ text.Append(level.Text[i]);
+ }
+ return (text.ToString(), numbers);
+ }
+
+ // ───────────────────────── Sections ─────────────────────────
+
+ /// Some section has a header or footer for even pages: the document has facing pages (\facingp).
+ private bool _facingPages;
+
+ private void Body()
+ {
+ var sections = _document.Sections.Count > 0 ? _document.Sections : [new HSection()];
+ _facingPages = sections.Any(s => s.Headers.Concat(s.Footers).Any(h => h.Pages == HPageType.Even));
+ for (var s = 0; s < sections.Count; s++)
+ {
+ var section = sections[s];
+ var page = section.Page ?? DefaultPage;
+ var parts = SplitAtColumnChanges(section);
+ for (var p = 0; p < parts.Count; p++)
+ {
+ _token.ThrowIfCancellationRequested();
+ var (columns, blocks) = parts[p];
+ if (s > 0 || p > 0)
+ {
+ _out.Control("\\sect");
+ _out.Line();
+ }
+ SectionProperties(section, page, columns, continuous: p > 0);
+ _width = ColumnWidth(page.TextWidth, columns);
+ Blocks(blocks, Story.Body, 0, BlockEnd.Story);
+ }
+ }
+ }
+
+ /// Splits a section where its columns change: each piece becomes a section of its own, without a page break.
+ private static List<(HColumns Columns, List Blocks)> SplitAtColumnChanges(HSection section)
+ {
+ var parts = new List<(HColumns, List)>();
+ var columns = section.Columns;
+ var current = new List();
+ foreach (var block in section.Blocks)
+ {
+ if (block is HParagraph { ColumnsChange: { } change })
+ {
+ if (current.Count > 0)
+ {
+ parts.Add((columns, current));
+ current = [];
+ }
+ columns = change;
+ }
+ current.Add(block);
+ }
+ parts.Add((columns, current));
+ return parts;
+ }
+
+ private static int ColumnWidth(int textWidth, HColumns columns) =>
+ columns.Count <= 1 ? textWidth : Math.Max(2000, (textWidth - columns.Gap * (columns.Count - 1)) / columns.Count);
+
+ ///
+ /// \sectd and the section's page, columns, numbering, headers and footers. The model's Top / Bottom run from the
+ /// paper edge to the header / footer and Header / Footer are their heights (as in 한글); RTF's margins reach the
+ /// body and \headery / \footery are the distances.
+ ///
+ private void SectionProperties(HSection section, HPage page, HColumns columns, bool continuous)
+ {
+ var o = _out;
+ var sb = new StringBuilder("\\sectd");
+ if (continuous)
+ sb.Append("\\sbknone");
+ sb.Append($"\\pgwsxn{Number(Twips(page.Width))}\\pghsxn{Number(Twips(page.Height))}")
+ .Append($"\\marglsxn{Number(Twips(page.Left))}\\margrsxn{Number(Twips(page.Right))}")
+ .Append($"\\margtsxn{Number(Twips(page.Top + page.Header))}\\margbsxn{Number(Twips(page.Bottom + page.Footer))}")
+ .Append($"\\guttersxn{Number(Twips(page.Gutter))}\\headery{Number(Twips(page.Top))}\\footery{Number(Twips(page.Bottom))}");
+ if (page.Landscape)
+ sb.Append("\\lndscpsxn");
+ if (columns.Count > 1)
+ {
+ sb.Append($"\\cols{Number(Math.Min(columns.Count, 255))}\\colsx{Number(Twips(columns.Gap))}");
+ if (columns.Separator)
+ sb.Append("\\linebetcol");
+ if (columns.Sizes is { } sizes && sizes.Count == columns.Count)
+ {
+ for (var i = 0; i < sizes.Count; i++)
+ {
+ sb.Append($"\\colno{Number(i + 1)}\\colw{Number(Twips(sizes[i].Width))}");
+ if (i + 1 < sizes.Count)
+ sb.Append($"\\colsr{Number(Twips(sizes[i].Gap))}");
+ }
+ }
+ }
+ if (columns.RightToLeft)
+ sb.Append("\\rtlsect");
+ if (!continuous && section.StartPageNumber is { } start)
+ sb.Append($"\\pgnstarts{Number(Math.Max(0, start))}\\pgnrestart");
+ var titlePage = !continuous && (section.HideFirstHeader || section.HideFirstFooter || section.FirstPageHeader is not null || section.FirstPageFooter is not null);
+ if (titlePage)
+ sb.Append("\\titlepg");
+ o.Control(sb.ToString());
+ o.Line();
+ if (continuous)
+ return;
+
+ _width = page.TextWidth;
+ HeadersFooters("header", section.Headers, section.HideFirstHeader ? [] : section.FirstPageHeader, titlePage);
+ HeadersFooters("footer", section.Footers, section.HideFirstFooter ? [] : section.FirstPageFooter, titlePage);
+ }
+
+ ///
+ /// \header (every page), \headerr and \headerl (odd and even pages, with facing pages) and \headerf (the first
+ /// page, empty when the section hides its header there).
+ ///
+ private void HeadersFooters(string kind, List items, List? firstPage, bool titlePage)
+ {
+ var both = items.LastOrDefault(i => i.Pages == HPageType.Both)?.Blocks;
+ var odd = items.LastOrDefault(i => i.Pages == HPageType.Odd)?.Blocks;
+ var even = items.LastOrDefault(i => i.Pages == HPageType.Even)?.Blocks;
+ if (_facingPages)
+ {
+ Part(kind + "r", odd ?? both);
+ Part(kind + "l", even ?? both);
+ }
+ else
+ {
+ Part(kind, odd ?? both);
+ }
+ if (titlePage)
+ Part(kind + "f", firstPage ?? odd ?? both ?? []);
+ }
+
+ private void Part(string destination, List? blocks)
+ {
+ if (blocks is null)
+ return;
+ _out.Open();
+ _out.Control("\\" + destination);
+ Blocks(blocks, Story.Header, 0, BlockEnd.Story);
+ _out.Close();
+ _out.Line();
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ /// HWPUNIT → twips (1/1440 inch).
+ private static int Twips(int hwpUnit) => (int)Math.Round(hwpUnit / 5.0);
+
+ private static string Number(int value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
index ab9160a77..03570139c 100644
--- a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
@@ -14,7 +14,7 @@ internal static class SheetDocument
{
/// The formats DocumentReaders reads into a document through .
public static readonly IReadOnlySet SourceFormats =
- new HashSet(["xlsx", "xlsm", "xltx", "xlsb", "csv", "tsv", "xls", "xlt", "ods"], StringComparer.OrdinalIgnoreCase);
+ new HashSet(["xlsx", "xlsm", "xltx", "xlsb", "csv", "tsv", "xls", "xlt", "ods", "ots", "fods"], StringComparer.OrdinalIgnoreCase);
/// Largest table written; bigger sheets are cut with a note (a PDF of 100 000 rows helps nobody).
private const int MaxRows = 5000;
diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
index 2defa4d08..b5c49c32c 100644
--- a/src/Filee.Engines/Infrastructure/ComplexScripts.cs
+++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
@@ -384,7 +384,7 @@ static bool InWord(string name, int before, int after)
return FindInString(message.HtmlBody ?? message.TextBody ?? "", classifier, skipBelow);
}
return format is "txt" or "md" or "html" or "csv" or "tsv" or "fb2" or "rtf" or "rst" or "tex" or "org" or "adoc"
- or "typ" or "mediawiki" or "dbk" or "textile" or "man" or "opml" or "mm"
+ or "typ" or "mediawiki" or "dbk" or "textile" or "man" or "opml" or "mm" or "fodt" or "fods" or "fodp" or "fodg"
? FindInText(path, classifier, skipBelow)
: null; // other binary formats (MOBI, ...): left to the engines
}
@@ -503,7 +503,7 @@ bool Xml(string folder, string prefix) =>
"pptx" or "pptm" or "potx" or "potm" or "ppsx" => Xml("ppt/slides/", "slide"),
"xlsx" or "xlsm" or "xltx" => Xml("xl/", "sharedStrings") || Xml("xl/worksheets/", "sheet"),
"hwpx" => Xml("Contents/", "section"),
- "odt" or "ods" or "odp" or "udf" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),
+ "odt" or "ott" or "ods" or "ots" or "odp" or "otp" or "odg" or "otg" or "udf" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),
"xmind" => name.Equals("content.json", StringComparison.OrdinalIgnoreCase) || name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),
// OFD: the pages and templates (Doc_0/Pages/Page_0/Content.xml, Doc_0/Tpls/Tpl_0/Content.xml).
"ofd" => name.EndsWith("/Content.xml", StringComparison.OrdinalIgnoreCase),
diff --git a/src/Filee.Engines/Ocr/OcrTextLayer.cs b/src/Filee.Engines/Ocr/OcrTextLayer.cs
index 3f2bc2e74..a4df92918 100644
--- a/src/Filee.Engines/Ocr/OcrTextLayer.cs
+++ b/src/Filee.Engines/Ocr/OcrTextLayer.cs
@@ -94,6 +94,15 @@ public void AddPage(string picture, double width, double height, IReadOnlyListThe document the pages go into (for a writer that draws its pages itself, DjvuPdfWriter).
+ internal PdfDocument Document => _document;
+
+ /// Adds as invisible text over a page of × points.
+ internal void AddText(PdfPage page, IReadOnlyList lines, double width, double height)
+ {
var text = TextLayer(lines, width, height);
if (text.Length == 0)
return;
diff --git a/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs b/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs
index f8daddc41..8f4d31ac6 100644
--- a/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs
+++ b/src/Filee.Engines/Odf/Draw/OdfDrawReader.cs
@@ -1,4 +1,4 @@
-// OpenDocument presentations (.odp, .otp, .fodp) and drawings (.odg, .fodg) → the slide model (Slides/SlideModel.cs),
+// OpenDocument presentations (.odp, .otp, .fodp) and drawings (.odg, .otg, .fodg) → the slide model (Slides/SlideModel.cs),
// read straight from the package or flat file per OpenDocument 1.3 Part 3, for pictures of each page drawn by the slide
// renderer (presentations through FileeRendererConverter, drawings through DrawingConverter) without LibreOffice.
//
@@ -47,7 +47,7 @@ internal sealed partial class OdfDrawReader
public static readonly string[] Presentations = ["odp", "otp", "fodp"];
/// Drawing formats (pages through the drawing converter).
- public static readonly string[] Drawings = ["odg", "fodg"];
+ public static readonly string[] Drawings = ["odg", "otg", "fodg"];
/// Path commands and points of all shapes of a deck at most, every use counting again.
private const int MaxDeckCommands = 2_000_000;
diff --git a/src/Filee.Engines/Odf/OdfFlat.cs b/src/Filee.Engines/Odf/OdfFlat.cs
new file mode 100644
index 000000000..11ddf7fd0
--- /dev/null
+++ b/src/Filee.Engines/Odf/OdfFlat.cs
@@ -0,0 +1,482 @@
+// Flat OpenDocument files (.fodt, .fods, .fodp, .fodg; OpenDocument 1.3 Part 3, 2.2) to and from packages. A flat
+// file is one office:document holding what the package keeps in its parts: office:meta (meta.xml), office:settings
+// (settings.xml), office:scripts, office:font-face-decls and office:automatic-styles (content.xml and styles.xml),
+// office:styles and office:master-styles (styles.xml) and office:body (content.xml). Pictures are base64 in
+// office:binary-data where the package has an xlink:href to a part, and an embedded object (a chart) is an
+// office:document of its own inside draw:object where the package has a folder ("Object 1/").
+//
+// Taking a flat file apart, the automatic styles go into both content.xml and styles.xml (the master pages use them
+// too) and each picture becomes a part under Pictures/ (one part for a picture stored more than once). Putting a package together, the automatic styles of styles.xml
+// that have the name of one in content.xml are renamed (with what refers to them) so both sets fit in one element.
+//
+// Limits: a flat file is read through SafeXml within the document limits' depth and element counts and at most
+// FlatPartFactor times what one package part may hold (as the ODP / ODG reader reads one, Odf/Draw/OdfDrawPackage); a
+// picture decodes to at most a part's size, all of them to at most the package size, in at most as many parts as a
+// package may have. A package is read through DocumentPackage, and a flat file made from it may hold at most what a flat
+// file may be read with: one picture referred to again and again is stored each time, and that can't grow without end.
+
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Xml;
+using System.Xml.Linq;
+using Filee.Engines.Documents;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Metafiles;
+using OdfNames = Filee.Engines.Hwp.Hwpx.Odt.Odf;
+
+namespace Filee.Engines.Odf;
+
+internal static class OdfFlat
+{
+ /// A flat file may be this many times a package part: it holds every part and the pictures in base64.
+ internal const int FlatPartFactor = 4;
+
+ /// Objects inside objects followed at most.
+ private const int MaxObjectDepth = 8;
+
+ private static readonly XNamespace Office = OdfNames.Office;
+ private static readonly XNamespace Style = OdfNames.Style;
+ private static readonly XNamespace Text = OdfNames.Text;
+ private static readonly XNamespace Draw = OdfNames.Draw;
+ private static readonly XNamespace XLink = OdfNames.XLink;
+ private static readonly XNamespace Manifest = OdfNames.Manifest;
+
+ /// The elements whose picture (or OLE object) is a part in a package and office:binary-data in a flat file.
+ private static readonly HashSet Binaries =
+ [
+ Draw + "image", Draw + "fill-image", Draw + "object-ole", Style + "background-image", Text + "list-level-style-image",
+ ];
+
+ /// The most a flat file may be, read or written, within .
+ internal static long MaxBytes(DocumentLimits limits) => limits.MaxPartBytes * FlatPartFactor;
+
+ // ───────────────────────── Flat → package ─────────────────────────
+
+ /// Writes the flat file as the package with .
+ /// The media types the flat file may say it has.
+ /// The type for messages ("an OpenDocument text").
+ public static void ToPackage(string input, string output, string mimeType, IReadOnlyCollection accepted, string kind,
+ DocumentLimits limits, CancellationToken cancellationToken)
+ {
+ var document = Load(input, kind, limits);
+ if ((string?)document.Attribute(Office + "mimetype") is { Length: > 0 } type && !accepted.Contains(type.Trim()))
+ throw new InvalidDataException($"The file is not {kind} ({type.Trim()}).");
+ var split = new Splitter(limits, cancellationToken);
+ split.Split(document, "", mimeType, 0);
+ OdfPackageWriter.Write(output, mimeType, (string?)document.Attribute(Office + "version") ?? OdfNames.Version, split.Parts, cancellationToken);
+ }
+
+ /// The office:document of a flat file, read within the limits.
+ internal static XElement Load(string path, string kind, DocumentLimits limits)
+ {
+ var maxBytes = MaxBytes(limits);
+ if (new FileInfo(path).Length > maxBytes)
+ throw DocumentLimits.Exceeded($"The file is larger than {DocumentLimits.Megabytes(maxBytes)}.");
+ XDocument document;
+ using (var stream = File.OpenRead(path))
+ {
+ try
+ {
+ document = SafeXml.Load(stream, new XmlLimits(limits.MaxXmlDepth, limits.MaxXmlElements, maxBytes), DocumentLimits.Exceeded);
+ }
+ catch (Exception ex) when (ex is XmlException or DecoderFallbackException or ArgumentException)
+ {
+ throw new InvalidDataException($"The file is not valid flat OpenDocument XML. It may be damaged. {ex.Message}", ex);
+ }
+ }
+ if (document.Root is not { } root || root.Name != Office + "document")
+ throw new InvalidDataException($"The file is not {kind} (no office:document).");
+ return root;
+ }
+
+ /// Takes office:document elements apart into the parts of a package.
+ private sealed class Splitter(DocumentLimits limits, CancellationToken cancellationToken)
+ {
+ public List Parts { get; } = [];
+
+ /// The part of each picture by its bytes' hash and folder: a picture stored again and again is one part.
+ private readonly Dictionary _stored = new(StringComparer.Ordinal);
+
+ private long _bytes;
+ private int _objects;
+
+ public void Split(XElement document, string folder, string mimeType, int depth)
+ {
+ Walk(document, folder, depth);
+ XElement Root(string name, params XName[] children)
+ {
+ var root = new XElement(Office + name, document.Attributes().Where(a => a.IsNamespaceDeclaration));
+ if (document.Attribute(Office + "version") is { } version)
+ root.Add(new XAttribute(version));
+ foreach (var child in children)
+ {
+ if (document.Element(child) is not { } element)
+ continue;
+ // Font faces and automatic styles go into both content.xml and styles.xml; the rest moves.
+ if (child == Office + "font-face-decls" || child == Office + "automatic-styles")
+ {
+ root.Add(new XElement(element));
+ }
+ else
+ {
+ element.Remove();
+ root.Add(element);
+ }
+ }
+ return root;
+ }
+ Add(folder + "content.xml", Root("document-content", Office + "scripts", Office + "font-face-decls", Office + "automatic-styles", Office + "body"));
+ Add(folder + "styles.xml", Root("document-styles", Office + "font-face-decls", Office + "styles", Office + "automatic-styles", Office + "master-styles"));
+ if (document.Element(Office + "meta") is not null)
+ Add(folder + "meta.xml", Root("document-meta", Office + "meta"));
+ if (document.Element(Office + "settings") is not null)
+ Add(folder + "settings.xml", Root("document-settings", Office + "settings"));
+ if (folder.Length > 0)
+ Parts.Add(new OdfPart(folder, mimeType));
+ }
+
+ private void Add(string path, XElement root)
+ {
+ using var stream = new MemoryStream();
+ using (var writer = XmlWriter.Create(stream, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
+ new XDocument(new XDeclaration("1.0", "UTF-8", null), root).Save(writer);
+ Parts.Add(new OdfPart(path, "text/xml", Bytes: stream.ToArray()));
+ }
+
+ ///
+ /// Turns office:binary-data into parts and embedded office:documents into folders, below
+ /// but not inside the documents of its objects (those are split on their own).
+ ///
+ private void Walk(XElement element, string folder, int depth)
+ {
+ foreach (var child in element.Elements().ToList())
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ if (child.Name == Office + "binary-data")
+ {
+ Picture(child, folder);
+ continue;
+ }
+ if (child.Name == Draw + "object" && child.Element(Office + "document") is { } inner)
+ {
+ Object(child, inner, folder, depth);
+ continue;
+ }
+ if (child.Name != Office + "document")
+ Walk(child, folder, depth);
+ }
+ }
+
+ private void Picture(XElement data, string folder)
+ {
+ var owner = data.Parent!;
+ data.Remove();
+ if (!Binaries.Contains(owner.Name))
+ return;
+ var text = data.Value;
+ if (text.Length / 4L * 3 > limits.MaxPartBytes)
+ throw DocumentLimits.Exceeded($"A picture stored in the file is larger than {DocumentLimits.Megabytes(limits.MaxPartBytes)}.");
+ byte[] bytes;
+ try
+ {
+ bytes = System.Convert.FromBase64String(text.Trim());
+ }
+ catch (FormatException)
+ {
+ return; // not base64: the picture is left out, as the readers leave it out
+ }
+ _bytes += bytes.Length;
+ if (_bytes > limits.MaxPackageBytes)
+ throw DocumentLimits.Exceeded($"The pictures stored in the file are larger than {DocumentLimits.Megabytes(limits.MaxPackageBytes)} together.");
+ var key = folder + ":" + System.Convert.ToHexString(SHA256.HashData(bytes));
+ if (_stored.TryGetValue(key, out var known))
+ {
+ Link(owner, known);
+ return;
+ }
+ if (Parts.Count >= limits.MaxPackageEntries)
+ throw DocumentLimits.Exceeded($"The file holds more than {DocumentLimits.Count(limits.MaxPackageEntries)} pictures and objects.");
+ var (extension, mediaType) = owner.Name == Draw + "object-ole" ? ("", "application/vnd.sun.star.oleobject") : Kind(bytes);
+ var name = (owner.Name == Draw + "object-ole" ? "OleObject" : "Pictures/image")
+ + (Parts.Count + 1).ToString(CultureInfo.InvariantCulture) + extension;
+ Parts.Add(new OdfPart(folder + name, mediaType, Bytes: bytes));
+ _stored[key] = name;
+ Link(owner, name);
+ }
+
+ private void Object(XElement frame, XElement inner, string folder, int depth)
+ {
+ inner.Remove();
+ if (depth >= MaxObjectDepth)
+ return;
+ if (++_objects > limits.MaxObjects)
+ throw DocumentLimits.Exceeded($"The file holds more than {DocumentLimits.Count(limits.MaxObjects)} objects.");
+ var name = "Object " + _objects.ToString(CultureInfo.InvariantCulture);
+ var type = ((string?)inner.Attribute(Office + "mimetype"))?.Trim() is { Length: > 0 } declared ? declared : "application/vnd.oasis.opendocument.chart";
+ Split(inner, folder + name + "/", type, depth + 1);
+ Link(frame, "./" + name);
+ }
+
+ private static void Link(XElement element, string href)
+ {
+ element.SetAttributeValue(XLink + "href", href);
+ element.SetAttributeValue(XLink + "type", "simple");
+ element.SetAttributeValue(XLink + "show", "embed");
+ element.SetAttributeValue(XLink + "actuate", "onLoad");
+ }
+ }
+
+ /// The extension and media type of a picture, by its signature.
+ internal static (string Extension, string MediaType) Kind(byte[] data)
+ {
+ var span = data.AsSpan();
+ if (span.StartsWith((ReadOnlySpan)[0x89, (byte)'P', (byte)'N', (byte)'G']))
+ return (".png", "image/png");
+ if (span.StartsWith((ReadOnlySpan)[0xFF, 0xD8, 0xFF]))
+ return (".jpg", "image/jpeg");
+ if (span.StartsWith("GIF8"u8))
+ return (".gif", "image/gif");
+ if (span.StartsWith("BM"u8))
+ return (".bmp", "image/bmp");
+ if (span.StartsWith("II*\0"u8) || span.StartsWith("MM\0*"u8))
+ return (".tif", "image/tiff");
+ if (span.Length >= 12 && span.StartsWith("RIFF"u8) && span[8..12].SequenceEqual("WEBP"u8))
+ return (".webp", "image/webp");
+ switch (Metafile.Detect(span[..Math.Min(span.Length, 64)]))
+ {
+ case MetafileFormat.Emf:
+ return (".emf", "image/x-emf");
+ case MetafileFormat.Wmf:
+ return (".wmf", "image/x-wmf");
+ }
+ var head = Encoding.UTF8.GetString(span[..Math.Min(span.Length, 1024)]);
+ if (head.Contains("