diff --git a/README.md b/README.md
index 8507f7781..d752e7e8d 100644
--- a/README.md
+++ b/README.md
@@ -172,7 +172,7 @@ To undo it, remove the entries in Windows Security → App & browser control →
| **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) 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 |
| **PDF** | DOCX, XLSX (tables), HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (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) 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² |
+| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG; OFD (Chinese e-invoices, official documents) and UYAP UDF (Turkish court documents) 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, 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² |
| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML, PPTX and ODP slides |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 2ec22312c..6a1838b01 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -18,9 +18,9 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **Spreadsheet printing** | built in | **XLSX (+ XLSM/XLTX), 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)) |
| Office Open XML | built in | **DOCM / DOTX / DOTM ↔ DOCX, XLSM / XLTX ↔ XLSX, PPTM / POTX / POTM / PPSX ↔ PPTX** (macros removed for macro-free types) |
| 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, HTML, MHTML, EPUB, MOBI/AZW3, FB2, CHM, PDB, PML, TCR, RB, SNB, OEB, HWPX, TXT, Markdown, RTF → 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, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP) → DOCX** |
-| **ODT writer** | built in | **DOCX (+ variants), DOC (+ DOT, WPS), HWPX, HWP, PDF, OFD, HTML, MHTML, EPUB, MOBI/AZW3, FB2 (and the older e-books), Markdown, TXT, RTF, XLSX, XLS, ODS, CSV, PPTX (+ variants), PPT, ODP (+ OTP, FODP) → ODT** (OpenDocument text, LibreOffice Writer) |
+| **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 → 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) → 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) → 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 |
| PDF text | built in (PdfPig) | **PDF → TXT, Markdown** (reading order, also two columns; Markdown keeps headings, emphasis, links and the pictures; no OCR) |
@@ -39,7 +39,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| 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, the markup languages Filee reads itself (and Pandoc's formats) → 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, RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats) → 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), GZ, BZ2, XZ, LZMA, Z, 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 |
@@ -1026,7 +1026,7 @@ test turns it on.
Word documents (DOCX, DOCM, DOTX, DOTM, and DOC, DOT, WPS through the [DOC reader](#doc-reader)), ODT, RTF, text,
Markdown, HTML and MHTML, EPUB, KEPUB, MOBI / AZW3 / AZW / PRC, FB2, HTMLZ, TXTZ, the other e-book and markup
formats Filee reads, CSV and TSV (one table each: sheet print needs a page setup), OFD (the pages the
- [OFD reader](#ofd-reader) rebuilds, tables and seals included), and Pandoc's formats when Pandoc is installed, to
+ [OFD reader](#ofd-reader) rebuilds, tables and seals included), UYAP documents (the [UYAP reader](#uyap-reader)), and Pandoc's formats when Pandoc is installed, to
PDF. Pictures of the pages go on from its PDF through PDFium, which applies the image options.
- **Slide decks** (`Slides/SlideFormats.cs`): PPTX, PPTM, POTX, POTM and PPSX, PPT through the PPTX package the
[PPT reader](#ppt-reader) translates it to, and ODP, OTP and FODP through the [ODP / ODG reader](#odp--odg-reader)
@@ -2160,6 +2160,48 @@ differently inside an exact line (Word and LibreOffice at its foot, 한글 and r
text sits up to 0.2 sizes higher than on the page. LibreOffice adds cell borders to row heights: the DOCX of a
full 140 mm invoice opened there puts its last line on a second page (rhwp's PDF keeps it on one).
+## UYAP reader
+
+UYAP's `.udf` (#1338) is the file of the UYAP Document Editor (UYAP Doküman Editörü), which Turkish courts, lawyers and
+citizens write petitions and decisions in. `Uyap/UyapReader.cs` reads it into the document model with no external
+engine, so UDF → PDF is one step through the Filee renderer (two, HWPX writer and rhwp, with it off), UDF → DOCX, ODT
+and HWPX one through their writers, and TXT, Markdown, HTML and EPUB follow from there. UDF is read only
+(`Writable: false`) and sits on the office donut (new libraries; an existing library learns `.udf` through a settings
+migration).
+
+- **Package**: a ZIP with one part, `content.xml`, read within `DocumentLimits` (`Documents/DocumentPackage`: part
+ sizes counted while unpacking, the inflate ratio, no DTD, depth and element limits). Its `` holds the whole
+ text in one CDATA block (paragraphs ended by a line feed), the page (``), the paragraphs
+ (``) and the styles. Runs (` `) point into the text by offset, in UTF-16
+ units as Java counts; offsets outside the text are cut to it.
+- **Formats**: a run takes what it doesn't say from its paragraph, then from the style `` names
+ (`hvl-default`, Times New Roman 12 pt), never from the editor's own grey Dialog `default` style, which UYAP doesn't
+ print. Family, size (points), bold, italic, underline, strikethrough, super- and subscript, foreground and background
+ (Java ARGB integers); Java's logical fonts (Dialog, Serif, Monospaced) become Arial, Times New Roman and Courier New.
+ Paragraphs: Swing alignment (0 left, 1 centre, 2 right, 3 justified), left, right and first-line indents, space
+ above and below, line spacing, and the TabSet (`position:alignment:leader`, from the left indent). Text is drawn
+ without kerning, as Java draws it, and Swing's default tab stops are every 72 pt.
+- **Line height**: Java's (`FontMetrics.getHeight`: the ascent rounded up, descent and leading rounded up together),
+ for the fonts UYAP documents use (Times New Roman, Calibri, Arial, Courier New, Tahoma, Verdana, Cambria, Georgia,
+ Segoe UI), as an "at least" height: a 12 pt Calibri or Times New Roman line is 15 pt as in the PDF the editor
+ prints, so pages break where they break there. Other fonts take their own single line height.
+- **Page**: A4 (`mediaSizeName` 1, and every other value until a file shows what it means), landscape for Java's
+ orientations 0 and 2; margins in points, the header and footer distances (`headerFOffset`, `footerFOffset`) as the
+ top of the header and footer areas.
+- **Tables** (``): the column spans as shares of the text width,
+ `borderNone` without lines, cell spans and fill where a cell gives them; tables nested past `Nesting.MaxDepth`
+ become plain paragraphs. **Pictures** (``, Base64 in the XML): PNG, JPEG, GIF and BMP up to 32 MB
+ each and 2,000 a document, left out when their header claims more pixels than `DocumentLimits` allows.
+ **Page breaks**, **headers and footers** (paragraphs in `` / ``) and page-number fields are read.
+- **The other `.udf`**: a Universal Disk Format disc image has the same extension. The content tells them apart
+ (`UyapReader.IsUyap`): a ZIP whose `content.xml` has a `` root is UYAP. Given to a document route, a disc
+ is refused with `error.udf_not_uyap`, which points to Extract; the archive engine has a UDF → folder edge (Extract
+ only, no repacking) and unpacks a disc as an ISO (`ArchiveExtractor`), a UYAP file as the ZIP it is.
+
+Compared with the PDF the editor prints, a petition in Calibri comes out on the same pages with the same page breaks,
+fonts, alignment and indents. Lines inside a paragraph may break a word earlier or later: Java lays text out with
+whole-point glyph advances, the Filee renderer with the font's own.
+
## PDF → XLSX
`Pdf/PdfTablesConverter.cs` puts the tables of a PDF into a workbook (#267). The tables are the ruled ones PDF → DOCX
@@ -3446,7 +3488,7 @@ paths leaving the folder, bombs, entry floods) are final and never retried. Sett
| CPIO | Filee (`CpioReader`: newc, crc with its byte sum checked, odc, old binary in either byte order; newc hard link groups become copies) | — |
| DEB (ar) | Filee (`ArReader`: GNU and BSD long names, symbol tables skipped): unpacks to `debian-binary`, `control.tar.*`, `data.tar.*` | — |
| RPM | Filee (`RpmReader`): the payload (gzip, bzip2, xz, LZMA, zstd or plain) becomes `.cpio`, unpacked in the next stage | — |
-| ISO | Filee (`IsoReader`: ISO 9660 with Rock Ridge names, else Joliet, else the plain names; multi-extent files); discs with UDF (Windows install discs, DVD and Blu-ray data discs, UDF 1.02 to 2.60) by DiscUtils.Udf through `DiskImageReader`, and when that fails by 7-Zip, or without 7-Zip by the ISO 9660 part of a bridge disc | — |
+| ISO | Filee (`IsoReader`: ISO 9660 with Rock Ridge names, else Joliet, else the plain names; multi-extent files); discs with UDF (Windows install discs, DVD and Blu-ray data discs, UDF 1.02 to 2.60) by DiscUtils.Udf through `DiskImageReader`, and when that fails by 7-Zip, or without 7-Zip by the ISO 9660 part of a bridge disc; a disc image named `.udf` too (Extract only; a `.udf` that is a ZIP is a UYAP document, see [UYAP reader](#uyap-reader)) | — |
| Split archives (.001, .7z.001, .zip.001, .tar.001) | the volumes read as one stream (`SplitVolumes`): 7z by Filee's reader, ZIP and RAR by SharpCompress, TAR by .NET | — |
| ALZ (ALZip) | Filee: store, deflate and ALZip's bzip2 variant | — |
| EGG (ALZip) | Filee: store, deflate, bzip2, LZMA (SharpCompress's decoder); several blocks per file | — |
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 106cec092..adb5532da 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "لا يحتوي ملف .p7m هذا إلا على التوقيع، لا على الملف الموقّع. حوّل الملف الذي يوقّعه بدلًا منه",
"error.p7m_encrypted": "ملف .p7m هذا مشفّر وليس موقّعًا فقط: لا يفتحه إلا مفتاح المستلم",
"error.p7m_unknown_content": "الملف داخل ملف .p7m هذا من نوع لا يحوّله Filee",
+ "error.udf_not_uyap": "ملف .udf هذا ليس مستند UYAP. إذا كان صورة قرص (Universal Disk Format)، فافتحه باستخدام «استخراج»",
"error.p7m_too_large": "الملف الموقّع أكبر من أن يُفتح",
"error.document_too_large": "يتوسّع هذا المستند إلى بيانات أكثر من اللازم أو أنه متداخل بعمق شديد بحيث لا يمكن فتحه بأمان",
"format_request.request": "طلب دعم هذه الصيغة",
diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json
index 61f58d739..747731f1d 100644
--- a/src/Filee.App/Assets/i18n/bn-BD.json
+++ b/src/Filee.App/Assets/i18n/bn-BD.json
@@ -124,6 +124,7 @@
"error.p7m_detached": "এই .p7m-এ শুধু স্বাক্ষর আছে, স্বাক্ষরিত ফাইলটি নেই। পরিবর্তে যে ফাইলে এটি স্বাক্ষর করা হয়েছে সেটি রূপান্তর করুন",
"error.p7m_encrypted": "এই .p7m শুধু স্বাক্ষরিত নয়, এনক্রিপ্টও করা: কেবল প্রাপকের কী দিয়ে এটি খোলা যায়",
"error.p7m_unknown_content": "এই .p7m-এর ভেতরের ফাইলটি এমন ধরনের যা ফাইলি রূপান্তর করে না",
+ "error.udf_not_uyap": "এই .udf ফাইলটি UYAP ডকুমেন্ট নয়। এটি ডিস্ক ইমেজ (Universal Disk Format) হলে «নিষ্কাশন করুন» দিয়ে খুলুন",
"error.p7m_too_large": "স্বাক্ষরিত ফাইলটি খোলার জন্য অতিরিক্ত বড়",
"error.document_too_large": "এই নথিটি খুললে অতিরিক্ত ডেটা তৈরি হয় বা এটি অতিরিক্ত গভীরভাবে নেস্ট করা, তাই নিরাপদে খোলা যাচ্ছে না",
"format_request.request": "এই ফরম্যাটের অনুরোধ করুন",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index a43119873..018f41739 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "Diese .p7m enthält nur die Signatur, nicht die signierte Datei. Konvertiere stattdessen die Datei, die sie signiert",
"error.p7m_encrypted": "Diese .p7m ist verschlüsselt, nicht nur signiert: Nur der Schlüssel des Empfängers öffnet sie",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 66a3b2bae..7b4914fa4 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "This .p7m holds only the signature, not the signed file. Convert the file it signs instead",
"error.p7m_encrypted": "This .p7m is encrypted, not only signed: only the recipient's key opens it",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 981a77e3c..e1add24a7 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "Este .p7m solo contiene la firma, no el archivo firmado. Convierte el archivo que firma",
"error.p7m_encrypted": "Este .p7m está cifrado, no solo firmado: solo lo abre la clave del destinatario",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json
index 2eb60c118..f9d12bfef 100644
--- a/src/Filee.App/Assets/i18n/fa.json
+++ b/src/Filee.App/Assets/i18n/fa.json
@@ -124,6 +124,7 @@
"error.p7m_detached": "این فایل .p7m فقط شامل امضا است، نه خود فایل امضاشده. به جای آن، فایلی را که امضا میکند تبدیل نمایید",
"error.p7m_encrypted": "این فایل .p7m رمزگذاری شده است و فقط امضا ندارد: تنها با کلید گیرنده باز میشود",
"error.p7m_unknown_content": "فایل داخل این .p7m از نوعی است که Filee تبدیل نمیکند",
+ "error.udf_not_uyap": "این فایل .udf سند UYAP نیست. اگر ایمیج دیسک (Universal Disk Format) است، آن را با «استخراج» باز کنید",
"error.p7m_too_large": "فایل امضاشده برای باز شدن بیش از حد بزرگ است",
"error.document_too_large": "دادههای استخراجشده از این سند بیش از حد مجاز است یا ساختار آن برای باز شدن ایمن بیش از حد تودرتو است",
"format_request.request": "درخواست این فرمت",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 289c11f6a..53a5a241e 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "Ce .p7m ne contient que la signature, pas le fichier signé. Convertissez plutôt le fichier qu'il signe",
"error.p7m_encrypted": "Ce .p7m est chiffré, pas seulement signé : seule la clé du destinataire peut l'ouvrir",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index afade73cc..a5b41b416 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "इस .p7m में सिर्फ़ सिग्नेचर है, साइन की गई फ़ाइल नहीं। इसकी जगह वह फ़ाइल बदलें जिस पर यह साइन है",
"error.p7m_encrypted": "यह .p7m सिर्फ़ साइन नहीं, एन्क्रिप्ट भी है: इसे सिर्फ़ प्राप्तकर्ता की कुंजी खोल सकती है",
"error.p7m_unknown_content": "इस .p7m के अंदर की फ़ाइल ऐसे प्रकार की है जिसे Filee नहीं बदलता",
+ "error.udf_not_uyap": "यह .udf फ़ाइल UYAP दस्तावेज़ नहीं है। अगर यह डिस्क इमेज (Universal Disk Format) है, तो इसे «निकालें» से खोलें",
"error.p7m_too_large": "साइन की गई फ़ाइल खोलने के लिए बहुत बड़ी है",
"error.document_too_large": "यह दस्तावेज़ खोलने पर बहुत ज़्यादा डेटा बनता है या बहुत गहराई तक नेस्टेड है, इसलिए इसे सुरक्षित रूप से नहीं खोला जा सकता",
"format_request.request": "इस फ़ॉर्मैट का अनुरोध करें",
diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json
index c47b231c2..9fa323f6c 100644
--- a/src/Filee.App/Assets/i18n/id.json
+++ b/src/Filee.App/Assets/i18n/id.json
@@ -110,6 +110,7 @@
"error.p7m_detached": ".p7m ini hanya berisi tanda tangan, bukan file yang ditandatangani. Konversikan file yang ditandatanganinya",
"error.p7m_encrypted": ".p7m ini dienkripsi, bukan hanya ditandatangani: hanya kunci penerima yang bisa membukanya",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json
index 41716ed6b..bd2145de7 100644
--- a/src/Filee.App/Assets/i18n/it.json
+++ b/src/Filee.App/Assets/i18n/it.json
@@ -109,6 +109,7 @@
"error.p7m_detached": "Questo .p7m contiene solo la firma, non il file firmato. Converti invece il file che firma",
"error.p7m_encrypted": "Questo .p7m è cifrato, non solo firmato: solo la chiave del destinatario può aprirlo",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 24ee0c8da..e73378a70 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "この .p7m には署名だけが入っていて、署名されたファイルはありません。署名対象のファイルを変換してください",
"error.p7m_encrypted": "この .p7m は署名だけでなく暗号化されています。受信者の鍵でしか開けません",
"error.p7m_unknown_content": "この .p7m の中のファイルは、Filee が変換できない形式です",
+ "error.udf_not_uyap": "この .udf ファイルは UYAP 文書ではありません。ディスクイメージ (Universal Disk Format) なら「展開」で開いてください",
"error.p7m_too_large": "署名付きファイルが大きすぎて開けません",
"error.document_too_large": "この文書は展開するとデータが大きすぎるか、入れ子が深すぎるため、安全に開けません",
"format_request.request": "この形式への対応をリクエスト",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 4bb97cb8f..d982b93bc 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "이 .p7m에는 서명만 있고 서명된 파일은 없어요. 서명 대상 파일을 변환해 주세요",
"error.p7m_encrypted": "이 .p7m은 서명만이 아니라 암호화돼 있어요. 받는 사람의 키로만 열 수 있어요",
"error.p7m_unknown_content": "이 .p7m 안의 파일은 Filee가 변환하지 않는 형식이에요",
+ "error.udf_not_uyap": "이 .udf 파일은 UYAP 문서가 아니에요. 디스크 이미지(Universal Disk Format)라면 압축 풀기로 열어 주세요",
"error.p7m_too_large": "서명 파일이 너무 커서 열 수 없어요",
"error.document_too_large": "이 문서는 풀면 데이터가 너무 크거나 너무 깊이 중첩되어 있어서 안전하게 열 수 없어요",
"format_request.request": "이 형식 요청하기",
diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json
index 191c4fa47..361f66c50 100644
--- a/src/Filee.App/Assets/i18n/mn.json
+++ b/src/Filee.App/Assets/i18n/mn.json
@@ -109,6 +109,7 @@
"error.p7m_detached": "Энэ .p7m файл нь зөвхөн цахим гарын үсгийг агуулсан бөгөөд гарын үсэг зурсан үндсэн файл нь байхгүй байна. Оронд нь үндсэн файлыг хөрвүүлнэ үү",
"error.p7m_encrypted": "Энэ .p7m файл нь зөвхөн гарын үсэгтэй бус шифрлэгдсэн байна: зөвхөн хүлээн авагчийн түлхүүрээр нээгдэнэ",
"error.p7m_unknown_content": "Энэ .p7m доторх файл нь Filee хөрвүүлдэггүй төрлийн файл байна",
+ "error.udf_not_uyap": "Энэ .udf файл UYAP баримт биш. Хэрэв дискний дүрс (Universal Disk Format) бол «Задлах»-аар нээнэ үү",
"error.p7m_too_large": "Гарын үсэгтэй файл нээхэд хэт том байна",
"error.document_too_large": "Энэ баримт нь задлахад хэт их өгөгдөлтэй эсвэл аюулгүй нээхэд хэт гүн давхарлагдсан байна",
"format_request.request": "Энэ форматыг хүсэх",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 6fe76091c..68de61aca 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "यो .p7m मा हस्ताक्षर मात्र छ, हस्ताक्षरित फाइल छैन। बरु यसले हस्ताक्षर गरेको फाइल रूपान्तरण गर्नुहोस्",
"error.p7m_encrypted": "यो .p7m हस्ताक्षरित मात्र होइन, इन्क्रिप्ट गरिएको छ: प्रापकको कुञ्जीले मात्र खोल्छ",
"error.p7m_unknown_content": "यो .p7m भित्रको फाइल Filee ले रूपान्तरण नगर्ने प्रकारको हो",
+ "error.udf_not_uyap": "यो .udf फाइल UYAP कागजात होइन। यो डिस्क इमेज (Universal Disk Format) हो भने «निकाल्नुहोस्» ले खोल्नुहोस्",
"error.p7m_too_large": "हस्ताक्षरित फाइल खोल्न धेरै ठूलो छ",
"error.document_too_large": "यो कागजात खोल्दा धेरै ठूलो डेटा बन्छ वा धेरै गहिरोसम्म नेस्ट गरिएको छ, त्यसैले सुरक्षित रूपमा खोल्न सकिँदैन",
"error.merge_paper_geometry": "पृष्ठको आकार, घुमाइ वा एकाइ मान्य छैन, त्यसैले यसलाई छानिएको कागजमा मिलाउन सकिँदैन",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index af5494ef7..e109dfee5 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "Ten .p7m zawiera tylko podpis, a nie podpisany plik. Przekonwertuj plik, który podpisuje",
"error.p7m_encrypted": "Ten .p7m jest zaszyfrowany, a nie tylko podpisany: otworzy go tylko klucz odbiorcy",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index e445f101e..cfe7fd8cb 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "Este .p7m contém só a assinatura, não o arquivo assinado. Converta o arquivo que ele assina",
"error.p7m_encrypted": "Este .p7m está criptografado, não só assinado: só a chave do destinatário o abre",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index 5648079ed..56dfa97d5 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "Este .p7m contém só a assinatura, não o ficheiro assinado. Converte o ficheiro que ele assina",
"error.p7m_encrypted": "Este .p7m está encriptado, não só assinado: só a chave do destinatário o abre",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index c40e284cb..5bdefe355 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "В этом .p7m только подпись, без подписанного файла. Конвертируйте сам подписанный файл",
"error.p7m_encrypted": "Этот .p7m зашифрован, а не только подписан: открыть его может только ключ получателя",
"error.p7m_unknown_content": "Файл внутри этого .p7m имеет тип, который Filee не конвертирует",
+ "error.udf_not_uyap": "Этот файл .udf не является документом UYAP. Если это образ диска (Universal Disk Format), откройте его командой «Распаковать»",
"error.p7m_too_large": "Подписанный файл слишком большой, чтобы его открыть",
"error.document_too_large": "Этот документ распаковывается в слишком большой объём данных или вложен слишком глубоко, чтобы его можно было безопасно открыть",
"error.merge_paper_geometry": "У страницы неверный размер, поворот или единицы измерения — её нельзя вписать в выбранный формат бумаги",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index ad797dcb4..3d897be04 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -110,6 +110,7 @@
"error.p7m_detached": ".p7m นี้มีแค่ลายเซ็น ไม่มีไฟล์ที่ลงนาม ให้แปลงไฟล์ที่ลายเซ็นนี้ลงนามแทน",
"error.p7m_encrypted": ".p7m นี้ถูกเข้ารหัส ไม่ใช่แค่ลงนาม: เปิดได้ด้วยกุญแจของผู้รับเท่านั้น",
"error.p7m_unknown_content": "ไฟล์ใน .p7m นี้เป็นชนิดที่ Filee ไม่แปลง",
+ "error.udf_not_uyap": "ไฟล์ .udf นี้ไม่ใช่เอกสาร UYAP หากเป็นอิมเมจดิสก์ (Universal Disk Format) ให้เปิดด้วย “แตกไฟล์”",
"error.p7m_too_large": "ไฟล์ที่ลงนามใหญ่เกินกว่าจะเปิดได้",
"error.document_too_large": "เอกสารนี้แตกออกเป็นข้อมูลมากเกินไปหรือซ้อนกันลึกเกินไป จึงเปิดอย่างปลอดภัยไม่ได้",
"format_request.request": "ขอให้รองรับฟอร์แมตนี้",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 0a28ddc25..513729ab1 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -110,6 +110,7 @@
"error.p7m_detached": "Bu .p7m yalnızca imzayı içeriyor, imzalanan dosyayı değil. Bunun yerine imzaladığı dosyayı dönüştürün",
"error.p7m_encrypted": "Bu .p7m yalnızca imzalı değil, şifreli: yalnızca alıcının anahtarı açabilir",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json
index 54b3d126a..c2dc87ecd 100644
--- a/src/Filee.App/Assets/i18n/vi.json
+++ b/src/Filee.App/Assets/i18n/vi.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "Tệp .p7m này chỉ chứa chữ ký, không chứa tệp đã ký. Hãy chuyển đổi tệp mà nó ký",
"error.p7m_encrypted": "Tệp .p7m này được mã hóa chứ không chỉ được ký: chỉ khóa của người nhận mới mở được",
"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.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",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 85714b4b9..1289411e3 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "这个 .p7m 只包含签名,没有被签名的文件。请转换它所签名的文件",
"error.p7m_encrypted": "这个 .p7m 已加密,而不只是签名:只有收件人的密钥才能打开",
"error.p7m_unknown_content": "这个 .p7m 中的文件是 Filee 不转换的类型",
+ "error.udf_not_uyap": "这个 .udf 文件不是 UYAP 文档。如果它是光盘映像(Universal Disk Format),请用“解压”打开",
"error.p7m_too_large": "已签名的文件太大,无法打开",
"error.document_too_large": "此文档解压后数据过多或嵌套过深,无法安全打开",
"format_request.request": "请求支持此格式",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 63259deb5..1ff2fe25c 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -116,6 +116,7 @@
"error.p7m_detached": "這個 .p7m 只包含簽章,沒有被簽署的檔案。請轉換它所簽署的檔案",
"error.p7m_encrypted": "這個 .p7m 已加密,而不只是簽署:只有收件人的金鑰才能開啟",
"error.p7m_unknown_content": "這個 .p7m 中的檔案是 Filee 不轉換的類型",
+ "error.udf_not_uyap": "這個 .udf 檔案不是 UYAP 文件。如果它是光碟映像(Universal Disk Format),請用「解壓縮」開啟",
"error.p7m_too_large": "已簽署的檔案太大,無法開啟",
"error.document_too_large": "此文件解壓縮後資料過多或巢狀層級過深,無法安全開啟",
"format_request.request": "請求支援此格式",
diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs
index 94e6aade5..e4d7393f6 100644
--- a/src/Filee.Core/Formats/FormatFields.cs
+++ b/src/Filee.Core/Formats/FormatFields.cs
@@ -65,7 +65,7 @@ .. 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",
- "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "abw", "pages", "pub", "eml", "msg",
+ "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "abw", "pages", "pub", "eml", "msg",
"p7m", "xlsm", "xltx", "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 1f3097de2..b4c89b00f 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -116,6 +116,9 @@ public static class FormatRegistry
new("wps", "WPS", FormatCategory.Document, ["wps"], Writable: false),
// The Chinese fixed-layout standard (GB/T 33190): e-invoices, official documents; read by the built-in OFD reader.
new("ofd", "OFD", FormatCategory.Document, ["ofd"], Writable: false),
+ // UYAP Document Editor files (Turkish courts and lawyers, #1338), read by the built-in UYAP reader. ".udf" is also
+ // a Universal Disk Format disc image: told apart by content, such a file unpacks with Extract (archive engine).
+ new("udf", "UYAP (UDF)", FormatCategory.Document, ["udf"], Writable: false),
new("wpd", "WPD", FormatCategory.Document, ["wpd"], Writable: false),
new("lwp", "LWP", FormatCategory.Document, ["lwp"], Writable: false),
new("abw", "ABW", FormatCategory.Document, ["abw", "zabw"], Writable: false),
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 68b88f28f..b591d04c8 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 = 102;
+ public const int CurrentSchemaVersion = 103;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 2ae475613..1a16a004e 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -1218,6 +1218,9 @@ public static bool ApplyToLibrary(int from, List presets, List new ConversionEdge(source, "iso", DirectOnly: true)),
.. folderTargets.Select(target => new ConversionEdge(FormatRegistry.Folder, target, DirectOnly: true)),
+ // ".udf" is a UYAP document (read by the document readers) or a Universal Disk Format disc: Extract unpacks
+ // either, the disc as a disc (ArchiveExtractor).
+ new ConversionEdge(UyapReader.Format, FormatRegistry.Folder),
];
}
diff --git a/src/Filee.Engines/Archives/ArchiveExtractor.cs b/src/Filee.Engines/Archives/ArchiveExtractor.cs
index f4de44910..7e2a2e62d 100644
--- a/src/Filee.Engines/Archives/ArchiveExtractor.cs
+++ b/src/Filee.Engines/Archives/ArchiveExtractor.cs
@@ -17,6 +17,7 @@
using Filee.Core.Conversion;
using Filee.Core.Formats;
using Filee.Core.Platform;
+using Filee.Engines.Uyap;
namespace Filee.Engines.Archives;
@@ -97,6 +98,11 @@ private async Task ExtractOnceAsync(string archive, string format, string folder
{
switch (format)
{
+ // A .udf is a UYAP document (a ZIP) or a Universal Disk Format disc, read like an .iso (a bridge disc's
+ // ISO 9660 part too).
+ case UyapReader.Format:
+ await ExtractOnceAsync(archive, UyapReader.IsZip(archive) ? "zip" : "iso", folder, scratchRoot, cancellationToken);
+ return;
// A PS Vita package is a ZIP under the same extension.
case "vpk" when Vpk.IsZip(archive):
await ExtractOnceAsync(archive, "zip", folder, scratchRoot, cancellationToken);
diff --git a/src/Filee.Engines/Hwp/HwpTextConverter.cs b/src/Filee.Engines/Hwp/HwpTextConverter.cs
index 50d160df3..c429f5abe 100644
--- a/src/Filee.Engines/Hwp/HwpTextConverter.cs
+++ b/src/Filee.Engines/Hwp/HwpTextConverter.cs
@@ -4,6 +4,10 @@
// Markdown puts the pictures into a "_files" folder next to it (MarkdownPictures); the HTML page embeds them as
// data: URIs, so it stays one file. "Leave out pictures" (DocumentOptions.LeaveOutPictures) leaves all of them out of
// the Markdown.
+//
+// RTF → TXT is here too (#1204): RtfReader's document written a line per paragraph, as a word processor saves plain
+// text. Without it the cheapest built-in route went through a PDF (the Filee renderer, then the PDF's text), which
+// wraps long lines and loses the indentation and the empty lines, or through the HWPX writer.
using System.Text;
using Filee.Core.Conversion;
@@ -14,7 +18,7 @@
namespace Filee.Engines.Hwp;
-/// Writes the text of HWP and HWPX documents as TXT, Markdown or HTML.
+/// Writes the text of HWP and HWPX documents as TXT, Markdown or HTML, and of RTF documents as TXT.
public sealed class HwpTextConverter : IConverter
{
/// The engine's id; settings that named Unhwp ("unhwp", the engine this replaced) are moved to it.
@@ -30,9 +34,13 @@ public sealed class HwpTextConverter : IConverter
new("hwp", "txt"), new("hwpx", "txt"),
new("hwp", "md"), new("hwpx", "md"),
new("hwp", "html", 14), new("hwpx", "html", 14),
+ // Direct only, as LibreOffice's RTF → TXT: a TXT step in another route would lose the formatting. Dearer than
+ // LibreOffice's chosen edge (10 + 9 in the default order against 16 + 4), so it stays LibreOffice's while that
+ // is installed, and cheaper than the renderer's PDF and its text (1 + 9 + 10 + 9).
+ new("rtf", "txt", 16, DirectOnly: true),
];
- public EngineStatus GetStatus() => EngineStatus.Available("HWP, HWPX → TXT, Markdown, HTML", EngineVersions.BuiltIn);
+ public EngineStatus GetStatus() => EngineStatus.Available("HWP, HWPX → TXT, Markdown, HTML; RTF → TXT", EngineVersions.BuiltIn);
public async Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken)
{
@@ -46,6 +54,7 @@ public async Task> ConvertAsync(ConversionStep step, IProg
return [];
var content = step.To switch
{
+ "txt" when step.From == "rtf" => PlainTextWriter.WriteLines(document),
"txt" => PlainTextWriter.Write(document),
"md" => Markdown(document, step, path),
"html" => Html(document, step),
diff --git a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
index a6b53170b..1898362c5 100644
--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
@@ -20,6 +20,7 @@
using Filee.Engines.Office.Sheets;
using Filee.Engines.Pdf;
using Filee.Engines.Slides;
+using Filee.Engines.Uyap;
namespace Filee.Engines.Hwp.Hwpx;
@@ -65,6 +66,8 @@ internal static class DocumentReaders
["fodp"] = ReadSlides,
["pdf"] = PdfDocumentReader.Read,
["ofd"] = OfdReader.Read,
+ // UYAP documents (Turkish courts); a .udf disc image is refused here and unpacks with Extract instead.
+ [UyapReader.Format] = UyapReader.Read,
["hwpx"] = HwpxReader.Read,
// HWP 5.0: its records become the HWPX package 한글 saves, read by HwpxReader (no rhwp needed).
["hwp"] = HwpReader.Read,
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
index 7ec47a69e..9d2415b40 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
@@ -43,6 +43,9 @@ private HTable ReadTable(XElement tbl)
grid),
};
+ if (tblPr?.Element(W + "tblpPr") is { } position)
+ Float(table, position);
+
// Borders and cell margins: table style chain, then the table's own properties.
var borders = new Dictionary();
HInsets? margins = null;
@@ -160,6 +163,47 @@ [.. styleChain.Select(s => s.PPr).Concat(cellConditions.Select(c => c.Element(W
return table;
}
+ ///
+ /// A floating table's place (w:tblpPr): against the paper (page), the margins (margin) or, down, the paragraph after
+ /// the table and, across, the column (text); at tblpX / tblpY from their left and top, or aligned by tblpXSpec /
+ /// tblpYSpec. Text goes around it on both sides, the From-text distances away.
+ ///
+ private static void Float(HTable table, XElement position)
+ {
+ static string Area(string? anchor, string text) => anchor switch
+ {
+ "page" => "PAPER",
+ "margin" => "PAGE",
+ _ => text,
+ };
+ static string Align(string? spec) => spec switch
+ {
+ "center" => "CENTER",
+ "right" => "RIGHT",
+ "inside" => "INSIDE",
+ "outside" => "OUTSIDE",
+ _ => "LEFT",
+ };
+ // Word's defaults where the attributes are left out: across from the column, down from the margin.
+ var across = Area(Attr(position, "horzAnchor"), "COLUMN");
+ var down = Area(Attr(position, "vertAnchor") ?? "margin", "PARA");
+ var xSpec = Attr(position, "tblpXSpec");
+ var ySpec = Attr(position, "tblpYSpec");
+ table.Float = new HAnchor(
+ across, Align(xSpec), xSpec is null ? HwpxUnits.FromTwips(Twips(position, "tblpX") ?? 0) : 0,
+ down, ySpec switch
+ {
+ "center" => "CENTER",
+ "bottom" => "BOTTOM",
+ "inside" => "INSIDE",
+ "outside" => "OUTSIDE",
+ _ => "TOP",
+ }, ySpec is null or "inline" ? HwpxUnits.FromTwips(Twips(position, "tblpY") ?? 0) : 0,
+ "SQUARE", true);
+ int Distance(string name) => HwpxUnits.FromTwips(Math.Max(0, Twips(position, name) ?? 0));
+ table.FloatDistance = new HInsets(Distance("leftFromText"), Distance("rightFromText"), Distance("topFromText"), Distance("bottomFromText"));
+ }
+
///
/// The conditional formatting of the table style (w:tblStylePr) that reaches each cell, given its row, grid column
/// and span: banded rows and columns, first and last column, header and total row, then the corner cells, each
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
index 78d498243..ceb7acbac 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
@@ -54,6 +54,9 @@ internal sealed partial class DocxReader
private bool _bordersAroundHeader = true;
private bool _bordersAroundFooter = true;
+ /// Neighbouring paragraphs keep the larger of their spaces between them, not both (see ).
+ private bool _collapseSpacing = true;
+
/// Width of each section's text column (HWPUNIT), for equations that don't fit a line.
private readonly List _columnWidths = [];
@@ -225,6 +228,7 @@ private HDocument ReadDocument()
_evenAndOddHeaders = settings?.Element(W + "evenAndOddHeaders") is { } evenOdd && Val(evenOdd) is not ("0" or "false");
_bordersAroundHeader = !(settings?.Element(W + "bordersDoNotSurroundHeader") is { } noHeader && Val(noHeader) is not ("0" or "false"));
_bordersAroundFooter = !(settings?.Element(W + "bordersDoNotSurroundFooter") is { } noFooter && Val(noFooter) is not ("0" or "false"));
+ _collapseSpacing = !(settings?.Element(W + "compat")?.Element(W + "doNotUseHTMLParagraphAutoSpacing") is { } sum && Val(sum) is not ("0" or "false"));
_footnotesPart = RelatedPart(main, "/footnotes");
_endnotesPart = RelatedPart(main, "/endnotes");
foreach (var note in _footnotesPart?.Xml.Root?.Elements(W + "footnote") ?? [])
@@ -523,6 +527,19 @@ private void ApplyContextualSpacing(HParagraph previous, HParagraph current, Par
current.Format = current.Format with { Before = 0 };
}
+ ///
+ /// Word puts the larger of a paragraph's space below and the next one's space above between them, not both (its HTML
+ /// paragraph spacing, which only w:doNotUseHTMLParagraphAutoSpacing turns off): 6 pt below a heading and 12 pt above
+ /// the next is 12 pt, as Word's own PDFs have it (#1152). The space below the first gives way to the space above.
+ ///
+ private void CollapseSpacing(HParagraph previous, HParagraph current)
+ {
+ if (!_collapseSpacing || current.PageBreakBefore || current.ColumnBreakBefore)
+ return;
+ if (previous.Format.After is > 0 and var after && current.Format.Before is > 0 and var before)
+ previous.Format = previous.Format with { After = Math.Max(0, after - before) };
+ }
+
///
/// Gives a paragraph with "multiple" line spacing the height its fonts have in Word: 한글's percentage is of the font
/// size, and a single Calibri line is 122% of it where one in Times New Roman is 115%.
@@ -973,6 +990,7 @@ private void Emit()
{
JoinBorders(previous, Current);
_reader.ApplyContextualSpacing(previous, Current, _props);
+ _reader.CollapseSpacing(previous, Current);
}
_reader.RememberParagraphStyle(Current, _props);
_output.Add(Current);
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 0f5ddb7a4..32a1ff001 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -448,6 +448,15 @@ internal sealed class HTable : HBlock
///
public HTableSizing? Sizing { get; set; }
+ ///
+ /// A Word floating table (w:tblpPr): placed by the anchor (PARA = the paragraph after the table), text going around
+ /// it, kept away from that text; null = in the flow. Only the layout engine uses it.
+ ///
+ public HAnchor? Float { get; set; }
+
+ /// The distance a floating table keeps from the text around it (w:leftFromText ...).
+ public HInsets FloatDistance { get; set; }
+
public List Caption { get; } = [];
}
diff --git a/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs b/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
index 9aeffa8b1..5a6cd618d 100644
--- a/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
@@ -1,6 +1,7 @@
// HDocument → plain text: paragraphs separated by an empty line, list markers and numbers written out, table rows
// as tab-separated cells, text boxes on lines of their own and footnotes collected at the end. Used for e-books and
-// HWP / HWPX → TXT.
+// HWP / HWPX → TXT. WriteLines is a word processor's "plain text" instead (RTF → TXT): a line per paragraph, an empty
+// paragraph an empty line, and the text's own spaces and tabs as they are.
using System.Globalization;
using System.Text;
@@ -9,22 +10,72 @@ namespace Filee.Engines.Hwp.Hwpx;
internal static class PlainTextWriter
{
- /// The text of a document.
- public static string Write(HDocument document)
+ /// The text of a document, its paragraphs separated by an empty line.
+ public static string Write(HDocument document) => Write(document, lines: false);
+
+ ///
+ /// The text of a document as a word processor saves it as plain text: a line per paragraph and per line break, an
+ /// empty paragraph an empty line, leading spaces, runs of spaces and tabs kept, no indentation added.
+ ///
+ public static string WriteLines(HDocument document) => Write(document, lines: true);
+
+ private static string Write(HDocument document, bool lines)
{
Nesting.Limit(document);
var sb = new StringBuilder();
var notes = new List();
var numbers = new ListNumbers();
foreach (var section in document.Sections)
- Blocks(section.Blocks, sb, notes, numbers);
+ {
+ if (lines)
+ Lines(section.Blocks, sb, notes, numbers);
+ else
+ Blocks(section.Blocks, sb, notes, numbers);
+ }
if (notes.Count > 0)
{
sb.AppendLine().AppendLine("----");
for (var i = 0; i < notes.Count; i++)
sb.AppendLine($"[{i + 1}] {notes[i]}");
}
- return sb.ToString().TrimEnd() + Environment.NewLine;
+ // Line by line, only the empty paragraphs at the end go: the last line keeps its own spaces.
+ return (lines ? sb.ToString().TrimEnd('\r', '\n') : sb.ToString().TrimEnd()) + Environment.NewLine;
+ }
+
+ /// The blocks for : every paragraph and table row ends with a line end.
+ private static void Lines(List blocks, StringBuilder sb, List notes, ListNumbers numbers)
+ {
+ foreach (var block in blocks)
+ {
+ switch (block)
+ {
+ case HParagraph paragraph:
+ {
+ var text = Inlines(paragraph.Inlines, notes, trim: false);
+ if (paragraph.Inlines.Count > 0 && paragraph.Inlines[^1] is HTextBox)
+ text = text.TrimEnd('\n'); // the box's own line end, not an empty line
+ if (paragraph.Inlines.Any(i => i is HShape { Kind: HShapeKind.Line }) && text.Trim().Length == 0)
+ text = "* * *";
+ if (paragraph.List is { } list)
+ {
+ var marker = list.Numbered ? numbers.Next(list) + " " : "";
+ var indent = new string(' ', list.Level * 4);
+ sb.Append(indent).Append(marker)
+ .Append(text.Replace("\n", Environment.NewLine + indent + new string(' ', marker.Length)));
+ }
+ else
+ {
+ sb.Append(text.Replace("\n", Environment.NewLine));
+ }
+ sb.AppendLine();
+ break;
+ }
+ case HTable { Rows.Count: > 0 } table:
+ foreach (var row in table.Rows)
+ sb.AppendJoin('\t', row.Cells.Select(c => Cell(c, notes))).AppendLine();
+ break;
+ }
+ }
}
private static void Blocks(List blocks, StringBuilder sb, List notes, ListNumbers numbers)
@@ -78,8 +129,11 @@ private static bool IsCode(HParagraph paragraph) =>
private static string Cell(HCell cell, List notes) =>
string.Join(" ", cell.Blocks.OfType().Select(p => Inlines(p.Inlines, notes).Replace('\n', ' ').Replace('\t', ' ')).Where(t => t.Length > 0));
- /// The text of inlines, lines separated by '\n' (the callers write the line ends).
- private static string Inlines(List inlines, List notes)
+ ///
+ /// The text of inlines, lines separated by '\n' (the callers write the line ends), without the white space at the
+ /// end unless is false.
+ ///
+ private static string Inlines(List inlines, List notes, bool trim = true)
{
var sb = new StringBuilder();
foreach (var inline in inlines)
@@ -119,7 +173,7 @@ private static string Inlines(List inlines, List notes)
}
}
}
- return sb.ToString().TrimEnd();
+ return trim ? sb.ToString().TrimEnd() : sb.ToString();
}
}
diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
index 1cd149dcf..b760b74c8 100644
--- a/src/Filee.Engines/Infrastructure/ComplexScripts.cs
+++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
@@ -500,7 +500,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" => name.Equals("content.xml", StringComparison.OrdinalIgnoreCase),
+ "odt" or "ods" or "odp" or "udf" => 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),
// EPUB, HTMLZ, TXTZ, ...: the chapters.
diff --git a/src/Filee.Engines/Office/Sheets/NumberFormatter.cs b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
index f96b733e0..2cbc8521a 100644
--- a/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
+++ b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
@@ -9,8 +9,86 @@ namespace Filee.Engines.Office.Sheets;
/// Formats cell values with Excel number format codes; parsed formats are cached per instance.
internal sealed class NumberFormatter(bool date1904 = false)
{
- /// Built-in number formats (ECMA-376 18.8.30); 14 uses the ISO date order most locales read.
- public static readonly IReadOnlyDictionary BuiltInFormats = new Dictionary
+ /// The built-in format Excel shows as the PC's short date (#1315).
+ private const int ShortDateId = 14;
+
+ /// The short date where the PC's can't be written as an Excel format: ISO order, which most locales read.
+ private const string IsoDate = "yyyy-mm-dd";
+
+ ///
+ /// Built-in number format (ECMA-376 18.8.30), or null for an id without one. 14 is the PC's
+ /// short date, as Excel shows it: 11/8/2026 in the US, 2026/11/8 in China, 08.11.2026 in Germany.
+ ///
+ public static string? BuiltIn(int id) => id == ShortDateId ? ShortDate(CultureInfo.CurrentCulture) : BuiltInFormats.GetValueOrDefault(id);
+
+ ///
+ /// The short date pattern of as an Excel format code ("M/d/yyyy" → "m/d/yyyy"), or
+ /// for a calendar other than the Gregorian one or a pattern with more than day, month and year.
+ ///
+ internal static string ShortDate(CultureInfo culture)
+ {
+ var format = culture.DateTimeFormat;
+ if (format.Calendar is not GregorianCalendar)
+ return IsoDate;
+ var pattern = format.ShortDatePattern;
+ var code = new System.Text.StringBuilder();
+ for (var i = 0; i < pattern.Length;)
+ {
+ var c = pattern[i];
+ var run = 1;
+ while (i + run < pattern.Length && pattern[i + run] == c)
+ run++;
+ switch (c)
+ {
+ case 'd' when run <= 2:
+ code.Append('d', run);
+ break;
+ case 'M' when run <= 2:
+ code.Append('m', run);
+ break;
+ case 'y':
+ code.Append('y', run <= 2 ? 2 : 4);
+ break;
+ case '/':
+ Literal(code, format.DateSeparator);
+ break;
+ case '\'' or '"':
+ {
+ var end = pattern.IndexOf(c, i + 1);
+ if (end < 0)
+ return IsoDate;
+ Literal(code, pattern[(i + 1)..end]);
+ i = end + 1;
+ continue;
+ }
+ case '\\' when i + 1 < pattern.Length:
+ Literal(code, pattern[i + 1].ToString());
+ i += 2;
+ continue;
+ default:
+ if (char.IsLetter(c))
+ return IsoDate; // an era, a day or month name: not a short date Excel would show
+ Literal(code, new string(c, run));
+ break;
+ }
+ i += run;
+ }
+ return code.ToString();
+
+ // Characters other than day, month and year are escaped, except the separators Excel's own codes write bare.
+ static void Literal(System.Text.StringBuilder code, string text)
+ {
+ foreach (var c in text)
+ {
+ if (c is not ('/' or '-' or ' '))
+ code.Append('\\');
+ code.Append(c);
+ }
+ }
+ }
+
+ /// Built-in number formats (ECMA-376 18.8.30) but 14, the PC's short date ( ).
+ private static readonly Dictionary BuiltInFormats = new()
{
[0] = "General",
[1] = "0",
@@ -22,7 +100,6 @@ internal sealed class NumberFormatter(bool date1904 = false)
[11] = "0.00E+00",
[12] = "# ?/?",
[13] = "# ??/??",
- [14] = "yyyy-mm-dd",
[15] = "d-mmm-yy",
[16] = "d-mmm",
[17] = "mmm-yy",
diff --git a/src/Filee.Engines/Office/Sheets/XlsReader.cs b/src/Filee.Engines/Office/Sheets/XlsReader.cs
index 21dd0a466..4a85ae17c 100644
--- a/src/Filee.Engines/Office/Sheets/XlsReader.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsReader.cs
@@ -175,10 +175,10 @@ private static Worksheet ReadSheet(IExcelDataReader reader, NumberFormatter form
break;
}
- // Built-in formats the XLSX reader knows (dates in ISO order) look the same from XLS; ExcelDataReader's
+ // Built-in formats the XLSX reader knows (14 is the PC's short date) look the same from XLS; ExcelDataReader's
// string is used for the workbook's own formats and localized built-ins.
var index = reader.GetNumberFormatIndex(column);
- var format = NumberFormatter.BuiltInFormats.TryGetValue(index, out var builtIn) ? builtIn : reader.GetNumberFormatString(column);
+ var format = NumberFormatter.BuiltIn(index) ?? reader.GetNumberFormatString(column);
return new SheetCell(formatter.Format(number, format), style, IsNumber: true)
{
Value = number,
diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
index a7a502de1..fab1cc8e4 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxReader.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
@@ -326,7 +326,7 @@ private void ReadStyles(XDocument? xml, Workbook book)
DiagonalDown = border.Down,
};
var formatId = Index(xf, "numFmtId");
- _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? NumberFormatter.BuiltInFormats.GetValueOrDefault(formatId, "General")));
+ _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? NumberFormatter.BuiltIn(formatId) ?? "General"));
}
foreach (var dxf in root.Element(S + "dxfs")?.Elements(S + "dxf") ?? [])
diff --git a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs
index 964827dfa..da0902919 100644
--- a/src/Filee.Engines/Typesetting/FileeRendererConverter.cs
+++ b/src/Filee.Engines/Typesetting/FileeRendererConverter.cs
@@ -56,7 +56,7 @@ public sealed partial class FileeRendererConverter : IConverter, ICapabilityChec
[
"hwpx", "hwp", "docx", "docm", "dotx", "dotm", "doc", "dot", "wps", "odt", "rtf", "txt", "md", "html", "mhtml",
"epub", "kepub", "mobi", "azw3", "azw", "prc", "fb2", "htmlz", "txtz", "chm", "pdb", "pml", "tcr", "rb", "snb", "oeb",
- "ipynb", "opml", "textile", "mediawiki", "rst", "org", "dbk", "csv", "tsv", "ofd",
+ "ipynb", "opml", "textile", "mediawiki", "rst", "org", "dbk", "csv", "tsv", "ofd", "udf",
];
///
diff --git a/src/Filee.Engines/Typesetting/PageComposer.cs b/src/Filee.Engines/Typesetting/PageComposer.cs
index 07e07c439..6cd8bf80e 100644
--- a/src/Filee.Engines/Typesetting/PageComposer.cs
+++ b/src/Filee.Engines/Typesetting/PageComposer.cs
@@ -28,7 +28,8 @@
// the reader keeps in a text box placed for rhwp, goes with its equation instead (ParagraphLayout.Equations.cs).
//
// - Tables (TableLayout): rows bound by spanning cells move to a page together, header rows repeat, and a table splits
-// by its page break mode.
+// by its page break mode. A Word floating table (HTable.Float) is placed as a floating object instead, against the
+// paragraph after it or the page, and the text after it goes around it (see Float).
// - Columns: a section's newspaper columns, with their gap and separator line; what doesn't fit in a column goes on in
// the next, and after the last on the next page. Columns change without a new page where the model says (Word's
// continuous section break, 한글's 다단 설정 나누기); the columns before are balanced then, so they end at about the
@@ -488,6 +489,8 @@ private void Body(List blocks)
{
var tableBox = next as TableBox ?? Tables.Layout(table, ColumnWidth);
next = null;
+ if (holder is null && table.Float is { } anchor && Float(table, anchor, tableBox, blocks, i, ref next))
+ continue;
PlaceTable(table, tableBox, holder, holder is null ? TableLayout.Follower(blocks, i) : null);
holder = null;
continue;
@@ -614,8 +617,9 @@ private void PlaceTable(HTable table, TableBox box, HParagraph? holder, HParagra
// paragraph's text right under it, without the space before.
_skipSpaceBefore = true;
}
- // A table of another format has the outer margin the HWPX writer gives it: 5 mm below unless it is tight.
- var margin = table.OuterMargin ?? (composer._styles is not null && !table.Tight ? new HInsets(0, 0, 0, 1417) : default);
+ // A table of another format has the outer margin the HWPX writer gives it: 5 mm below unless it is tight. A
+ // Word table (sized by Word's rules) has none: Word puts the next paragraph right under it.
+ var margin = table.OuterMargin ?? (composer._styles is not null && !table.Tight && table.Sizing is null ? new HInsets(0, 0, 0, 1417) : default);
_y += (table.VerticalOffset + margin.Top) / 100f;
// Filee's rows are not 한글's unless the table is as high as 한글's (its line for it, else its stored size);
// else the stored places hold again on 한글's next page.
@@ -1096,6 +1100,56 @@ private List Anchor(HParagraph paragraph, float top, FuncA Word floating table laid out, placed as a floating object.
+ private sealed class FloatingTable(TableBox box) : HObject
+ {
+ public TableBox Box { get; } = box;
+ }
+
+ ///
+ /// Places a Word floating table where its anchor puts it: down from the top of the paragraph after it (laid out
+ /// ahead into , so it keeps its list number), never above the text before it, or against
+ /// the page. Text after it goes around it (as around a picture wrapped square). One that moves with the text and
+ /// would run past the column's bottom goes to the next column with its paragraph. False for a table taller than a
+ /// column, which stays in the flow (split by its rows).
+ ///
+ private bool Float(HTable table, HAnchor anchor, TableBox box, List blocks, int index, ref object? next)
+ {
+ var (width, height) = (box.Width, box.Height);
+ if (height > ColumnHeight + Epsilon || width <= 0)
+ return false;
+ var withText = anchor.VerticalRelativeTo == "PARA";
+ HParagraph? paragraph = null;
+ ParagraphBox? following = null;
+ if (index + 1 < blocks.Count && blocks[index + 1] is HParagraph after && !TableLayout.HoldsTable(blocks, index + 1))
+ {
+ paragraph = composer.Resolve(after, index + 2 < blocks.Count ? blocks[index + 2] : null);
+ following = Layout(paragraph, ColumnWidth);
+ next = following;
+ }
+ SKRect area;
+ while (true)
+ {
+ var top = _y + (_columnEmpty || following is null ? 0 : following.SpaceBefore);
+ area = FloatingObjects.Place(anchor, width, height, Frame(top, paragraph));
+ if (!withText)
+ break;
+ var y = Math.Max(_y, top + anchor.VerticalOffset / 100f);
+ area = new SKRect(area.Left, y, area.Right, y + height);
+ if (_columnEmpty || area.Bottom <= Bottom + Epsilon)
+ break;
+ NextColumn();
+ _inStep = false;
+ }
+ Current.Objects.Add(FloatingObjects.Placed(new FloatingTable(box) { OuterMargin = table.FloatDistance }, anchor, area, _objects++));
+ for (; _numberedChecked < _numbered.Count; _numberedChecked++)
+ {
+ if (!_notesPlaced.Contains(_numbered[_numberedChecked]))
+ AddNote(_numbered[_numberedChecked]);
+ }
+ return true;
+ }
+
/// Draws a page's floating objects, behind or in front of its text, lower z-order first.
private void DrawObjects(Page page)
{
@@ -1104,7 +1158,10 @@ private void DrawObjects(Page page)
foreach (var item in page.Objects.OrderBy(o => o.Order).ThenBy(o => o.Sequence))
{
var layer = new PageContent(page.Content.Width, page.Content.Height);
- FloatingObjects.Draw(layer, item.Object, item.Area, (blocks, width) => Tables.Stack(blocks, width));
+ if (item.Object is FloatingTable table)
+ TableLayout.Draw(layer, table.Box.Rows, item.Area.Left, item.Area.Top);
+ else
+ FloatingObjects.Draw(layer, item.Object, item.Area, (blocks, width) => Tables.Stack(blocks, width));
page.Content.Add(layer, item.Behind);
}
}
diff --git a/src/Filee.Engines/Typesetting/ParagraphLayout.cs b/src/Filee.Engines/Typesetting/ParagraphLayout.cs
index 1a748ef2b..6b6e2f69c 100644
--- a/src/Filee.Engines/Typesetting/ParagraphLayout.cs
+++ b/src/Filee.Engines/Typesetting/ParagraphLayout.cs
@@ -1169,7 +1169,7 @@ private LineBox Place(ParagraphText source, LineIndex ranges, int start, int end
var (height, baseline, textHeight) = stored is var (segment, _)
? ((segment.VerticalSize + segment.Spacing) / 100f, segment.Baseline / 100f, segment.TextHeight / 100f)
- : LineHeight(parts, settings, mark);
+ : LineHeight(parts, settings, mark, source);
var bookmarks = ranges.Bookmarks(start, end, text.Length).Select(b => (lineLeft + offset, b.Name)).ToList();
return new LineBox
{
@@ -1234,12 +1234,14 @@ private void Decorate(Part part, float x0, float x1, List fills, Lis
}
/// The line's pitch, the distance from its top to the baseline and the height of its text.
- private (float Height, float Baseline, float TextHeight) LineHeight(List parts, Settings settings, TextStyle mark)
+ private (float Height, float Baseline, float TextHeight) LineHeight(List parts, Settings settings, TextStyle mark, ParagraphText source)
{
var rule = settings.LineHeight;
var fromFont = settings.FontLineHeight || rule.Rule == HLineHeightRule.Multiple;
float objectAscent = 0, objectDescent = 0, textAscent = 0, textDescent = 0;
- bool anyText = false, anyObject = false;
+ // Word's multiple spaces text and equations, not pictures: their extent apart.
+ float mathAscent = 0, mathDescent = 0;
+ bool anyText = false, anyObject = false, anyMath = false;
foreach (var part in parts)
{
if (part.Item.Kind == ItemKind.Object)
@@ -1248,6 +1250,12 @@ private void Decorate(Part part, float x0, float x1, List fills, Lis
objectAscent = Math.Max(objectAscent, part.Size.Height);
objectDescent = Math.Max(objectDescent, part.Size.Depth);
anyObject = true;
+ if (source.Objects.GetValueOrDefault(part.Start) is HEquation)
+ {
+ mathAscent = Math.Max(mathAscent, part.Size.Height);
+ mathDescent = Math.Max(mathDescent, part.Size.Depth);
+ anyMath = true;
+ }
continue;
}
if (part.Item.Kind != ItemKind.Text)
@@ -1272,12 +1280,21 @@ private void Decorate(Part part, float x0, float x1, List fills, Lis
// 한글's percentage adds its share of the text's size, not of an object's height: a line holding a 60 pt
// picture at 160 % with 10 pt text is 66 pt high, as 한글 stores such lines.
HLineHeightRule.Percent => textHeight + (fontAscent + fontDescent) * (rule.Value - 100) / 100f,
+ // Word's multiple spaces the line's text and equations; a picture taller than them adds its height unspaced: a
+ // picture on a 1.5 line with 12 pt text is its height and half the text's line, not 1.5 times the picture (as
+ // Word's own PDFs have such lines). A line of pictures only adds the paragraph mark's share, as 한글's does.
+ HLineHeightRule.Multiple when anyObject && (anyText || anyMath) => Spaced(Math.Max(textAscent, mathAscent), Math.Max(textDescent, mathDescent)),
+ HLineHeightRule.Multiple when anyObject => textHeight + (fontAscent + fontDescent) * (rule.Value - 240) / 240f,
HLineHeightRule.Multiple => textHeight * rule.Value / 240f,
HLineHeightRule.Exact => value,
HLineHeightRule.AtLeast => Math.Max(value, textHeight),
_ => textHeight + value,
};
return (Math.Max(0, height), ascent, textHeight);
+
+ // The text's extent spaced by the multiple, with what the pictures reach beyond it.
+ float Spaced(float textUp, float textDown) =>
+ (textUp + textDown) * rule.Value / 240f + Math.Max(0, ascent - textUp) + Math.Max(0, descent - textDown);
}
/// Ascent and descent of a style: 한글's share of the size, or the font's own metrics.
diff --git a/src/Filee.Engines/Uyap/UyapReader.cs b/src/Filee.Engines/Uyap/UyapReader.cs
new file mode 100644
index 000000000..97098f4dd
--- /dev/null
+++ b/src/Filee.Engines/Uyap/UyapReader.cs
@@ -0,0 +1,613 @@
+// UYAP documents (.udf, #1338): the files of the UYAP Document Editor (UYAP Doküman Editörü), which Turkish courts,
+// lawyers and citizens write petitions and decisions in. Read into the document model with no external engine, so the
+// Filee renderer turns them into PDF and the writers into DOCX, ODT, HWPX, TXT and the rest.
+//
+// A UYAP document is a ZIP package with one part, content.xml (format_id 1.x), written by the editor's Java text
+// component:
+//
+//
+//
+//
+//
+//
+//
+//
+//
+//
+//
+//
+// The text lives once, in the CDATA block; every run names its stretch of it by offset and length (UTF-16 units, as
+// Java counts). Lengths are points; sizes are points; colours are Java ARGB integers; alignment is Swing's (0 left,
+// 1 centre, 2 right, 3 justified). A run takes what it doesn't say from its paragraph, then from the style the
+// elements name (their resolver, "hvl-default": Times New Roman 12 pt); Java's logical fonts (Dialog, Serif, ...)
+// become the fonts Java draws them with on Windows. Text is drawn without kerning, as Java draws it.
+//
+// Lines are as high as Java makes them (FontMetrics: the ascent rounded up, then descent and leading rounded up
+// together), for the fonts UYAP documents use, as an "at least" height: a 12 pt Calibri line is 15 pt, as in the PDF the
+// editor prints, so pages break where they break there. Swing's default tab stops are every 72 pt.
+//
+// ".udf" also names Universal Disk Format disc images. Which one a file is, is told by its content (IsUyap): a ZIP
+// whose content.xml has a root. A disc image given to a document route is refused with
+// error.udf_not_uyap, which points to Extract; the archive engine unpacks it as the disc it is (ArchiveExtractor).
+//
+// The package is read within DocumentLimits (Documents/DocumentPackage: part sizes counted while unpacking, the
+// inflate ratio, no DTD, depth and element limits); pictures are Base64 in the XML, decoded up to MaxPictureBytes each
+// and MaxPictures in all, and left out when their header claims more pixels than the limits allow. Tables nested past
+// Nesting.MaxDepth become plain paragraphs.
+
+using System.Globalization;
+using System.Xml;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Engines.Documents;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Uyap;
+
+/// Reads UYAP documents (.udf) into the document model.
+internal sealed class UyapReader
+{
+ /// The format id of UYAP documents.
+ public const string Format = "udf";
+
+ /// The refusal of a .udf that is not a UYAP document (a disc image, most likely).
+ public const string NotUyapKey = "error.udf_not_uyap";
+
+ private const string ContentPart = "content.xml";
+
+ /// Largest picture decoded; bigger ones are left out.
+ internal const int MaxPictureBytes = 32 * 1024 * 1024;
+
+ /// Pictures written per document; further ones are left out.
+ internal const int MaxPictures = 2_000;
+
+ /// Swing's tab stops when a paragraph sets none: every 72 pt.
+ private const int DefaultTabStop = 7200;
+
+ ///
+ /// Ascent, descent and line gap (hhea, in em) of the fonts UYAP documents use, for Java's line height; regular and
+ /// bold share them. A font not listed takes the font's own single line height.
+ ///
+ private static readonly Dictionary JavaMetrics = new(StringComparer.OrdinalIgnoreCase)
+ {
+ ["Times New Roman"] = (0.8911, 0.2163, 0.0425),
+ ["Calibri"] = (0.75, 0.25, 0.2207),
+ ["Arial"] = (0.9053, 0.2119, 0.0327),
+ ["Courier New"] = (0.8325, 0.3003, 0),
+ ["Tahoma"] = (1.0005, 0.2065, 0),
+ ["Verdana"] = (1.0054, 0.21, 0),
+ ["Cambria"] = (0.9502, 0.2222, 0),
+ ["Georgia"] = (0.917, 0.2192, 0),
+ ["Segoe UI"] = (1.0791, 0.251, 0),
+ };
+
+ private readonly string _text;
+ private readonly XElement? _baseStyle;
+ private readonly string _mediaFolder;
+ private readonly DocumentBudget _budget = new(DocumentLimits.Default);
+ private int _pictures;
+ private bool _breakBefore;
+
+ private UyapReader(string text, Dictionary styles, string? resolver, string mediaFolder)
+ {
+ _text = text;
+ _baseStyle = resolver is not null && styles.TryGetValue(resolver, out var style) ? style : null;
+ _mediaFolder = mediaFolder;
+ }
+
+ // ───────────────────────── Detection ─────────────────────────
+
+ ///
+ /// True when is a UYAP document: a ZIP package with a content.xml whose root is
+ /// <template>. A disc image (Universal Disk Format), another ZIP or a file that can't be read is not.
+ ///
+ public static bool IsUyap(string path)
+ {
+ try
+ {
+ if (!IsZip(path))
+ return false;
+ using var package = DocumentPackage.Open(path);
+ if (Content(package) is not { } entry)
+ return false;
+ using var stream = package.Open(entry);
+ using var reader = XmlReader.Create(stream, new XmlReaderSettings
+ {
+ DtdProcessing = DtdProcessing.Prohibit,
+ XmlResolver = null,
+ IgnoreComments = true,
+ IgnoreProcessingInstructions = true,
+ CheckCharacters = false,
+ });
+ return reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "template";
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or XmlException
+ or ConversionRefusedException or NotSupportedException)
+ {
+ return false;
+ }
+ }
+
+ /// True when the file starts like a ZIP package (a disc image starts with its zeroed system area).
+ internal static bool IsZip(string path)
+ {
+ using var stream = File.OpenRead(path);
+ Span head = stackalloc byte[4];
+ return stream.ReadAtLeast(head, 4, throwOnEndOfStream: false) == 4 && head is [0x50, 0x4B, 0x03, 0x04];
+ }
+
+ private static System.IO.Compression.ZipArchiveEntry? Content(DocumentPackage package) =>
+ package.GetEntry(ContentPart)
+ ?? package.Entries.FirstOrDefault(e => e.FullName.Equals(ContentPart, StringComparison.OrdinalIgnoreCase));
+
+ private static ConversionRefusedException NotUyap() => new(NotUyapKey);
+
+ // ───────────────────────── Document ─────────────────────────
+
+ /// Reads the UYAP document at ; pictures go into .
+ public static HDocument Read(string path, string mediaFolder)
+ {
+ if (!IsZip(path))
+ throw NotUyap();
+ XDocument xml;
+ using (var package = DocumentPackage.Open(path, notAPackage: NotUyap))
+ {
+ var entry = Content(package) ?? throw NotUyap();
+ using var stream = package.Open(entry);
+ try
+ {
+ // Java writes whatever the text holds into the CDATA block, control characters too.
+ xml = SafeXml.Load(stream, package.Limits.Xml(0, preserveWhitespace: true) with { CheckCharacters = false },
+ message => DocumentLimits.Exceeded($"{ContentPart}: {message}"));
+ }
+ catch (XmlException ex)
+ {
+ throw new InvalidDataException($"The {ContentPart} of the UYAP document is not well-formed XML ({ex.Message}). It may be damaged.", ex);
+ }
+ }
+ var root = xml.Root;
+ if (root is null || root.Name.LocalName != "template")
+ throw NotUyap();
+ return Nesting.OnLargeStack(() => Build(root, mediaFolder));
+ }
+
+ private static HDocument Build(XElement root, string mediaFolder)
+ {
+ var text = Child(root, "content")?.Value ?? "";
+ var styles = new Dictionary(StringComparer.Ordinal);
+ foreach (var style in Children(Child(root, "styles"), "style"))
+ {
+ if (Attr(style, "name") is { Length: > 0 } name)
+ styles.TryAdd(name, style);
+ }
+ var elements = Child(root, "elements");
+ var reader = new UyapReader(text, styles, Attr(elements, "resolver") ?? "hvl-default", mediaFolder);
+
+ var section = new HSection { Page = Page(Child(Child(root, "properties"), "pageFormat")) };
+ if (elements is not null)
+ reader.Blocks(elements, section.Blocks, section, depth: 0);
+ // A file without paragraph elements: its text, a paragraph per line.
+ if (section.Blocks.Count == 0 && text.Length > 0)
+ {
+ var format = reader.CharFormat(null, null);
+ foreach (var line in text.Split('\n'))
+ {
+ reader._budget.Paragraph();
+ var paragraph = new HParagraph { Format = reader.ParaFormat(null, [format]), MarkFormat = format };
+ reader.AddText(paragraph, line, format, last: true);
+ section.Blocks.Add(paragraph);
+ }
+ }
+ var document = new HDocument { DefaultTabStop = DefaultTabStop };
+ document.Sections.Add(section);
+ return document;
+ }
+
+ ///
+ /// The page: A4 (UYAP's mediaSizeName 1, and what the editor uses for others Filee hasn't seen), turned for
+ /// Java's landscape orientations (0 and 2); margins and the header and footer distances in points.
+ ///
+ private static HPage Page(XElement? format)
+ {
+ int width = 59528, height = 84189;
+ if (Number(format, "paperOrientation") is 0 or 2)
+ (width, height) = (height, width);
+ int Margin(string name, double fallback) => HwpxUnits.FromPoints(Math.Clamp(Number(format, name) ?? fallback, 0, 1000));
+ var left = Margin("leftMargin", 42.525);
+ var right = Margin("rightMargin", 42.525);
+ var top = Margin("topMargin", 42.525);
+ var bottom = Margin("bottomMargin", 42.525);
+ var header = Math.Min(top, Margin("headerFOffset", 20));
+ var footer = Math.Min(bottom, Margin("footerFOffset", 20));
+ // The text keeps at least a fifth of the paper.
+ if (left + right > width * 4 / 5)
+ left = right = width / 10;
+ if (top + bottom > height * 4 / 5)
+ top = bottom = header = footer = height / 10;
+ return new HPage(width, height, left, right, header, footer, top - header, bottom - footer, 0);
+ }
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ private void Blocks(XElement container, List output, HSection? section, int depth)
+ {
+ foreach (var element in container.Elements())
+ {
+ switch (element.Name.LocalName)
+ {
+ case "paragraph":
+ output.Add(Paragraph(element));
+ break;
+ case "table":
+ Table(element, output, depth);
+ break;
+ case "page-break" or "pageBreak":
+ _breakBefore = true;
+ break;
+ case "header" or "footer" when section is not null:
+ {
+ var part = new HHeaderFooter(HPageType.Both);
+ var breakBefore = _breakBefore;
+ Blocks(element, part.Blocks, null, depth);
+ _breakBefore = breakBefore;
+ if (part.Blocks.Count > 0)
+ (element.Name.LocalName == "header" ? section.Headers : section.Footers).Add(part);
+ break;
+ }
+ }
+ }
+ }
+
+ private HParagraph Paragraph(XElement element)
+ {
+ _budget.Paragraph();
+ var paragraph = new HParagraph { PageBreakBefore = _breakBefore };
+ _breakBefore = false;
+ var formats = new List();
+ HCharFormat? mark = null;
+ var runs = element.Elements().ToList();
+ for (var i = 0; i < runs.Count; i++)
+ {
+ var run = runs[i];
+ switch (run.Name.LocalName)
+ {
+ case "image":
+ Image(run, paragraph);
+ break;
+ case "page-break" or "pageBreak":
+ if (paragraph.Inlines.Count == 0)
+ paragraph.PageBreakBefore = true;
+ else
+ _breakBefore = true;
+ break;
+ case "field" when FieldKind(run) is { } kind:
+ {
+ var format = CharFormat(run, element);
+ formats.Add(format);
+ paragraph.Inlines.Add(new HField(kind, format));
+ break;
+ }
+ default:
+ if (run.Attribute("startOffset") is not null)
+ {
+ var format = CharFormat(run, element);
+ formats.Add(format);
+ mark = format;
+ AddText(paragraph, Slice(run), format, last: i == runs.Count - 1);
+ }
+ break;
+ }
+ }
+ mark ??= CharFormat(null, element);
+ if (formats.Count == 0)
+ formats.Add(mark.Value);
+ paragraph.MarkFormat = mark.Value;
+ paragraph.Format = ParaFormat(element, formats);
+ return paragraph;
+ }
+
+ /// The stretch of the text a run names, cut to the text.
+ private string Slice(XElement run)
+ {
+ var start = (int)Math.Clamp(Number(run, "startOffset") ?? 0, 0, _text.Length);
+ var length = (int)Math.Clamp(Number(run, "length") ?? 0, 0, _text.Length - start);
+ return _text.Substring(start, length);
+ }
+
+ /// Text with its tabs; the newline that ends the paragraph goes, one inside it breaks the line.
+ private void AddText(HParagraph paragraph, string text, HCharFormat format, bool last)
+ {
+ if (last && text.EndsWith('\n'))
+ text = text[..^1];
+ var start = 0;
+ for (var i = 0; i <= text.Length; i++)
+ {
+ var c = i < text.Length ? text[i] : '\0';
+ if (i < text.Length && !char.IsControl(c))
+ continue;
+ if (i > start)
+ paragraph.Inlines.Add(new HText(text[start..i], format));
+ start = i + 1;
+ if (c == '\t')
+ paragraph.Inlines.Add(new HTab(format));
+ else if (c is '\n' or '\v' && i < text.Length)
+ paragraph.Inlines.Add(new HLineBreak(format));
+ }
+ }
+
+ private static HFieldKind? FieldKind(XElement field)
+ {
+ var name = string.Join(' ', field.Attributes().Where(a => a.Name.LocalName is "fieldName" or "type" or "name").Select(a => a.Value)).ToLowerInvariant();
+ if (!name.Contains("page") && !name.Contains("sayfa"))
+ return null;
+ return name.Contains("count") || name.Contains("total") || name.Contains("toplam") ? HFieldKind.TotalPages : HFieldKind.PageNumber;
+ }
+
+ // ───────────────────────── Tables ─────────────────────────
+
+ private void Table(XElement element, List output, int depth)
+ {
+ var rows = Children(element, "row").ToList();
+ if (depth >= Nesting.MaxDepth)
+ {
+ // Nested past what the writers follow: the cells' content as paragraphs.
+ foreach (var cell in rows.SelectMany(row => Children(row, "cell")))
+ Blocks(cell, output, null, depth);
+ return;
+ }
+ _budget.Object();
+ var limits = _budget.Limits;
+ var table = new HTable { PageBreakBefore = _breakBefore };
+ _breakBefore = false;
+ var bordered = Attr(element, "border") is not { } border || !border.Contains("none", StringComparison.OrdinalIgnoreCase);
+ table.Borders = bordered ? HBorders.Grid : HBorders.Empty;
+ foreach (var row in rows)
+ {
+ var model = new HRow();
+ foreach (var cell in Children(row, "cell"))
+ {
+ var modelCell = new HCell
+ {
+ ColSpan = (int)Math.Clamp(Number(cell, "colspan") ?? Number(cell, "colSpan") ?? Number(cell, "columnSpan") ?? 1, 1, limits.MaxTableColumns),
+ RowSpan = (int)Math.Clamp(Number(cell, "rowspan") ?? Number(cell, "rowSpan") ?? 1, 1, 100_000),
+ Fill = Color(cell, "bgColor") ?? Color(cell, "background"),
+ VerticalAlign = (Attr(cell, "verticalAlignment") ?? Attr(cell, "vAlign"))?.ToLowerInvariant() switch
+ {
+ "1" or "center" or "middle" => HVerticalAlign.Center,
+ "2" or "bottom" => HVerticalAlign.Bottom,
+ _ => HVerticalAlign.Top,
+ },
+ };
+ if (!bordered)
+ modelCell.Borders = HBorders.Empty;
+ Blocks(cell, modelCell.Blocks, null, depth + 1);
+ if (modelCell.Blocks.Count == 0)
+ modelCell.Blocks.Add(new HParagraph { MarkFormat = CharFormat(null, null) });
+ model.Cells.Add(modelCell);
+ }
+ if (model.Cells.Count > 0)
+ table.Rows.Add(model);
+ }
+ if (table.Rows.Count == 0)
+ return;
+ var columns = table.Rows.Max(r => r.Cells.Sum(c => c.ColSpan));
+ columns = Math.Clamp(Math.Max(columns, (int)Math.Clamp(Number(element, "columnCount") ?? 0, 0, limits.MaxTableColumns)), 1, limits.MaxTableColumns);
+ table.ColumnCount = columns;
+ // columnSpans: the columns' widths, taken as shares of the text width.
+ var spans = (Attr(element, "columnSpans") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Take(columns)
+ .Select(s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) && v > 0 && double.IsFinite(v) ? v : 0)
+ .ToArray();
+ if (spans.Length == columns && spans.Sum() is > 0 and var total)
+ table.RelativeWidths = [.. spans.Select(s => s / total)];
+ output.Add(table);
+ }
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ private void Image(XElement element, HParagraph paragraph)
+ {
+ var data = Attr(element, "imageData") ?? Attr(element, "data");
+ if (string.IsNullOrWhiteSpace(data) || _pictures >= MaxPictures || data.Length / 4L * 3 > MaxPictureBytes)
+ return;
+ byte[] bytes;
+ try
+ {
+ bytes = Convert.FromBase64String(data.Trim());
+ }
+ catch (FormatException)
+ {
+ return;
+ }
+ var extension = bytes switch
+ {
+ [0x89, (byte)'P', (byte)'N', (byte)'G', ..] => ".png",
+ [0xFF, 0xD8, ..] => ".jpg",
+ [(byte)'G', (byte)'I', (byte)'F', ..] => ".gif",
+ [(byte)'B', (byte)'M', ..] => ".bmp",
+ _ => null,
+ };
+ if (extension is null)
+ return;
+ _budget.Object();
+ Directory.CreateDirectory(_mediaFolder);
+ var file = Path.Combine(_mediaFolder, $"udf-image{++_pictures:0000}{extension}");
+ File.WriteAllBytes(file, bytes);
+ if (PictureSize.Read(file) is not { } size || (long)size.Width * size.Height > _budget.Limits.MaxPicturePixels)
+ {
+ File.Delete(file);
+ return;
+ }
+ var image = new HImage(file);
+ if (Number(element, "width") is > 0 and < 10_000 and var width && Number(element, "height") is > 0 and < 10_000 and var height)
+ {
+ image.Width = HwpxUnits.FromPoints(width);
+ image.Height = HwpxUnits.FromPoints(height);
+ }
+ paragraph.Inlines.Add(image);
+ }
+
+ // ───────────────────────── Formats ─────────────────────────
+
+ ///
+ /// What a run says about , else its paragraph, else the elements' style. The editor's own
+ /// "default" style (Dialog, dark grey) is its window's, not the document's: the editor prints black Times New Roman.
+ ///
+ private string? Lookup(XElement? run, XElement? paragraph, string name) =>
+ Attr(run, name) ?? Attr(paragraph, name) ?? Attr(_baseStyle, name);
+
+ private HCharFormat CharFormat(XElement? run, XElement? paragraph)
+ {
+ bool Flag(string name) => string.Equals(Lookup(run, paragraph, name), "true", StringComparison.OrdinalIgnoreCase);
+ var size = double.TryParse(Lookup(run, paragraph, "size"), NumberStyles.Float, CultureInfo.InvariantCulture, out var points)
+ && points is > 0 and < 1000 ? points : 12;
+ var shade = Color(run, "background") ?? Color(paragraph, "background");
+ return new HCharFormat(
+ Bold: Flag("bold"),
+ Italic: Flag("italic"),
+ Underline: Flag("underline"),
+ Strike: Flag("strikethrough"),
+ Superscript: Flag("superscript") ? true : null,
+ Subscript: Flag("subscript") ? true : null,
+ Size: (int)Math.Round(size * 100),
+ Font: FontName(Lookup(run, paragraph, "family")),
+ Color: ColorOf(Lookup(run, paragraph, "foreground")) ?? "#000000",
+ Shade: shade is "#FFFFFF" ? null : shade,
+ // Java draws text without the font's kerning.
+ Layout: NoKerning);
+ }
+
+ private static readonly HCharLayout NoKerning = new(Kerning: false);
+
+ /// A font family, with Java's logical fonts as Java draws them on Windows.
+ private static string FontName(string? family) => family?.Trim() switch
+ {
+ null or "" or "Serif" or "serif" => "Times New Roman",
+ "Dialog" or "SansSerif" or "sansserif" or "dialog" => "Arial",
+ "DialogInput" or "Monospaced" or "monospaced" => "Courier New",
+ var name => name,
+ };
+
+ private HParaFormat ParaFormat(XElement? element, IReadOnlyList formats)
+ {
+ double Points(string name, double min, double max) => Math.Clamp(Number(element, name) ?? 0, min, max);
+ var spacing = Math.Clamp(Number(element, "LineSpacing") ?? 0, 0, 10);
+ HLineSpacing lineSpacing;
+ HLineHeight lineHeight;
+ if (JavaLineHeight(formats) is { } height)
+ {
+ var value = (int)Math.Round(height * (1 + spacing));
+ lineSpacing = new HLineSpacing(HLineSpacingKind.AtLeast, value);
+ lineHeight = new HLineHeight(HLineHeightRule.AtLeast, value);
+ }
+ else
+ {
+ lineSpacing = new HLineSpacing(HLineSpacingKind.Percent, (int)Math.Round(120 * (1 + spacing)));
+ lineHeight = new HLineHeight(HLineHeightRule.Multiple, (int)Math.Round(240 * (1 + spacing)));
+ }
+ return new HParaFormat(
+ Align: (int?)Number(element, "Alignment") switch
+ {
+ 1 => HAlign.Center,
+ 2 => HAlign.Right,
+ 3 => HAlign.Justify,
+ _ => HAlign.Left,
+ },
+ Left: HwpxUnits.FromPoints(Points("LeftIndent", -1000, 1000)),
+ Right: HwpxUnits.FromPoints(Points("RightIndent", -1000, 1000)),
+ FirstLine: HwpxUnits.FromPoints(Points("FirstLineIndent", -1000, 1000)),
+ Before: HwpxUnits.FromPoints(Points("SpaceAbove", 0, 1000)),
+ After: HwpxUnits.FromPoints(Points("SpaceBelow", 0, 1000)),
+ LineSpacing: lineSpacing,
+ KeepWithNext: false,
+ KeepLines: false,
+ WidowOrphan: false,
+ Tabs: Tabs(Attr(element, "TabSet")),
+ Layout: new HParaLayout(LineHeight: lineHeight, SnapToGrid: false));
+ }
+
+ ///
+ /// The height Java gives a line of these runs (HWPUNIT): the tallest of ascent rounded up plus descent and leading
+ /// rounded up, as FontMetrics.getHeight does; null when a run's font has no metrics here.
+ ///
+ private static int? JavaLineHeight(IReadOnlyList formats)
+ {
+ var tallest = 0;
+ foreach (var format in formats)
+ {
+ if (format.Font is not { } font || !JavaMetrics.TryGetValue(font, out var metrics))
+ return null;
+ var size = (format.Size ?? 1200) / 100.0;
+ var ascent = (int)(0.95 + metrics.Ascent * size);
+ tallest = Math.Max(tallest, ascent + (int)(0.95 + (metrics.Descent + metrics.Gap) * size));
+ }
+ return tallest > 0 ? tallest * 100 : null;
+ }
+
+ ///
+ /// Swing's TabSet ("position:alignment:leader", comma separated; positions in points from the left indent).
+ /// Alignment 1 right, 2 centre, 4 decimal; leader 1 dots, 2 hyphens, 3 underline, 4 thick line, 5 equals.
+ ///
+ private static List? Tabs(string? tabSet)
+ {
+ if (string.IsNullOrWhiteSpace(tabSet))
+ return null;
+ var stops = new List();
+ foreach (var item in tabSet.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Take(64))
+ {
+ var parts = item.Split(':');
+ if (!double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var position) || position is <= 0 or > 2000)
+ continue;
+ var kind = parts.Length > 1 ? parts[1] switch
+ {
+ "1" => HTabKind.Right,
+ "2" => HTabKind.Center,
+ "4" => HTabKind.Decimal,
+ _ => HTabKind.Left,
+ } : HTabKind.Left;
+ var leader = parts.Length > 2 ? parts[2] switch
+ {
+ "1" => "DOT",
+ "2" => "DASH",
+ "3" or "4" or "5" => "SOLID",
+ _ => "NONE",
+ } : "NONE";
+ stops.Add(new HTabStop(HwpxUnits.FromPoints(position), kind, leader));
+ }
+ return stops.Count == 0 ? null : [.. stops.OrderBy(s => s.Position)];
+ }
+
+ /// A Java colour (signed ARGB integer, or #RRGGBB) as "#RRGGBB"; null when absent or fully transparent.
+ internal static string? ColorOf(string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return null;
+ value = value.Trim();
+ if (value.StartsWith('#') && value.Length == 7 && int.TryParse(value.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var hex))
+ return $"#{hex:X6}";
+ if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
+ return null;
+ var argb = unchecked((uint)number);
+ // A value without alpha bits is an RGB colour; one with them but none of alpha is transparent.
+ if (number is >= 0 and <= 0xFFFFFF)
+ return $"#{argb:X6}";
+ return (argb >> 24) == 0 ? null : $"#{argb & 0xFFFFFF:X6}";
+ }
+
+ private static string? Color(XElement? element, string name) => ColorOf(Attr(element, name));
+
+ // ───────────────────────── XML ─────────────────────────
+
+ private static XElement? Child(XElement? parent, string name) => parent?.Elements().FirstOrDefault(e => e.Name.LocalName == name);
+
+ private static IEnumerable Children(XElement? parent, string name) =>
+ parent?.Elements().Where(e => e.Name.LocalName == name) ?? [];
+
+ private static string? Attr(XElement? element, string name) => element?.Attribute(name)?.Value;
+
+ private static double? Number(XElement? element, string name) =>
+ double.TryParse(Attr(element, name), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && double.IsFinite(value) ? value : null;
+}
diff --git a/tests/Filee.Core.Tests/FormatFieldsTests.cs b/tests/Filee.Core.Tests/FormatFieldsTests.cs
index 3cc6e8466..e85b59999 100644
--- a/tests/Filee.Core.Tests/FormatFieldsTests.cs
+++ b/tests/Filee.Core.Tests/FormatFieldsTests.cs
@@ -144,7 +144,7 @@ public void Grade_counts_match_the_published_table()
new Dictionary
{
[FormatGrade.Everyday] = 19,
- [FormatGrade.General] = 99,
+ [FormatGrade.General] = 100,
[FormatGrade.Specialist] = 131,
[FormatGrade.Legacy] = 52,
},
diff --git a/tests/Filee.Core.Tests/UyapSettingsTests.cs b/tests/Filee.Core.Tests/UyapSettingsTests.cs
new file mode 100644
index 000000000..c82422f8b
--- /dev/null
+++ b/tests/Filee.Core.Tests/UyapSettingsTests.cs
@@ -0,0 +1,31 @@
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class UyapSettingsTests
+{
+ [Fact]
+ public void A_uyap_document_has_a_donut_in_a_new_library() =>
+ Assert.NotNull(ProfileSelector.Select(BuiltInData.CreateProfiles(), ["dilekce.udf"]));
+
+ [Fact]
+ public void Version_103_donuts_learn_udf_without_taking_custom_claims()
+ {
+ var presets = BuiltInData.CreatePresets();
+ var profiles = BuiltInData.CreateProfiles();
+ var id = ProfileSelector.Select(profiles, ["dilekce.udf"])!.Id;
+ var donut = profiles.Single(p => p.Id == id).Extensions;
+ donut.Remove("udf");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(102, presets, profiles));
+ Assert.Contains("udf", donut);
+ Assert.False(SettingsMigrations.ApplyToLibrary(102, presets, profiles));
+
+ donut.Remove("udf");
+ profiles.Insert(0, new ToolbarProfile { Id = "my-court", Name = "Court", Extensions = ["UDF"] });
+ Assert.False(SettingsMigrations.ApplyToLibrary(102, presets, profiles));
+ Assert.DoesNotContain("udf", donut); // the user's own donut has it
+ }
+}
diff --git a/tests/Filee.Engines.Tests/CultureScope.cs b/tests/Filee.Engines.Tests/CultureScope.cs
new file mode 100644
index 000000000..19c728a88
--- /dev/null
+++ b/tests/Filee.Engines.Tests/CultureScope.cs
@@ -0,0 +1,15 @@
+// A regional format for one test: what follows the PC's (Excel's built-in short date, number format 14) comes out the
+// same on every machine. The culture flows with the test's async code and is set back when the scope ends.
+
+using System.Globalization;
+
+namespace Filee.Engines.Tests;
+
+internal sealed class CultureScope : IDisposable
+{
+ private readonly CultureInfo _before = CultureInfo.CurrentCulture;
+
+ public CultureScope(string name) => CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(name);
+
+ public void Dispose() => CultureInfo.CurrentCulture = _before;
+}
diff --git a/tests/Filee.Engines.Tests/FileeRendererConverterTests.cs b/tests/Filee.Engines.Tests/FileeRendererConverterTests.cs
index 18b123d97..e146e2c07 100644
--- a/tests/Filee.Engines.Tests/FileeRendererConverterTests.cs
+++ b/tests/Filee.Engines.Tests/FileeRendererConverterTests.cs
@@ -98,6 +98,7 @@ public void On_documents_go_to_pdf_through_it_and_sheets_and_pdf_keep_their_rout
[InlineData("csv", "layout")] // no page setup for sheet print: one table, no longer the HWPX writer and rhwp
[InlineData("tsv", "layout")]
[InlineData("ofd", "layout")]
+ [InlineData("udf", "layout")]
[InlineData("pptx", "layout")]
[InlineData("potm", "layout")]
[InlineData("xlsx", "sheet-print")]
@@ -111,6 +112,15 @@ public void On_each_kind_of_document_goes_to_pdf_in_one_step(string from, string
Assert.Equal(engine == "layout", step.Checked);
}
+ [Fact]
+ public void On_rtf_to_txt_reads_the_rtf_not_the_text_of_its_pdf()
+ {
+ // #1204: through the PDF the text came out wrapped, without its indentation and its empty lines.
+ Assert.Equal(["hwp-text"], Engines(WithLibreOffice(installed: false).Plan("rtf", "txt")));
+ Assert.Equal(["libreoffice"], Engines(WithLibreOffice().Plan("rtf", "txt")));
+ Assert.Equal(["libreoffice"], Engines(WithLibreOffice(documents: true).Plan("rtf", "txt")));
+ }
+
[Fact]
public void On_slide_decks_go_to_pdf_and_pictures_through_it()
{
diff --git a/tests/Filee.Engines.Tests/OfficeTests.cs b/tests/Filee.Engines.Tests/OfficeTests.cs
index f8878944a..ac4f0917c 100644
--- a/tests/Filee.Engines.Tests/OfficeTests.cs
+++ b/tests/Filee.Engines.Tests/OfficeTests.cs
@@ -61,13 +61,14 @@ internal static string SalesWorkbook(string folder)
[Fact]
public void Xlsx_values_and_styles_are_read_like_excel_shows_them()
{
+ using var culture = new CultureScope("en-US"); // the date's format 14 is the PC's short date
var book = XlsxReader.Read(SalesWorkbook(fx.NewFolder()));
Assert.Equal(["매출", "메모", "넓은 표"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
var sales = book.Sheets[0];
Assert.Equal("1,350,000원", sales.Get(2, 1)!.Text);
Assert.True(sales.Get(2, 1)!.IsNumber);
- Assert.Equal("2026-10-01", sales.Get(2, 2)!.Text);
+ Assert.Equal("10/1/2026", sales.Get(2, 2)!.Text);
Assert.Equal("12.8%", sales.Get(2, 3)!.Text);
Assert.Equal("2,220,000원", sales.Get(4, 1)!.Text); // cached formula result
Assert.Equal("TRUE", sales.Get(4, 2)!.Text);
@@ -96,6 +97,7 @@ public void Xlsx_values_and_styles_are_read_like_excel_shows_them()
[Fact]
public async Task Xlsx_to_csv_writes_one_file_per_sheet_for_excel()
{
+ using var culture = new CultureScope("en-US"); // the date's format 14 is the PC's short date
var outputs = await ConvertAsync(SalesWorkbook(fx.NewFolder()), "csv");
Assert.Equal(["매출보고_매출.csv", "매출보고_메모.csv", "매출보고_넓은 표.csv"], outputs.Select(Path.GetFileName));
@@ -104,8 +106,8 @@ public async Task Xlsx_to_csv_writes_one_file_per_sheet_for_excel()
Assert.Equal(
"지점별 매출,,,\r\n" +
"지점,매출,일자,성장률\r\n" +
- "서울 강남,\"1,350,000원\",2026-10-01,12.8%\r\n" +
- "부산 서면,\"870,000원\",2026-10-02,9.0%\r\n" +
+ "서울 강남,\"1,350,000원\",10/1/2026,12.8%\r\n" +
+ "부산 서면,\"870,000원\",10/2/2026,9.0%\r\n" +
"합계,\"2,220,000원\",TRUE,\"메모, \"\"따옴표\"\"\"\r\n",
Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3));
}
diff --git a/tests/Filee.Engines.Tests/ReportedCasesTests.cs b/tests/Filee.Engines.Tests/ReportedCasesTests.cs
index 0a0eee6c7..f79b55b61 100644
--- a/tests/Filee.Engines.Tests/ReportedCasesTests.cs
+++ b/tests/Filee.Engines.Tests/ReportedCasesTests.cs
@@ -673,6 +673,93 @@ public async Task Issue1313_a_frame_sits_where_its_page_position_puts_it()
Assert.True(check.Y > code[0].Y && check.Y < 720 + 98, $"second line at {check.Y}");
}
+ // ───────────────────────── Word: floating tables and paragraph spacing (#1194, #1152) ─────────────────────────
+
+ /// A one-cell table (Table Grid) 2 inches wide holding , with in its properties.
+ private static string OneCellTable(string text, string position = "") =>
+ $"{position} " +
+ $" {P(R(text))} ";
+
+ private static SKPoint Where(PageContent page, string text) => Runs(page).First(r => r.Text.Contains(text, StringComparison.Ordinal)).Positions[0];
+
+ [Fact]
+ public async Task Issue1194_text_after_a_floating_table_goes_around_it()
+ {
+ // The report's figure captions are floating tables (w:tblpPr), placed from the top of the paragraph after them;
+ // the empty paragraphs after them sat beside the caption in Word and under it in Filee, a page longer in all.
+ const string Right = "";
+ var floating = Single(await DocxAsync(Docx(P(R("Before")) + OneCellTable("Cell", Right) + P(R("Beside")) + P(R("Next")))));
+ var flowing = Single(await DocxAsync(Docx(P(R("Before")) + OneCellTable("Cell") + P(R("Beside")))));
+
+ var (before, cell, beside, next) = (Where(floating, "Before"), Where(floating, "Cell"), Where(floating, "Beside"), Where(floating, "Next"));
+ // The table at the right margin, 10 pt below the top of the paragraph after it.
+ Assert.Equal(RightMargin - 144 + 5.4f, cell.X, 1f);
+ var pitch = LineHeight(RepositoryFonts.Latin, 10);
+ Assert.Equal(before.Y + pitch + 10, cell.Y, 1f);
+ // The paragraphs after it on their own lines at the left margin, beside it.
+ Assert.Equal(LeftMargin, beside.X, 0.5f);
+ Assert.Equal(before.Y + pitch, beside.Y, 0.5f);
+ Assert.Equal(beside.Y + pitch, next.Y, 0.5f);
+ // In the flow the paragraph goes under the table.
+ Assert.True(Where(flowing, "Beside").Y > Where(flowing, "Cell").Y + pitch - 0.5f);
+ }
+
+ [Fact]
+ public async Task Issue1194_a_table_placed_on_the_page_leaves_the_text_where_it_is()
+ {
+ // A floating table 5 inches down the page (vertAnchor page) takes no room in the text above it.
+ const string Page = "";
+ var page = Single(await DocxAsync(Docx(P(R("Before")) + OneCellTable("Cell", Page) + P(R("After")))));
+
+ var pitch = LineHeight(RepositoryFonts.Latin, 10);
+ Assert.Equal(Where(page, "Before").Y + pitch, Where(page, "After").Y, 0.5f);
+ Assert.InRange(Where(page, "Cell").Y, 360, 360 + pitch + 1);
+ }
+
+ [Fact]
+ public async Task Issue1194_a_word_table_has_no_space_below_it()
+ {
+ // The next paragraph sits right under a Word table; the 5 mm the HWPX writer leaves under one is not Word's.
+ var page = Single(await DocxAsync(Docx(OneCellTable("Cell") + P(R("After")))));
+
+ var pitch = LineHeight(RepositoryFonts.Latin, 10);
+ Assert.InRange(Where(page, "After").Y - Where(page, "Cell").Y, pitch, pitch + 1.5f);
+ }
+
+ [Fact]
+ public async Task Issue1194_line_spacing_does_not_stretch_a_picture()
+ {
+ // A 72 pt picture in a paragraph with 1.5 lines: Word adds half the paragraph's text line, not half the picture.
+ async Task After(string line)
+ {
+ var docx = Docx("");
+ var id = docx.Image(HalfRedHalfBlue());
+ docx.Paragraph(P(InlinePicture(id, 914400, 914400), $"") + P(R("After")));
+ return Where(Single(await DocxAsync(docx)), "After").Y;
+ }
+
+ var single = await After("240");
+ var half = LineHeight(RepositoryFonts.Latin, 10) / 2;
+ Assert.Equal(single + half, await After("360"), 0.5f);
+ }
+
+ [Fact]
+ public async Task Issue1152_the_larger_of_the_spaces_between_two_paragraphs_counts()
+ {
+ // Word keeps the larger of a heading's 6 pt after and the next heading's 12 pt before between them (12 pt, not 18),
+ // unless its settings turn its HTML paragraph spacing off.
+ const string Spacing = "";
+ var body = P(R("First"), Spacing) + P(R("Second"), Spacing);
+ var larger = Single(await DocxAsync(Docx(body)));
+ var both = Docx(body);
+ both.Settings = " ";
+ var summed = Single(await DocxAsync(both));
+
+ var single = LineHeight(RepositoryFonts.Latin, 10);
+ Assert.Equal(single + 12, Pitch(larger), 0.1f);
+ Assert.Equal(single + 18, Pitch(summed), 0.1f);
+ }
+
// ───────────────────────── Word: right-to-left documents (#202, #216, #620) ─────────────────────────
[Fact]
diff --git a/tests/Filee.Engines.Tests/RtfToTextTests.cs b/tests/Filee.Engines.Tests/RtfToTextTests.cs
index 8578cb01c..bc8e93b9f 100644
--- a/tests/Filee.Engines.Tests/RtfToTextTests.cs
+++ b/tests/Filee.Engines.Tests/RtfToTextTests.cs
@@ -1,14 +1,19 @@
-// RTF → TXT through LibreOffice (#1204): code copied from an IDE (a colour run per token and an italic run here and
-// there) keeps its text, its indentation and its blank lines. The route itself is in LibreOfficeRouteTests.
+// RTF → TXT through LibreOffice and through Filee's own reader (#1204): code copied from an IDE (a colour run per token
+// and an italic run here and there) keeps its text, its indentation and its blank lines. The LibreOffice route is in
+// LibreOfficeRouteTests; with the Filee renderer on, in FileeRendererConverterTests.
using Filee.Core.Conversion;
using Filee.Core.Presets;
+using Filee.Core.Settings;
+using Filee.Engines.Hwp;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
namespace Filee.Engines.Tests;
public class RtfToTextTests(EngineFixture fx) : IClassFixture
{
- private const string IdeCode = """
+ internal const string IdeCode = """
{\rtf1\ansi\ansicpg1252\cocoartf2907
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fmodern\fcharset0 Courier;\f1\fmodern\fcharset0 Courier-Oblique;}
{\colortbl;\red255\green255\blue255;\red195\green122\blue88;\red175\green177\blue183;\red186\green102\blue173;
@@ -55,3 +60,139 @@ public async Task Code_copied_from_an_IDE_keeps_its_text()
Assert.Contains(" System.out.println(\"Java word is found \" + count);", lines); // the italic run
}
}
+
+/// RTF → TXT without LibreOffice or Pandoc: RtfReader's document, a line per paragraph.
+[Collection("EngineEnvironment")] // the Filee renderer is on, as in the app, so the route through a PDF is there to lose
+public sealed class RtfToBuiltInTextTests(EngineFixture fx) : IClassFixture, IDisposable
+{
+ // Plain code from TextEdit (Helvetica): a \tab, runs of spaces, an empty paragraph, a \line and a trailing space.
+ private const string PlainCode = """
+ {\rtf1\ansi\ansicpg1254\cocoartf2822{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+ \pard\tx560\tx1120\pardirnatural\partightenfactor0
+
+ \f0\fs24 \cf0 #include \
+ \
+ int main(void) \{\
+ int arr[3] = \{1, 2, 3\};\
+ \tab for (int i = 0; i < 3; i++) \{\
+ if (arr[i] > 1) printf("%d\\n", arr[i]);\
+ \}\
+ return x ** 2 # two spaces\
+ \}\par
+ first\line second \par
+ \pard\par
+ last\par
+ }
+ """;
+
+ public void Dispose()
+ {
+ EngineEnvironment.FileeRenderer = false;
+ fx.Catalog.Refresh();
+ }
+
+ private async Task ConvertAsync(string rtf)
+ {
+ EngineEnvironment.FileeRenderer = true;
+ var catalog = new ConverterCatalog(fx.Converters.Where(c => c.Id is not ("libreoffice" or "pandoc")))
+ {
+ Priority = new AppSettings().EnginePriority,
+ };
+ // Not the renderer's PDF and the PDF's text, which wrapped long lines and lost the indentation.
+ Assert.Equal(HwpTextConverter.EngineId, Assert.Single(catalog.CreatePlanner().Plan("rtf", "txt")!.Steps).Converter.Id);
+
+ var source = Path.Combine(fx.NewFolder(), "code.rtf");
+ await File.WriteAllTextAsync(source, rtf, TestContext.Current.CancellationToken);
+ var output = await MarkupTestKit.ConvertAsync(catalog, source, "txt");
+ return (await File.ReadAllTextAsync(output, TestContext.Current.CancellationToken)).TrimStart('').ReplaceLineEndings("\n");
+ }
+
+ [Fact]
+ public async Task Code_copied_from_an_ide_comes_out_line_for_line()
+ {
+ var text = await ConvertAsync(RtfToTextTests.IdeCode);
+
+ Assert.Equal("""
+ import java.io.BufferedReader;
+
+ class FileTask implements Runnable {
+ private String fileName;
+
+ public void run() {
+ int count = 0;
+ content.append(line).append("\n");
+ for (String word : line.split("\\W+")) {
+ count++;
+ }
+ System.out.println("Java word is found " + count);
+ }
+ }
+
+ """.ReplaceLineEndings("\n"), text);
+ }
+
+ [Fact]
+ public async Task Plain_code_keeps_its_tabs_spaces_empty_lines_and_line_breaks()
+ {
+ var text = await ConvertAsync(PlainCode);
+
+ string[] expected =
+ [
+ "#include ",
+ "", // the empty paragraph, and no empty line between the others
+ "int main(void) {",
+ " int arr[3] = {1, 2, 3};",
+ "\tfor (int i = 0; i < 3; i++) {", // \tab
+ " if (arr[i] > 1) printf(\"%d\\n\", arr[i]);",
+ " }",
+ " return x ** 2 # two spaces",
+ "}",
+ "first", // \line
+ "second ",
+ "",
+ "last",
+ "",
+ ];
+ Assert.Equal(string.Join("\n", expected), text);
+ }
+
+ [Fact]
+ public void Lists_and_tables_take_a_line_each()
+ {
+ var document = new HDocument();
+ var section = new HSection();
+ document.Sections.Add(section);
+ var numbering = new HNumbering { Levels = { new HNumberingLevel("DIGIT", "^1.", 1, Bullet: false) } };
+ section.Blocks.Add(Paragraph("Steps:"));
+ var one = Paragraph("one");
+ one.List = new HListRef(numbering, 0, Numbered: true);
+ var two = Paragraph("two");
+ two.List = new HListRef(numbering, 0, Numbered: true);
+ section.Blocks.AddRange([one, two]);
+ var table = new HTable();
+ foreach (var (left, right) in new[] { ("a", "b"), ("c", "d") })
+ {
+ var row = new HRow();
+ row.Cells.AddRange([Cell(left), Cell(right)]);
+ table.Rows.Add(row);
+ }
+ section.Blocks.Add(table);
+ section.Blocks.Add(Paragraph(" end"));
+
+ Assert.Equal("Steps:\n1. one\n2. two\na\tb\nc\td\n end\n", PlainTextWriter.WriteLines(document).ReplaceLineEndings("\n"));
+
+ static HParagraph Paragraph(string text)
+ {
+ var paragraph = new HParagraph();
+ paragraph.Inlines.Add(new HText(text, default));
+ return paragraph;
+ }
+
+ static HCell Cell(string text)
+ {
+ var cell = new HCell();
+ cell.Blocks.Add(Paragraph(text));
+ return cell;
+ }
+ }
+}
diff --git a/tests/Filee.Engines.Tests/SheetPrintTests.cs b/tests/Filee.Engines.Tests/SheetPrintTests.cs
index d34bd9597..edf0e6a64 100644
--- a/tests/Filee.Engines.Tests/SheetPrintTests.cs
+++ b/tests/Filee.Engines.Tests/SheetPrintTests.cs
@@ -983,4 +983,43 @@ public void Header_codes_are_parsed_without_trusting_them()
Assert.Contains(sections.Right, p => p.Text.Contains('&'));
Assert.True(HeaderFooterText.Parse(new string('&', 100_000)).Center.Sum(p => p.Text.Length) <= 4096);
}
+
+ // ───────────────────────── Number formats ─────────────────────────
+
+ [Theory]
+ [InlineData("en-US", "11/8/2026")]
+ [InlineData("zh-CN", "2026/11/8")]
+ [InlineData("de-DE", "08.11.2026")]
+ public void Issue1315_the_built_in_short_date_prints_as_the_pcs_short_date(string culture, string expected)
+ {
+ // Format 14 is the short date of the PC's regional format in Excel. It printed as 2026-11-08, one character
+ // more than Excel shows in China or the US, so the reporter's dates came out as ####.
+ using var scope = new CultureScope(culture);
+ var book = new XlsxBuilder();
+ book.Sheet("Order", Row(1, Number("B1", 46334, XlsxBuilder.Date)),
+ before: " ", after: A4);
+
+ var page = Assert.Single(Print(Save(book, "order.xlsx")));
+
+ Assert.Equal(expected, page);
+ }
+
+ [Theory]
+ [InlineData("M/d/yyyy", "/", "m/d/yyyy")]
+ [InlineData("yyyy/M/d", "/", "yyyy/m/d")]
+ [InlineData("M/d/yyyy", ".", "m\\.d\\.yyyy")] // "/" is the date separator
+ [InlineData("dd.MM.yy", "/", "dd\\.mm\\.yy")]
+ [InlineData("yyyy. MM. dd.", "/", "yyyy\\. mm\\. dd\\.")]
+ [InlineData("d.MM.yyyy 'г'.", "/", "d\\.mm\\.yyyy \\г\\.")]
+ [InlineData("dddd, MMMM d, yyyy", "/", "yyyy-mm-dd")] // names: not a short date Excel would show
+ [InlineData("gg yyyy/MM/dd", "/", "yyyy-mm-dd")] // an era
+ public void Short_date_patterns_become_excel_format_codes(string pattern, string separator, string expected)
+ {
+ var culture = (System.Globalization.CultureInfo)System.Globalization.CultureInfo.InvariantCulture.Clone();
+ culture.DateTimeFormat.ShortDatePattern = pattern;
+ culture.DateTimeFormat.DateSeparator = separator;
+
+ Assert.Equal(expected, NumberFormatter.ShortDate(culture));
+ Assert.Equal("yyyy-mm-dd", NumberFormatter.ShortDate(System.Globalization.CultureInfo.GetCultureInfo("th-TH"))); // Buddhist years
+ }
}
diff --git a/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs b/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs
index ae7e2b458..7890c5f7d 100644
--- a/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs
+++ b/tests/Filee.Engines.Tests/SpreadsheetFormatTests.cs
@@ -70,6 +70,7 @@ private static string SalesXls(string folder, int filler = 0)
[Fact]
public void Xls_values_formats_and_layout_are_read_like_excel_shows_them()
{
+ using var culture = new CultureScope("en-US"); // the date's format 14 is the PC's short date
var book = XlsReader.Read(SalesXls(fx.NewFolder()));
Assert.Equal(["매출", "메모"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
@@ -77,7 +78,7 @@ public void Xls_values_formats_and_layout_are_read_like_excel_shows_them()
var won = sales.Get(2, 1)!;
Assert.Equal(("1,350,000원", true, 1350000.0, "#,##0\"원\""), (won.Text, won.IsNumber, won.Value, won.NumberFormat));
var date = sales.Get(2, 2)!;
- Assert.Equal(("2026-10-01", October1, "yyyy-mm-dd"), (date.Text, date.Value, date.NumberFormat));
+ Assert.Equal(("10/1/2026", October1, "m/d/yyyy"), (date.Text, date.Value, date.NumberFormat));
Assert.Equal(("12.8%", "0.0%"), (sales.Get(2, 3)!.Text, sales.Get(2, 3)!.NumberFormat));
Assert.Equal("2,220,000원", sales.Get(4, 1)!.Text);
Assert.Equal(("TRUE", true, 1.0), (sales.Get(4, 2)!.Text, sales.Get(4, 2)!.IsBoolean, sales.Get(4, 2)!.Value));
@@ -128,6 +129,7 @@ public void Xlsx_saved_with_an_xls_name_is_read_as_xlsx()
[Fact]
public async Task Xls_to_xlsx_keeps_numbers_dates_and_their_formats()
{
+ using var culture = new CultureScope("en-US"); // the date's format 14 is the PC's short date
var dir = fx.NewFolder();
var xls = SalesXls(dir, filler: 400);
Assert.True(new FileInfo(xls).Length > 8192);
@@ -155,7 +157,7 @@ string FormatCode(string reference)
Assert.Null(cells["B3"].Attribute("t"));
Assert.Equal("1350000", (string)cells["B3"].Element(S + "v")!);
Assert.Equal("#,##0\"원\"", FormatCode("B3"));
- Assert.Equal(("46296", "yyyy-mm-dd"), ((string)cells["C3"].Element(S + "v")!, FormatCode("C3")));
+ Assert.Equal(("46296", "m/d/yyyy"), ((string)cells["C3"].Element(S + "v")!, FormatCode("C3")));
Assert.Equal("b", (string?)cells["C5"].Attribute("t"));
}
@@ -510,10 +512,11 @@ public async Task Tsv_to_xlsx_and_back_keeps_every_value()
[Fact]
public async Task Workbook_to_tsv_writes_one_file_per_sheet()
{
+ using var culture = new CultureScope("en-US"); // the date's format 14 is the PC's short date
var outputs = await ConvertAsync(OfficeTests.SalesWorkbook(fx.NewFolder()), "tsv");
Assert.Equal(["매출보고_매출.tsv", "매출보고_메모.tsv", "매출보고_넓은 표.tsv"], outputs.Select(Path.GetFileName));
- Assert.StartsWith("지점별 매출\t\t\t\r\n지점\t매출\t일자\t성장률\r\n서울 강남\t1,350,000원\t2026-10-01\t12.8%\r\n",
+ Assert.StartsWith("지점별 매출\t\t\t\r\n지점\t매출\t일자\t성장률\r\n서울 강남\t1,350,000원\t10/1/2026\t12.8%\r\n",
(await File.ReadAllTextAsync(outputs[0], TestContext.Current.CancellationToken)).TrimStart(''));
}
diff --git a/tests/Filee.Engines.Tests/UyapTests.cs b/tests/Filee.Engines.Tests/UyapTests.cs
new file mode 100644
index 000000000..dc65f7ef6
--- /dev/null
+++ b/tests/Filee.Engines.Tests/UyapTests.cs
@@ -0,0 +1,338 @@
+// UYAP documents (.udf, #1338) → the document model, PDF and DOCX with the built-in reader, and the other ".udf": a
+// Universal Disk Format disc image, which still unpacks with Extract and is refused by the document routes with the
+// reason. The documents are written here the way the UYAP Document Editor writes them (one content.xml in a ZIP, the
+// text in a CDATA block, runs by offset); the disc is written with DiscUtils' UDF builder.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Text;
+using DiscUtils.Udf;
+using DocumentFormat.OpenXml.Packaging;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Archives;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Uyap;
+using ImageMagick;
+using PigDocument = UglyToad.PdfPig.PdfDocument;
+using W = DocumentFormat.OpenXml.Wordprocessing;
+
+namespace Filee.Engines.Tests;
+
+[Collection("EngineEnvironment")] // the Filee renderer switch is process-wide
+public sealed class UyapTests(EngineFixture fx) : IClassFixture, IDisposable
+{
+ public void Dispose()
+ {
+ EngineEnvironment.FileeRenderer = false;
+ fx.Catalog.Refresh();
+ }
+
+ // ───────────────────────── Writing UYAP files ─────────────────────────
+
+ /// A paragraph of a UYAP file: its attributes and runs (text, run attributes).
+ private sealed record Para(string Attributes, params (string Text, string Attributes)[] Runs);
+
+ ///
+ /// Writes a UYAP document: the paragraphs' text joined into the CDATA block, each paragraph ended by "\n" in its
+ /// last run, runs pointing into it by offset. adds elements after them, with their text.
+ ///
+ private static string MakeUdf(string folder, string name, IEnumerable paragraphs, int orientation = 1,
+ Func? extraWithText = null)
+ {
+ var text = new StringBuilder();
+ var elements = new StringBuilder();
+ foreach (var paragraph in paragraphs)
+ elements.Append(Paragraph(text, paragraph));
+ if (extraWithText is not null)
+ elements.Append(extraWithText(text));
+ var xml = $"""
+
+
+
+
+
+ {elements}
+
+
+
+ """;
+ var path = Path.Combine(folder, name);
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ using var writer = new StreamWriter(zip.CreateEntry("content.xml").Open(), new UTF8Encoding(false));
+ writer.Write(xml);
+ return path;
+ }
+
+ /// A paragraph's XML, its text appended to .
+ private static string Paragraph(StringBuilder text, Para paragraph)
+ {
+ var xml = new StringBuilder($"");
+ for (var i = 0; i < paragraph.Runs.Length; i++)
+ {
+ var (run, attributes) = paragraph.Runs[i];
+ if (i == paragraph.Runs.Length - 1)
+ run += "\n";
+ xml.Append(CultureInfo.InvariantCulture, $" ");
+ text.Append(run);
+ }
+ return xml.Append(" ").ToString();
+ }
+
+ /// A petition laid out as UYAP lays one out: a centred bold title, a label with a tab, justified hanging items.
+ private static string MakePetition(string folder) => MakeUdf(folder, "petition.udf",
+ [
+ new("Alignment=\"1\"", ("Sample Court Office", "bold=\"true\" family=\"Calibri\" size=\"14\"")),
+ new("Alignment=\"3\"", ("FILE NO", "bold=\"true\" family=\"Calibri\""), ("\t: 2026/1", "family=\"Calibri\"")),
+ new("Alignment=\"3\" LeftIndent=\"47.0\" FirstLineIndent=\"-22.0\" TabSet=\"0.0:0:0\"",
+ ("1.\tThe first item of the request, written long enough to run over more than one line of the page so the hanging indent shows.", "family=\"Calibri\"")),
+ new("Alignment=\"2\" SpaceAbove=\"6\"", ("Signed ", "family=\"Calibri\" italic=\"true\""), ("Applicant", "family=\"Calibri\" underline=\"true\" foreground=\"-65536\"")),
+ new("Alignment=\"0\"", ("Default style text", "")),
+ ]);
+
+ // ───────────────────────── Reading ─────────────────────────
+
+ [Fact]
+ public void A_petition_reads_with_its_formats_page_and_tabs()
+ {
+ var folder = fx.NewFolder();
+ var document = UyapReader.Read(MakePetition(folder), Path.Combine(folder, "media"));
+
+ var section = Assert.Single(document.Sections);
+ // A4, 42.525 pt margins; the header distance (20 pt) is the top of the header area, the body starts at the margin.
+ Assert.Equal(new HPage(59528, 84189, 4252, 4252, 2000, 2000, 2252, 2252, 0), section.Page);
+ Assert.Equal(7200, document.DefaultTabStop);
+ var paragraphs = section.Blocks.Cast().ToList();
+ Assert.Equal(5, paragraphs.Count);
+
+ var title = paragraphs[0];
+ Assert.Equal(HAlign.Center, title.Format.Align);
+ var titleText = Assert.IsType(Assert.Single(title.Inlines));
+ Assert.Equal("Sample Court Office", titleText.Text); // the "\n" ending the paragraph is gone
+ Assert.True(titleText.Format.Bold);
+ Assert.Equal(1400, titleText.Format.Size);
+ Assert.Equal("Calibri", titleText.Format.Font);
+ Assert.False(titleText.Format.Layout?.Kerning); // Java draws without kerning
+ // Java's line height of 14 pt Calibri: ascent 10.5 → 11, descent and leading 6.59 → 7 (pt, ×100).
+ Assert.Equal(new HLineSpacing(HLineSpacingKind.AtLeast, 1800), title.Format.LineSpacing);
+
+ var label = paragraphs[1];
+ Assert.Equal(HAlign.Justify, label.Format.Align);
+ Assert.Collection(label.Inlines,
+ i => Assert.Equal("FILE NO", Assert.IsType(i).Text),
+ i => Assert.IsType(i),
+ i => Assert.Equal(": 2026/1", Assert.IsType(i).Text));
+ // 12 pt Calibri: 15 pt lines, as the editor prints them.
+ Assert.Equal(new HLineSpacing(HLineSpacingKind.AtLeast, 1500), label.Format.LineSpacing);
+
+ var item = paragraphs[2];
+ Assert.Equal(4700, item.Format.Left);
+ Assert.Equal(-2200, item.Format.FirstLine);
+ Assert.Null(item.Format.Tabs); // the stop at 0 is the hanging indent's own
+
+ var signature = paragraphs[3];
+ Assert.Equal(HAlign.Right, signature.Format.Align);
+ Assert.Equal(600, signature.Format.Before);
+ var signed = signature.Inlines.OfType().ToList();
+ Assert.True(signed[0].Format.Italic);
+ Assert.True(signed[1].Format.Underline);
+ Assert.Equal("#FF0000", signed[1].Format.Color);
+
+ // A run without attributes takes the elements' style (hvl-default), not the editor's grey Dialog "default".
+ var plain = Assert.IsType(Assert.Single(paragraphs[4].Inlines)).Format;
+ Assert.Equal("Times New Roman", plain.Font);
+ Assert.Equal(1200, plain.Size);
+ Assert.Equal("#000000", plain.Color);
+ Assert.False(plain.Bold);
+ }
+
+ [Fact]
+ public void Tables_pictures_page_breaks_and_landscape_pages_are_read()
+ {
+ var folder = fx.NewFolder();
+ var png = Convert.ToBase64String(File.ReadAllBytes(EngineFixture.MakeImage(folder, "logo.png", MagickFormat.Png, 60, 60)));
+ var path = MakeUdf(folder, "table.udf", [new("", ("Before the table", ""))], orientation: 0,
+ extraWithText: text =>
+ {
+ string Cell(string value) => "| " + Paragraph(text, new Para("", (value, ""))) + " | ";
+ var table = $"""{Cell("A1")}{Cell("B1")} {Cell("A2")}{Cell("B2")} """;
+ var picture = $""" """;
+ text.Append(" \n");
+ return table + " " + picture + Paragraph(text, new Para("", ("After the break", "")));
+ });
+
+ var document = UyapReader.Read(path, Path.Combine(folder, "media"));
+
+ var section = Assert.Single(document.Sections);
+ Assert.True(section.Page!.Landscape);
+ var table = Assert.IsType(section.Blocks[1]);
+ Assert.Equal(2, table.ColumnCount);
+ Assert.Equal([0.25, 0.75], table.RelativeWidths);
+ Assert.Equal(HBorders.Grid, table.Borders);
+ Assert.Equal(["A1", "B1", "A2", "B2"], table.Rows.SelectMany(r => r.Cells)
+ .Select(c => Assert.IsType(Assert.Single(Assert.IsType(Assert.Single(c.Blocks)).Inlines)).Text));
+ var picture = Assert.IsType(section.Blocks[2]);
+ Assert.True(picture.PageBreakBefore);
+ var image = Assert.IsType(Assert.Single(picture.Inlines));
+ Assert.Equal((4000, 2000), (image.Width, image.Height));
+ Assert.True(File.Exists(image.Path));
+ Assert.False(Assert.IsType(section.Blocks[3]).PageBreakBefore);
+ }
+
+ [Fact]
+ public void Runs_pointing_outside_the_text_and_a_file_without_elements_still_read()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "odd.udf");
+ using (var zip = ZipFile.Open(path, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(zip.CreateEntry("content.xml").Open()))
+ {
+ writer.Write("""
+
+ """);
+ }
+ var paragraph = Assert.IsType(Assert.Single(Assert.Single(UyapReader.Read(path, folder).Sections).Blocks));
+ Assert.Collection(paragraph.Inlines,
+ i => Assert.Equal("Line one", Assert.IsType(i).Text),
+ i => Assert.IsType(i),
+ i => Assert.Equal("Line two", Assert.IsType(i).Text));
+
+ var bare = Path.Combine(folder, "bare.udf");
+ using (var zip = ZipFile.Open(bare, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(zip.CreateEntry("content.xml").Open()))
+ writer.Write(" ");
+ var lines = Assert.Single(UyapReader.Read(bare, folder).Sections).Blocks.Cast()
+ .Select(p => string.Concat(p.Inlines.OfType().Select(t => t.Text))).ToList();
+ Assert.Equal(["First", "Second"], lines);
+ }
+
+ [Fact]
+ public void A_content_part_with_a_dtd_is_refused()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "dtd.udf");
+ using (var zip = ZipFile.Open(path, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(zip.CreateEntry("content.xml").Open()))
+ writer.Write("""]>&a; """);
+
+ Assert.Throws(() => UyapReader.Read(path, folder));
+ Assert.False(UyapReader.IsUyap(path));
+ }
+
+ // ───────────────────────── Telling the two .udf apart ─────────────────────────
+
+ [Fact]
+ public void Only_a_zip_with_a_template_content_part_is_a_uyap_document()
+ {
+ var folder = fx.NewFolder();
+ Assert.True(UyapReader.IsUyap(MakePetition(folder)));
+ Assert.False(UyapReader.IsUyap(MakeDisc(folder)));
+
+ var other = Path.Combine(folder, "other.udf");
+ using (var zip = ZipFile.Open(other, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(zip.CreateEntry("content.xml").Open()))
+ writer.Write("");
+ Assert.False(UyapReader.IsUyap(other));
+ var empty = Path.Combine(folder, "empty.udf");
+ File.WriteAllBytes(empty, []);
+ Assert.False(UyapReader.IsUyap(empty));
+ }
+
+ /// A UDF 2.01 disc image named .udf, holding readme.txt.
+ private static string MakeDisc(string folder)
+ {
+ var builder = new UdfBuilder { VolumeIdentifier = "DISC" };
+ builder.AddFile("readme.txt", Encoding.UTF8.GetBytes("on the disc"));
+ var path = Path.Combine(folder, "disc.udf");
+ builder.Build(path);
+ return path;
+ }
+
+ [Fact]
+ public void Udf_is_a_read_only_document_and_extract_takes_it_too()
+ {
+ var format = FormatRegistry.Detect("petition.udf");
+ Assert.Equal(UyapReader.Format, format?.Id);
+ Assert.Equal(FormatCategory.Document, format!.Category);
+ Assert.False(format.Writable);
+ Assert.Contains(UyapReader.Format, DocumentReaders.BuiltInFormats);
+
+ var planner = fx.Catalog.CreatePlanner();
+ Assert.Equal(["docx-writer"], planner.Plan("udf", "docx")!.Steps.Select(s => s.Converter.Id));
+ Assert.Equal(["archive"], planner.Plan("udf", FormatRegistry.Folder)!.Steps.Select(s => s.Converter.Id));
+ // Only Extract: a UYAP document is no archive to repack.
+ Assert.Null(planner.Plan("udf", "7z"));
+ }
+
+ [Fact]
+ public async Task A_udf_disc_image_unpacks_with_extract_and_is_refused_as_a_document()
+ {
+ var folder = fx.NewFolder();
+ var disc = MakeDisc(folder);
+
+ var extracted = await fx.ConvertAsync([disc], new Preset { TargetFormat = FormatRegistry.Folder });
+ Assert.True(extracted.State == JobState.Completed, string.Join("; ", extracted.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var output = Assert.Single(extracted.Outputs);
+ Assert.Equal("on the disc", await File.ReadAllTextAsync(Path.Combine(output, "readme.txt"), TestContext.Current.CancellationToken));
+
+ var refused = await fx.ConvertAsync([disc], new Preset { TargetFormat = "docx" });
+ Assert.Equal(UyapReader.NotUyapKey, Assert.Single(refused.Files).ErrorKey);
+ }
+
+ [Fact]
+ public async Task A_uyap_document_unpacks_with_extract_to_its_content_part()
+ {
+ var folder = fx.NewFolder();
+ var job = await fx.ConvertAsync([MakePetition(folder)], new Preset { TargetFormat = FormatRegistry.Folder });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ Assert.True(File.Exists(Path.Combine(Assert.Single(job.Outputs), "content.xml")));
+ }
+
+ // ───────────────────────── Converting ─────────────────────────
+
+ [Fact]
+ public async Task A_petition_becomes_a_pdf_with_the_filee_renderer()
+ {
+ EngineEnvironment.FileeRenderer = true;
+ fx.Catalog.Refresh();
+ var folder = fx.NewFolder();
+ Assert.Equal(["layout"], fx.Catalog.CreatePlanner().Plan("udf", "pdf")!.Steps.Select(s => s.Converter.Id));
+
+ var job = await fx.ConvertAsync([MakePetition(folder)], new Preset { TargetFormat = "pdf" });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ using var pdf = PigDocument.Open(job.Outputs.Single());
+ Assert.Equal(1, pdf.NumberOfPages);
+ var page = pdf.GetPage(1);
+ Assert.Equal(595, page.Width, 0);
+ var words = page.GetWords().ToList();
+ Assert.Contains(words, w => w.Text == "Sample");
+ Assert.Contains(words, w => w.Text == "Applicant");
+ // The title is centred: its middle on the middle of the text area.
+ var title = words.Where(w => w.Text is "Sample" or "Court" or "Office").ToList();
+ var middle = (title.Min(w => w.BoundingBox.Left) + title.Max(w => w.BoundingBox.Right)) / 2;
+ Assert.InRange(middle, 595.28 / 2 - 6, 595.28 / 2 + 6);
+ // The signature is right-aligned at the right margin.
+ Assert.InRange(words.Single(w => w.Text == "Applicant").BoundingBox.Right, 595.28 - 42.5 - 4, 595.28 - 42.5 + 1);
+ }
+
+ [Fact]
+ public async Task A_petition_becomes_a_docx_with_its_formatting()
+ {
+ var folder = fx.NewFolder();
+ var job = await fx.ConvertAsync([MakePetition(folder)], new Preset { TargetFormat = "docx" });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ using var docx = WordprocessingDocument.Open(job.Outputs.Single(), false);
+ var paragraphs = docx.MainDocumentPart!.Document!.Body!.Elements().ToList();
+ var title = paragraphs.First(p => p.InnerText == "Sample Court Office");
+ Assert.Equal(W.JustificationValues.Center, title.ParagraphProperties?.Justification?.Val?.Value);
+ Assert.NotNull(title.Descendants().FirstOrDefault());
+ Assert.Contains(paragraphs, p => p.InnerText.StartsWith("1.", StringComparison.Ordinal) && p.Descendants().Any());
+ var page = docx.MainDocumentPart.Document.Body.Descendants().First();
+ Assert.Equal(11906u, page.Width!.Value, 2u);
+ }
+}
|