diff --git a/.github/workflows/portable.yml b/.github/workflows/portable.yml
index 713ac57d9..9e69199aa 100644
--- a/.github/workflows/portable.yml
+++ b/.github/workflows/portable.yml
@@ -181,6 +181,10 @@ jobs:
if ($project -eq 'Filee.App.Tests') {
$testArguments += @('--blame-crash', '--blame-hang-timeout', '5m', '--logger', 'console;verbosity=normal')
}
+ # A native crash in the engine tests (Skia, HarfBuzz) names the test that was running and leaves a dump.
+ if ($project -eq 'Filee.Engines.Tests') {
+ $testArguments += @('--blame-crash')
+ }
if ($IsLinux) {
xvfb-run -a env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 dotnet @testArguments
} else {
diff --git a/README.md b/README.md
index d752e7e8d..162c4a78f 100644
--- a/README.md
+++ b/README.md
@@ -172,8 +172,8 @@ 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) 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² |
+| **Documents**: DOCX, DOCM, DOTX, DOC, DOT, ODT, EML, Outlook MSG; OFD (Chinese e-invoices, official documents), UYAP UDF (Turkish court documents) and XPS / OpenXPS read FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, ODT, HWPX, EPUB, TXT, HTML, PPTX and ODP slides; DOCX, HTML tables → XLSX, ODS, CSV; MSG → EML FODT, OTT² |
+| **Spreadsheets**: XLSX, XLSM, XLSB, XLS, XLT, ODS, CSV, TSV OTS, FODS, Numbers, ET² | PDF, XLSX, ODS, CSV, TSV, JSON, HWPX, HTML XLT, OTS² |
| **Presentations**: PPTX, PPTM, POTX, POTM, PPSX, PPT, ODP, OTP, FODP PowerPoint 95 PPT, Keynote² | PDF, PNG, JPG, ODP, DOCX, HWPX; PPT → PPTX OTP² |
| **HWP**: HWP, HWPX | PDF, PNG, DOCX, HWPX ↔ HWP, TXT, Markdown, HTML, PPTX and ODP slides |
| **Text**: TXT, LOG, script source (PY, PAC, BAT, COMMAND; read, never run), Arduino and Processing sketches (INO, PDE), Markdown, HTML; MHTML (saved web pages) read Jupyter, reStructuredText, Org, MediaWiki, DocBook, Textile, OPML LaTeX, AsciiDoc, Typst, man³ | UTF-8 TXT, PDF, DOCX, HWPX, EPUB, PPTX and ODP slides (a slide per heading) each other, PPTX and ODP slides³ |
@@ -181,7 +181,7 @@ To undo it, remove the entries in Windows Security → App & browser control →
| **Video**⁵: MP4, MOV, MKV, WEBM, AVI, WMV, FLV, MPEG, Video CD (DAT), TS, M2TS, 3GP, OGV, VOB, …; Wisenet WAVE / Nx Witness exports (NOV) read | MP4 (H.264, HEVC, AV1), WEBM, MOV, MKV, AVI, GIF, APNG, WEBP, MP3, M4A, 720p, split into parts; subtitle tracks kept (MKV, MP4, MOV, WebM); subtitles (SRT, ASS, WebVTT) |
| **Audio**⁵: MP3, M4A, AAC, WAV, FLAC, OGG, OPUS, WMA, AIFF, AMR, APE, WavPack, TTA, DSD (DSF, DFF), DTS, AC3, E-AC3, …; tracker modules (XM, IT, S3M) read | MP3, M4A (AAC, ALAC), M4R (iPhone ringtone), WAV, FLAC, OGG, OPUS, AAC, WavPack, TTA, W64, AC3, E-AC3 |
| **Subtitles**: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KRC, TTML, MicroDVD, SCC | each other as UTF-8 (Korean CP949 files read correctly) |
-| **Archives**: ZIP, ANSYS Workbench (WBPZ), 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, GZ, XZ, ISO, UDF, IMG, DMG, CAB, LHA, ARJ, ALZ, EGG, Garry's Mod addon (GMA), Valve pak (VPK), files packed into a Source map (BSP), …; JAR, NuGet (NUPKG), Android packages (APKS, XAPK, APKM, AAB), Adobe extensions (ZXP) read | extract, ZIP, 7Z, TAR, TAR.GZ, TAR.XZ, XZ, GMA; any files → one ZIP; folders → ZIP, ISO (Joliet or UDF 2.01), GMA |
+| **Archives**: ZIP, ANSYS Workbench (WBPZ), 7Z, RAR, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, TAR.ZST, GZ, XZ, ZST, ISO, UDF, IMG, DMG, CAB, LHA, ARJ, ALZ, EGG, Garry's Mod addon (GMA), Valve pak (VPK), files packed into a Source map (BSP), …; JAR, NuGet (NUPKG), Android packages (APKS, XAPK, APKM, AAB), Adobe extensions (ZXP) read | extract, ZIP, 7Z, TAR, TAR.GZ, TAR.XZ, XZ, GMA; any files → one ZIP; folders → ZIP, ISO (Joliet or UDF 2.01), GMA |
| **CAD**: DWG, DXF Gerber PCB layers (GBR, GTL, GBL, GTO, …) read; G-code of 3D printers and CNC machines (GCODE, GCO, NGC) read | PDF, SVG, PNG, DWG ↔ DXF; G-code → toolpath (from above or isometric) or the slicer's preview |
| **Fonts**: TTF, OTF, WOFF, WOFF2, EOT; FON (Windows bitmap fonts) read | each other; FON → one font per size |
| **Data**: JSON, JSON Lines, YAML, TOML, XML vCard, iCalendar | each other, CSV and XLSX (tables); vCard, iCalendar ↔ CSV |
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 6a1838b01..7969aedab 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -14,8 +14,8 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **HWP text** | built in | **HWP/HWPX → TXT, Markdown, HTML** with the [HWP](#hwp-reader) and [HWPX readers](#hwpx-reader) (pictures in a `_files` folder next to the Markdown, embedded in the HTML; see [HWP text, Markdown and HTML](#hwp-text-markdown-and-html)) |
| Text & Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT**; **TXT, LOG, CXLOG, PY, PAC, BAT, CMD, COMMAND, LUA, CSS, PS1, SQL, AHK, INI, RSC, C, H, CPP, CC, CXX, HPP, HH, HXX, CS, DART, HQL, DBML, JAVA, INO, PDE → UTF-8 TXT**, preserving source text without running scripts (and → PDF through the Filee renderer, → DOCX through the DOCX writer) |
| **Markup languages** | built in | **Jupyter notebooks (IPYNB), OPML, Textile, MediaWiki, reStructuredText, Org, DocBook 5 → Markdown, HTML, TXT and each other**; every document the built-in readers read → each of them; each → DOCX, ODT, HWPX, PDF through the document writers (see [Lightweight markup languages](#lightweight-markup-languages)) |
-| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |
-| **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)) |
+| Spreadsheets (ExcelDataReader for XLS) | built in (library) | **XLSX, XLSB, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV** (one CSV / TSV per sheet) |
+| **Spreadsheet printing** | built in | **XLSX (+ XLSM/XLTX), XLSB, XLS (+ XLT), ODS → PDF** printed the way Excel prints them: page setup, print areas and titles, scaling and fit to pages, page breaks, headers and footers (see [Spreadsheet printing](#spreadsheet-printing)) |
| 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, 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 |
@@ -32,7 +32,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Signed files | built in (System.Security.Cryptography.Pkcs) | **P7M → the signed file inside** (CMS / PKCS #7, CAdES: Italian e-invoices `*.xml.p7m`, signed PDFs `*.pdf.p7m`), then on from its format (P7M → PDF → JPG); the signature isn't checked |
| Data | built in (System.Text.Json, YamlDotNet, Tomlyn, System.Xml) | **JSON, JSON Lines, YAML, TOML, XML, CSV ↔ each other** (CSV for tables); **vCard, iCalendar ↔ CSV**; **property lists (.plist, XML and binary) → each of them and TXT**; FreeMASTER oscilloscope TXT → CSV; spreadsheets, contacts and events reach JSON / YAML / TOML / XML through CSV |
| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ, CHM, PDB, PML, TCR, RB, SNB, OEB → EPUB, AZW3, MOBI, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/AZW3/MOBI/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) |
-| **Drawings** | built in | **Visio VSDX, ODG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route |
+| **Drawings** | built in | **Visio VSDX, ODG, FODG → PDF, SVG, PNG** with the slide renderer (a page per drawing page; see [Drawings](#drawings-visio-odg)); **XPS, OpenXPS → PDF, SVG, PNG** with Filee's own XPS reader ([XPS reader](#xps-and-openxps-reader)); a binary `.vsd` and a drawing with what the readers don't draw yet (charts, OLE objects, 3D) keep LibreOffice's route |
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| G-code | built in | **G-code (3D printers, CNC machines) → PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, …: the toolpath from above or isometric, or the preview the slicer saved in the file |
| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, KuGou KRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD, TXT**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |
@@ -41,7 +41,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| **Geospatial vector data** | built in | **GeoJSON, KML, KMZ, GPX, Shapefile ↔ each other and CSV** (longitude / latitude or WKT); Garmin FIT (activities) and OpenStreetMap XML (`.osm`), both read only, → each of them and CSV; projected Shapefiles (UTM, Web Mercator, Lambert, Albers) are converted to WGS 84; through CSV to XLSX, JSON, … (see below) |
| **Filee renderer** | built in, on by default (Settings → Engines → *Use the Filee renderer*) | **HWPX, HWP, Word documents (DOCX and DOC), ODT, RTF, TXT, Markdown, HTML, e-books, CSV / TSV, OFD, UYAP (UDF), the markup languages Filee reads itself (and Pandoc's formats) → 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 |
+| Archives | built in (SharpCompress, DiscUtils, .NET and Filee's own readers and writers); 7-Zip optional (Settings → *Engines*, ~2 MB download) | **in-process**: ZIP (including ANSYS Workbench WBPZ and Adobe ZXP, and Windows app packages MSIX / APPX), Minecraft and Modrinth packs, Garry's Mod addons (GMA), Valve paks (VPK), the files packed into Source maps (BSP), 7Z (solid ones too), RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ/ZST), GZ, BZ2, XZ, LZMA, Z, ZST, lzip, CPIO, DEB, RPM, ISO (UDF discs too), IMG and DMG disk images, split (.001), ALZ, EGG, CAB, LHA, ARJ; **7-Zip, when installed**: the rare variants the in-process readers leave to it (see [Archives](#archives)) **→ folder, ZIP, 7Z, TAR, TAR.GZ, TAR.BZ2, TAR.XZ, BZ2, XZ, the packs, GMA** (in-process); "Compress into one archive" for any files |
| LibreOffice | **optional download** (~370 MB, 1.1 GB on disk) | older and rare formats only: Word 6.0 / 95 and Works documents, PowerPoint 95 and older PPT, binary Visio (`.vsd`), and ODP / ODG with what Filee doesn't draw yet (charts, OLE objects, 3D) → PDF; XLS, PPT, RTF and OpenDocument to each other, output as DOCX/ODT/ODS, and ODP for what the [ODP writer](#odp-writer) doesn't take (OpenDocument presentations themselves, Keynote, decks with charts, effects or 3D); read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (LaTeX, AsciiDoc, Typst, man; and RTF / EPUB from the built-in ones) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT); their AST feeds the built-in PPTX writer (Pandoc's own slides only where Filee assumes a Pandoc that isn't installed) |
| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PostScript-based AI → PDF (images through PDF and PDFium), EPS/PS → PNG; PDF → EPS/PS only when moved above the built-in PostScript writer; smaller PDFs when a preset asks for it; PDF/A-2b for PDF/A presets; renders CMYK PDF/AI pages for CMYK JPG/TIFF |
@@ -833,13 +833,14 @@ which is also the equation's alternative text in HWPX.
## Spreadsheets
-`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLS (and XLT templates, read only), ODS, CSV and TSV (also
+`SpreadsheetConverter` (engine id `spreadsheet`) converts between XLSX, XLSB (read only), XLS (and XLT templates, read only), ODS, CSV and TSV (also
`.tab`) in-process; every format goes through one in-memory workbook (`Office/Sheets/Workbook.cs`) whose cells keep
the text the spreadsheet shows, the value behind it and its Excel number format.
| Format | Read | Written |
|---|---|---|
| XLSX | own reader: values, number formats, rich text, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows, print titles; for printing the page setup, print areas, page breaks, headers and footers, conditional formats and pictures | every sheet, numbers and dates as numbers with their formats, booleans, styles, merges, widths, heights, hidden rows / columns, frozen rows |
+| XLSB (Excel binary workbook) | own reader from [MS-XLSB] (`XlsbReader.cs`): the BIFF12 records of the workbook, shared strings, styles and sheets give what the XLSX reader gives (values, formulas' cached values, number formats, rich text, fonts, fills, borders, alignment, merges, widths, heights, hidden rows / columns / sheets, frozen rows, print areas and titles, page setup, breaks, headers and footers, pictures); conditional formats and comments are not read | no |
| XLS (Excel 97–2003, also Excel 5/95) | ExcelDataReader (MIT): values, number formats, merges; fonts, fills, borders and alignment (BIFF8), widths, heights, hidden rows / columns and the page setup from the BIFF records (`XlsLayout.cs`) | no (LibreOffice) |
| ODS | own reader (`content.xml`, `styles.xml`, `settings.xml`): repeated rows / columns (the empty repeats up to the end of the sheet are skipped), spans, every value type, the text Calc shows (`text:p`), data styles as Excel codes, cell styles, widths, heights, hidden rows / columns / sheets, frozen and header rows | every sheet, typed cells (float, percentage, currency, date, time, boolean) with data styles and the shown text, styles, merges, widths, heights, hidden rows / columns, frozen rows |
| CSV / TSV | delimiter (CSV: comma, semicolon or tab; TSV: tab) and encoding (UTF-8 / UTF-16 with BOM, CP949 when it looks Korean or on Korean Windows, else the PC's code page) | UTF-8 with BOM, CRLF, one file per sheet |
@@ -852,8 +853,9 @@ the text the spreadsheet shows, the value behind it and its Excel number format.
measures with its own fonts, so a width can differ by up to a fifth after LibreOffice opens the file.
- XLS fonts, fills and borders come from the FONT, XF and PALETTE records of BIFF8 files (Excel 97–2003); Excel 5/95
files keep the default look. XLS output still needs LibreOffice. Password-protected XLS and ODS files stop with a
- clear message. XLSX and ODS packages are read within `DocumentLimits` (sizes, inflate ratio, XML depth and
- elements); ODS repeats expand to at most 20,000,000 cells.
+ clear message. XLSX, XLSB and ODS packages are read within `DocumentLimits` (sizes, inflate ratio, XML depth and
+ elements; XLSB records count as elements, a record the reader takes apart holds at most 1 MB); ODS repeats expand
+ to at most 20,000,000 cells.
- Not converted to other spreadsheets: formulas (their cached results are kept), charts, pictures, comments,
conditional formatting, data validation, print areas and page breaks (the print engine reads the page setup,
print areas, breaks, conditional formats and pictures for PDF).
@@ -871,7 +873,7 @@ selected large page.
## Spreadsheet printing
-`SheetPrintConverter` (engine id `sheet-print`) prints XLSX (and XLSM / XLTX), XLS (and XLT) and ODS to PDF the way
+`SheetPrintConverter` (engine id `sheet-print`) prints XLSX (and XLSM / XLTX), XLSB, XLS (and XLT) and ODS to PDF the way
Excel prints a whole workbook, without Excel or LibreOffice (GitHub Project 4, item *Spreadsheet print layout →
PDF*). The readers above keep each sheet's page setup; `Office/Sheets/Print` lays the pages out with Excel's page logic
and draws them with the Filee renderer's PDF writer (`Rendering/PdfPageWriter`, fonts subset by Filee) and its text
@@ -2733,6 +2735,8 @@ its reader, one line in `Drawings/DrawingFormats.cs`:
WMF). Cells, geometry and text are inherited from master shapes and style sheets; colours by index come from the
document's colour table, fonts from its face names. Only stored values (`V`) are read; formulas aren't calculated.
- **ODG and FODG** (OpenDocument drawings, packaged and flat): the [ODP / ODG reader](#odp--odg-reader).
+- **XPS and OpenXPS** (`.xps`, `.oxps`, format id `xps`): not slides; the [XPS reader](#xps-and-openxps-reader) draws
+ its pages straight into the page model (`DrawingFormat.ReadPages`, `IFixedPages`).
Its edges are `Checked` (`ICapabilityCheck`): a format's check names what its reader doesn't draw, and such a file
takes the route it would take without this engine, LibreOffice Draw. That is a binary `.vsd` (Visio 2003–2010, a
@@ -2756,6 +2760,55 @@ sections, shadows, rounding, the full arrowhead table, text backgrounds, formula
`.vssx` / `.vstx`. The slide model has one size per deck, so pages of other sizes sit at the top left of the largest
page's size. Checked against drawings built from the specification, not against files Visio saved.
+## XPS and OpenXPS reader
+
+Built in (#613), in `Xps/`, written from the XPS 1.0 specification and ECMA-388 (OpenXPS); both namespaces are read.
+The [drawing engine](#drawings-visio-odg) converts `.xps` and `.oxps` (one format, id `xps`, documents donut) to PDF,
+SVG and PNG, page by page: `XpsDocument` reads the package's page list once and each page when it is drawn
+(`XpsPageReader` → `XpsPageWriter` → the page model `PageContent`), so pictures of a few pages don't read the rest.
+PDF goes through `PdfPageWriter` (fonts subset, text mapped), PNG through `PageContent.Render`, SVG through the slide
+output's SVG writer.
+
+- **Package:** the fixed representation relationship of either spec (else the `.fdseq` part), its FixedDocuments and
+ their PageContent list, LinkTargets, the title from the core properties. Part names are URIs (`%20`), resolved
+ against the referring part and never outside the package; interleaved parts (`[0].piece` … `[n].last.piece`) are
+ joined, and one with a gap is damage.
+- **Elements:** Canvas, Path and Glyphs with RenderTransform, Clip, Opacity, OpacityMask (a DstIn layer),
+ `RenderOptions.EdgeMode`, `FixedPage.NavigateUri` (URL links and links to link targets, which become named
+ destinations), properties as attributes or property elements, `{StaticResource}` from FixedPage and Canvas
+ resources (inline or a remote ResourceDictionary part), markup compatibility's AlternateContent (Fallback, else the
+ first Choice).
+- **Geometry:** the abbreviated syntax (F, M, L, H, V, C, Q, S, A, Z, relative forms) and PathGeometry with PathFigure
+ (IsFilled, IsClosed), PolyLine, PolyBezier, PolyQuadraticBezier and Arc segments (IsStroked), with its Transform.
+ Strokes: thickness, joins, miter limit, start / dash caps, dash arrays and offsets.
+- **Brushes:** SolidColorBrush (`#RRGGBB`, `#AARRGGBB`, scRGB, ContextColor without its ICC profile),
+ LinearGradientBrush and RadialGradientBrush (spread methods, stops outside 0–1 cut there), ImageBrush (PNG, JPEG,
+ GIF, BMP by Skia, TIFF by ImageMagick; sized by the picture's resolution, 96 dpi when it has none; `TileMode` none
+ draws the picture as it is, so a PDF keeps the JPEG) and VisualBrush (untiled: drawn as vector; tiled: a picture
+ shader, which Skia's PDF writer rasterises).
+- **Glyphs:** embedded fonts, obfuscated `.odttf` ones restored (the first 32 bytes XORed with the GUID of the part
+ name) and read by Filee's SFNT parser before Skia sees them; `Indices` (glyph, advance, offsets, cluster maps),
+ `UnicodeString` (with the `{}` escape), BidiLevel (odd: right to left), StyleSimulations (bold and italic drawn
+ synthetically), FontRenderingEmSize, OriginX / OriginY. A run with a solid colour whose clips are rectangles is a
+ glyph item of the page model (the PDF writer subsets its font and maps its text); others are drawn by
+ `XpsPainter` as text blobs of the whole font. A run whose font is missing or damaged draws its text with an installed
+ font.
+- **Left out and named in the file's result** (`notice.renderer_left_out` with `.pictures`): JPEG XR (HD Photo)
+ pictures and pictures that are damaged or too large. Not drawn: IsSideways glyphs are upright, the Triangle cap is
+ flat, scRGB gradients interpolate in sRGB, ICC profiles aren't applied; print tickets, signatures, document
+ structure and story fragments aren't read.
+- **Hostile input:** parts through `DocumentPackage` (`DocumentLimits`: part and package sizes counted while
+ unpacking, inflate ratio, XML depth and elements, joined pieces included); `XpsLimits`: pages (`MaxPages`), canvas
+ and visual brush nesting (64, which also ends a visual brush that draws itself), elements (2 million), points of all
+ paths and glyphs (40 million), one path's data (32 M characters), dash patterns (1,024 entries, longer ones are
+ drawn solid), page sides cut at 200 inches; pictures within `MaxPartBytes` and `MaxPicturePixels` (read from the
+ header before decoding). Refusals are `error.document_too_complex`. `XpsFuzzTests` fuzzes the reader and the
+ drawing together.
+- Tests: `XpsTests` (packages built in code by `XpsBuilder`, checked as pixels at 96 dpi, one pixel per XPS unit, and
+ as PDF text), `XpsSettingsTests` (settings v105: existing documents donuts learn `.xps` and `.oxps`). Compared by eye
+ with WPF's own rendering of documents its XPS writer saved (text in Latin, Korean, Japanese, Arabic and Hebrew,
+ gradients, pictures at 96 and 192 dpi, dashes, transparency, clips, tiled image and visual brushes, opacity masks).
+
## Gerber PCB layers
Built in (`Filee.Engines/Vector/Gerber`), read only. A Gerber file (RS-274X, Gerber X2 and X3, "The Gerber Layer
@@ -3478,11 +3531,12 @@ paths leaving the folder, bombs, entry floods) are final and never retried. Sett
| 7Z | Filee (`SevenZipReader`: Copy, LZMA, LZMA2, BCJ, BCJ2, ARM64, ARM, ARMT, PPC, SPARC, IA64, Delta, Deflate, BZip2; solid blocks decoded once, see below); other methods (PPMd, RISC-V …) by 7-Zip when it is installed, else SharpCompress, else the method is named in the "install 7-Zip" error | in-process (Filee's `SevenZipWriter`, LZMA2): UTF-16 names, times, attributes, empty folders |
| RAR 4 / 5 | SharpCompress (only unpacks, under the unRAR terms, see THIRD-PARTY-NOTICES), with the other volumes (`.part2.rar`, `.r00`) | — |
| TAR | .NET's System.Formats.Tar (ustar, PAX, GNU, V7): tells symbolic from hard links | in-process (System.Formats.Tar, PAX: UTF-8 names, times) |
-| TAR.GZ, TAR.BZ2, TAR.XZ, TAR.Z, TAR.LZ, TAR.7Z | in two stages: the outer layer as below, then the TAR | TAR.GZ, TAR.BZ2 and TAR.XZ in-process |
+| TAR.GZ, TAR.BZ2, TAR.XZ, TAR.Z, TAR.LZ, TAR.ZST, TAR.7Z | in two stages: the outer layer as below, then the TAR | TAR.GZ, TAR.BZ2 and TAR.XZ in-process |
| GZ | .NET's gzip decoder (CRC-32 checked) | in-process (GZipStream); one file only |
| BZ2 | SharpCompress | in-process (Filee's `Bzip2Writer`); one file only |
| XZ | Filee (`XzReader`) | in-process (Filee's `XzWriter`); one file only |
| LZMA (`.lzma`) | Filee (`LzmaRawReader`) | — |
+| ZST (Zstandard, #1646) | SharpCompress through `ZstdReader`: frames one after another, skippable frames passed over; not starting with a frame is "not an archive"; windows over 128 MiB (`zstd --long=28` and up) are left to 7-Zip, as the zstd tool needs `--memory` for them | — (rule 5 of [FORMAT-RULES](FORMAT-RULES.md): a new output only developers make waits while that field is on by default) |
| Z (Unix compress) | Filee (`UnixCompressStream`: LZW, 9–16-bit codes, block mode with table clears) | — |
| LZ (lzip) | Filee: members found from the end, each LZMA stream decoded by SharpCompress, CRC-32 and sizes checked (data longer than the trailer states is refused) | — |
| CPIO | Filee (`CpioReader`: newc, crc with its byte sum checked, odc, old binary in either byte order; newc hard link groups become copies) | — |
@@ -3583,7 +3637,7 @@ paths leaving the folder, bombs, entry floods) are final and never retried. Sett
levels and chunk buffers over 64 MB are refused before DiscUtils reads them, and DiscUtils itself only reads through
a window with a budget per call (256 MB, plus the file being copied) and a stack check, so structures that lead in
circles end as damage instead of running on.
-- **Single compressed streams** (GZ, BZ2, XZ, LZMA, Z, and the first stage of TAR.GZ, TAR.BZ2, TAR.XZ, TAR.Z) state
+- **Single compressed streams** (GZ, BZ2, XZ, LZMA, Z, ZST, and the first stage of TAR.GZ, TAR.BZ2, TAR.XZ, TAR.Z, TAR.ZST) state
no size (bzip2) or one their author chose (gzip, modulo 4 GiB), so the listing can't be trusted: the in-process
decoders stop once one passes the room on the drive less a tenth of the free space (`ArchiveSafety.StreamLimit`,
"unpacks to more than …, but only … is free") and delete what was written; when 7-Zip decodes one (the fallback),
@@ -3776,7 +3830,7 @@ all expected bytes have been written; failures and cancellation preserve any pre
- It is the only reader of rarer formats, converted to PDF and to the editable formats of their kind: Word 6.0 / 95
and Microsoft Works documents (a `.doc`, `.dot` or `.wps` the [DOC reader](#doc-reader) names as such), WordPerfect,
Lotus Word Pro, AbiWord, Apple Pages, StarWriter, ClarisWorks / AppleWorks (`.cwk`), MacWrite (`.mcw`), T602
- (`.602`) and Pocket Word (`.psw`) (→ DOCX, ODT, FODT, OTT, DOC, RTF, TXT, HTML); WPS Spreadsheets (ET), Apple Numbers, StarCalc and flat ODS (`.fods`) (→ XLSX, ODS, OTS, XLS, XLT, CSV, HTML); Apple
+ (`.602`) and Pocket Word (`.psw`) (→ DOCX, ODT, FODT, OTT, DOC, RTF, TXT, HTML); WPS Spreadsheets (ET), Apple Numbers, StarCalc and flat ODS (`.fods`) (→ XLSX, ODS, OTS, XLS, XLT, CSV, HTML); XLSB too, where the built-in reader has no route (→ XLS, XLT, OTS) and for a workbook with what the print engine doesn't draw; Apple
Keynote, WPS Presentation (DPS), StarImpress / StarDraw and PowerPoint 95 and older PPT (→ PPTX, ODP, OTP, PPT);
Publisher, CorelDRAW, binary Visio (`.vsd`) and CGM (→ ODG, SVG, PNG, EMF, WMF). VSDX, ODP, FODP, ODG and FODG
are read by Filee itself ([Drawings](#drawings-visio-odg), [ODP / ODG reader](#odp--odg-reader)); LibreOffice keeps
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index adb5532da..b190e5a2d 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "حُذف عنصر تحكم نموذج واحد",
"notice.renderer_left_out.videos": "مقاطع فيديو محذوفة: {0}",
"notice.renderer_left_out.videos_one": "حُذف مقطع فيديو واحد",
+ "notice.renderer_left_out.pictures": "صور محذوفة: {0}",
+ "notice.renderer_left_out.pictures_one": "حُذفت صورة واحدة",
"notice.renderer_left_out.objects_pictured": "كائنات مضمّنة رُسمت من صورها المحفوظة: {0}",
"notice.renderer_left_out.objects_pictured_one": "رُسم كائن مضمّن واحد من صورته المحفوظة",
"notice.renderer_left_out.formulas": "صيغ كُتبت نصًا عاديًا: {0}",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "مسارات الطابعات ثلاثية الأبعاد وآلات CNC (G-code) إلى PDF وSVG وصور، أو معاينة برنامج التقطيع.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "تحويل رسومات Visio (VSDX) ورسومات OpenDocument (ODG وFODG) إلى PDF وSVG وPNG دون Visio أو LibreOffice.\nلا تزال ملفات Visio الثنائية القديمة (.vsd) تحتاج إلى LibreOffice.",
+ "engine.drawing.description": "تحويل رسومات Visio (VSDX) ورسومات OpenDocument (ODG وFODG) إلى PDF وSVG وPNG دون Visio أو LibreOffice.\nوكذلك مستندات XPS وOpenXPS (.xps و.oxps).\nلا تزال ملفات Visio الثنائية القديمة (.vsd) تحتاج إلى LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "التحويل بين النماذج ثلاثية الأبعاد: GLB وglTF وSTL وOBJ و3MF وPLY، وتحويل FBX إلى أي منها، وإنشاء معاينة PNG.",
"engine.image3d.name": "صور إلى نقش بارز ثلاثي الأبعاد (مدمج)",
diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json
index 747731f1d..c5989b448 100644
--- a/src/Filee.App/Assets/i18n/bn-BD.json
+++ b/src/Filee.App/Assets/i18n/bn-BD.json
@@ -260,6 +260,8 @@
"notice.renderer_left_out.form_controls_one": "1টি ফর্ম কন্ট্রোল বাদ দেওয়া হয়েছে",
"notice.renderer_left_out.videos": "{0}টি ভিডিও বাদ দেওয়া হয়েছে",
"notice.renderer_left_out.videos_one": "1টি ভিডিও বাদ দেওয়া হয়েছে",
+ "notice.renderer_left_out.pictures": "{0}টি ছবি বাদ দেওয়া হয়েছে",
+ "notice.renderer_left_out.pictures_one": "1টি ছবি বাদ দেওয়া হয়েছে",
"notice.renderer_left_out.objects_pictured": "{0}টি এমবেড করা অবজেক্ট তাদের সংরক্ষিত ছবি থেকে আঁকা হয়েছে",
"notice.renderer_left_out.objects_pictured_one": "1টি এমবেড করা অবজেক্ট তার সংরক্ষিত ছবি থেকে আঁকা হয়েছে",
"notice.renderer_left_out.formulas": "{0}টি সূত্র সাধারণ লেখা হিসেবে লেখা হয়েছে",
@@ -328,7 +330,7 @@
"engine.gcode.name": "G-code (বিল্ট-ইন)",
"engine.gcode.description": "3D প্রিন্টার ও CNC মেশিনের টুলপাথ (G-code) PDF, SVG ও ছবিতে, অথবা স্লাইসারের নিজের প্রিভিউ।",
"engine.drawing.name": "ড্রয়িং (বিল্ট-ইন)",
- "engine.drawing.description": "Visio ড্রয়িং (VSDX) ও OpenDocument ড্রয়িং (ODG, FODG) থেকে পিডিএফ, SVG ও PNG, Visio বা LibreOffice ছাড়াই।\nপুরোনো বাইনারি Visio ফাইলের (.vsd) জন্য এখনও LibreOffice লাগে।",
+ "engine.drawing.description": "Visio ড্রয়িং (VSDX) ও OpenDocument ড্রয়িং (ODG, FODG) থেকে পিডিএফ, SVG ও PNG, Visio বা LibreOffice ছাড়াই।\nXPS ও OpenXPS ডকুমেন্টও (.xps, .oxps)।\nপুরোনো বাইনারি Visio ফাইলের (.vsd) জন্য এখনও LibreOffice লাগে।",
"engine.model3d.name": "3D মডেল (বিল্ট-ইন)",
"engine.model3d.description": "3D মডেল: GLB, glTF, STL, OBJ, 3MF এবং PLY একে অপরে রূপান্তর, যেকোনোটিতে FBX রূপান্তর এবং একটি PNG প্রিভিউ।",
"engine.image3d.name": "ছবি থেকে 3D রিলিফ (বিল্ট-ইন)",
diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json
index 018f41739..c36f41e20 100644
--- a/src/Filee.App/Assets/i18n/de.json
+++ b/src/Filee.App/Assets/i18n/de.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 Formularsteuerelement weggelassen",
"notice.renderer_left_out.videos": "{0} Videos weggelassen",
"notice.renderer_left_out.videos_one": "1 Video weggelassen",
+ "notice.renderer_left_out.pictures": "{0} Bilder weggelassen",
+ "notice.renderer_left_out.pictures_one": "1 Bild weggelassen",
"notice.renderer_left_out.objects_pictured": "{0} eingebettete Objekte aus ihrem gespeicherten Bild gezeichnet",
"notice.renderer_left_out.objects_pictured_one": "1 eingebettetes Objekt aus seinem gespeicherten Bild gezeichnet",
"notice.renderer_left_out.formulas": "{0} Formeln als einfacher Text geschrieben",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (integriert)",
"engine.gcode.description": "Werkzeugwege von 3D-Druckern und CNC-Maschinen (G-Code) als PDF, SVG und Bild, oder die Vorschau des Slicers.",
"engine.drawing.name": "Zeichnungen (integriert)",
- "engine.drawing.description": "Visio-Zeichnungen (VSDX) und OpenDocument-Zeichnungen (ODG, FODG) in PDF, SVG und PNG, ohne Visio oder LibreOffice.\nFür alte binäre Visio-Dateien (.vsd) ist weiterhin LibreOffice nötig.",
+ "engine.drawing.description": "Visio-Zeichnungen (VSDX) und OpenDocument-Zeichnungen (ODG, FODG) in PDF, SVG und PNG, ohne Visio oder LibreOffice.\nAuch XPS- und OpenXPS-Dokumente (.xps, .oxps).\nFür alte binäre Visio-Dateien (.vsd) ist weiterhin LibreOffice nötig.",
"engine.model3d.name": "3D-Modelle (integriert)",
"engine.model3d.description": "3D-Modelle: Konvertiert GLB, glTF, STL, OBJ, 3MF und PLY untereinander, FBX in jedes dieser Formate und erstellt eine PNG-Vorschau.",
"engine.image3d.name": "Bilder zu 3D-Relief (integriert)",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 7b4914fa4..b37832e4a 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "1 form control left out",
"notice.renderer_left_out.videos": "{0} videos left out",
"notice.renderer_left_out.videos_one": "1 video left out",
+ "notice.renderer_left_out.pictures": "{0} pictures left out",
+ "notice.renderer_left_out.pictures_one": "1 picture left out",
"notice.renderer_left_out.objects_pictured": "{0} embedded objects drawn from their saved pictures",
"notice.renderer_left_out.objects_pictured_one": "1 embedded object drawn from its saved picture",
"notice.renderer_left_out.formulas": "{0} formulas written as plain text",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "Toolpaths of 3D printers and CNC machines (G-code) to PDF, SVG and pictures, or the slicer's own preview.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Visio drawings (VSDX) and OpenDocument drawings (ODG, FODG) to PDF, SVG and PNG, without Visio or LibreOffice.\nOld binary Visio files (.vsd) still need LibreOffice.",
+ "engine.drawing.description": "Visio drawings (VSDX) and OpenDocument drawings (ODG, FODG) to PDF, SVG and PNG, without Visio or LibreOffice.\nAlso XPS and OpenXPS documents (.xps, .oxps).\nOld binary Visio files (.vsd) still need LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, FBX into any of them, and a PNG preview.",
"engine.image3d.name": "Pictures to 3D relief (built-in)",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index e1add24a7..08816e86e 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 control de formulario omitido",
"notice.renderer_left_out.videos": "{0} vídeos omitidos",
"notice.renderer_left_out.videos_one": "1 vídeo omitido",
+ "notice.renderer_left_out.pictures": "{0} imágenes omitidas",
+ "notice.renderer_left_out.pictures_one": "1 imagen omitida",
"notice.renderer_left_out.objects_pictured": "{0} objetos incrustados dibujados a partir de su imagen guardada",
"notice.renderer_left_out.objects_pictured_one": "1 objeto incrustado dibujado a partir de su imagen guardada",
"notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto sin formato",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "Trayectorias de impresoras 3D y máquinas CNC (G-code) a PDF, SVG e imágenes, o la vista previa del laminador.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Dibujos de Visio (VSDX) y de OpenDocument (ODG, FODG) a PDF, SVG y PNG, sin Visio ni LibreOffice.\nLos archivos binarios antiguos de Visio (.vsd) siguen necesitando LibreOffice.",
+ "engine.drawing.description": "Dibujos de Visio (VSDX) y de OpenDocument (ODG, FODG) a PDF, SVG y PNG, sin Visio ni LibreOffice.\nTambién documentos XPS y OpenXPS (.xps, .oxps).\nLos archivos binarios antiguos de Visio (.vsd) siguen necesitando LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, FBX a cualquiera de ellos, además de una vista previa en PNG.",
"engine.image3d.name": "Imágenes a relieve 3D (integrado)",
diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json
index f9d12bfef..c109d2bf6 100644
--- a/src/Filee.App/Assets/i18n/fa.json
+++ b/src/Filee.App/Assets/i18n/fa.json
@@ -260,6 +260,8 @@
"notice.renderer_left_out.form_controls_one": "یک کنترل فرم حذف شد",
"notice.renderer_left_out.videos": "{0} ویدیو حذف شد",
"notice.renderer_left_out.videos_one": "یک ویدیو حذف شد",
+ "notice.renderer_left_out.pictures": "{0} تصویر حذف شد",
+ "notice.renderer_left_out.pictures_one": "یک تصویر حذف شد",
"notice.renderer_left_out.objects_pictured": "{0} شیء جاسازیشده از تصویر ذخیرهشدهاش رسم شد",
"notice.renderer_left_out.objects_pictured_one": "یک شیء جاسازیشده از تصویر ذخیرهشدهاش رسم شد",
"notice.renderer_left_out.formulas": "{0} فرمول بهصورت متن ساده نوشته شد",
@@ -328,7 +330,7 @@
"engine.gcode.name": "G-code (داخلی)",
"engine.gcode.description": "مسیرهای چاپگرهای سهبعدی و دستگاههای CNC (G-code) به PDF، SVG و تصویر، یا پیشنمایش خود اسلایسر.",
"engine.drawing.name": "نمودارها و نقشهها (داخلی)",
- "engine.drawing.description": "نمودارهای Visio (VSDX) و نقشههای OpenDocument (ODG، FODG) به PDF، SVG و PNG، بدون Visio یا LibreOffice.\nفایلهای باینری قدیمی Visio (.vsd) همچنان به LibreOffice نیاز دارند.",
+ "engine.drawing.description": "نمودارهای Visio (VSDX) و نقشههای OpenDocument (ODG، FODG) به PDF، SVG و PNG، بدون Visio یا LibreOffice.\nهمچنین سندهای XPS و OpenXPS (.xps، .oxps).\nفایلهای باینری قدیمی Visio (.vsd) همچنان به LibreOffice نیاز دارند.",
"engine.model3d.name": "مدلهای سهبعدی (داخلی)",
"engine.model3d.description": "مدلهای سهبعدی: GLB، glTF، STL، OBJ، 3MF و PLY به یکدیگر، FBX به هر یک از آنها، همراه با پیشنمایش PNG.",
"engine.image3d.name": "تبدیل تصاویر به برجستهسازی سهبعدی (داخلی)",
diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json
index 53a5a241e..2e3d07f7e 100644
--- a/src/Filee.App/Assets/i18n/fr.json
+++ b/src/Filee.App/Assets/i18n/fr.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "1 contrôle de formulaire omis",
"notice.renderer_left_out.videos": "{0} vidéos omises",
"notice.renderer_left_out.videos_one": "1 vidéo omise",
+ "notice.renderer_left_out.pictures": "{0} images omises",
+ "notice.renderer_left_out.pictures_one": "1 image omise",
"notice.renderer_left_out.objects_pictured": "{0} objets incorporés dessinés d'après leur image enregistrée",
"notice.renderer_left_out.objects_pictured_one": "1 objet incorporé dessiné d'après son image enregistrée",
"notice.renderer_left_out.formulas": "{0} formules écrites en texte brut",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "Parcours d'imprimantes 3D et de machines CNC (G-code) en PDF, SVG et images, ou l'aperçu du slicer.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Dessins Visio (VSDX) et OpenDocument (ODG, FODG) en PDF, SVG et PNG, sans Visio ni LibreOffice.\nLes anciens fichiers Visio binaires (.vsd) nécessitent toujours LibreOffice.",
+ "engine.drawing.description": "Dessins Visio (VSDX) et OpenDocument (ODG, FODG) en PDF, SVG et PNG, sans Visio ni LibreOffice.\nAussi les documents XPS et OpenXPS (.xps, .oxps).\nLes anciens fichiers Visio binaires (.vsd) nécessitent toujours LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modèles 3D : GLB, glTF, STL, OBJ, 3MF et PLY entre eux, FBX vers chacun d'eux, et un aperçu PNG.",
"engine.image3d.name": "Images vers relief 3D (intégré)",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index a5b41b416..ef80cd11b 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 फ़ॉर्म कंट्रोल छोड़ दिया गया",
"notice.renderer_left_out.videos": "{0} वीडियो छोड़ दिए गए",
"notice.renderer_left_out.videos_one": "1 वीडियो छोड़ दिया गया",
+ "notice.renderer_left_out.pictures": "{0} चित्र छोड़ दिए गए",
+ "notice.renderer_left_out.pictures_one": "1 चित्र छोड़ दिया गया",
"notice.renderer_left_out.objects_pictured": "{0} एम्बेड किए गए ऑब्जेक्ट उनकी सहेजी गई तस्वीर से बनाए गए",
"notice.renderer_left_out.objects_pictured_one": "1 एम्बेड किया गया ऑब्जेक्ट उसकी सहेजी गई तस्वीर से बनाया गया",
"notice.renderer_left_out.formulas": "{0} सूत्र सादे टेक्स्ट के रूप में लिखे गए",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "3D प्रिंटर और CNC मशीनों के टूलपाथ (G-code) को PDF, SVG और चित्र में, या स्लाइसर का अपना प्रीव्यू।",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Visio ड्रॉइंग (VSDX) और OpenDocument ड्रॉइंग (ODG, FODG) से PDF, SVG और PNG, बिना Visio या LibreOffice के।\nपुरानी बाइनरी Visio फ़ाइलों (.vsd) के लिए अब भी LibreOffice चाहिए।",
+ "engine.drawing.description": "Visio ड्रॉइंग (VSDX) और OpenDocument ड्रॉइंग (ODG, FODG) से PDF, SVG और PNG, बिना Visio या LibreOffice के।\nXPS और OpenXPS दस्तावेज़ (.xps, .oxps) भी।\nपुरानी बाइनरी Visio फ़ाइलों (.vsd) के लिए अब भी LibreOffice चाहिए।",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D मॉडल: GLB, glTF, STL, OBJ, 3MF और PLY एक-दूसरे में, FBX इनमें से किसी में भी, और PNG प्रीव्यू।",
"engine.image3d.name": "चित्र से 3D रिलीफ़ (बिल्ट-इन)",
diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json
index 9fa323f6c..9332026c8 100644
--- a/src/Filee.App/Assets/i18n/id.json
+++ b/src/Filee.App/Assets/i18n/id.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 kontrol formulir tidak disertakan",
"notice.renderer_left_out.videos": "{0} video tidak disertakan",
"notice.renderer_left_out.videos_one": "1 video tidak disertakan",
+ "notice.renderer_left_out.pictures": "{0} gambar tidak disertakan",
+ "notice.renderer_left_out.pictures_one": "1 gambar tidak disertakan",
"notice.renderer_left_out.objects_pictured": "{0} objek tersemat digambar dari gambar tersimpannya",
"notice.renderer_left_out.objects_pictured_one": "1 objek tersemat digambar dari gambar tersimpannya",
"notice.renderer_left_out.formulas": "{0} rumus ditulis sebagai teks biasa",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (bawaan)",
"engine.gcode.description": "Jalur printer 3D dan mesin CNC (G-code) ke PDF, SVG, dan gambar, atau pratinjau dari slicer.",
"engine.drawing.name": "Diagram (bawaan)",
- "engine.drawing.description": "Diagram Visio (VSDX) dan gambar OpenDocument (ODG, FODG) ke PDF, SVG, dan PNG, tanpa Visio atau LibreOffice.\nFile Visio biner lama (.vsd) masih memerlukan LibreOffice.",
+ "engine.drawing.description": "Diagram Visio (VSDX) dan gambar OpenDocument (ODG, FODG) ke PDF, SVG, dan PNG, tanpa Visio atau LibreOffice.\nJuga dokumen XPS dan OpenXPS (.xps, .oxps).\nFile Visio biner lama (.vsd) masih memerlukan LibreOffice.",
"engine.model3d.name": "Model 3D (bawaan)",
"engine.model3d.description": "Model 3D: GLB, glTF, STL, OBJ, 3MF, dan PLY saling konversi, FBX ke format mana pun, serta pratinjau gambar PNG.",
"engine.image3d.name": "Gambar ke relief 3D (bawaan)",
diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json
index bd2145de7..e1cf5b01e 100644
--- a/src/Filee.App/Assets/i18n/it.json
+++ b/src/Filee.App/Assets/i18n/it.json
@@ -245,6 +245,8 @@
"notice.renderer_left_out.form_controls_one": "1 controllo modulo omesso",
"notice.renderer_left_out.videos": "{0} video omessi",
"notice.renderer_left_out.videos_one": "1 video omesso",
+"notice.renderer_left_out.pictures": "{0} immagini omesse",
+"notice.renderer_left_out.pictures_one": "1 immagine omessa",
"notice.renderer_left_out.objects_pictured": "{0} oggetti incorporati disegnati dalla loro immagine salvata",
"notice.renderer_left_out.objects_pictured_one": "1 oggetto incorporato disegnato dalla sua immagine salvata",
"notice.renderer_left_out.formulas": "{0} formule scritte come testo semplice",
@@ -313,7 +315,7 @@
"engine.gcode.name": "G-code (integrato)",
"engine.gcode.description": "Percorsi di stampanti 3D e macchine CNC (G-code) in PDF, SVG e immagini, o l'anteprima dello slicer.",
"engine.drawing.name": "Disegni (integrato)",
-"engine.drawing.description": "Disegni Visio (VSDX) e OpenDocument (ODG, FODG) in PDF, SVG e PNG, senza Visio né LibreOffice.\nI vecchi file binari di Visio (.vsd) richiedono ancora LibreOffice.",
+"engine.drawing.description": "Disegni Visio (VSDX) e OpenDocument (ODG, FODG) in PDF, SVG e PNG, senza Visio né LibreOffice.\nAnche documenti XPS e OpenXPS (.xps, .oxps).\nI vecchi file binari di Visio (.vsd) richiedono ancora LibreOffice.",
"engine.model3d.name": "Modelli 3D (integrato)",
"engine.model3d.description": "Modelli 3D: GLB, glTF, STL, OBJ, 3MF e PLY convertibili tra loro, FBX in uno qualsiasi di essi, e un'anteprima PNG.",
"engine.image3d.name": "Immagini in rilievo 3D (integrato)",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index e73378a70..657dc177a 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "フォームコントロール 1 個を省略",
"notice.renderer_left_out.videos": "動画 {0} 本を省略",
"notice.renderer_left_out.videos_one": "動画 1 本を省略",
+ "notice.renderer_left_out.pictures": "画像 {0} 枚を省略",
+ "notice.renderer_left_out.pictures_one": "画像 1 枚を省略",
"notice.renderer_left_out.objects_pictured": "埋め込みオブジェクト {0} 個を保存済みの画像で描画",
"notice.renderer_left_out.objects_pictured_one": "埋め込みオブジェクト 1 個を保存済みの画像で描画",
"notice.renderer_left_out.formulas": "数式 {0} 個をプレーンテキストで表示",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "3D プリンターと CNC マシンのツールパス (G-code) を PDF、SVG、画像に。スライサーのプレビューも使えます。",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Visio図面(VSDX)とOpenDocument図面(ODG、FODG)を、VisioやLibreOfficeなしでPDF、SVG、PNGに変換します。\n古いバイナリ形式のVisioファイル(.vsd)には引き続きLibreOfficeが必要です。",
+ "engine.drawing.description": "Visio図面(VSDX)とOpenDocument図面(ODG、FODG)を、VisioやLibreOfficeなしでPDF、SVG、PNGに変換します。\nXPS・OpenXPS文書(.xps、.oxps)にも対応しています。\n古いバイナリ形式のVisioファイル(.vsd)には引き続きLibreOfficeが必要です。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3Dモデル(GLB、glTF、STL、OBJ、3MF、PLY)を相互変換します。FBXから各形式への変換と、PNGプレビューの作成にも対応します。",
"engine.image3d.name": "画像から3Dレリーフ(内蔵)",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index d982b93bc..9308d6913 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "양식 컨트롤 1개 빠짐",
"notice.renderer_left_out.videos": "동영상 {0}개 빠짐",
"notice.renderer_left_out.videos_one": "동영상 1개 빠짐",
+ "notice.renderer_left_out.pictures": "그림 {0}개 빠짐",
+ "notice.renderer_left_out.pictures_one": "그림 1개 빠짐",
"notice.renderer_left_out.objects_pictured": "삽입된 개체 {0}개는 저장된 그림으로 그림",
"notice.renderer_left_out.objects_pictured_one": "삽입된 개체 1개는 저장된 그림으로 그림",
"notice.renderer_left_out.formulas": "수식 {0}개는 일반 글자로 씀",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "3D 프린터와 CNC 기계의 툴패스(G-code)를 PDF, SVG, 그림으로 바꿔요. 슬라이서가 저장한 미리보기도 쓸 수 있어요.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Visio 도면(VSDX)과 오픈도큐먼트 도면(ODG, FODG)을 Visio나 LibreOffice 없이 PDF, SVG, PNG로 바꿔요.\n오래된 바이너리 Visio 파일(.vsd)은 여전히 LibreOffice가 필요해요.",
+ "engine.drawing.description": "Visio 도면(VSDX)과 오픈도큐먼트 도면(ODG, FODG)을 Visio나 LibreOffice 없이 PDF, SVG, PNG로 바꿔요.\nXPS·OpenXPS 문서(.xps, .oxps)도 바꿔요.\n오래된 바이너리 Visio 파일(.vsd)은 여전히 LibreOffice가 필요해요.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고, FBX도 이 형식들로 바꾸고, PNG 미리보기도 만들어요.",
"engine.image3d.name": "이미지를 3D 부조로 (내장)",
diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json
index 361f66c50..1558d49fc 100644
--- a/src/Filee.App/Assets/i18n/mn.json
+++ b/src/Filee.App/Assets/i18n/mn.json
@@ -245,6 +245,8 @@
"notice.renderer_left_out.form_controls_one": "1 маягтын удирдлага орхигдлоо",
"notice.renderer_left_out.videos": "{0} видео орхигдлоо",
"notice.renderer_left_out.videos_one": "1 видео орхигдлоо",
+ "notice.renderer_left_out.pictures": "{0} зураг орхигдлоо",
+ "notice.renderer_left_out.pictures_one": "1 зураг орхигдлоо",
"notice.renderer_left_out.objects_pictured": "{0} шигтгэсэн объектыг хадгалсан зургаас нь зурлаа",
"notice.renderer_left_out.objects_pictured_one": "1 шигтгэсэн объектыг хадгалсан зургаас нь зурлаа",
"notice.renderer_left_out.formulas": "{0} томьёог энгийн текстээр бичлээ",
@@ -313,7 +315,7 @@
"engine.gcode.name": "G-code (суурилагдсан)",
"engine.gcode.description": "3D принтер болон CNC машины замыг (G-code) PDF, SVG, зураг руу, эсвэл слайсерын өөрийн урьдчилан харах зураг руу.",
"engine.drawing.name": "Зураг төсөл (суурилагдсан)",
- "engine.drawing.description": "Visio зураг (VSDX) болон OpenDocument зургийг (ODG, FODG) Visio эсвэл LibreOffice-гүйгээр PDF, SVG болон PNG болгоно.\nХуучин хоёртын Visio файлд (.vsd) LibreOffice хэрэгтэй хэвээр.",
+ "engine.drawing.description": "Visio зураг (VSDX) болон OpenDocument зургийг (ODG, FODG) Visio эсвэл LibreOffice-гүйгээр PDF, SVG болон PNG болгоно.\nМөн XPS болон OpenXPS баримт бичиг (.xps, .oxps).\nХуучин хоёртын Visio файлд (.vsd) LibreOffice хэрэгтэй хэвээр.",
"engine.model3d.name": "3D загвар (суурилагдсан)",
"engine.model3d.description": "3D загварууд: GLB, glTF, STL, OBJ, 3MF болон PLY хоорондоо, FBX-ийг эдгээрийн аль руу ч хөрвүүлэх ба PNG урьдчилж харах зураг үүсгэнэ.",
"engine.image3d.name": "Зургийг 3D рельеф болгох (суурилагдсан)",
diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json
index 68de61aca..e4887eada 100644
--- a/src/Filee.App/Assets/i18n/ne.json
+++ b/src/Filee.App/Assets/i18n/ne.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 फारम नियन्त्रण छोडियो",
"notice.renderer_left_out.videos": "{0} भिडियो छोडिए",
"notice.renderer_left_out.videos_one": "1 भिडियो छोडियो",
+ "notice.renderer_left_out.pictures": "{0} चित्र छोडिए",
+ "notice.renderer_left_out.pictures_one": "1 चित्र छोडियो",
"notice.renderer_left_out.objects_pictured": "{0} सम्मिलित वस्तु तिनको सुरक्षित चित्रबाट कोरिए",
"notice.renderer_left_out.objects_pictured_one": "1 सम्मिलित वस्तु यसको सुरक्षित चित्रबाट कोरियो",
"notice.renderer_left_out.formulas": "{0} सूत्र सादा पाठका रूपमा लेखिए",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "3D प्रिन्टर र CNC मेसिनका टूलपाथ (G-code) लाई PDF, SVG र चित्रमा, वा स्लाइसरकै पूर्वावलोकन।",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Visio रेखाचित्र (VSDX) र OpenDocument रेखाचित्र (ODG, FODG) बाट PDF, SVG र PNG, Visio वा LibreOffice बिना।\nपुराना बाइनरी Visio फाइलहरू (.vsd) का लागि अझै LibreOffice चाहिन्छ।",
+ "engine.drawing.description": "Visio रेखाचित्र (VSDX) र OpenDocument रेखाचित्र (ODG, FODG) बाट PDF, SVG र PNG, Visio वा LibreOffice बिना।\nXPS र OpenXPS कागजातहरू (.xps, .oxps) पनि।\nपुराना बाइनरी Visio फाइलहरू (.vsd) का लागि अझै LibreOffice चाहिन्छ।",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "थ्रीडी मोडलहरू: GLB, glTF, STL, OBJ, 3MF र PLY एकअर्कामा, FBX यीमध्ये कुनैमा पनि, र PNG पूर्वावलोकन।",
"engine.image3d.name": "चित्रबाट थ्रीडी रिलिफ (बिल्ट-इन)",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index e109dfee5..407170ba7 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "pominięta 1 kontrolka formularza",
"notice.renderer_left_out.videos": "pominięte filmy: {0}",
"notice.renderer_left_out.videos_one": "pominięty 1 film",
+ "notice.renderer_left_out.pictures": "pominięte obrazy: {0}",
+ "notice.renderer_left_out.pictures_one": "pominięty 1 obraz",
"notice.renderer_left_out.objects_pictured": "obiekty osadzone narysowane z zapisanych obrazów: {0}",
"notice.renderer_left_out.objects_pictured_one": "1 obiekt osadzony narysowany z zapisanego obrazu",
"notice.renderer_left_out.formulas": "formuły zapisane zwykłym tekstem: {0}",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "Ścieżki drukarek 3D i maszyn CNC (G-code) do PDF, SVG i obrazów albo podgląd zapisany przez slicer.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Rysunki Visio (VSDX) i OpenDocument (ODG, FODG) do PDF, SVG i PNG, bez Visio i LibreOffice.\nStare binarne pliki Visio (.vsd) nadal wymagają LibreOffice.",
+ "engine.drawing.description": "Rysunki Visio (VSDX) i OpenDocument (ODG, FODG) do PDF, SVG i PNG, bez Visio i LibreOffice.\nTakże dokumenty XPS i OpenXPS (.xps, .oxps).\nStare binarne pliki Visio (.vsd) nadal wymagają LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą, FBX do każdego z nich oraz podgląd PNG.",
"engine.image3d.name": "Obrazy na płaskorzeźbę 3D (wbudowany)",
diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json
index cfe7fd8cb..6fe00b692 100644
--- a/src/Filee.App/Assets/i18n/pt-BR.json
+++ b/src/Filee.App/Assets/i18n/pt-BR.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "1 controle de formulário deixado de fora",
"notice.renderer_left_out.videos": "{0} vídeos deixados de fora",
"notice.renderer_left_out.videos_one": "1 vídeo deixado de fora",
+ "notice.renderer_left_out.pictures": "{0} imagens deixadas de fora",
+ "notice.renderer_left_out.pictures_one": "1 imagem deixada de fora",
"notice.renderer_left_out.objects_pictured": "{0} objetos incorporados desenhados a partir da imagem salva",
"notice.renderer_left_out.objects_pictured_one": "1 objeto incorporado desenhado a partir da imagem salva",
"notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto simples",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (mecanismo integrado)",
"engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a prévia do fatiador.",
"engine.drawing.name": "Desenhos (mecanismo integrado)",
- "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nArquivos binários antigos do Visio (.vsd) ainda precisam do LibreOffice.",
+ "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nArquivos binários antigos do Visio (.vsd) ainda precisam do LibreOffice.",
"engine.model3d.name": "Modelos 3D (mecanismo integrado)",
"engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF e PLY entre si, FBX para qualquer um deles, e uma prévia em PNG.",
"engine.image3d.name": "Imagens para relevo 3D (mecanismo integrado)",
diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json
index 56dfa97d5..42ecf92e7 100644
--- a/src/Filee.App/Assets/i18n/pt-PT.json
+++ b/src/Filee.App/Assets/i18n/pt-PT.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "1 controlo de formulário omitido",
"notice.renderer_left_out.videos": "{0} vídeos omitidos",
"notice.renderer_left_out.videos_one": "1 vídeo omitido",
+ "notice.renderer_left_out.pictures": "{0} imagens omitidas",
+ "notice.renderer_left_out.pictures_one": "1 imagem omitida",
"notice.renderer_left_out.objects_pictured": "{0} objetos incorporados desenhados a partir da imagem guardada",
"notice.renderer_left_out.objects_pictured_one": "1 objeto incorporado desenhado a partir da imagem guardada",
"notice.renderer_left_out.formulas": "{0} fórmulas escritas como texto simples",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (motor integrado)",
"engine.gcode.description": "Percursos de impressoras 3D e máquinas CNC (G-code) para PDF, SVG e imagens, ou a pré-visualização do fatiador.",
"engine.drawing.name": "Desenhos (motor integrado)",
- "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nOs ficheiros binários antigos do Visio (.vsd) continuam a precisar do LibreOffice.",
+ "engine.drawing.description": "Desenhos do Visio (VSDX) e do OpenDocument (ODG, FODG) para PDF, SVG e PNG, sem Visio nem LibreOffice.\nTambém documentos XPS e OpenXPS (.xps, .oxps).\nOs ficheiros binários antigos do Visio (.vsd) continuam a precisar do LibreOffice.",
"engine.model3d.name": "Modelos 3D (motor integrado)",
"engine.model3d.description": "Converte modelos 3D entre GLB, glTF, STL, OBJ, 3MF e PLY, de FBX para qualquer um destes formatos e para uma pré-visualização PNG.",
"engine.image3d.name": "Imagens para relevo 3D (motor integrado)",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 5bdefe355..1c05484fd 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "пропущен 1 элемент управления формы",
"notice.renderer_left_out.videos": "пропущено видео: {0}",
"notice.renderer_left_out.videos_one": "пропущено 1 видео",
+ "notice.renderer_left_out.pictures": "пропущено изображений: {0}",
+ "notice.renderer_left_out.pictures_one": "пропущено 1 изображение",
"notice.renderer_left_out.objects_pictured": "внедрённых объектов нарисовано по сохранённым изображениям: {0}",
"notice.renderer_left_out.objects_pictured_one": "1 внедрённый объект нарисован по сохранённому изображению",
"notice.renderer_left_out.formulas": "формул записано обычным текстом: {0}",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "Траектории 3D-принтеров и станков с ЧПУ (G-code) в PDF, SVG и изображения или превью слайсера.",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "Схемы Visio (VSDX) и рисунки OpenDocument (ODG, FODG) — в PDF, SVG и PNG без Visio и LibreOffice.\nДля старых двоичных файлов Visio (.vsd) по-прежнему нужен LibreOffice.",
+ "engine.drawing.description": "Схемы Visio (VSDX) и рисунки OpenDocument (ODG, FODG) — в PDF, SVG и PNG без Visio и LibreOffice.\nА также документы XPS и OpenXPS (.xps, .oxps).\nДля старых двоичных файлов Visio (.vsd) по-прежнему нужен LibreOffice.",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "3D-модели: GLB, glTF, STL, OBJ, 3MF и PLY друг в друга, FBX — в любой из них, плюс превью в PNG.",
"engine.image3d.name": "Изображения в 3D-рельеф (встроенный)",
diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json
index 3d897be04..00c42fb13 100644
--- a/src/Filee.App/Assets/i18n/th.json
+++ b/src/Filee.App/Assets/i18n/th.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "ละตัวควบคุมฟอร์ม 1 รายการ",
"notice.renderer_left_out.videos": "ละวิดีโอ {0} รายการ",
"notice.renderer_left_out.videos_one": "ละวิดีโอ 1 รายการ",
+ "notice.renderer_left_out.pictures": "ละรูปภาพ {0} รายการ",
+ "notice.renderer_left_out.pictures_one": "ละรูปภาพ 1 รายการ",
"notice.renderer_left_out.objects_pictured": "วาดวัตถุที่ฝังไว้ {0} รายการจากรูปที่บันทึกไว้",
"notice.renderer_left_out.objects_pictured_one": "วาดวัตถุที่ฝังไว้ 1 รายการจากรูปที่บันทึกไว้",
"notice.renderer_left_out.formulas": "เขียนสูตร {0} รายการเป็นข้อความธรรมดา",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "เส้นทางของเครื่องพิมพ์ 3 มิติและเครื่อง CNC (G-code) เป็น PDF, SVG และรูปภาพ หรือภาพตัวอย่างของสไลเซอร์",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "แปลงไดอะแกรม Visio (VSDX) และภาพวาด OpenDocument (ODG, FODG) เป็น PDF, SVG และ PNG โดยไม่ต้องใช้ Visio หรือ LibreOffice\nไฟล์ Visio แบบไบนารีรุ่นเก่า (.vsd) ยังต้องใช้ LibreOffice",
+ "engine.drawing.description": "แปลงไดอะแกรม Visio (VSDX) และภาพวาด OpenDocument (ODG, FODG) เป็น PDF, SVG และ PNG โดยไม่ต้องใช้ Visio หรือ LibreOffice\nรวมถึงเอกสาร XPS และ OpenXPS (.xps, .oxps)\nไฟล์ Visio แบบไบนารีรุ่นเก่า (.vsd) ยังต้องใช้ LibreOffice",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "โมเดล 3D: GLB, glTF, STL, OBJ, 3MF และ PLY สลับกันได้ FBX เป็นฟอร์แมตใดก็ได้ และแสดงตัวอย่างเป็น PNG",
"engine.image3d.name": "รูปภาพเป็นภาพนูน 3D (ในตัว)",
diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json
index 513729ab1..99a46de17 100644
--- a/src/Filee.App/Assets/i18n/tr.json
+++ b/src/Filee.App/Assets/i18n/tr.json
@@ -246,6 +246,8 @@
"notice.renderer_left_out.form_controls_one": "1 form denetimi çıkarıldı",
"notice.renderer_left_out.videos": "{0} video çıkarıldı",
"notice.renderer_left_out.videos_one": "1 video çıkarıldı",
+ "notice.renderer_left_out.pictures": "{0} resim çıkarıldı",
+ "notice.renderer_left_out.pictures_one": "1 resim çıkarıldı",
"notice.renderer_left_out.objects_pictured": "{0} gömülü nesne kayıtlı resminden çizildi",
"notice.renderer_left_out.objects_pictured_one": "1 gömülü nesne kayıtlı resminden çizildi",
"notice.renderer_left_out.formulas": "{0} formül düz metin olarak yazıldı",
@@ -314,7 +316,7 @@
"engine.gcode.name": "G-code (yerleşik)",
"engine.gcode.description": "3B yazıcıların ve CNC makinelerinin takım yolları (G-code) PDF, SVG ve resme, ya da dilimleyicinin kendi önizlemesi.",
"engine.drawing.name": "Çizimler (yerleşik)",
- "engine.drawing.description": "Visio çizimleri (VSDX) ve OpenDocument çizimleri (ODG, FODG) → PDF, SVG ve PNG; Visio veya LibreOffice gerekmez.\nEski ikili Visio dosyaları (.vsd) için hâlâ LibreOffice gerekir.",
+ "engine.drawing.description": "Visio çizimleri (VSDX) ve OpenDocument çizimleri (ODG, FODG) → PDF, SVG ve PNG; Visio veya LibreOffice gerekmez.\nXPS ve OpenXPS belgeleri (.xps, .oxps) de.\nEski ikili Visio dosyaları (.vsd) için hâlâ LibreOffice gerekir.",
"engine.model3d.name": "3B modeller (yerleşik)",
"engine.model3d.description": "3B modeller: GLB, glTF, STL, OBJ, 3MF ve PLY arasında dönüştürme; FBX'ten bunların tümüne ve PNG önizlemesine dönüştürme.",
"engine.image3d.name": "Resimden 3B kabartma (yerleşik)",
diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json
index c2dc87ecd..22ff52c33 100644
--- a/src/Filee.App/Assets/i18n/vi.json
+++ b/src/Filee.App/Assets/i18n/vi.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "bỏ qua 1 điều khiển biểu mẫu",
"notice.renderer_left_out.videos": "bỏ qua {0} video",
"notice.renderer_left_out.videos_one": "bỏ qua 1 video",
+ "notice.renderer_left_out.pictures": "bỏ qua {0} hình ảnh",
+ "notice.renderer_left_out.pictures_one": "bỏ qua 1 hình ảnh",
"notice.renderer_left_out.objects_pictured": "{0} đối tượng nhúng được vẽ từ ảnh đã lưu của chúng",
"notice.renderer_left_out.objects_pictured_one": "1 đối tượng nhúng được vẽ từ ảnh đã lưu của nó",
"notice.renderer_left_out.formulas": "{0} công thức được viết dưới dạng văn bản thường",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (tích hợp)",
"engine.gcode.description": "Đường chạy của máy in 3D và máy CNC (G-code) sang PDF, SVG và ảnh, hoặc ảnh xem trước của slicer.",
"engine.drawing.name": "Bản vẽ (tích hợp)",
- "engine.drawing.description": "Bản vẽ Visio (VSDX) và bản vẽ OpenDocument (ODG, FODG) sang PDF, SVG và PNG, không cần Visio hay LibreOffice.\nTệp Visio nhị phân cũ (.vsd) vẫn cần LibreOffice.",
+ "engine.drawing.description": "Bản vẽ Visio (VSDX) và bản vẽ OpenDocument (ODG, FODG) sang PDF, SVG và PNG, không cần Visio hay LibreOffice.\nCả tài liệu XPS và OpenXPS (.xps, .oxps).\nTệp Visio nhị phân cũ (.vsd) vẫn cần LibreOffice.",
"engine.model3d.name": "Mô hình 3D (tích hợp)",
"engine.model3d.description": "Mô hình 3D: GLB, glTF, STL, OBJ, 3MF và PLY chuyển đổi qua lại, FBX sang bất kỳ định dạng nào trong số đó, và ảnh xem trước PNG.",
"engine.image3d.name": "Ảnh sang phù điêu 3D (tích hợp)",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 1289411e3..c69d574b9 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "省略了 1 个表单控件",
"notice.renderer_left_out.videos": "省略了 {0} 个视频",
"notice.renderer_left_out.videos_one": "省略了 1 个视频",
+ "notice.renderer_left_out.pictures": "省略了 {0} 张图片",
+ "notice.renderer_left_out.pictures_one": "省略了 1 张图片",
"notice.renderer_left_out.objects_pictured": "{0} 个嵌入对象按其保存的图片绘制",
"notice.renderer_left_out.objects_pictured_one": "1 个嵌入对象按其保存的图片绘制",
"notice.renderer_left_out.formulas": "{0} 个公式以纯文本显示",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "将 3D 打印机和 CNC 机床的刀路 (G-code) 转为 PDF、SVG 和图片,或使用切片软件保存的预览图。",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "将 Visio 图表(VSDX)和 OpenDocument 绘图(ODG、FODG)转为 PDF、SVG 和 PNG,无需 Visio 或 LibreOffice。\n旧的二进制 Visio 文件(.vsd)仍需 LibreOffice。",
+ "engine.drawing.description": "将 Visio 图表(VSDX)和 OpenDocument 绘图(ODG、FODG)转为 PDF、SVG 和 PNG,无需 Visio 或 LibreOffice。\n也支持 XPS 和 OpenXPS 文档(.xps、.oxps)。\n旧的二进制 Visio 文件(.vsd)仍需 LibreOffice。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,FBX 可转换为其中任意格式,并可生成 PNG 预览。",
"engine.image3d.name": "图片转 3D 浮雕(内置)",
diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json
index 1ff2fe25c..13efccba7 100644
--- a/src/Filee.App/Assets/i18n/zh-TW.json
+++ b/src/Filee.App/Assets/i18n/zh-TW.json
@@ -252,6 +252,8 @@
"notice.renderer_left_out.form_controls_one": "略過了 1 個表單控制項",
"notice.renderer_left_out.videos": "略過了 {0} 個影片",
"notice.renderer_left_out.videos_one": "略過了 1 個影片",
+ "notice.renderer_left_out.pictures": "略過了 {0} 張圖片",
+ "notice.renderer_left_out.pictures_one": "略過了 1 張圖片",
"notice.renderer_left_out.objects_pictured": "{0} 個內嵌物件以其儲存的圖片繪製",
"notice.renderer_left_out.objects_pictured_one": "1 個內嵌物件以其儲存的圖片繪製",
"notice.renderer_left_out.formulas": "{0} 個公式以純文字顯示",
@@ -321,7 +323,7 @@
"engine.gcode.name": "G-code (built-in)",
"engine.gcode.description": "將 3D 印表機和 CNC 機台的刀具路徑 (G-code) 轉為 PDF、SVG 和圖片,或使用切片軟體儲存的預覽圖。",
"engine.drawing.name": "Drawings (built-in)",
- "engine.drawing.description": "將 Visio 圖表(VSDX)和 OpenDocument 繪圖(ODG、FODG)轉為 PDF、SVG 和 PNG,不需 Visio 或 LibreOffice。\n舊的二進位 Visio 檔案(.vsd)仍需 LibreOffice。",
+ "engine.drawing.description": "將 Visio 圖表(VSDX)和 OpenDocument 繪圖(ODG、FODG)轉為 PDF、SVG 和 PNG,不需 Visio 或 LibreOffice。\n也支援 XPS 和 OpenXPS 文件(.xps、.oxps)。\n舊的二進位 Visio 檔案(.vsd)仍需 LibreOffice。",
"engine.model3d.name": "3D models (built-in)",
"engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相轉換,FBX 可轉換為其中任意格式,並可產生 PNG 預覽。",
"engine.image3d.name": "圖片轉 3D 浮雕(內建)",
diff --git a/src/Filee.Core/Formats/FormatFields.cs b/src/Filee.Core/Formats/FormatFields.cs
index e4d7393f6..fa3b90d5e 100644
--- a/src/Filee.Core/Formats/FormatFields.cs
+++ b/src/Filee.Core/Formats/FormatFields.cs
@@ -65,8 +65,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow
(FormatGrade.General,
[
"tiff", "bmp", "ico", "avif", "jxl", "tga", "apng", "jxr", "livp", "exe", "svg", "svgz", "emf", "vsd", "odg", "canvas",
- "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",
+ "docm", "dotx", "dotm", "doc", "odt", "ott", "rtf", "wps", "ofd", "udf", "xps", "abw", "pages", "pub", "eml", "msg",
+ "p7m", "xlsm", "xltx", "xlsb", "xls", "ods", "ots", "tsv", "et", "numbers", "pptm", "potx", "potm", "ppsx", "ppt",
"odp", "otp", "key", "dps", "md", "html", "mhtml", "opml", "json", "xml", "vcf", "ics", "epub", "kepub",
"azw3", "fb2", "cbz", "cbr", "cb7", "cbt", "cbc", "m4v", "mkv", "webm", "avi", "wmv", "mpg", "ts",
"m2ts", "ogv", "m4b", "m4r", "aac", "flac", "ogg", "opus", "wma", "aiff", "weba", "mka", "qta", "7z", "rar",
@@ -80,8 +80,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow
"fodt", "fods", "fodp", "rst", "tex", "org", "adoc", "typ", "mediawiki", "dbk", "ipynb", "textile", "man",
"jsonl", "yaml", "toml", "har", "plist", "htmlz", "txtz", "chm", "dv", "mxf", "cavs", "usm", "m4s", "dav", "nov", "bik",
"h265", "h264", "ac3", "caf", "mp2", "dss", "wv", "tta", "w64", "eac3", "ape", "tak", "dsf", "dff",
- "dts", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "gz", "bz2", "xz", "lz", "lzma", "jar", "zxp", "nupkg", "apks",
- "aab", "msix", "mcpack", "mcaddon", "mcworld", "mctemplate", "mrpack", "cab", "gerber",
+ "dts", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "tzst", "gz", "bz2", "xz", "lz", "lzma", "zst", "jar", "zxp",
+ "nupkg", "apks", "aab", "msix", "mcpack", "mcaddon", "mcworld", "mctemplate", "mrpack", "cab", "gerber",
"cpio", "deb", "rpm", "dwg", "ttf", "otf", "woff", "woff2", "ass", "ssa", "ttml", "scc", "glb", "gltf",
"stl", "obj", "3mf", "ply", "fbx", "gcode", "geojson", "kml", "kmz", "gpx", "shp", "fit", "osm", "xm", "it", "ani", "vtf", "gma", "vpk", "bsp"
]),
@@ -107,8 +107,8 @@ .. Enum.GetValues().Select(category => category.ToString().ToLow
// ODF for version control, man pages, streaming segments, packages and compressed archives.
([
"ppm", "icns", "qoi", "cur", "ani", "xpm", "xbm", "pam", "pfm", "miff", "fodg", "fodt", "fods", "fodp", "man",
- "jsonl", "yaml", "toml", "har", "plist", "m4s", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "gz", "bz2", "xz",
- "lz", "lzma", "jar", "zxp", "nupkg", "apks", "aab", "msix", "cab", "cpio", "deb", "rpm"
+ "jsonl", "yaml", "toml", "har", "plist", "m4s", "tar", "tgz", "tbz2", "txz", "tar7z", "tlz", "tzst", "gz", "bz2",
+ "xz", "lz", "lzma", "zst", "jar", "zxp", "nupkg", "apks", "aab", "msix", "cab", "cpio", "deb", "rpm"
], ["developer"]),
// Markup sources, papers and outlines, maintenance-doc drawings (CGM), Calibre's ebook formats.
(["cgm", "rst", "tex", "org", "adoc", "typ", "mediawiki", "dbk", "textile", "htmlz", "txtz"], ["writing"]),
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index b4c89b00f..c78c4e2d7 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -119,6 +119,8 @@ public static class FormatRegistry
// 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),
+ // XPS and OpenXPS (ECMA-388) fixed-layout documents (#613), read by the built-in XPS reader (drawing engine).
+ new("xps", "XPS", FormatCategory.Document, ["xps", "oxps"], Writable: false),
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),
@@ -143,6 +145,8 @@ public static class FormatRegistry
new("xlsx", "XLSX", FormatCategory.Spreadsheet, ["xlsx"]),
new("xlsm", "XLSM", FormatCategory.Spreadsheet, ["xlsm"]),
new("xltx", "XLTX", FormatCategory.Spreadsheet, ["xltx"]),
+ // Excel binary workbooks, read by the built-in XLSB reader (#1535).
+ new("xlsb", "XLSB", FormatCategory.Spreadsheet, ["xlsb"], Writable: false),
new("xls", "XLS", FormatCategory.Spreadsheet, ["xls"]),
new("xlt", "XLT", FormatCategory.Spreadsheet, ["xlt"]),
new("ods", "ODS", FormatCategory.Spreadsheet, ["ods"]),
@@ -335,12 +339,16 @@ public static class FormatRegistry
new("tar7z", "TAR.7Z", FormatCategory.Archive, ["tar.7z"], Writable: false),
new("tlz", "TAR.LZ", FormatCategory.Archive, ["tar.lz", "tlz"], Writable: false),
new("tz", "TAR.Z", FormatCategory.Archive, ["tar.z", "tz"], Writable: false),
+ // Zstandard (#1646): read only. Writing would add a developer-only output, which docs/FORMAT-RULES.md rule 5
+ // keeps out while the developer field is on by default.
+ new("tzst", "TAR.ZST", FormatCategory.Archive, ["tar.zst", "tzst"], Writable: false),
new("gz", "GZ", FormatCategory.Archive, ["gz"]),
new("bz2", "BZ2", FormatCategory.Archive, ["bz2", "bz"]),
new("xz", "XZ", FormatCategory.Archive, ["xz"]),
new("lz", "LZ", FormatCategory.Archive, ["lz"], Writable: false),
new("lzma", "LZMA", FormatCategory.Archive, ["lzma"], Writable: false),
new("z", "Z", FormatCategory.Archive, ["z"], Writable: false),
+ new("zst", "ZST", FormatCategory.Archive, ["zst"], Writable: false),
new("jar", "JAR", FormatCategory.Archive, ["jar"], Writable: false),
// Adobe extension packages for After Effects, Premiere Pro, Photoshop … (#1382): signed ZIPs. Never a target,
// since installing one needs the signature its developer makes with Adobe's ZXPSignCmd.
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index b591d04c8..e9007b535 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 = 103;
+ public const int CurrentSchemaVersion = 106;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 1a16a004e..c8fe19b25 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -1221,6 +1221,15 @@ public static bool ApplyToLibrary(int from, List presets, ListCompressed single files (no names or folders inside); they convert among each other.
- private static readonly string[] SingleFileSources = ["gz", "bz2", "xz", "lzma", "z", "lz"];
+ private static readonly string[] SingleFileSources = ["gz", "bz2", "xz", "lzma", "z", "lz", "zst"];
private static readonly IReadOnlyList AllEdges = CreateEdges();
diff --git a/src/Filee.Engines/Archives/ArchiveExtractor.cs b/src/Filee.Engines/Archives/ArchiveExtractor.cs
index 7e2a2e62d..6513af2c2 100644
--- a/src/Filee.Engines/Archives/ArchiveExtractor.cs
+++ b/src/Filee.Engines/Archives/ArchiveExtractor.cs
@@ -39,7 +39,7 @@ internal sealed class ArchiveExtractor(SevenZip? sevenZip, Func? s
public static readonly IReadOnlyList BuiltInFormats =
[
"zip", "jar", "zxp", "nupkg", "apks", "aab", "msix", "7z", "rar", "tar", "tgz", "tbz2", "txz", "tar7z", "tz", "tlz",
- "gz", "bz2", "xz", "lzma", "z", "lz", "cpio", "deb", "rpm", "iso", "alz", "egg", "split", "cab", "lha", "arj", "dmg",
+ "tzst", "gz", "bz2", "xz", "lzma", "z", "lz", "zst", "cpio", "deb", "rpm", "iso", "alz", "egg", "split", "cab", "lha", "arj", "dmg",
"img", "gma", "vpk", "bsp",
"mcpack", "mcaddon", "mcworld", "mctemplate", "mrpack",
];
@@ -47,19 +47,19 @@ internal sealed class ArchiveExtractor(SevenZip? sevenZip, Func? s
/// Formats 7-Zip can read too, so it may try again after an in-process reader gave up.
private static readonly HashSet SevenZipAlsoReads =
[
- "zip", "jar", "zxp", "nupkg", "apks", "aab", "msix", "7z", "rar", "tar", "tgz", "tbz2", "txz", "tar7z", "tz", "gz",
- "bz2", "xz", "lzma", "z", "cpio", "deb", "rpm", "iso", "split", "cab", "lha", "arj", "dmg", "img", "mcpack",
+ "zip", "jar", "zxp", "nupkg", "apks", "aab", "msix", "7z", "rar", "tar", "tgz", "tbz2", "txz", "tar7z", "tz", "tzst",
+ "gz", "bz2", "xz", "lzma", "z", "zst", "cpio", "deb", "rpm", "iso", "split", "cab", "lha", "arj", "dmg", "img", "mcpack",
"mcaddon", "mcworld", "mctemplate", "mrpack",
];
/// A TAR inside a compressed stream (or a 7z): unpacking the outer layer yields one .tar file.
- private static readonly HashSet TarWrapped = ["tgz", "tbz2", "txz", "tar7z", "tz", "tlz"];
+ private static readonly HashSet TarWrapped = ["tgz", "tbz2", "txz", "tar7z", "tz", "tlz", "tzst"];
///
/// One compressed stream, no names or sizes to check beforehand (bzip2 states no size, gzip one modulo 4 GiB that
/// its author chose).
///
- private static readonly HashSet SingleStream = ["gz", "bz2", "xz", "lzma", "z", "zst", "tgz", "tbz2", "txz", "tz"];
+ private static readonly HashSet SingleStream = ["gz", "bz2", "xz", "lzma", "z", "zst", "tgz", "tbz2", "txz", "tz", "tzst"];
/// Formats an RPM payload comes in (7-Zip shows it as one compressed CPIO file).
private static readonly HashSet RpmPayload = ["cpio", "gz", "bz2", "xz", "lzma", "z", "zst"];
diff --git a/src/Filee.Engines/Archives/Bzip2BlockEncoder.cs b/src/Filee.Engines/Archives/Bzip2BlockEncoder.cs
index 443d6516d..55a52488f 100644
--- a/src/Filee.Engines/Archives/Bzip2BlockEncoder.cs
+++ b/src/Filee.Engines/Archives/Bzip2BlockEncoder.cs
@@ -192,7 +192,7 @@ private int MoveToFront(ReadOnlySpan bwt, ReadOnlySpan number, int i
run = 0;
}
var j = list[1..inUse].IndexOf(value) + 1;
- list[..j].CopyTo(list[1..]);
+ Bzip2Decoder.MoveUp(list, j);
list[0] = value;
symbols[count++] = (ushort)(j + 1);
frequencies[j + 1]++;
diff --git a/src/Filee.Engines/Archives/Bzip2Decoder.cs b/src/Filee.Engines/Archives/Bzip2Decoder.cs
index fb973b8f4..0f501a14c 100644
--- a/src/Filee.Engines/Archives/Bzip2Decoder.cs
+++ b/src/Filee.Engines/Archives/Bzip2Decoder.cs
@@ -15,7 +15,10 @@
using System.Buffers;
using System.Collections.Concurrent;
+using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
namespace Filee.Engines.Archives;
@@ -299,15 +302,7 @@ private Block ReadBlock(int[] tt, int blockMax, uint? expectedCrc)
if (index >= inUseCount)
throw new InvalidDataException("invalid bzip2 symbol");
var front = mtf[index];
- if (index < 16)
- {
- for (var k = index; k > 0; k--)
- mtf[k] = mtf[k - 1];
- }
- else
- {
- mtf[..index].CopyTo(mtf[1..]);
- }
+ MoveUp(mtf, index);
mtf[0] = front;
var b = seqToUnseq[front];
counts[b]++;
@@ -340,6 +335,25 @@ int NextSymbol()
}
}
+ ///
+ /// Moves the first bytes of the 256-byte move-to-front list one place up (count below
+ /// 256): 16 bytes at a time from the top while there are that many, each load taken before the store above it,
+ /// then byte by byte. One thread decodes the symbols of every block (the inverse transforms run on others), so
+ /// this step sets the pace; Bzip2BlockEncoder uses it too.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static void MoveUp(Span mtf, int count)
+ {
+ if ((uint)count >= (uint)mtf.Length || mtf.Length < 256)
+ throw new ArgumentOutOfRangeException(nameof(count));
+ ref var list = ref MemoryMarshal.GetReference(mtf);
+ var i = count;
+ for (; i >= 16; i -= 16)
+ Vector128.LoadUnsafe(ref list, (nuint)(i - 16)).StoreUnsafe(ref list, (nuint)(i - 15));
+ for (; i > 0; i--)
+ Unsafe.Add(ref list, i) = Unsafe.Add(ref list, i - 1);
+ }
+
///
/// Canonical Huffman decode tables as in the reference bzip2 (limit / base / perm per code length), plus a table
/// of the codes of up to bits found the same way.
diff --git a/src/Filee.Engines/Archives/Bzip2Sort.cs b/src/Filee.Engines/Archives/Bzip2Sort.cs
index d62eb7333..796d5f9fb 100644
--- a/src/Filee.Engines/Archives/Bzip2Sort.cs
+++ b/src/Filee.Engines/Archives/Bzip2Sort.cs
@@ -44,7 +44,11 @@ public static int Transform(ReadOnlySpan block, Span output, Cancell
var at = sa[i];
if (at == start)
origin = row;
- output.Slice(row, repeats).Fill(word[at == 0 ? root - 1 : at - 1]);
+ var last = word[at == 0 ? root - 1 : at - 1];
+ if (repeats == 1)
+ output[row] = last; // nearly every block: no repeating root
+ else
+ output.Slice(row, repeats).Fill(last);
row += repeats;
}
return origin;
diff --git a/src/Filee.Engines/Archives/CompressedFile.cs b/src/Filee.Engines/Archives/CompressedFile.cs
index e11345e2f..ce8f724a0 100644
--- a/src/Filee.Engines/Archives/CompressedFile.cs
+++ b/src/Filee.Engines/Archives/CompressedFile.cs
@@ -1,14 +1,13 @@
-// Unpacks a compressed single file (.gz, .bz2, .xz, .lzma, .Z, .zst and the outer layer of .tar.gz, .tar.bz2, .tar.xz
-// and .tar.Z) in-process: gzip with .NET's own decoder, zstd with SharpCompress (MIT), bzip2, xz, LZMA and Unix
-// compress with Filee's own decoders (Bzip2Decoder, XzReader, LzmaRawReader, UnixCompressStream; bzip2 with
-// randomised blocks from old encoders goes back to SharpCompress). None of these
+// Unpacks a compressed single file (.gz, .bz2, .xz, .lzma, .Z, .zst and the outer layer of .tar.gz, .tar.bz2, .tar.xz,
+// .tar.Z and .tar.zst) in-process: gzip with .NET's own decoder, zstd with SharpCompress (MIT, see ZstdReader), bzip2,
+// xz, LZMA and Unix compress with Filee's own decoders (Bzip2Decoder, XzReader, LzmaRawReader, UnixCompressStream;
+// bzip2 with randomised blocks from old encoders goes back to SharpCompress). None of these
// formats declares a size it must keep (gzip's is the size modulo 4 GiB), so what comes out is counted by
// UnpackBudget against bombs and a full drive.
using System.IO.Compression;
using Filee.Engines.Archives.Lzma;
using SharpCompress.Compressors.BZip2;
-using SharpCompress.Compressors.ZStandard;
using SharpCompressMode = SharpCompress.Compressors.CompressionMode;
namespace Filee.Engines.Archives;
@@ -18,7 +17,7 @@ internal static class CompressedFile
{
/// Formats (and TAR wrappers) reads.
public static readonly IReadOnlySet Formats =
- new HashSet { "gz", "tgz", "bz2", "tbz2", "xz", "txz", "lzma", "z", "tz", "zst" };
+ new HashSet { "gz", "tgz", "bz2", "tbz2", "xz", "txz", "lzma", "z", "tz", "zst", "tzst" };
///
/// The largest dictionary a .lzma (or EGG LZMA) header may name: real files use at most a few hundred MiB. (Filee's
@@ -90,7 +89,8 @@ internal static Stream Open(string format, Stream input, string name, ref long d
case "tz":
return new UnixCompressStream(new NonClosingStream(input));
case "zst":
- return new DecompressionStream(new NonClosingStream(input));
+ case "tzst":
+ return new ZstdReader(input, name);
case "lzma":
{
// "LZMA alone": properties (lc/lp/pb, dictionary size), unpacked size u64 (all ones: not known,
diff --git a/src/Filee.Engines/Archives/Lzma/LzmaDecoder.cs b/src/Filee.Engines/Archives/Lzma/LzmaDecoder.cs
index 7066a4e0f..a8bfdc33f 100644
--- a/src/Filee.Engines/Archives/Lzma/LzmaDecoder.cs
+++ b/src/Filee.Engines/Archives/Lzma/LzmaDecoder.cs
@@ -9,6 +9,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
+using System.Runtime.Intrinsics.X86;
namespace Filee.Engines.Archives.Lzma;
@@ -511,7 +512,9 @@ private int MatchRun(RangeDecoder rc, bool allowEndMarker) where TInput
var pbMask = _pbMask;
ref var probs = ref MemoryMarshal.GetArrayDataReference(_probabilities);
var state = _state;
- uint rep0 = _rep0, rep1 = _rep1, rep2 = _rep2, rep3 = _rep3;
+ // The last distance stays in a register; the three before it, used only by repeats, stay in the fields, so the
+ // coder and the loop's other values have the registers.
+ var rep0 = _rep0;
ref var input = ref MemoryMarshal.GetArrayDataReference(rc.Buffer);
var inEnd = rc.End;
rc.Take(out var range, out var code, out var inPos);
@@ -539,30 +542,30 @@ private int MatchRun(RangeDecoder rc, bool allowEndMarker) where TInput
uint distance;
if (Bit(ref Unsafe.Add(ref probs, IsRepG1At + state), ref range, ref code, ref input, ref inPos, ref inEnd, rc) == 0)
{
- distance = rep1;
+ distance = _rep1;
}
else
{
if (Bit(ref Unsafe.Add(ref probs, IsRepG2At + state), ref range, ref code, ref input, ref inPos, ref inEnd, rc) == 0)
{
- distance = rep2;
+ distance = _rep2;
}
else
{
- distance = rep3;
- rep3 = rep2;
+ distance = _rep3;
+ _rep3 = _rep2;
}
- rep2 = rep1;
+ _rep2 = _rep1;
}
- rep1 = rep0;
+ _rep1 = rep0;
rep0 = distance;
}
}
else
{
- rep3 = rep2;
- rep2 = rep1;
- rep1 = rep0;
+ _rep3 = _rep2;
+ _rep2 = _rep1;
+ _rep1 = rep0;
lengthModel = MatchLengthAt;
}
@@ -623,7 +626,9 @@ private int MatchRun(RangeDecoder rc, bool allowEndMarker) where TInput
// The bytes are copied later, several matches at a time: the copies' sources are far apart in the window
// and mostly not in the cache, and done back to back their loads overlap. Nothing before the copies reads
- // the window (only literals do), so the bytes come out the same.
+ // the window (only literals do), so the bytes come out the same. The source is asked into the cache now,
+ // so it arrives while the next symbols are decoded.
+ Prefetch(window, pos - (int)rep0 - 1, copyLength);
Unsafe.Add(ref deferred, copies * 3) = pos;
Unsafe.Add(ref deferred, copies * 3 + 1) = (int)rep0 + 1;
Unsafe.Add(ref deferred, copies * 3 + 2) = copyLength;
@@ -650,13 +655,27 @@ private int MatchRun(RangeDecoder rc, bool allowEndMarker) where TInput
_pos = pos;
_state = state;
_rep0 = rep0;
- _rep1 = rep1;
- _rep2 = rep2;
- _rep3 = rep3;
rc.Put(range, code, inPos);
return next;
}
+ ///
+ /// A hint to load the source of a copy into the cache (x86; elsewhere nothing). may be
+ /// below zero (the source wrapped to the window's end); only the address is used, nothing is read through it.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static unsafe void Prefetch(byte[] window, int source, int count)
+ {
+ if (!Sse.IsSupported)
+ return;
+ if (source < 0)
+ source += window.Length;
+ // Both addresses stay inside the window (a source that wraps around its end is only hinted up to there).
+ ref var data = ref MemoryMarshal.GetArrayDataReference(window);
+ Sse.Prefetch0(Unsafe.AsPointer(ref Unsafe.Add(ref data, source)));
+ Sse.Prefetch0(Unsafe.AsPointer(ref Unsafe.Add(ref data, Math.Min(source + count - 1, window.Length - 1))));
+ }
+
/// Does the first copies MatchRun put off, in order.
private void CopyDeferred(byte[] window, int count)
{
diff --git a/src/Filee.Engines/Archives/Lzma/MatchFinder.cs b/src/Filee.Engines/Archives/Lzma/MatchFinder.cs
index f3d5eb3d5..fbb2ad515 100644
--- a/src/Filee.Engines/Archives/Lzma/MatchFinder.cs
+++ b/src/Filee.Engines/Archives/Lzma/MatchFinder.cs
@@ -6,7 +6,8 @@
// rebuilds the tree on the way with the cursor as the new root (everything smaller to its left, larger to its
// right). Bytes already known to match on both sides are not compared again, so the longest matches are found in
// far fewer steps than a chain needs; inserting a position costs the same walk.
-// Two chainless tables keyed by the next two and three bytes catch close short matches either way.
+// Two chainless tables keyed by the next two and three bytes catch close short matches either way (the two-byte one
+// a small hash of them with the chain, so the fast level's tables stay in the cache).
//
// The window is one array: the dictionary behind the cursor plus room ahead for new input, slid back when the room
// is used up. Positions are stored as buffer index + an offset that grows with each slide, so the tables never need
@@ -27,6 +28,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics.X86;
namespace Filee.Engines.Archives.Lzma;
@@ -48,7 +50,10 @@ internal sealed class MatchFinder
private readonly int[] _links; // chain: one previous position per slot; tree: left and right child per slot
private readonly int[] _head4;
private readonly int[] _head3 = new int[1 << Hash3Bits];
- private readonly int[] _head2 = new int[1 << 16];
+ // Two-byte table: the bytes themselves with the tree (every pair its slot); a 10-bit hash of them with the chain,
+ // whose small dictionary and many threads want tables that stay in the cache.
+ private const int ChainHash2Bits = 10;
+ private readonly int[] _head2;
private readonly int _hash4Shift;
private readonly int _depth;
private readonly int _nice;
@@ -73,6 +78,7 @@ public MatchFinder(int dictionary, int ahead, int depth, int nice, bool tree)
_mask = dictionary - 1;
_tree = tree;
_links = new int[tree ? 2L * dictionary : dictionary];
+ _head2 = new int[tree ? 1 << 16 : 1 << ChainHash2Bits];
var hashBits = Math.Clamp(BitOperations.Log2((uint)dictionary) - 1, 16, 24);
_head4 = new int[1 << hashBits];
_hash4Shift = 32 - hashBits;
@@ -85,7 +91,7 @@ public MatchFinder(int dictionary, int ahead, int depth, int nice, bool tree)
public static long TableBytes(int dictionary, bool tree)
{
var hashBits = Math.Clamp(BitOperations.Log2((uint)dictionary) - 1, 16, 24);
- return 4L * ((tree ? 2L : 1L) * dictionary + (1 << hashBits) + (1 << Hash3Bits) + (1 << 16));
+ return 4L * ((tree ? 2L : 1L) * dictionary + (1 << hashBits) + (1 << Hash3Bits) + (tree ? 1 << 16 : 1 << ChainHash2Bits));
}
/// Forgets the input and every position entered, keeping the buffer and the tables' memory.
@@ -172,7 +178,9 @@ static void Rebase(int[] table, int delta)
/// bytes, each longer than the one before; returns how many.
///
public int FindAll(int pos, int maxLength, int[] lengths, uint[] distances) =>
- _ahead is { } ahead ? ahead.Take(pos, maxLength, lengths, distances) : Search(pos, maxLength, lengths, distances, out _);
+ _ahead is { } ahead ? ahead.Take(pos, maxLength, lengths, distances)
+ : _tree ? Search(pos, maxLength, lengths, distances, out _)
+ : ChainSearch(pos, maxLength, lengths, distances);
///
/// Starts searching every position from to on
@@ -266,8 +274,10 @@ private void NearSearch(int pos, int maxLength, ref Found found)
}
}
+ /// A search of the binary tree (the hash chain has ).
private int Search(int pos, int maxLength, int[]? lengths, uint[]? distances, out uint distance)
{
+ System.Diagnostics.Debug.Assert(_tree, "the chain searches with ChainSearch");
distance = 0;
System.Diagnostics.Debug.Assert(pos >= _nextInsert, "a position is searched twice");
SkipTo(pos);
@@ -306,33 +316,15 @@ private int Search(int pos, int maxLength, int[]? lengths, uint[]? distances, ou
}
}
- if (_tree)
- {
- TreeWalk(pos, stored, candidate, ref found);
- // The tree compares at most the nice length; a match that long may go on.
- if (found.Best >= _nice && found.Best < maxLength)
- {
- var at = pos - (int)found.Distance - 1;
- var longer = Common(buffer, pos, at, maxLength);
- found.Best = longer;
- if (lengths is not null)
- lengths[found.Count - 1] = longer;
- }
- }
- else
+ TreeWalk(pos, stored, candidate, ref found);
+ // The tree compares at most the nice length; a match that long may go on.
+ if (found.Best >= _nice && found.Best < maxLength)
{
- _links[stored & _mask] = candidate;
- for (var depth = _depth; candidate > 0 && depth > 0 && found.Best < maxLength && found.Best < _nice; depth--)
- {
- var gap = stored - candidate;
- if (gap <= 0 || gap >= _dictionary)
- break;
- var at = candidate - _offset;
- candidate = _links[candidate & _mask];
- if (buffer[at + found.Best] != buffer[pos + found.Best] || buffer[at] != buffer[pos])
- continue;
- found.Offer(Common(buffer, pos, at, maxLength), gap);
- }
+ var at = pos - (int)found.Distance - 1;
+ var longer = Common(buffer, pos, at, maxLength);
+ found.Best = longer;
+ if (lengths is not null)
+ lengths[found.Count - 1] = longer;
}
distance = found.Distance;
@@ -341,6 +333,104 @@ private int Search(int pos, int maxLength, int[]? lengths, uint[]? distances, ou
return lengths is null ? found.Best : found.Count;
}
+ ///
+ /// for the hash chain (the fast level), on its own so its loop keeps its values in registers:
+ /// the same tables, candidates and lists. A candidate is only measured when its two bytes ending at the best length
+ /// so far agree with the cursor's (a match longer than the best has them), which takes one load per candidate.
+ ///
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private int ChainSearch(int pos, int maxLength, int[] lengths, uint[] distances)
+ {
+ System.Diagnostics.Debug.Assert(pos >= _nextInsert, "a position is searched twice");
+ SkipTo(pos);
+ _nextInsert = pos + 1;
+ var buffer = Buffer;
+ if (pos + 4 > Filled || (uint)pos > (uint)(buffer.Length - Math.Max(4, maxLength)))
+ return 0;
+
+ ref var data = ref MemoryMarshal.GetArrayDataReference(buffer);
+ ref var cursor = ref Unsafe.Add(ref data, pos);
+ var value = Unsafe.ReadUnaligned(ref cursor);
+ if (!BitConverter.IsLittleEndian)
+ value = BinaryPrimitives.ReverseEndianness(value);
+ var offset = _offset;
+ var dictionary = _dictionary;
+ var stored = pos + offset;
+ // The hashes are below the tables' sizes by construction: 16 bits, Hash3Bits and the shift for _head4.
+ ref var slot2 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head2), ChainHash2(value));
+ ref var slot3 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head3), (int)(((value & 0xFFFFFF) * 0x9E3779B1u) >> (32 - Hash3Bits)));
+ ref var slot4 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head4), (int)((value * 2654435761u) >> _hash4Shift));
+ var candidate2 = slot2;
+ slot2 = stored;
+ var candidate3 = slot3;
+ slot3 = stored;
+ var candidate = slot4;
+ slot4 = stored;
+ ref var links = ref MemoryMarshal.GetArrayDataReference(_links);
+ var mask = _mask;
+ Unsafe.Add(ref links, stored & mask) = candidate;
+ // The next position is searched or entered right after this one: its table slots (mostly not in the cache)
+ // are asked for now, so they arrive while this chain is walked.
+ if (pos + 5 <= Filled)
+ PrefetchSlots(Unsafe.ReadUnaligned(ref Unsafe.Add(ref cursor, 1)));
+
+ // Candidates lie within the dictionary behind pos, so they and maxLength bytes after them fit the buffer.
+ var best = 1;
+ var count = 0;
+ if (maxLength >= 2)
+ {
+ if (candidate2 > 0 && stored - candidate2 < dictionary && Unsafe.Add(ref data, candidate2 - offset) == cursor)
+ Offer(Common(buffer, pos, candidate2 - offset, maxLength), stored - candidate2, ref best, ref count, lengths, distances);
+ if (candidate3 > 0 && stored - candidate3 < dictionary && best < maxLength && Unsafe.Add(ref data, candidate3 - offset) == cursor)
+ Offer(Common(buffer, pos, candidate3 - offset, maxLength), stored - candidate3, ref best, ref count, lengths, distances);
+ }
+ var stopAt = Math.Min(maxLength, _nice);
+ for (var depth = _depth; candidate > 0 && depth > 0 && best < stopAt; depth--)
+ {
+ var gap = stored - candidate;
+ if (gap <= 0 || gap >= dictionary)
+ break;
+ var at = candidate - offset;
+ candidate = Unsafe.Add(ref links, candidate & mask);
+ if (Unsafe.ReadUnaligned(ref Unsafe.Add(ref data, at + best - 1)) != Unsafe.ReadUnaligned(ref Unsafe.Add(ref cursor, best - 1)))
+ continue;
+ Offer(Common(buffer, pos, at, maxLength), gap, ref best, ref count, lengths, distances);
+ }
+ return best < 2 ? 0 : count;
+ }
+
+ ///
+ /// A hint to load the three- and four-byte table slots of the position whose first bytes are
+ /// (little-endian) into the cache (x86; elsewhere nothing). Nothing is read through the
+ /// addresses.
+ ///
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private unsafe void PrefetchSlots(uint value)
+ {
+ if (!Sse.IsSupported)
+ return;
+ if (!BitConverter.IsLittleEndian)
+ value = BinaryPrimitives.ReverseEndianness(value);
+ Sse.Prefetch0(Unsafe.AsPointer(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head3), (int)(((value & 0xFFFFFF) * 0x9E3779B1u) >> (32 - Hash3Bits)))));
+ Sse.Prefetch0(Unsafe.AsPointer(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head4), (int)((value * 2654435761u) >> _hash4Shift))));
+ }
+
+ /// The chain's two-byte slot for the bytes in the low half of .
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static int ChainHash2(uint value) => (int)(((value & 0xFFFF) * 2654435761u) >> (32 - ChainHash2Bits));
+
+ /// on locals.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static void Offer(int length, int gap, ref int best, ref int count, int[] lengths, uint[] distances)
+ {
+ if (length <= best)
+ return;
+ best = length;
+ lengths[count] = length;
+ distances[count] = (uint)(gap - 1);
+ count++;
+ }
+
///
/// Walks the tree of (the old root) for the position , offering
/// what matches, and makes the root.
@@ -448,11 +538,13 @@ private void Insert(int pos)
var found = new Found(0, null, null);
for (var p = _nextInsert; p < end; p++)
{
+ if (!_tree && p + 8 < end)
+ PrefetchSlots(BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(p + 4)));
var value = BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(p));
var h4 = (int)((value * 2654435761u) >> _hash4Shift);
var h3 = (int)(((value & 0xFFFFFF) * 0x9E3779B1u) >> (32 - Hash3Bits));
var stored = p + _offset;
- Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head2), (int)(value & 0xFFFF)) = stored;
+ Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head2), _tree ? (int)(value & 0xFFFF) : ChainHash2(value)) = stored;
Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head3), h3) = stored;
ref var slot4 = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(_head4), h4);
var candidate = slot4;
diff --git a/src/Filee.Engines/Archives/SevenZipCoders.cs b/src/Filee.Engines/Archives/SevenZipCoders.cs
index c8fc638b3..3af63398a 100644
--- a/src/Filee.Engines/Archives/SevenZipCoders.cs
+++ b/src/Filee.Engines/Archives/SevenZipCoders.cs
@@ -404,7 +404,10 @@ private int Convert(Span data)
///
internal sealed class Bcj2Stream : ReadOnlyDecoderStream
{
- private readonly ByteInput _main;
+ private readonly Stream _main;
+ private readonly byte[] _mainBuffer = new byte[1 << 16];
+ private int _mainPosition;
+ private int _mainEnd;
private readonly ByteInput _call;
private readonly ByteInput _jump;
private readonly RangeDecoder _rc = new();
@@ -418,7 +421,7 @@ internal sealed class Bcj2Stream : ReadOnlyDecoderStream
public Bcj2Stream(Stream main, Stream call, Stream jump, Stream rc, long size)
{
- _main = new ByteInput(main);
+ _main = main;
_call = new ByteInput(call);
_jump = new ByteInput(jump);
_size = size;
@@ -437,17 +440,41 @@ public override int Read(Span buffer)
_done++;
continue;
}
- var b = _main.ReadByte();
- if (b < 0)
- throw new InvalidDataException("the BCJ2 main stream ends too early");
- buffer[n++] = (byte)b;
- _done++;
- if (!IsJump(_previous, (byte)b) || _done == _size)
+ if (_mainPosition == _mainEnd)
{
- _previous = (byte)b;
+ _mainPosition = 0;
+ _mainEnd = Math.Max(0, _main.Read(_mainBuffer, 0, _mainBuffer.Length));
+ if (_mainEnd == 0)
+ throw new InvalidDataException("the BCJ2 main stream ends too early");
+ }
+ // The main stream's bytes up to and with the next opcode that may have a target taken out, in one copy.
+ var run = _mainBuffer.AsSpan(_mainPosition, (int)Math.Min(Math.Min(_mainEnd - _mainPosition, buffer.Length - n), _size - _done));
+ var previous = _previous;
+ var length = 0;
+ var jump = false;
+ while (length < run.Length)
+ {
+ var c = run[length++];
+ if (IsJump(previous, c))
+ {
+ jump = true;
+ previous = c;
+ break;
+ }
+ previous = c;
+ }
+ run[..length].CopyTo(buffer[n..]);
+ n += length;
+ _done += length;
+ _mainPosition += length;
+ var b = run[length - 1];
+ var before = length >= 2 ? run[length - 2] : _previous;
+ if (!jump || _done == _size)
+ {
+ _previous = previous;
continue;
}
- var index = b == 0xE8 ? _previous : b == 0xE9 ? 256 : 257;
+ var index = b == 0xE8 ? before : b == 0xE9 ? 256 : 257;
if (_rc.DecodeBit(ref _probabilities[index]) == 0)
{
_previous = (byte)b;
diff --git a/src/Filee.Engines/Archives/ZstdReader.cs b/src/Filee.Engines/Archives/ZstdReader.cs
new file mode 100644
index 000000000..6d7ce53fa
--- /dev/null
+++ b/src/Filee.Engines/Archives/ZstdReader.cs
@@ -0,0 +1,89 @@
+// Reads Zstandard data (.zst, the outer layer of .tar.zst, zstd RPM payloads) with SharpCompress's decoder (MIT).
+// Frames follow one another (what "zstd -c a b > ab.zst" makes), and skippable frames (magic 0x184D2A5?) are passed
+// over. Filee checks the first frame's magic itself, so a file that isn't zstd is "not an archive" instead of an empty
+// result, and turns the decoder's errors into Filee's messages. A frame whose window is larger than 128 MiB (made with
+// "zstd --long=28" or more) is left to 7-Zip, as the zstd tool refuses it without --memory: the decoder would set the
+// window aside before a single byte shows the file is real.
+
+using System.Buffers.Binary;
+using SharpCompress.Compressors.ZStandard;
+using SharpCompress.Compressors.ZStandard.Unsafe;
+
+namespace Filee.Engines.Archives;
+
+/// A read-only stream of the data inside a zstd file.
+internal sealed class ZstdReader : Stream
+{
+ private const uint FrameMagic = 0xFD2FB528;
+ private const uint SkippableMagic = 0x184D2A50;
+
+ private readonly DecompressionStream _decoder;
+ private readonly string _name;
+
+ /// Reads zstd frames from the current position of (which stays open).
+ public ZstdReader(Stream input, string name)
+ {
+ _name = name;
+ Span magic = stackalloc byte[4];
+ var start = input.Position;
+ if (input.ReadAtLeast(magic, magic.Length, throwOnEndOfStream: false) < magic.Length || !IsFrameStart(magic))
+ throw ArchiveSafety.NotAnArchive(name);
+ input.Position = start;
+ _decoder = new DecompressionStream(new NonClosingStream(input), leaveOpen: false);
+ }
+
+ /// True for the magic of a zstd frame or a skippable frame.
+ internal static bool IsFrameStart(ReadOnlySpan magic)
+ {
+ var value = BinaryPrimitives.ReadUInt32LittleEndian(magic);
+ return value == FrameMagic || (value & 0xFFFFFFF0) == SkippableMagic;
+ }
+
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => false;
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
+
+ public override int Read(Span buffer)
+ {
+ try
+ {
+ return _decoder.Read(buffer);
+ }
+ catch (ZstdException ex) when (ex.Code == ZSTD_ErrorCode.ZSTD_error_frameParameter_windowTooLarge)
+ {
+ throw new NotSupportedException("The zstd window is larger than 128 MiB (made with zstd --long).", ex);
+ }
+ catch (ZstdException ex)
+ {
+ throw ArchiveSafety.Damaged(_name, "zstd: " + ex.Message, ex);
+ }
+ catch (EndOfStreamException ex)
+ {
+ throw ArchiveSafety.Damaged(_name, "the zstd data ends early", ex);
+ }
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ _decoder.Dispose();
+ base.Dispose(disposing);
+ }
+}
diff --git a/src/Filee.Engines/Drawings/DrawingConverter.cs b/src/Filee.Engines/Drawings/DrawingConverter.cs
index c94203c7a..2f1746214 100644
--- a/src/Filee.Engines/Drawings/DrawingConverter.cs
+++ b/src/Filee.Engines/Drawings/DrawingConverter.cs
@@ -6,12 +6,17 @@
// Formats whose reader draws only part of what they hold come with a check (DrawingFormat.FirstUnsupported), which
// FirstUnsupported (ICapabilityCheck) asks: their edges are Checked, so a file the reader can't draw (a binary .vsd)
// keeps the route it would take without this converter.
+//
+// Fixed-layout documents (XPS, DrawingFormat.ReadPages) draw their own pages into the page model; the same outputs
+// are written from those pages, and what the reader left out is named in the file's result (ConversionStep.LeftOut).
using Filee.Core.Conversion;
using Filee.Engines.Infrastructure;
using Filee.Engines.Magick;
+using Filee.Engines.Rendering;
using Filee.Engines.Slides;
using ImageMagick;
+using SkiaSharp;
namespace Filee.Engines.Drawings;
@@ -58,7 +63,15 @@ public Task> ConvertAsync(ConversionStep step, IProgress>(() =>
{
var format = Find(step.From) ?? throw new NotSupportedException($"The drawing converter doesn't read {step.From}.");
- var deck = format.Read(step.InputPath, cancellationToken);
+ if (format.ReadPages is { } open)
+ {
+ using var document = open(step.InputPath, cancellationToken);
+ var written = WriteFixed(step, document, progress, cancellationToken);
+ if (document.LeftOut.Count > 0)
+ step.LeftOut?.Invoke(new LeftOutNotice("notice.renderer_left_out", document.LeftOut));
+ return written;
+ }
+ var deck = format.Read!(step.InputPath, cancellationToken);
if (deck.Slides.Count == 0)
throw new InvalidDataException("The drawing has no pages.");
progress?.Report(0.2);
@@ -77,6 +90,82 @@ public Task> ConvertAsync(ConversionStep step, IProgress _formats.FirstOrDefault(f => f.Id == format);
+ /// A fixed-layout document's pages as a PDF, SVG files or pictures.
+ private static List WriteFixed(ConversionStep step, IFixedPages document, IProgress? progress, CancellationToken cancellationToken)
+ {
+ progress?.Report(0.1);
+ if (step.To == "pdf")
+ {
+ var all = new List(document.Count);
+ for (var i = 0; i < document.Count; i++)
+ {
+ all.Add(document.Page(i, cancellationToken));
+ progress?.Report(0.1 + 0.4 * (i + 1) / document.Count);
+ }
+ if (step.Output.Allocate("pdf") is not { } target)
+ return [];
+ using (var output = File.Create(target))
+ {
+ PdfPageWriter.Write(output, all, new PdfDocumentInfo { Title = document.Title },
+ progress is null ? null : new Progress(p => progress.Report(0.5 + 0.5 * p)), cancellationToken);
+ }
+ return [target];
+ }
+ var pages = PageRange.Parse(step.Preset.Pdf.PageRange, document.Count);
+ var extension = step.To == "svg" ? "svg" : ImageEncoder.OutputFormat(step.To, step.Preset.Image).Extension;
+ var written = new List();
+ var done = 0;
+ foreach (var index in pages)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var page = document.Page(index, cancellationToken);
+ var suffix = pages.Count > 1 ? $"_p{index + 1}" : null;
+ if (step.To == "svg")
+ {
+ var svg = SlideOutput.Svg(page, cancellationToken);
+ if (step.Output.Allocate(extension, suffix) is { } path)
+ {
+ File.WriteAllBytes(path, svg);
+ written.Add(path);
+ }
+ }
+ else
+ {
+ var dpi = Resolution(step, page.Width, page.Height);
+ using var bitmap = page.Render(dpi);
+ if (WritePicture(step, bitmap, dpi, extension, suffix) is { } path)
+ written.Add(path);
+ }
+ done++;
+ progress?.Report(0.1 + 0.9 * done / pages.Count);
+ }
+ return written;
+ }
+
+ ///
+ /// The preset's resolution, lowered so a page of × points fits
+ /// : a large page at a high resolution would take gigabytes.
+ ///
+ private static float Resolution(ConversionStep step, float width, float height)
+ {
+ var dpi = (float)Math.Clamp(step.Preset.Pdf.RenderDpi, 36, 1200);
+ var inches = width / 72.0 * (height / 72.0);
+ return (float)Math.Min(dpi, Math.Sqrt(MaxPagePixels / Math.Max(inches, 1e-6)));
+ }
+
+ /// Writes a page's picture with the image options applied; null when the output was skipped.
+ private static string? WritePicture(ConversionStep step, SKBitmap bitmap, float dpi, string extension, string? suffix)
+ {
+ using var data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
+ using var image = new MagickImage(data.ToArray());
+ image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);
+ ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);
+ if (step.Output.Allocate(extension, suffix) is not { } path)
+ return null;
+ ImageEncoder.WriteImage(image, path, step.To);
+ return path;
+ }
+
private static List WriteSvg(ConversionStep step, SlideDeck deck, IReadOnlyList pages, IProgress? progress, CancellationToken cancellationToken)
{
var written = new List();
@@ -96,26 +185,16 @@ private static List WriteSvg(ConversionStep step, SlideDeck deck, IReadO
private static List WritePictures(ConversionStep step, SlideDeck deck, IReadOnlyList pages, IProgress? progress, CancellationToken cancellationToken)
{
- var dpi = (float)Math.Clamp(step.Preset.Pdf.RenderDpi, 36, 1200);
- // A large page at a high resolution would take gigabytes: the resolution comes down to fit.
- var inches = deck.Width / 72.0 * (deck.Height / 72.0);
- dpi = (float)Math.Min(dpi, Math.Sqrt(MaxPagePixels / Math.Max(inches, 1e-6)));
+ var dpi = Resolution(step, deck.Width, deck.Height);
var (_, extension) = ImageEncoder.OutputFormat(step.To, step.Preset.Image);
var written = new List();
var done = 0;
foreach (var bitmap in SlideOutput.ToBitmaps(deck, dpi, pages, cancellationToken))
{
using (bitmap)
- using (var data = bitmap.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100))
- using (var image = new MagickImage(data.ToArray()))
{
- image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);
- ImageEncoder.ApplyOptions(image, step.Preset.Image, step.To);
- if (step.Output.Allocate(extension, pages.Count > 1 ? $"_p{pages[done] + 1}" : null) is { } path)
- {
- ImageEncoder.WriteImage(image, path, step.To);
+ if (WritePicture(step, bitmap, dpi, extension, pages.Count > 1 ? $"_p{pages[done] + 1}" : null) is { } path)
written.Add(path);
- }
}
done++;
progress?.Report(0.2 + 0.8 * done / pages.Count);
diff --git a/src/Filee.Engines/Drawings/DrawingFormats.cs b/src/Filee.Engines/Drawings/DrawingFormats.cs
index 19d8b25e3..6aab66c51 100644
--- a/src/Filee.Engines/Drawings/DrawingFormats.cs
+++ b/src/Filee.Engines/Drawings/DrawingFormats.cs
@@ -2,22 +2,51 @@
// into the slide model (one slide per page, the page's size as the slide's) and, when the reader draws only part of
// what the format can hold, a check that names the first thing it can't draw (once the converter's edges are Checked,
// see DrawingConverter, such a file keeps the route it would take without the converter, LibreOffice Draw). The
-// readers add their line here: VSDX (Visio/), ODG / FODG (Odf/Draw).
+// readers add their line here: VSDX (Visio/), ODG / FODG (Odf/Draw), XPS / OpenXPS (Xps/).
+//
+// Fixed-layout documents (XPS) are not slides: their reader draws pages straight into the page model (IFixedPages).
+using Filee.Core.Conversion;
using Filee.Engines.Odf.Draw;
+using Filee.Engines.Rendering;
using Filee.Engines.Slides;
using Filee.Engines.Visio;
+using Filee.Engines.Xps;
namespace Filee.Engines.Drawings;
/// A drawing format the converter reads.
/// The format id (FormatRegistry).
-/// Reads a file into pages; refuses a damaged or hostile one with InvalidDataException or the document limits' error.
+///
+/// Reads a file into pages; refuses a damaged or hostile one with InvalidDataException or the document limits' error.
+/// Null for a format read by .
+///
/// The first thing in a file the reader can't draw, or null; null when it draws everything.
internal sealed record DrawingFormat(
string Id,
- Func Read,
- Func? FirstUnsupported = null);
+ Func? Read,
+ Func? FirstUnsupported = null)
+{
+ /// Opens a fixed-layout document whose pages its reader draws itself (instead of ).
+ public Func? ReadPages { get; init; }
+}
+
+///
+/// A fixed-layout document opened for drawing: its pages are read and drawn when asked for, so pictures of a few pages
+/// don't read the rest.
+///
+internal interface IFixedPages : IDisposable
+{
+ int Count { get; }
+
+ string? Title { get; }
+
+ /// Page drawn into the page model.
+ PageContent Page(int index, CancellationToken cancellationToken = default);
+
+ /// What the pages drawn so far left out (pictures that can't be decoded), for the file's result.
+ IReadOnlyList LeftOut { get; }
+}
internal static class DrawingFormats
{
@@ -29,6 +58,8 @@ internal static class DrawingFormats
// OpenDocument drawings, packaged and flat; charts, OLE objects and 3D scenes are left to LibreOffice Draw.
new("odg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)),
new("fodg", (path, token) => OdfDrawReader.Read(path, cancellationToken: token), path => OdfDrawReader.FirstUnsupported(path)),
+ // XPS and OpenXPS documents (.xps, .oxps): Filee's own reader draws every page.
+ new("xps", null) { ReadPages = (path, token) => XpsDocument.Open(path, token) },
];
/// What every drawing format is converted to.
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index 867ac31fb..00856d175 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -5,6 +5,8 @@
Filee.Engines
+
+ true
diff --git a/src/Filee.Engines/Hwp/HwpTextConverter.cs b/src/Filee.Engines/Hwp/HwpTextConverter.cs
index c429f5abe..35649f396 100644
--- a/src/Filee.Engines/Hwp/HwpTextConverter.cs
+++ b/src/Filee.Engines/Hwp/HwpTextConverter.cs
@@ -7,7 +7,8 @@
//
// 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.
+// wraps long lines and loses the indentation and the empty lines, or through the HWPX writer. Word documents (DOCX and
+// its macro-enabled and template variants, Word 97–2003 DOC, DOT and WPS) and ODT go the same way.
using System.Text;
using Filee.Core.Conversion;
@@ -18,8 +19,8 @@
namespace Filee.Engines.Hwp;
-/// Writes the text of HWP and HWPX documents as TXT, Markdown or HTML, and of RTF documents as TXT.
-public sealed class HwpTextConverter : IConverter
+/// Writes the text of HWP and HWPX documents as TXT, Markdown or HTML, and of Word, ODT and RTF as TXT.
+public sealed class HwpTextConverter : IConverter, ICapabilityCheck
{
/// The engine's id; settings that named Unhwp ("unhwp", the engine this replaced) are moved to it.
public const string EngineId = "hwp-text";
@@ -38,9 +39,24 @@ public sealed class HwpTextConverter : IConverter
// 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),
+ // Word and ODT, direct only as well. LibreOffice's edge for them is its fallback (25), so the cost sits between:
+ // 24 + 4 is cheaper than the renderer's PDF and its text (29) and the routes through Pandoc's Markdown (29) or
+ // the HWPX writer (32), and dearer than LibreOffice moved to the top of the engine list (25 + 0), which keeps
+ // the conversion it had there. The DOC reader checks each file (a Word 6.0 / 95 file goes another way).
+ .. LineFormats.Where(f => f != "rtf")
+ .Select(f => new ConversionEdge(f, "txt", 24, DirectOnly: true, Checked: DocumentReaders.Checked(f))),
];
- public EngineStatus GetStatus() => EngineStatus.Available("HWP, HWPX → TXT, Markdown, HTML; RTF → TXT", EngineVersions.BuiltIn);
+ ///
+ /// Word processor documents, whose TXT is a line per paragraph () as the
+ /// word processor itself saves plain text.
+ ///
+ internal static readonly string[] LineFormats = ["rtf", "docx", "docm", "dotx", "dotm", "doc", "dot", "wps", "odt"];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("HWP, HWPX → TXT, Markdown, HTML; Word, ODT, RTF → TXT", EngineVersions.BuiltIn);
+
+ /// A Word 6.0 / 95 or Works file with a .doc or .wps name, which the DOC reader doesn't read.
+ public string? FirstUnsupported(string sourcePath, string sourceFormat) => DocumentReaders.Unsupported(sourcePath, sourceFormat);
public async Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken)
{
@@ -54,7 +70,7 @@ public async Task> ConvertAsync(ConversionStep step, IProg
return [];
var content = step.To switch
{
- "txt" when step.From == "rtf" => PlainTextWriter.WriteLines(document),
+ "txt" when LineFormats.Contains(step.From) => 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 1898362c5..8bd797608 100644
--- a/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/DocumentReaders.cs
@@ -48,6 +48,7 @@ internal static class DocumentReaders
["xlsx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
["xlsm"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
["xltx"] = (path, _) => SheetDocument.Build(XlsxReader.Read(path)),
+ [XlsbReader.Format] = (path, _) => SheetDocument.Build(XlsbReader.Read(path)),
["csv"] = (path, _) => SheetDocument.Build(CsvFormat.Read(path)),
["tsv"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "tsv")),
["xls"] = (path, _) => SheetDocument.Build(SpreadsheetConverter.Read(path, "xls")),
diff --git a/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs b/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
index 5a6cd618d..dcbe49e5e 100644
--- a/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/PlainTextWriter.cs
@@ -1,7 +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. 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.
+// HWP / HWPX → TXT. WriteLines is a word processor's "plain text" instead (RTF, Word and ODT → 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;
@@ -126,8 +126,27 @@ private static void Blocks(List blocks, StringBuilder sb, List n
private static bool IsCode(HParagraph paragraph) =>
paragraph.Inlines.Count > 0 && paragraph.Inlines.All(i => i is HText { Format.Shade: HtmlReader.CodeShade });
- 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));
+ /// A cell's text on one line: its paragraphs, and the cells of a table inside it, separated by a space.
+ private static string Cell(HCell cell, List notes) => string.Join(" ", CellTexts(cell.Blocks, notes));
+
+ private static IEnumerable CellTexts(List blocks, List notes)
+ {
+ foreach (var block in blocks)
+ {
+ IEnumerable texts = block switch
+ {
+ HParagraph p => [Inlines(p.Inlines, notes).Replace('\n', ' ').Replace('\t', ' ')],
+ // A table in the cell (Word, ODT and RTF nest them); Nesting.Limit bounds how deep this goes.
+ HTable table => table.Rows.SelectMany(r => r.Cells).SelectMany(c => CellTexts(c.Blocks, notes)),
+ _ => [],
+ };
+ foreach (var text in texts)
+ {
+ if (text.Length > 0)
+ yield return text;
+ }
+ }
+ }
///
/// The text of inlines, lines separated by '\n' (the callers write the line ends), without the white space at the
diff --git a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
index 995972b1a..ab9160a77 100644
--- a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
@@ -14,7 +14,7 @@ internal static class SheetDocument
{
/// The formats DocumentReaders reads into a document through .
public static readonly IReadOnlySet SourceFormats =
- new HashSet(["xlsx", "xlsm", "xltx", "csv", "tsv", "xls", "xlt", "ods"], StringComparer.OrdinalIgnoreCase);
+ new HashSet(["xlsx", "xlsm", "xltx", "xlsb", "csv", "tsv", "xls", "xlt", "ods"], StringComparer.OrdinalIgnoreCase);
/// Largest table written; bigger sheets are cut with a note (a PDF of 100 000 rows helps nobody).
private const int MaxRows = 5000;
@@ -53,8 +53,9 @@ private static HSection Section(Worksheet sheet, bool withTitle)
columns = columns.Take(MaxColumns).ToList();
// Excel widths count digits of Calibri 11 (7 px each + 5 px padding). The 한글 fonts that render the table have
- // wider digits, so a character gets 8 px plus room for the cell margins; 75 HWPUNIT per pixel.
- var widths = columns.Select(c => (int)Math.Round((sheet.ColumnWidth(c) * 8 + 10) * 75)).ToArray();
+ // wider digits, so a character gets 8 px plus room for the cell margins; 75 HWPUNIT per pixel. Excel's widest
+ // column is 255 characters: a file that claims more can't overflow the table's width.
+ var widths = columns.Select(c => (int)Math.Round((Math.Clamp(sheet.ColumnWidth(c), 0, 255) * 8 + 10) * 75)).ToArray();
var total = Math.Max(1, widths.Sum());
var landscape = total > A4Short - 2 * Margin;
var page = landscape
diff --git a/src/Filee.Engines/Infrastructure/ComplexScripts.cs b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
index b760b74c8..79636104d 100644
--- a/src/Filee.Engines/Infrastructure/ComplexScripts.cs
+++ b/src/Filee.Engines/Infrastructure/ComplexScripts.cs
@@ -358,6 +358,9 @@ static bool InWord(string name, int before, int after)
{
try
{
+ // Excel binary workbooks keep their text in records: their cells, as the built-in reader reads them.
+ if (format == XlsbReader.Format)
+ return FindInCells(XlsbReader.Read(path), classifier, skipBelow);
if (IsZip(path))
return FindInPackage(path, format == "hwp" ? "hwpx" : format, classifier, skipBelow); // an .hwp that is HWPX
// HWP 5.0 is binary: its records written out as the HWPX package 한글 saves, whose sections are scanned.
diff --git a/src/Filee.Engines/Magick/ImageReader.cs b/src/Filee.Engines/Magick/ImageReader.cs
index e4be76847..e4d65a310 100644
--- a/src/Filee.Engines/Magick/ImageReader.cs
+++ b/src/Filee.Engines/Magick/ImageReader.cs
@@ -27,7 +27,7 @@ internal static class ImageReader
/// Reads as format . Layered formats come back as a single,
/// flattened image; other multi-frame formats (TIFF pages, GIF frames, ICO sizes) keep all frames.
///
- /// Stops the merge of a GIMP file between rows; other formats are read at once.
+ /// Stops the merge of a GIMP file between rows and the drawing of an EMF / WMF between records; other formats are read at once.
public static MagickImageCollection Read(string path, string formatId, Preset preset,
CancellationToken cancellationToken = default)
{
@@ -51,7 +51,7 @@ public static MagickImageCollection Read(string path, string formatId, Preset pr
return ReadPackaged(ProgramIcon.Read(path), "ico", preset);
if (formatId == "fits")
return [FitsRendering.ToMagick(Fits.Read(path), preset.Image.FitsDebayer)];
- if (formatId is "emf" or "wmf" && ReadMetafile(path, preset) is { } metafile)
+ if (formatId is "emf" or "wmf" && ReadMetafile(path, preset, cancellationToken) is { } metafile)
return metafile;
var images = new MagickImageCollection();
@@ -106,12 +106,12 @@ public static MagickImageCollection Read(string path, string formatId, Preset pr
/// a transparent background. Null for an EMF+ only file on Windows, which ImageMagick then reads through GDI+;
/// elsewhere such a file fails with the renderer's reason.
///
- private static MagickImageCollection? ReadMetafile(string path, Preset preset)
+ private static MagickImageCollection? ReadMetafile(string path, Preset preset, CancellationToken cancellationToken)
{
var dpi = Math.Max(MinimumMetafileDpi, Math.Clamp(preset.Pdf.RenderDpi, 36, 1200));
try
{
- var (bitmap, used) = Metafile.Render(path, dpi);
+ var (bitmap, used) = Metafile.Render(path, dpi, cancellationToken: cancellationToken);
using (bitmap)
return [SvgRenderer.ToMagick(bitmap, used)];
}
diff --git a/src/Filee.Engines/Metafiles/Dib.cs b/src/Filee.Engines/Metafiles/Dib.cs
index a21e40b0f..6ba6288af 100644
--- a/src/Filee.Engines/Metafiles/Dib.cs
+++ b/src/Filee.Engines/Metafiles/Dib.cs
@@ -1,8 +1,9 @@
// Device-independent bitmaps as metafiles carry them ([MS-WMF] 2.2.2.9 DeviceIndependentBitmap): a BITMAPCOREHEADER
// or BITMAPINFOHEADER (and its V4 / V5 extensions), a colour table, and the pixels in rows padded to 32 bits, bottom-up
// unless the height is negative. 1, 4, 8, 16, 24 and 32 bits per pixel, uncompressed, RLE4 / RLE8 and bit fields;
-// JPEG and PNG pixels are decoded by Skia. The pixel count is checked against the metafile's budget before anything is
-// allocated.
+// JPEG and PNG pixels are decoded by Skia. The pixel count is checked against the metafile's budget, and the pixel data
+// against the size the header gives, before anything is allocated; the pixels are then decoded straight into the
+// bitmap Skia draws from, the one copy of them.
using System.Buffers.Binary;
using System.Runtime.InteropServices;
@@ -59,23 +60,30 @@ internal static class Dib
if (header.Compression is Jpeg or Png)
return Encoded(bits, budget);
+ var runLength = header.Compression == Rle8 && header.BitCount == 8 || header.Compression == Rle4 && header.BitCount == 4;
+ if (!runLength && header.Compression is not (Rgb or BitFields or AlphaBitFields))
+ return null; // CMYK or an unknown compression: nothing GDI would draw either
budget.Bitmap(width, height);
var colors = ColorTable(info, header, options);
- var pixels = new uint[(long)width * height]; // BGRA, top-down
+ if (!runLength)
+ CheckUncompressed(bits, header, width, height);
+
+ var alphaType = options.Alpha && header.BitCount == 32 ? SKAlphaType.Premul : SKAlphaType.Unpremul;
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Bgra8888, alphaType));
+ if (bitmap.GetPixels() == IntPtr.Zero)
+ throw new InvalidOperationException("Skia could not allocate the bitmap.");
+ if (bitmap.RowBytes != width * 4)
+ throw new InvalidOperationException("Skia gave the bitmap unexpected row bytes.");
+ var pixels = MemoryMarshal.Cast(bitmap.GetPixelSpan()); // BGRA, top-down
var bottomUp = header.Height > 0;
- switch (header.Compression)
+ if (runLength)
{
- case Rle8 when header.BitCount == 8:
- case Rle4 when header.BitCount == 4:
- RunLength(bits, header.Compression == Rle4, width, height, bottomUp, colors, pixels);
- break;
- case Rgb:
- case BitFields:
- case AlphaBitFields:
- Uncompressed(bits, header, info, colors, options, width, height, bottomUp, pixels);
- break;
- default:
- return null; // CMYK or an unknown compression: nothing GDI would draw either
+ pixels.Clear(); // pixels the runs skip stay transparent
+ RunLength(bits, header.Compression == Rle4, width, height, bottomUp, colors, pixels);
+ }
+ else
+ {
+ Uncompressed(bits, header, info, colors, options, width, height, bottomUp, pixels);
}
if (options.TransparentColor is { } key)
@@ -87,13 +95,6 @@ internal static class Dib
pixels[i] = 0;
}
}
-
- var alphaType = options.Alpha && header.BitCount == 32 ? SKAlphaType.Premul : SKAlphaType.Unpremul;
- using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Bgra8888, alphaType));
- var bytes = MemoryMarshal.AsBytes(pixels.AsSpan());
- if (bitmap.RowBytes != width * 4)
- throw new InvalidOperationException("Skia gave the bitmap unexpected row bytes.");
- Marshal.Copy(bytes.ToArray(), 0, bitmap.GetPixels(), bytes.Length);
bitmap.SetImmutable();
var image = SKImage.FromBitmap(bitmap) ?? throw new InvalidOperationException("Skia could not make an image of the bitmap.");
return new DibImage(image, header.BitCount == 1);
@@ -140,15 +141,25 @@ private static SKColor[] ColorTable(ReadOnlySpan info, Header header, DibO
return colors;
}
- private static void Uncompressed(ReadOnlySpan bits, Header header, ReadOnlySpan info, SKColor[] colors, DibOptions options,
- int width, int height, bool bottomUp, uint[] pixels)
+ /// Refuses uncompressed pixels of a depth GDI doesn't have, or fewer than the header's size needs.
+ private static void CheckUncompressed(ReadOnlySpan bits, Header header, int width, int height)
{
var bpp = header.BitCount;
if (bpp is not (1 or 2 or 4 or 8 or 16 or 24 or 32))
throw new DibFormatException($"has a bitmap of {bpp} bits per pixel");
- var stride = ((long)width * bpp + 31) / 32 * 4;
- if (stride * height > bits.Length)
+ if (Stride(width, bpp) * height > bits.Length)
throw new DibFormatException($"has a bitmap of {width} × {height} pixels whose pixel data is cut off");
+ }
+
+ /// Bytes of one row of pixels, padded to 32 bits.
+ private static long Stride(int width, int bpp) => ((long)width * bpp + 31) / 32 * 4;
+
+ /// Uncompressed pixels, once passed them.
+ private static void Uncompressed(ReadOnlySpan bits, Header header, ReadOnlySpan info, SKColor[] colors, DibOptions options,
+ int width, int height, bool bottomUp, Span pixels)
+ {
+ var bpp = header.BitCount;
+ var stride = Stride(width, bpp);
var palette = new uint[colors.Length];
for (var i = 0; i < colors.Length; i++)
palette[i] = Bgra(colors[i]);
@@ -217,13 +228,13 @@ private static uint Channel(uint value, uint mask)
}
/// RLE8 and RLE4 ([MS-WMF] 3.1.6): runs and literal groups, end of line, end of bitmap and deltas.
- private static void RunLength(ReadOnlySpan bits, bool four, int width, int height, bool bottomUp, SKColor[] colors, uint[] pixels)
+ private static void RunLength(ReadOnlySpan bits, bool four, int width, int height, bool bottomUp, SKColor[] colors, Span pixels)
{
var palette = new uint[colors.Length];
for (var i = 0; i < colors.Length; i++)
palette[i] = Bgra(colors[i]);
int x = 0, y = 0, at = 0;
- void Put(int index)
+ void Put(Span pixels, int index)
{
if (x < width && y < height)
pixels[(bottomUp ? height - 1 - y : y) * width + x] = palette[index % palette.Length];
@@ -236,7 +247,7 @@ void Put(int index)
if (count > 0)
{
for (var i = 0; i < count; i++)
- Put(four ? (i % 2 == 0 ? value >> 4 : value & 0x0F) : value);
+ Put(pixels, four ? (i % 2 == 0 ? value >> 4 : value & 0x0F) : value);
continue;
}
switch (value)
@@ -259,7 +270,7 @@ void Put(int index)
if (at + bytes > bits.Length)
throw new DibFormatException("has a run-length bitmap that is cut off");
for (var i = 0; i < value; i++)
- Put(four ? (i % 2 == 0 ? bits[at + i / 2] >> 4 : bits[at + i / 2] & 0x0F) : bits[at + i]);
+ Put(pixels, four ? (i % 2 == 0 ? bits[at + i / 2] >> 4 : bits[at + i / 2] & 0x0F) : bits[at + i]);
at += (bytes + 1) & ~1;
break;
}
diff --git a/src/Filee.Engines/Metafiles/Metafile.cs b/src/Filee.Engines/Metafiles/Metafile.cs
index 90dd5e4f5..5d3893af6 100644
--- a/src/Filee.Engines/Metafiles/Metafile.cs
+++ b/src/Filee.Engines/Metafiles/Metafile.cs
@@ -212,6 +212,7 @@ public static (SKBitmap Bitmap, float Dpi) Render(byte[] data, float dpi, Metafi
if (longEdge > 0)
scale = Math.Min(scale, Math.Min(MaximumLongEdge / longEdge, MathF.Sqrt(MaximumPixels / Math.Max(1e-6f, size.Width * size.Height))));
using var drawing = Draw(data, scale, limits, cancellationToken);
+ cancellationToken.ThrowIfCancellationRequested();
return (Rasterize(drawing, scale), scale * 72);
}
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index 95fc48b9f..17af6d673 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -51,7 +51,7 @@ public sealed class LibreOfficeConverter : IConverter
// LibreOffice 26.2: the DocumentService of each type's preferred import filter). ClarisWorks / AppleWorks files can
// also be spreadsheets or drawings; they are taken as word processor files, the common case.
private static readonly string[] WriterImport = ["dot", "wps", "wpd", "lwp", "abw", "pages", "sdw", "cwk", "mcw", "602", "psw"];
- private static readonly string[] CalcImport = ["et", "numbers", "sdc", "fods"];
+ private static readonly string[] CalcImport = ["et", "numbers", "sdc", "fods", "xlsb"];
/// "sda" also covers .sdd: StarDraw files (.sda) open in Draw, StarImpress files (.sdd) in Impress.
private static readonly string[] ImpressImport = ["key", "dps", "sda", "fodp"];
@@ -257,7 +257,7 @@ internal static Func OutputComplete(string outDir)
///
private static string FirstPage(ConversionStep step)
{
- using var source = PdfReader.Open(step.InputPath, PdfDocumentOpenMode.Import);
+ using var source = PdfObjectNesting.Open(step.InputPath, PdfDocumentOpenMode.Import);
var pages = PageRange.Parse(step.Preset.Pdf.PageRange, source.PageCount);
if (pages.Count == 0)
throw new InvalidOperationException("The PDF has no pages in the selected range.");
diff --git a/src/Filee.Engines/Office/Ooxml/OpcPackage.cs b/src/Filee.Engines/Office/Ooxml/OpcPackage.cs
index afa7a74fb..3755c91a1 100644
--- a/src/Filee.Engines/Office/Ooxml/OpcPackage.cs
+++ b/src/Filee.Engines/Office/Ooxml/OpcPackage.cs
@@ -76,6 +76,19 @@ private XDocument Load(ZipArchiveEntry entry)
return copy.Length > max ? null : copy.ToArray();
}
+ ///
+ /// A binary part to read from start to end (an XLSB record stream), counted against the package's limits while it
+ /// is read; null when it doesn't exist.
+ ///
+ public Stream? OpenPart(string partPath)
+ {
+ if (Entry(partPath) is not { } entry)
+ return null;
+ if (_limited is not null)
+ return _limited.Open(entry);
+ return entry.Open();
+ }
+
/// The main part (target of the package's officeDocument relationship), e.g. xl/workbook.xml.
public string? MainPartPath =>
Relationships("").Values.FirstOrDefault(r => r.Type.EndsWith("/officeDocument", StringComparison.Ordinal)).Target;
diff --git a/src/Filee.Engines/Office/SheetPrintConverter.cs b/src/Filee.Engines/Office/SheetPrintConverter.cs
index cb556fc49..03768498f 100644
--- a/src/Filee.Engines/Office/SheetPrintConverter.cs
+++ b/src/Filee.Engines/Office/SheetPrintConverter.cs
@@ -1,4 +1,4 @@
-// XLSX (and XLSM / XLTX), XLS (and XLT) and ODS → PDF printed the way Excel prints them, without Excel or LibreOffice:
+// XLSX (and XLSM / XLTX), XLSB, XLS (and XLT) and ODS → PDF printed the way Excel prints them, without Excel or LibreOffice:
// the built-in readers (Office/Sheets) keep each sheet's page setup, and SheetPrinter lays the pages out with Excel's
// page logic and writes them with the PDF writer of the Filee renderer. CSV and TSV have no page setup and keep their
// route through the HWPX writer (each sheet fitted to the page width).
@@ -28,7 +28,7 @@ public sealed class SheetPrintConverter : IConverter
/// Shown with a workbook printed without what named.
internal const string LeftOutNotice = "notice.sheet_objects_left_out";
- private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xls", "xlt", "ods"];
+ private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xlsb", "xls", "xlt", "ods"];
public string Id => "sheet-print";
public string DisplayName => "Spreadsheet printing (built-in)";
@@ -42,7 +42,7 @@ public sealed class SheetPrintConverter : IConverter
///
internal Func?, CancellationToken, Task>?>? Fallback { get; set; }
- public EngineStatus GetStatus() => EngineStatus.Available("XLSX, XLS, ODS → PDF", EngineVersions.BuiltIn);
+ public EngineStatus GetStatus() => EngineStatus.Available("XLSX, XLSB, XLS, ODS → PDF", EngineVersions.BuiltIn);
/// Gives the sheet printer among LibreOffice, when it is there, for what it doesn't draw.
internal static IReadOnlyList WithFallback(IReadOnlyList converters)
diff --git a/src/Filee.Engines/Office/Sheets/NumberFormatter.cs b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
index 2cbc8521a..15bd9461b 100644
--- a/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
+++ b/src/Filee.Engines/Office/Sheets/NumberFormatter.cs
@@ -25,11 +25,20 @@ internal sealed class NumberFormatter(bool date1904 = false)
/// 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)
+ internal static string ShortDate(CultureInfo culture) => ExcelShortDate(culture) ?? IsoDate;
+
+ ///
+ /// True when is the PC's short date (format 14 as this PC shows it), so a writer can store
+ /// it as format 14 and Excel shows the reader's own short date. Not the ISO date this PC falls back to.
+ ///
+ public static bool IsShortDate(string code) => ExcelShortDate(CultureInfo.CurrentCulture) == code;
+
+ /// , or null where the culture's short date can't be written as an Excel format.
+ private static string? ExcelShortDate(CultureInfo culture)
{
var format = culture.DateTimeFormat;
if (format.Calendar is not GregorianCalendar)
- return IsoDate;
+ return null;
var pattern = format.ShortDatePattern;
var code = new System.Text.StringBuilder();
for (var i = 0; i < pattern.Length;)
@@ -56,7 +65,7 @@ internal static string ShortDate(CultureInfo culture)
{
var end = pattern.IndexOf(c, i + 1);
if (end < 0)
- return IsoDate;
+ return null;
Literal(code, pattern[(i + 1)..end]);
i = end + 1;
continue;
@@ -67,7 +76,7 @@ internal static string ShortDate(CultureInfo culture)
continue;
default:
if (char.IsLetter(c))
- return IsoDate; // an era, a day or month name: not a short date Excel would show
+ return null; // an era, a day or month name: not a short date Excel would show
Literal(code, new string(c, run));
break;
}
diff --git a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs
index 994ce977a..67f8a3ebc 100644
--- a/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs
+++ b/src/Filee.Engines/Office/Sheets/SheetCapabilities.cs
@@ -6,6 +6,7 @@
// SmartArt, embedded objects, ink, text in shapes, freeform shapes, ...); form controls (ctrlProp parts, or legacy
// VML controls); embedded OLE objects. Comments are not printed unless the page setup asks for them, and are
// left out of the check.
+// * XLSB: the same relationships as XLSX; the visible sheets come from the binary workbook part.
// * XLS: the reader takes no drawing at all, so every object of a visible sheet is named by its OBJ record's type
// (charts, pictures, text boxes, shapes, form controls; comments aside), and a visible chart sheet.
// * ODS: the reader takes no drawing either: pictures, charts and other embedded objects, shapes, text boxes and
@@ -39,7 +40,7 @@ internal static partial class SheetCapabilities
private const long MaxVmlBytes = 16L * 1024 * 1024;
/// The first thing in the workbook the sheet printer doesn't draw; null when it draws everything (or can't read the file).
- /// Format id: xlsx, xlsm, xltx, xls, xlt or ods.
+ /// Format id: xlsx, xlsm, xltx, xlsb, xls, xlt or ods.
public static string? FirstUnsupported(string path, string format)
{
try
@@ -47,6 +48,8 @@ internal static partial class SheetCapabilities
return format switch
{
"xlsx" or "xlsm" or "xltx" => Xlsx(path),
+ // An Excel 97–2003 workbook with an .xlsb name is read as one (XlsbReader).
+ XlsbReader.Format => IsZip(path) ? Xlsb(path) : XlsLayout.FirstObject(path),
// Web apps often save XLSX with an .xls name; the XLSX reader reads those (XlsReader).
"xls" or "xlt" => IsZip(path) ? Xlsx(path) : XlsLayout.FirstObject(path),
"ods" => Ods(path),
@@ -79,27 +82,51 @@ private static bool IsZip(string path)
var relationships = package.Relationships(workbookPath);
foreach (var sheet in workbook.Element(S + "sheets")?.Elements(S + "sheet") ?? [])
{
- if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden"
- || (string?)sheet.Attribute(R + "id") is not { } id || !relationships.TryGetValue(id, out var relationship) || relationship.External)
+ if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden")
continue;
- if (relationship.Type.EndsWith("/chartsheet", StringComparison.Ordinal))
- return "charts";
- if (!relationship.Type.EndsWith("/worksheet", StringComparison.Ordinal))
- continue;
- // The sheet's parts tell what it holds, without reading its cells.
- foreach (var part in package.Relationships(relationship.Target).Values.Where(r => !r.External))
+ if (SheetFeature(package, relationships, (string?)sheet.Attribute(R + "id"), theme) is { } feature)
+ return feature;
+ }
+ return null;
+ }
+
+ private static string? Xlsb(string path)
+ {
+ using var package = new OpcPackage(path, DocumentLimits.Default);
+ var workbookPath = package.MainPartPath ?? "xl/workbook.bin";
+ if (workbookPath.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
+ return Xlsx(path); // an XLSX with an .xlsb name (XlsbReader)
+ var theme = package.TargetOfType(workbookPath, "/theme") is { } themePath ? package.Part(themePath)?.Root : null;
+ var relationships = package.Relationships(workbookPath);
+ foreach (var sheet in XlsbReader.ListSheets(package, workbookPath, DocumentLimits.Default))
+ {
+ if (sheet.State == 0 && SheetFeature(package, relationships, sheet.RelationshipId, theme) is { } feature)
+ return feature;
+ }
+ return null;
+ }
+
+ /// What a visible sheet holds that the printer doesn't draw, from its relationships, without reading its cells.
+ private static string? SheetFeature(OpcPackage package, Dictionary relationships, string? id, XElement? theme)
+ {
+ if (id is null || !relationships.TryGetValue(id, out var relationship) || relationship.External)
+ return null;
+ if (relationship.Type.EndsWith("/chartsheet", StringComparison.Ordinal))
+ return "charts";
+ if (!relationship.Type.EndsWith("/worksheet", StringComparison.Ordinal))
+ return null;
+ foreach (var part in package.Relationships(relationship.Target).Values.Where(r => !r.External))
+ {
+ var feature = part.Type switch
{
- var feature = part.Type switch
- {
- var type when type.EndsWith("/drawing", StringComparison.Ordinal) => XlsxDrawing.Read(package, part.Target, theme, read: false).FirstLeftOut,
- var type when type.EndsWith("/ctrlProp", StringComparison.Ordinal) => "form controls",
- var type when type.EndsWith("/oleObject", StringComparison.Ordinal) || type.EndsWith("/package", StringComparison.Ordinal) => "embedded objects",
- var type when type.EndsWith("/vmlDrawing", StringComparison.Ordinal) => Vml(package, part.Target),
- _ => null,
- };
- if (feature is not null)
- return feature;
- }
+ var type when type.EndsWith("/drawing", StringComparison.Ordinal) => XlsxDrawing.Read(package, part.Target, theme, read: false).FirstLeftOut,
+ var type when type.EndsWith("/ctrlProp", StringComparison.Ordinal) => "form controls",
+ var type when type.EndsWith("/oleObject", StringComparison.Ordinal) || type.EndsWith("/package", StringComparison.Ordinal) => "embedded objects",
+ var type when type.EndsWith("/vmlDrawing", StringComparison.Ordinal) => Vml(package, part.Target),
+ _ => null,
+ };
+ if (feature is not null)
+ return feature;
}
return null;
}
diff --git a/src/Filee.Engines/Office/Sheets/XlsbReader.cs b/src/Filee.Engines/Office/Sheets/XlsbReader.cs
new file mode 100644
index 000000000..3af80a055
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/XlsbReader.cs
@@ -0,0 +1,1044 @@
+// XLSB (Excel binary workbook) → Workbook, read directly from Microsoft's published format ([MS-XLSB]): the same ZIP
+// package and relationships as XLSX, with the workbook, shared strings, styles and worksheets stored as BIFF12
+// records (a 1–2 byte type and a 1–4 byte size, 7 bits per byte) instead of XML. It fills the same sheet model as the
+// XLSX reader, so every sheet output (XLSX, ODS, CSV, PDF, HWPX, HTML, ...) works from it.
+//
+// Read: sheets (hidden ones skipped), the 1904 date system, print areas and print titles (defined names), shared
+// strings with rich text runs, number formats, fonts, fills (solid, patterns, gradients), borders, cell formats with
+// their alignment, cell values (numbers, RK numbers, text, booleans, errors; formulas as the value Excel last
+// calculated, the formula itself is not read), column widths and hidden columns, row heights and hidden rows, merged
+// cells, frozen rows, right-to-left sheets, manual page breaks, the page setup, margins, print options, headers and
+// footers (with their pictures) and each sheet's drawing (pictures and shapes; drawings are DrawingML XML in XLSB too).
+// Left out: conditional formats (binary rules), comments, tables, data validation.
+//
+// The input is untrusted: the package is read within DocumentLimits (part and total sizes counted while unpacking,
+// inflate ratio), records count against MaxXmlElements like XML elements do, a record the reader takes apart may hold
+// at most MaxRecordBytes, every field is read within its record, and rows, columns and expanded column ranges are
+// bounded as in the XLSX reader.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Text;
+using System.Xml.Linq;
+using Filee.Engines.Documents;
+using Filee.Engines.Office.Ooxml;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal sealed class XlsbReader
+{
+ public const string Format = "xlsb";
+
+ /// Bytes of one record the reader takes apart (the largest real ones, strings and names, stay below 200 KB).
+ internal const int MaxRecordBytes = 1024 * 1024;
+
+ /// Column entries (BrtColInfo ranges expanded) one workbook may set, as in the XLSX reader.
+ private const int MaxColumnEntries = 4_000_000;
+
+ /// Days between the 1900 and 1904 date systems.
+ private const double Date1904Offset = 1462;
+
+ // Record types ([MS-XLSB] 2.3).
+ private const int RowHdr = 0;
+ private const int CellBlank = 1;
+ private const int CellRk = 2;
+ private const int CellError = 3;
+ private const int CellBool = 4;
+ private const int CellReal = 5;
+ private const int CellSt = 6;
+ private const int CellIsst = 7;
+ private const int FmlaString = 8;
+ private const int FmlaNum = 9;
+ private const int FmlaBool = 10;
+ private const int FmlaError = 11;
+ private const int SstItem = 19;
+ private const int Name = 39;
+ private const int Font = 43;
+ private const int Fmt = 44;
+ private const int Fill = 45;
+ private const int Border = 46;
+ private const int Xf = 47;
+ private const int ColInfo = 60;
+ private const int CellRString = 62;
+ private const int BeginWsView = 137;
+ private const int EndWsView = 138;
+ private const int WsProp = 147;
+ private const int Pane = 151;
+ private const int WbProp = 153;
+ private const int BundleSh = 156;
+ private const int MergeCell = 176;
+ private const int BeginRwBrk = 392;
+ private const int EndRwBrk = 393;
+ private const int BeginColBrk = 394;
+ private const int EndColBrk = 395;
+ private const int Brk = 396;
+ private const int Margins = 476;
+ private const int PrintOptions = 477;
+ private const int PageSetup = 478;
+ private const int BeginHeaderFooter = 479;
+ private const int WsFmtInfo = 485;
+ private const int Drawing = 550;
+ private const int LegacyDrawingHF = 552;
+ private const int BeginCellXfs = 617;
+ private const int EndCellXfs = 618;
+ private const int BeginCellStyleXfs = 626;
+ private const int EndCellStyleXfs = 627;
+
+ /// Fill patterns by BrtFill fls (1 = solid, 0x28 = gradient), as SpreadsheetML names them.
+ private static readonly string?[] Patterns =
+ [
+ null, "solid", "mediumGray", "darkGray", "lightGray", "darkHorizontal", "darkVertical", "darkDown", "darkUp", "darkGrid",
+ "darkTrellis", "lightHorizontal", "lightVertical", "lightDown", "lightUp", "lightGrid", "lightTrellis", "gray125", "gray0625",
+ ];
+
+ /// Border styles by Blxf dg.
+ private static readonly string[] BorderStyles =
+ [
+ "none", "thin", "medium", "dashed", "dotted", "thick", "double", "hair", "mediumDashed", "dashDot", "mediumDashDot",
+ "dashDotDot", "mediumDashDotDot", "slantDashDot",
+ ];
+
+ private readonly OpcPackage _package;
+ private readonly DocumentLimits _limits;
+ private readonly List<(string Text, IReadOnlyList? Runs)> _sharedStrings = [];
+ private readonly List<(CellStyle Style, string Format)> _cellFormats = [];
+ private readonly List _fonts = [];
+ private OoxmlColors _colors = OoxmlColors.FromTheme(null);
+ private XDocument? _theme;
+ private NumberFormatter _formatter = new();
+ private bool _date1904;
+ private int _records;
+ private int _columnEntries;
+
+ private XlsbReader(OpcPackage package, DocumentLimits limits)
+ {
+ _package = package;
+ _limits = limits;
+ }
+
+ /// Reads every visible sheet of .
+ public static Workbook Read(string path) => Read(path, DocumentLimits.Default);
+
+ internal static Workbook Read(string path, DocumentLimits limits)
+ {
+ // An encrypted workbook is a compound file holding the encrypted package; an Excel 97–2003 workbook may also
+ // carry an .xlsb name.
+ if (CompoundFile.HasSignature(path))
+ {
+ using (var cfb = CompoundFile.Open(path, limits))
+ {
+ if (cfb.Exists("EncryptedPackage") || cfb.Exists("EncryptionInfo"))
+ throw new InvalidDataException("The workbook is protected with a password (encrypted). Remove the password in Excel and convert it again.");
+ }
+ return XlsReader.Read(path);
+ }
+ using var package = new OpcPackage(path, limits);
+ var workbookPath = package.MainPartPath ?? "xl/workbook.bin";
+ // An XLSX saved with an .xlsb name: its workbook part is XML.
+ if (workbookPath.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
+ return XlsxReader.Read(path);
+ return new XlsbReader(package, limits).ReadWorkbook(workbookPath);
+ }
+
+ // ───────────────────────── Workbook ─────────────────────────
+
+ /// A sheet of the workbook part: its visibility (0 visible, 1 hidden, 2 very hidden), relationship and name.
+ internal readonly record struct SheetEntry(uint State, string? RelationshipId, string Name);
+
+ private sealed class WorkbookPart
+ {
+ public List Sheets { get; } = [];
+ public bool Date1904 { get; set; }
+
+ /// Print titles and print areas by the sheet's position (hidden sheets count).
+ public Dictionary> Titles { get; } = [];
+ public Dictionary> Areas { get; } = [];
+ }
+
+ /// The sheets the workbook part lists, in order (for SheetCapabilities, which reads no cells).
+ internal static List ListSheets(OpcPackage package, string workbookPath, DocumentLimits limits) =>
+ new XlsbReader(package, limits).ReadWorkbookPart(workbookPath).Sheets;
+
+ private WorkbookPart ReadWorkbookPart(string workbookPath)
+ {
+ var result = new WorkbookPart();
+ using var stream = _package.OpenPart(workbookPath)
+ ?? throw new InvalidDataException("The file is not an Excel binary workbook (no xl/workbook.bin).");
+ var records = new Records(stream, workbookPath, this);
+ while (records.Next())
+ {
+ switch (records.Type)
+ {
+ case WbProp:
+ var properties = records.Fields();
+ result.Date1904 = (properties.U32() & 1) != 0;
+ break;
+ case BundleSh:
+ // Sheet ids run from 1 to 0xFFFF: more sheets than that is no workbook Excel wrote.
+ if (result.Sheets.Count >= 0xFFFF)
+ throw DocumentLimits.Exceeded("The workbook lists more than 65,535 sheets.");
+ var sheet = records.Fields();
+ var state = sheet.U32();
+ sheet.U32(); // iTabID
+ var relationship = sheet.String(nullable: true);
+ result.Sheets.Add(new SheetEntry(state, relationship, sheet.String() ?? ""));
+ break;
+ case Name:
+ DefinedName(records.Fields(), result);
+ break;
+ }
+ }
+ return result;
+ }
+
+ /// A BrtName: print titles and print areas, which are built-in names scoped to a sheet.
+ private static void DefinedName(Fields name, WorkbookPart result)
+ {
+ var flags = name.U32();
+ name.U8(); // chKey
+ var sheet = name.U32();
+ var text = name.String() ?? "";
+ // A built-in name is "_xlnm.Print_Area", or "Print_Area" with fBuiltin set.
+ if (sheet > int.MaxValue || (flags & 0x20) == 0 && !text.StartsWith("_xlnm.", StringComparison.OrdinalIgnoreCase))
+ return;
+ var target = (text.StartsWith("_xlnm.", StringComparison.OrdinalIgnoreCase) ? text[6..] : text) switch
+ {
+ var n when n.Equals("Print_Titles", StringComparison.OrdinalIgnoreCase) => result.Titles,
+ var n when n.Equals("Print_Area", StringComparison.OrdinalIgnoreCase) => result.Areas,
+ _ => null,
+ };
+ if (target is null)
+ return;
+ var length = name.U32();
+ if (length > name.Left)
+ return;
+ target[(int)sheet] = Areas(name.Bytes((int)length));
+ }
+
+ ///
+ /// The ranges of a defined name's parsed formula: 3-D references and areas, joined by unions (PtgUnion inside a
+ /// PtgMemFunc); anything else ends the list.
+ ///
+ private static List Areas(ReadOnlySpan rgce)
+ {
+ var ranges = new List();
+ var at = 0;
+ while (at < rgce.Length)
+ {
+ var ptg = rgce[at++];
+ switch (ptg)
+ {
+ case 0x3B or 0x5B or 0x7B when at + 14 <= rgce.Length: // PtgArea3d: ixti, RgceAreaRel
+ Add(BinaryPrimitives.ReadUInt32LittleEndian(rgce[(at + 2)..]), BinaryPrimitives.ReadUInt32LittleEndian(rgce[(at + 6)..]),
+ BinaryPrimitives.ReadUInt16LittleEndian(rgce[(at + 10)..]) & 0x3FFF, BinaryPrimitives.ReadUInt16LittleEndian(rgce[(at + 12)..]) & 0x3FFF);
+ at += 14;
+ break;
+ case 0x3A or 0x5A or 0x7A when at + 8 <= rgce.Length: // PtgRef3d: ixti, RgceLocRel
+ var row = BinaryPrimitives.ReadUInt32LittleEndian(rgce[(at + 2)..]);
+ var column = BinaryPrimitives.ReadUInt16LittleEndian(rgce[(at + 6)..]) & 0x3FFF;
+ Add(row, row, column, column);
+ at += 8;
+ break;
+ case 0x29 or 0x49 or 0x69 when at + 2 <= rgce.Length: // PtgMemFunc: the expression follows
+ at += 2;
+ break;
+ case 0x10: // PtgUnion
+ break;
+ default:
+ return ranges;
+ }
+ }
+ return ranges;
+
+ void Add(uint top, uint bottom, int left, int right)
+ {
+ if (top <= bottom && bottom <= SheetPagination.MaxRow && left <= right && right <= SheetPagination.MaxColumn)
+ ranges.Add(new CellRange((int)top, left, (int)bottom, right));
+ }
+ }
+
+ private Workbook ReadWorkbook(string workbookPath)
+ {
+ var part = ReadWorkbookPart(workbookPath);
+ _date1904 = part.Date1904;
+ _formatter = new NumberFormatter(_date1904);
+ _theme = _package.TargetOfType(workbookPath, "/theme") is { } theme ? _package.Part(theme) : null;
+ _colors = OoxmlColors.FromTheme(_theme);
+
+ var result = new Workbook();
+ // Styles first: rich text runs of the shared strings point into the fonts.
+ if (_package.TargetOfType(workbookPath, "/styles") is { } styles)
+ ReadStyles(styles, result);
+ if (_package.TargetOfType(workbookPath, "/sharedStrings") is { } shared)
+ ReadSharedStrings(shared);
+
+ var relationships = _package.Relationships(workbookPath);
+ for (var index = 0; index < part.Sheets.Count; index++)
+ {
+ var entry = part.Sheets[index];
+ if (entry.State != 0 || entry.RelationshipId is null || !relationships.TryGetValue(entry.RelationshipId, out var relationship)
+ || relationship.External || !relationship.Type.EndsWith("/worksheet", StringComparison.Ordinal))
+ continue; // hidden sheets, chart sheets, dialog and macro sheets
+ var sheet = ReadSheet(entry.Name.Length > 0 ? entry.Name : "Sheet", relationship.Target);
+ if (part.Titles.TryGetValue(index, out var titles))
+ {
+ // Whole rows repeat at the top, whole columns at the left.
+ foreach (var range in titles)
+ {
+ if (range.Left == 0 && range.Right == SheetPagination.MaxColumn)
+ sheet.TitleRows ??= (range.Top, range.Bottom);
+ else if (range.Top == 0 && range.Bottom == SheetPagination.MaxRow)
+ sheet.TitleColumns ??= (range.Left, range.Right);
+ }
+ }
+ if (part.Areas.TryGetValue(index, out var areas))
+ sheet.PrintArea.AddRange(areas);
+ result.Sheets.Add(sheet);
+ }
+ return result;
+ }
+
+ // ───────────────────────── Shared strings ─────────────────────────
+
+ private void ReadSharedStrings(string partPath)
+ {
+ using var stream = _package.OpenPart(partPath);
+ if (stream is null)
+ return;
+ var records = new Records(stream, partPath, this);
+ while (records.Next())
+ {
+ if (records.Type == SstItem)
+ {
+ var item = records.Fields();
+ _sharedStrings.Add(RichText(ref item));
+ }
+ }
+ }
+
+ /// A RichStr: the text and, when it has runs, the pieces in their fonts (phonetic text skipped).
+ private (string Text, IReadOnlyList? Runs) RichText(ref Fields fields)
+ {
+ var flags = fields.U8();
+ var text = fields.String() ?? "";
+ if ((flags & 1) == 0)
+ return (text, null);
+ var count = fields.U32();
+ if (count == 0 || count > 0x7FFF || count > fields.Left / 4)
+ return (text, null);
+ var starts = new List<(int Start, int Font)>();
+ for (var i = 0; i < count; i++)
+ {
+ var start = fields.U16();
+ var font = fields.U16();
+ if (start < text.Length && (starts.Count == 0 || start > starts[^1].Start))
+ starts.Add((start, font));
+ }
+ if (starts.Count == 0)
+ return (text, null);
+ var runs = new List();
+ if (starts[0].Start > 0)
+ runs.Add(new CellRun(text[..starts[0].Start]));
+ for (var i = 0; i < starts.Count; i++)
+ {
+ var end = i + 1 < starts.Count ? starts[i + 1].Start : text.Length;
+ var piece = text[starts[i].Start..end];
+ if (starts[i].Font >= _fonts.Count)
+ {
+ runs.Add(new CellRun(piece));
+ continue;
+ }
+ var font = _fonts[starts[i].Font];
+ runs.Add(new CellRun(piece)
+ {
+ Bold = font.Bold,
+ Italic = font.Italic,
+ Underline = font.Underline,
+ Strike = font.Strike,
+ FontSize = font.Size,
+ Color = font.Color,
+ FontName = font.Name,
+ Script = font.Script,
+ });
+ }
+ return (text, runs);
+ }
+
+ // ───────────────────────── Styles ─────────────────────────
+
+ private sealed record FontInfo(bool Bold, bool Italic, bool Underline, bool DoubleUnderline, bool Strike, double? Size, string? Color, string? Name, int Script);
+
+ private void ReadStyles(string partPath, Workbook book)
+ {
+ using var stream = _package.OpenPart(partPath);
+ if (stream is null)
+ return;
+ var formats = new Dictionary();
+ var fills = new List<(string? Color, string? Pattern, string? Background, CellGradient? Gradient)>();
+ var borders = new List<(CellBorder Left, CellBorder Right, CellBorder Top, CellBorder Bottom, CellBorder Up, CellBorder Down)>();
+ var styleFonts = new List();
+ var cellXfs = new List<(int Format, int Font, int Fill, int Border, int Rotation, int Indent, int Alignment)>();
+ var inCellXfs = false;
+ var inStyleXfs = false;
+ var records = new Records(stream, partPath, this);
+ while (records.Next())
+ {
+ switch (records.Type)
+ {
+ case Fmt:
+ var format = records.Fields();
+ var id = format.U16();
+ var code = format.String();
+ formats.TryAdd(id, code ?? "General");
+ break;
+ case Font:
+ _fonts.Add(ReadFont(records.Fields()));
+ break;
+ case Fill:
+ fills.Add(ReadFill(records.Fields()));
+ break;
+ case Border:
+ borders.Add(ReadBorder(records.Fields()));
+ break;
+ case BeginCellXfs:
+ inCellXfs = true;
+ break;
+ case EndCellXfs:
+ inCellXfs = false;
+ break;
+ case BeginCellStyleXfs:
+ inStyleXfs = true;
+ break;
+ case EndCellStyleXfs:
+ inStyleXfs = false;
+ break;
+ case Xf when inCellXfs || inStyleXfs:
+ var xf = records.Fields();
+ xf.U16(); // ixfeParent
+ var numberFormat = xf.U16();
+ var font = xf.U16();
+ var fill = xf.U16();
+ var border = xf.U16();
+ var rotation = xf.U8();
+ var indent = xf.U8();
+ var alignment = xf.U16();
+ if (inStyleXfs)
+ styleFonts.Add(font);
+ else
+ cellXfs.Add((numberFormat, font, fill, border, rotation, indent, alignment));
+ break;
+ }
+ }
+
+ // The Normal style's font (the first cell style): Excel measures column widths in its digits.
+ var normal = styleFonts.Count > 0 && styleFonts[0] < _fonts.Count ? _fonts[styleFonts[0]] : _fonts.FirstOrDefault();
+ if (normal?.Name is { Length: > 0 } fontName)
+ book.DefaultFontName = fontName;
+ if (normal?.Size is > 0 and <= 409 && normal.Size is { } fontSize)
+ book.DefaultFontSize = fontSize;
+
+ foreach (var (formatId, fontId, fillId, borderId, rotation, indent, alignment) in cellXfs)
+ {
+ var font = fontId < _fonts.Count ? _fonts[fontId] : null;
+ var fill = fillId < fills.Count ? fills[fillId] : default;
+ var border = borderId < borders.Count ? borders[borderId] : NoBorders;
+ var horizontal = alignment & 0x07;
+ var vertical = (alignment >> 3) & 0x07;
+ var style = new CellStyle
+ {
+ Bold = font?.Bold ?? false,
+ Italic = font?.Italic ?? false,
+ Underline = font?.Underline ?? false,
+ DoubleUnderline = font?.DoubleUnderline ?? false,
+ Strike = font?.Strike ?? false,
+ FontSize = font?.Size,
+ FontName = font?.Name,
+ Script = font?.Script ?? 0,
+ Color = font?.Color,
+ Fill = fill.Color,
+ FillPattern = fill.Pattern,
+ PatternBackground = fill.Background,
+ Gradient = fill.Gradient,
+ // alc: general, left, center, right, fill, justify, center across selection, distributed.
+ Align = horizontal switch
+ {
+ 1 => CellAlign.Left,
+ 2 or 6 => CellAlign.Center,
+ 3 => CellAlign.Right,
+ _ => CellAlign.General,
+ },
+ SpecialAlign = horizontal switch
+ {
+ 4 => CellSpecialAlign.Fill,
+ 5 => CellSpecialAlign.Justify,
+ 6 => CellSpecialAlign.CenterAcross,
+ 7 => CellSpecialAlign.Distributed,
+ _ => CellSpecialAlign.None,
+ },
+ // alcv: top, center, bottom, justify, distributed.
+ VerticalAlign = vertical switch
+ {
+ 0 or 3 or 4 => CellVerticalAlign.Top,
+ 1 => CellVerticalAlign.Center,
+ _ => CellVerticalAlign.Bottom,
+ },
+ VerticalJustify = vertical is 3 or 4,
+ Wrap = (alignment & 0x40) != 0,
+ Shrink = (alignment & 0x100) != 0,
+ Indent = Math.Min(indent, 250),
+ Rotation = XlsxReader.Rotation(rotation),
+ Left = border.Left,
+ Right = border.Right,
+ Top = border.Top,
+ Bottom = border.Bottom,
+ DiagonalUp = border.Up,
+ DiagonalDown = border.Down,
+ };
+ _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? NumberFormatter.BuiltIn(formatId) ?? "General"));
+ }
+ }
+
+ private static readonly (CellBorder Left, CellBorder Right, CellBorder Top, CellBorder Bottom, CellBorder Up, CellBorder Down) NoBorders =
+ (CellBorder.None, CellBorder.None, CellBorder.None, CellBorder.None, CellBorder.None, CellBorder.None);
+
+ private FontInfo ReadFont(Fields font)
+ {
+ var height = font.U16();
+ var flags = font.U16();
+ var weight = font.U16();
+ var script = font.U16();
+ var underline = font.U8();
+ font.Skip(3); // bFamily, bCharSet, unused
+ var color = Color(ref font);
+ font.U8(); // bFontScheme
+ var name = font.String();
+ return new FontInfo(
+ weight >= 700,
+ (flags & 0x02) != 0,
+ underline is not 0,
+ underline is 0x02 or 0x22,
+ (flags & 0x08) != 0,
+ height is >= 20 and <= 0x1FFF ? height / 20.0 : null,
+ color,
+ name is { Length: > 0 } ? name : null,
+ script switch { 1 => 1, 2 => -1, _ => 0 });
+ }
+
+ private (string? Color, string? Pattern, string? Background, CellGradient? Gradient) ReadFill(Fields fill)
+ {
+ var pattern = fill.U32();
+ var foreground = Color(ref fill);
+ var background = Color(ref fill);
+ if (pattern == 0x28)
+ {
+ var type = fill.U32();
+ var degree = fill.F64();
+ fill.Skip(32); // the inner rectangle of a rectangular gradient
+ var count = fill.U32();
+ var stops = new List<(double Position, string Color)>();
+ for (var i = 0; i < Math.Min(count, 16u) && fill.Left >= 16; i++)
+ {
+ var color = Color(ref fill);
+ var position = fill.F64();
+ if (color is not null)
+ stops.Add((double.IsFinite(position) ? Math.Clamp(position, 0, 1) : 0, color));
+ }
+ if (stops.Count == 0)
+ return default;
+ // A rectangular (path) gradient is drawn as a linear one from its first colour to its last.
+ return (stops[0].Color, null, null, stops.Count > 1 ? new CellGradient(type == 0 && double.IsFinite(degree) ? degree : 0, stops) : null);
+ }
+ if (pattern >= Patterns.Length || Patterns[pattern] is not { } name || name == "gray125")
+ return default;
+ return name == "solid"
+ ? (foreground ?? background, null, null, null)
+ : (foreground ?? "#000000", name, background, null);
+ }
+
+ private (CellBorder Left, CellBorder Right, CellBorder Top, CellBorder Bottom, CellBorder Up, CellBorder Down) ReadBorder(Fields border)
+ {
+ var flags = border.U8();
+ var top = Side(ref border);
+ var bottom = Side(ref border);
+ var left = Side(ref border);
+ var right = Side(ref border);
+ var diagonal = Side(ref border);
+ return (left, right, top, bottom, (flags & 2) != 0 ? diagonal : CellBorder.None, (flags & 1) != 0 ? diagonal : CellBorder.None);
+ }
+
+ /// A Blxf: the line style and colour of one border side.
+ private CellBorder Side(ref Fields fields)
+ {
+ var style = fields.U8();
+ fields.U8();
+ var color = Color(ref fields);
+ return style is 0 or >= 14 ? CellBorder.None : new CellBorder(BorderStyles[style], color);
+ }
+
+ ///
+ /// A BrtColor as "#RRGGBB", or null for automatic. Theme indexes and tints mean what they mean in SpreadsheetML,
+ /// so they go through the same resolution.
+ ///
+ private string? Color(ref Fields fields)
+ {
+ var type = fields.U8() >> 1;
+ var index = fields.U8();
+ var tint = fields.I16();
+ var (red, green, blue) = (fields.U8(), fields.U8(), fields.U8());
+ fields.U8(); // alpha
+ var color = type switch
+ {
+ 1 => new XElement("color", new XAttribute("indexed", index)),
+ 2 => new XElement("color", new XAttribute("rgb", $"FF{red:X2}{green:X2}{blue:X2}")),
+ 3 => new XElement("color", new XAttribute("theme", index)),
+ _ => null,
+ };
+ if (color is null)
+ return null;
+ if (tint != 0)
+ color.SetAttributeValue("tint", Math.Clamp(tint / 32767.0, -1, 1).ToString("R", CultureInfo.InvariantCulture));
+ return _colors.Spreadsheet(color);
+ }
+
+ // ───────────────────────── Sheets ─────────────────────────
+
+ private Worksheet ReadSheet(string name, string partPath)
+ {
+ var sheet = new Worksheet(name);
+ using var stream = _package.OpenPart(partPath);
+ if (stream is null)
+ return sheet;
+
+ var row = -1;
+ var views = 0;
+ var inView = false;
+ var breaks = 0; // 1 = row breaks, 2 = column breaks
+ var fitToPage = false;
+ (uint Paper, uint Scale, int FirstPage, uint FitWidth, uint FitHeight, int Flags)? page = null;
+ double[]? margins = null;
+ int? options = null;
+ SheetHeaderFooter? headerFooter = null;
+ string? headerPictures = null;
+ string? drawing = null;
+
+ var records = new Records(stream, partPath, this);
+ while (records.Next())
+ {
+ switch (records.Type)
+ {
+ case RowHdr:
+ row = ReadRow(records.Fields(), sheet);
+ break;
+ case >= CellBlank and <= FmlaError or CellRString:
+ if (row >= 0)
+ ReadCell(records.Type, records.Fields(), row, sheet);
+ break;
+ case WsProp:
+ fitToPage = (records.Fields().U16() & 0x100) != 0;
+ break;
+ case WsFmtInfo:
+ ReadFormatInfo(records.Fields(), sheet);
+ break;
+ case BeginWsView:
+ // The first view is the one Excel opens with.
+ inView = views++ == 0;
+ if (inView)
+ sheet.RightToLeft = (records.Fields().U16() & 0x20) != 0;
+ break;
+ case EndWsView:
+ inView = false;
+ break;
+ case Pane when inView:
+ var pane = records.Fields();
+ pane.F64(); // xnumXSplit: columns (the spec's prose swaps the two; the order is BIFF8 PANE's x, y)
+ var frozen = pane.F64();
+ pane.Skip(12);
+ if ((pane.U8() & 0x03) != 0 && double.IsFinite(frozen) && frozen is >= 0 and <= SheetPagination.MaxRow)
+ sheet.FrozenRows = (int)frozen;
+ break;
+ case ColInfo:
+ ReadColumns(records.Fields(), sheet);
+ break;
+ case MergeCell:
+ var merge = records.Fields();
+ var (top, bottom, left, right) = (merge.U32(), merge.U32(), merge.U32(), merge.U32());
+ if (top <= bottom && left <= right && (bottom > top || right > left) && bottom <= SheetPagination.MaxRow && right <= SheetPagination.MaxColumn)
+ sheet.Merges.Add(new CellRange((int)top, (int)left, (int)bottom, (int)right));
+ break;
+ case BeginRwBrk:
+ breaks = 1;
+ break;
+ case BeginColBrk:
+ breaks = 2;
+ break;
+ case EndRwBrk or EndColBrk:
+ breaks = 0;
+ break;
+ case Brk when breaks != 0:
+ var brk = records.Fields();
+ var at = brk.U32();
+ brk.Skip(8);
+ var manual = brk.U32() != 0;
+ if (manual && at > 0 && at <= (breaks == 1 ? SheetPagination.MaxRow : SheetPagination.MaxColumn))
+ (breaks == 1 ? sheet.RowBreaks : sheet.ColumnBreaks).Add((int)at);
+ break;
+ case PrintOptions:
+ options = records.Fields().U16();
+ break;
+ case Margins:
+ var fields = records.Fields();
+ margins = [fields.F64(), fields.F64(), fields.F64(), fields.F64(), fields.F64(), fields.F64()];
+ break;
+ case PageSetup:
+ var setup = records.Fields();
+ var paper = setup.U32();
+ var scale = setup.U32();
+ setup.Skip(12); // iRes, iVRes, iCopies
+ var firstPage = setup.I32();
+ var fitWidth = setup.U32();
+ var fitHeight = setup.U32();
+ page = (paper, scale, firstPage, fitWidth, fitHeight, setup.U16());
+ break;
+ case BeginHeaderFooter:
+ headerFooter = ReadHeaderFooter(records.Fields());
+ break;
+ case Drawing:
+ drawing = records.Fields().String(nullable: true);
+ break;
+ case LegacyDrawingHF:
+ headerPictures = records.Fields().String(nullable: true);
+ break;
+ }
+ }
+
+ sheet.PageSetup = PageSetupOf(page, margins, options, fitToPage, headerFooter, partPath, headerPictures);
+ if (_package.Target(partPath, drawing) is { } drawingPart)
+ sheet.Drawings.AddRange(XlsxDrawing.Read(_package, drawingPart, _theme?.Root, read: true).Drawings);
+ return sheet;
+ }
+
+ /// A BrtRowHdr: the row's height and visibility; returns the row (or -1 for one beyond the sheet).
+ private static int ReadRow(Fields fields, Worksheet sheet)
+ {
+ var row = fields.U32();
+ fields.U32(); // ixfe
+ var height = fields.U16();
+ fields.U8();
+ var flags = fields.U8();
+ if (row > SheetPagination.MaxRow)
+ return -1;
+ var r = (int)row;
+ if ((flags & 0x10) != 0) // fDyZero
+ sheet.HiddenRows.Add(r);
+ // miyRw in twips: the custom height (fUnsynced), else the height Excel last fitted the row to.
+ if (height is > 0 and <= 8192)
+ {
+ if ((flags & 0x20) != 0)
+ sheet.RowHeights[r] = height / 20.0;
+ else
+ sheet.AutoRowHeights[r] = height / 20.0;
+ }
+ return r;
+ }
+
+ private void ReadCell(int type, Fields fields, int row, Worksheet sheet)
+ {
+ var column = fields.U32();
+ var s = (int)(fields.U32() & 0xFFFFFF);
+ if (column > SheetPagination.MaxColumn)
+ return;
+ var (style, format) = s < _cellFormats.Count ? _cellFormats[s] : (CellStyle.Default, "General");
+ var cell = type switch
+ {
+ CellBlank => new SheetCell("", style),
+ CellRk => Number(Rk(fields.U32()), style, format),
+ CellReal or FmlaNum => Number(fields.F64(), style, format),
+ CellError or FmlaError => new SheetCell(ErrorText(fields.U8()), style) { IsError = true },
+ CellBool or FmlaBool => fields.U8() != 0
+ ? new SheetCell("TRUE", style) { Value = 1, IsBoolean = true }
+ : new SheetCell("FALSE", style) { Value = 0, IsBoolean = true },
+ CellSt or FmlaString => new SheetCell(fields.String() ?? "", style),
+ CellIsst => fields.U32() is var index && index < _sharedStrings.Count
+ ? new SheetCell(_sharedStrings[(int)index].Text, style) { Runs = _sharedStrings[(int)index].Runs }
+ : new SheetCell("", style),
+ _ => RichCell(ref fields, style),
+ };
+ if (cell.HasContent)
+ sheet.Set(row, (int)column, cell);
+ }
+
+ private SheetCell RichCell(ref Fields fields, CellStyle style)
+ {
+ var (text, runs) = RichText(ref fields);
+ return new SheetCell(text, style) { Runs = runs };
+ }
+
+ /// An RkNumber: the high 30 bits of a double or a 30-bit integer, perhaps × 100.
+ internal static double Rk(uint raw)
+ {
+ var value = (raw & 0x02) != 0 ? (int)raw >> 2 : BitConverter.Int64BitsToDouble((long)(raw & 0xFFFFFFFC) << 32);
+ return (raw & 0x01) != 0 ? value / 100 : value;
+ }
+
+ /// The stored number, in the workbook's own date system.
+ private SheetCell Number(double value, CellStyle style, string format) => !double.IsFinite(value)
+ ? new SheetCell("#NUM!", style) { IsError = true }
+ : new SheetCell(_formatter.Format(value, format), style, IsNumber: true)
+ {
+ Value = _date1904 && _formatter.IsDate(format) ? value + Date1904Offset : value,
+ NumberFormat = NumberFormatter.IsGeneral(format) ? null : format,
+ };
+
+ private static string ErrorText(byte code) => code switch
+ {
+ 0x00 => "#NULL!",
+ 0x07 => "#DIV/0!",
+ 0x0F => "#VALUE!",
+ 0x17 => "#REF!",
+ 0x1D => "#NAME?",
+ 0x24 => "#NUM!",
+ 0x2A => "#N/A",
+ _ => "#GETTING_DATA",
+ };
+
+ /// A BrtWsFmtInfo: the default column width (or Excel's base width) and the default row height.
+ private static void ReadFormatInfo(Fields fields, Worksheet sheet)
+ {
+ var width = fields.U32();
+ var baseWidth = fields.U16();
+ var height = fields.U16();
+ if (width != 0xFFFFFFFF && width / 256.0 <= 255)
+ {
+ sheet.DefaultColumnWidth = width / 256.0;
+ sheet.HasDefaultColumnWidth = true;
+ }
+ else if (width == 0xFFFFFFFF && baseWidth <= 255)
+ {
+ sheet.BaseColumnWidth = baseWidth;
+ }
+ if (height is > 0 and <= 8190)
+ sheet.DefaultRowHeight = height / 20.0;
+ }
+
+ /// A BrtColInfo: the width (in characters × 256) and visibility of a range of columns.
+ private void ReadColumns(Fields fields, Worksheet sheet)
+ {
+ var first = fields.U32();
+ var last = Math.Min(fields.U32(), (uint)SheetPagination.MaxColumn);
+ var width = Math.Min(fields.U32(), 65535) / 256.0; // Excel's widest column is 255 characters
+ fields.U32(); // ixfe
+ var hidden = (fields.U16() & 0x01) != 0 || width == 0;
+ if (first > last)
+ return;
+ if ((_columnEntries += (int)(last - first + 1)) > MaxColumnEntries)
+ throw DocumentLimits.Exceeded("The workbook sets more than 4,000,000 column widths.");
+ for (var c = (int)first; c <= last; c++)
+ {
+ sheet.ColumnWidths[c] = width;
+ if (hidden)
+ sheet.HiddenColumns.Add(c);
+ }
+ }
+
+ private static SheetHeaderFooter ReadHeaderFooter(Fields fields)
+ {
+ var flags = fields.U16();
+ return new SheetHeaderFooter
+ {
+ OddHeader = fields.String(nullable: true),
+ OddFooter = fields.String(nullable: true),
+ EvenHeader = fields.String(nullable: true),
+ EvenFooter = fields.String(nullable: true),
+ FirstHeader = fields.String(nullable: true),
+ FirstFooter = fields.String(nullable: true),
+ DifferentOddEven = (flags & 0x01) != 0,
+ DifferentFirst = (flags & 0x02) != 0,
+ ScaleWithDocument = (flags & 0x04) != 0,
+ AlignWithMargins = (flags & 0x08) != 0,
+ };
+ }
+
+ /// The page setup the way the XLSX reader makes it from pageSetup, pageMargins, printOptions and headerFooter.
+ private SheetPageSetup PageSetupOf((uint Paper, uint Scale, int FirstPage, uint FitWidth, uint FitHeight, int Flags)? page, double[]? margins,
+ int? options, bool fitToPage, SheetHeaderFooter? headerFooter, string partPath, string? headerPictures)
+ {
+ var setup = page is null ? SheetPageSetup.ForRegion() : new SheetPageSetup { PaperWidth = Sheets.Paper.Letter.Width, PaperHeight = Sheets.Paper.Letter.Height };
+ if (page is { } p)
+ {
+ if (p.Paper <= int.MaxValue && Sheets.Paper.FromCode((int)p.Paper) is { } paper)
+ setup = setup with { PaperWidth = paper.Width, PaperHeight = paper.Height };
+ setup = setup with
+ {
+ // fNoOrient leaves the orientation to the printer.
+ Landscape = (p.Flags & 0x02) != 0 && (p.Flags & 0x40) == 0,
+ Scale = p.Scale is >= 10 and <= 400 ? (int)p.Scale : 100,
+ FitWidth = p.FitWidth <= 32767 ? (int)p.FitWidth : 1,
+ FitHeight = p.FitHeight <= 32767 ? (int)p.FitHeight : 1,
+ OverThenDown = (p.Flags & 0x01) != 0,
+ FirstPageNumber = (p.Flags & 0x80) != 0 && p.FirstPage is >= -32768 and <= 32767 ? p.FirstPage : null,
+ };
+ }
+ setup = setup with { FitToPage = fitToPage };
+ if (margins is not null)
+ {
+ double Margin(double inches, double fallback) => double.IsFinite(inches) && inches is >= 0 and <= 50 ? inches * 72 : fallback;
+ setup = setup with
+ {
+ LeftMargin = Margin(margins[0], setup.LeftMargin),
+ RightMargin = Margin(margins[1], setup.RightMargin),
+ TopMargin = Margin(margins[2], setup.TopMargin),
+ BottomMargin = Margin(margins[3], setup.BottomMargin),
+ HeaderMargin = Margin(margins[4], setup.HeaderMargin),
+ FooterMargin = Margin(margins[5], setup.FooterMargin),
+ };
+ }
+ if (options is { } o)
+ {
+ setup = setup with
+ {
+ CenterHorizontally = (o & 0x01) != 0,
+ CenterVertically = (o & 0x02) != 0,
+ PrintHeadings = (o & 0x04) != 0,
+ PrintGridLines = (o & 0x08) != 0,
+ };
+ }
+ if (headerFooter is not null)
+ {
+ setup = setup with
+ {
+ HeaderFooter = headerFooter with
+ {
+ Pictures = _package.Target(partPath, headerPictures) is { } vml ? XlsxReader.HeaderPictures(_package, vml) : [],
+ },
+ };
+ }
+ return setup;
+ }
+
+ // ───────────────────────── Records ─────────────────────────
+
+ /// Counts a record against what one workbook may hold (as many as the XML elements an XLSX may).
+ private void Count()
+ {
+ if (++_records > _limits.MaxXmlElements)
+ throw DocumentLimits.Exceeded($"The workbook has more than {DocumentLimits.Count(_limits.MaxXmlElements)} records.");
+ }
+
+ /// The records of one part, read one after the other.
+ private sealed class Records(Stream stream, string part, XlsbReader reader)
+ {
+ private readonly BufferedStream _stream = new(stream, 64 * 1024);
+ private byte[] _data = new byte[256];
+ private int _length;
+ private bool _tooLarge;
+
+ public int Type { get; private set; }
+
+ /// Moves to the next record; false at the end of the part.
+ public bool Next()
+ {
+ var low = _stream.ReadByte();
+ if (low < 0)
+ return false;
+ var type = low & 0x7F;
+ if ((low & 0x80) != 0)
+ type |= (Byte() & 0x7F) << 7;
+ var size = 0;
+ for (var i = 0; i < 4; i++)
+ {
+ var b = Byte();
+ size |= (b & 0x7F) << (7 * i);
+ if ((b & 0x80) == 0 || i == 3)
+ break;
+ }
+ reader.Count();
+ Type = type;
+ _tooLarge = size > MaxRecordBytes;
+ if (_tooLarge)
+ {
+ // Kept out of memory: only records the reader skips may be this large.
+ Skip(size);
+ _length = 0;
+ return true;
+ }
+ if (_data.Length < size)
+ _data = new byte[Math.Max(size, _data.Length * 2)];
+ if (_stream.ReadAtLeast(_data.AsSpan(0, size), size, throwOnEndOfStream: false) != size)
+ throw Damaged();
+ _length = size;
+ return true;
+ }
+
+ /// The fields of the current record.
+ public Fields Fields() => _tooLarge
+ ? throw DocumentLimits.Exceeded($"A record of {part} holds more than {DocumentLimits.Megabytes(MaxRecordBytes)}.")
+ : new Fields(_data.AsSpan(0, _length), part);
+
+ private int Byte()
+ {
+ var b = _stream.ReadByte();
+ return b < 0 ? throw Damaged() : b;
+ }
+
+ private void Skip(int count)
+ {
+ Span buffer = stackalloc byte[4096];
+ while (count > 0)
+ {
+ var read = _stream.Read(buffer[..Math.Min(count, buffer.Length)]);
+ if (read <= 0)
+ throw Damaged();
+ count -= read;
+ }
+ }
+
+ private InvalidDataException Damaged() => new($"The part {part} of the workbook ends inside a record. The file may be damaged.");
+ }
+
+ /// The fields of one record, read in order; reading past its end is damage.
+ private ref struct Fields(ReadOnlySpan data, string part)
+ {
+ private readonly ReadOnlySpan _data = data;
+ private int _at;
+
+ public readonly int Left => _data.Length - _at;
+
+ public byte U8() => Take(1)[0];
+
+ public ushort U16() => BinaryPrimitives.ReadUInt16LittleEndian(Take(2));
+
+ public short I16() => BinaryPrimitives.ReadInt16LittleEndian(Take(2));
+
+ public uint U32() => BinaryPrimitives.ReadUInt32LittleEndian(Take(4));
+
+ public int I32() => BinaryPrimitives.ReadInt32LittleEndian(Take(4));
+
+ public double F64() => BinaryPrimitives.ReadDoubleLittleEndian(Take(8));
+
+ public void Skip(int count) => Take(count);
+
+ public ReadOnlySpan Bytes(int count) => Take(count);
+
+ /// An XLWideString (or, , an XLNullableWideString whose 0xFFFFFFFF length is null).
+ public string? String(bool nullable = false)
+ {
+ var count = U32();
+ if (nullable && count == 0xFFFFFFFF)
+ return null;
+ if (count > Left / 2)
+ throw Damaged();
+ return Encoding.Unicode.GetString(Take((int)count * 2));
+ }
+
+ private ReadOnlySpan Take(int count)
+ {
+ if (count < 0 || count > Left)
+ throw Damaged();
+ var span = _data.Slice(_at, count);
+ _at += count;
+ return span;
+ }
+
+ private readonly InvalidDataException Damaged() => new($"A record of {part} in the workbook is shorter than its fields. The file may be damaged.");
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
index fab1cc8e4..e2e954d49 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxReader.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
@@ -592,7 +592,7 @@ private SheetPageSetup PageSetup(XElement xml, string partPath)
DifferentFirst = On(hf.Attribute("differentFirst")),
ScaleWithDocument = hf.Attribute("scaleWithDoc") is not { } scaleWith || On(scaleWith),
AlignWithMargins = hf.Attribute("alignWithMargins") is not { } align || On(align),
- Pictures = _package.Target(partPath, (string?)xml.Element(S + "legacyDrawingHF")?.Attribute(R + "id")) is { } vml ? HeaderPictures(vml) : [],
+ Pictures = _package.Target(partPath, (string?)xml.Element(S + "legacyDrawingHF")?.Attribute(R + "id")) is { } vml ? HeaderPictures(_package, vml) : [],
},
};
}
@@ -600,13 +600,13 @@ private SheetPageSetup PageSetup(XElement xml, string partPath)
}
/// The pictures of headers and footers: VML shapes named LH, CH, RH, LF, CF, RF (+ FIRST / EVEN).
- private Dictionary HeaderPictures(string vmlPath)
+ internal static Dictionary HeaderPictures(OpcPackage package, string vmlPath)
{
var pictures = new Dictionary(StringComparer.OrdinalIgnoreCase);
XDocument? vml;
try
{
- vml = _package.Part(vmlPath);
+ vml = package.Part(vmlPath);
}
catch (InvalidDataException)
{
@@ -616,7 +616,7 @@ private SheetPageSetup PageSetup(XElement xml, string partPath)
{
var id = (string?)shape.Attribute("id");
var relation = (string?)shape.Element(V + "imagedata")?.Attribute(O + "relid") ?? (string?)shape.Element(V + "imagedata")?.Attribute(R + "id");
- if (id is null || _package.Target(vmlPath, relation) is not { } image || _package.Bytes(image, MaxPictureBytes) is not { } data)
+ if (id is null || package.Target(vmlPath, relation) is not { } image || package.Bytes(image, MaxPictureBytes) is not { } data)
continue;
var style = ((string?)shape.Attribute("style") ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split(':', 2)).Where(p => p.Length == 2).GroupBy(p => p[0].Trim(), StringComparer.OrdinalIgnoreCase)
diff --git a/src/Filee.Engines/Office/Sheets/XlsxWriter.cs b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
index c8fba27cc..e98283c39 100644
--- a/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
+++ b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
@@ -28,6 +28,9 @@ internal static class XlsxWriter
["@"] = 49,
};
+ /// Excel's built-in short date, which it shows in the PC's regional format (#1315).
+ private const int ShortDateId = 14;
+
public static void Write(Workbook book, string path)
{
var sheets = book.Sheets.Count > 0 ? book.Sheets : [new Worksheet("Sheet1")];
@@ -188,7 +191,12 @@ public int Index(CellStyle style, string? format)
{
if (_xfs.TryGetValue((style, format), out var index))
return index;
- var formatId = format is null ? 0 : BuiltInIds.TryGetValue(format, out var builtIn) ? builtIn : FormatId(format);
+ // The PC's short date (what format 14 is read as here) is written as format 14, not as a format of the
+ // file's own: Excel then shows the date in the short date of whoever opens the file.
+ var formatId = format is null ? 0
+ : BuiltInIds.TryGetValue(format, out var builtIn) ? builtIn
+ : NumberFormatter.IsShortDate(format) ? ShortDateId
+ : FormatId(format);
var fontId = Add(_fonts, Font(style));
var fillId = style.Fill is { } fill ? Add(_fills, $"""""") : 0;
var borderId = Add(_borders, $"{Side("left", style.Left)}{Side("right", style.Right)}{Side("top", style.Top)}{Side("bottom", style.Bottom)}");
diff --git a/src/Filee.Engines/Office/SpreadsheetConverter.cs b/src/Filee.Engines/Office/SpreadsheetConverter.cs
index a5754a46e..98e49393e 100644
--- a/src/Filee.Engines/Office/SpreadsheetConverter.cs
+++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs
@@ -1,4 +1,4 @@
-// Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS / XLT and the XLSM / XLTX
+// Spreadsheets between XLSX, XLS, ODS, CSV and TSV without Excel or LibreOffice (XLS / XLT, XLSB and the XLSM / XLTX
// variants are read, not written).
// XLSX / XLS / ODS → PDF are printed by SheetPrintConverter; CSV / TSV → PDF and every sheet → HWPX and HTML go
// through the HWPX writer (sheets become 한글 tables), see HwpxConverter and SheetDocument.
@@ -12,7 +12,7 @@ namespace Filee.Engines.Office;
/// Converts between spreadsheet formats in-process.
public sealed class SpreadsheetConverter : IConverter
{
- private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xls", "xlt", "ods", "csv", "tsv"];
+ private static readonly string[] Sources = ["xlsx", "xlsm", "xltx", "xlsb", "xls", "xlt", "ods", "csv", "tsv"];
private static readonly string[] Targets = ["xlsx", "ods", "csv", "tsv"];
public string Id => "spreadsheet";
@@ -25,7 +25,7 @@ [.. Sources.SelectMany(from => Targets.Where(to => to != from && !(to == "xlsx"
.Select(to => new ConversionEdge(from, to)))];
public EngineStatus GetStatus() =>
- EngineStatus.Available("XLSX, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV",
+ EngineStatus.Available("XLSX, XLSB, XLS, ODS, CSV, TSV → XLSX, ODS, CSV, TSV",
$"{EngineVersions.BuiltIn} · {EngineVersions.Library("ExcelDataReader", typeof(ExcelDataReader.ExcelReaderFactory))}");
public Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken cancellationToken) =>
@@ -79,6 +79,7 @@ internal static List Write(Workbook book, ConversionStep step)
internal static Workbook Read(string path, string format) => format switch
{
"xls" or "xlt" => XlsReader.Read(path),
+ XlsbReader.Format => XlsbReader.Read(path),
"ods" => OdsReader.Read(path),
"csv" => CsvFormat.Read(path),
"tsv" => CsvFormat.ReadTsv(path),
diff --git a/src/Filee.Engines/Pdf/PdfBlankPages.cs b/src/Filee.Engines/Pdf/PdfBlankPages.cs
index 1b80e7a98..e81cfe297 100644
--- a/src/Filee.Engines/Pdf/PdfBlankPages.cs
+++ b/src/Filee.Engines/Pdf/PdfBlankPages.cs
@@ -36,7 +36,7 @@ public static int Remove(string path)
try
{
int removed;
- using (var document = PdfReader.Open(fullPath, PdfDocumentOpenMode.Modify))
+ using (var document = PdfObjectNesting.Open(fullPath, PdfDocumentOpenMode.Modify))
{
var blank = Enumerable.Range(0, document.PageCount).Where(i => IsBlank(document.Pages[i])).ToList();
if (blank.Count == 0 || blank.Count == document.PageCount)
diff --git a/src/Filee.Engines/Pdf/PdfObjectNesting.cs b/src/Filee.Engines/Pdf/PdfObjectNesting.cs
new file mode 100644
index 000000000..80a679097
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfObjectNesting.cs
@@ -0,0 +1,691 @@
+// PDFsharp's object parser reads arrays and dictionaries recursively, with no limit, and PdfReader.Open reads every
+// object of a file at once, the ones packed in object streams and the ones nothing refers to included: about 1,900
+// "[" in one object (a few kilobytes) overflow a 1 MB stack, and a stack overflow ends the process with every
+// conversion in it. Every PDFsharp open of a file Filee did not write itself goes through Open here, which reads the
+// file first and refuses one nested more than MaxDepth deep with error.document_too_complex. PdfContentNesting does
+// the same for content streams before PDFsharp's ContentReader.
+//
+// PDFsharp jumps to each object from the cross-reference table, so reading the file from front to back is not enough:
+// a string that never closes, or the data of a stream, would hide an object from such a reading while PDFsharp still
+// parses it. The check therefore reads from every "obj" and "trailer" keyword in the file, wherever it is (in a string,
+// in stream data), the way PDFsharp's parser reads from there: strings with balanced parentheses and escapes,
+// comments, hex strings and names, up to the end of the object (a keyword such as endobj or stream at the top level).
+// Readings overlap only in damaged or crafted files; the bytes read in all are capped at a few times the file.
+//
+// Object streams hold objects without an "obj" keyword. PDFsharp finds them through the cross-reference stream and
+// doesn't need /Type /ObjStm, so every stream whose dictionary has /N is unpacked (with PDFsharp's own filters, which
+// it also applies without decrypting first, so the check sees exactly what the parser gets) and each object read from
+// the offset the stream's header gives.
+
+using System.Globalization;
+using System.Text;
+using Filee.Engines.Documents;
+using Microsoft.Win32.SafeHandles;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.Filters;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Pdf;
+
+/// Opens PDFs with PDFsharp once their arrays and dictionaries are known to nest few enough levels.
+internal static class PdfObjectNesting
+{
+ ///
+ /// Arrays and dictionaries inside each other at most. Real files nest a handful of levels (a page tree, an outline
+ /// and a structure tree link their entries by reference); PDFsharp overflowed a 1 MB stack at about 1,900.
+ ///
+ public const int MaxDepth = 256;
+
+ /// How many times its size (and its unpacked object streams) a file may be read in all.
+ private const int MaxReadsPerByte = 4;
+
+ /// What may always be read, whatever the file's size.
+ private const long ReadFloor = 16L * 1024 * 1024;
+
+ /// Opens with PDFsharp after checking it.
+ /// The file nests too deeply.
+ public static PdfDocument Open(string path, PdfDocumentOpenMode mode, CancellationToken cancellationToken = default)
+ {
+ Check(path, cancellationToken);
+ return PdfReader.Open(path, mode);
+ }
+
+ /// Opens a PDF in memory with PDFsharp after checking it.
+ /// The file nests too deeply.
+ public static PdfDocument Open(byte[] pdf, PdfDocumentOpenMode mode, CancellationToken cancellationToken = default)
+ {
+ Check(pdf, cancellationToken);
+ return PdfReader.Open(new MemoryStream(pdf), mode);
+ }
+
+ /// Checks the PDF at , reading it in windows (it is not loaded whole).
+ /// The file nests too deeply.
+ public static void Check(string path, CancellationToken cancellationToken = default)
+ {
+ using var file = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ new Checker(new Source(file), cancellationToken).Run();
+ }
+
+ /// Checks a PDF in memory.
+ /// The file nests too deeply.
+ public static void Check(byte[] pdf, CancellationToken cancellationToken = default) =>
+ new Checker(new Source(pdf), cancellationToken).Run();
+
+ private static Core.Conversion.ConversionRefusedException TooDeep() =>
+ DocumentLimits.Exceeded($"The PDF nests arrays or dictionaries more than {MaxDepth} deep.");
+
+ // ───────────────────────── The check ─────────────────────────
+
+ private sealed class Checker(Source file, CancellationToken cancellationToken)
+ {
+ /// Where the value of each numbered object starts (after "N G obj"); more than one after an update.
+ private readonly Dictionary> _objects = [];
+
+ private long _read;
+ private long _allowed = file.Length * MaxReadsPerByte + ReadFloor;
+
+ public void Run()
+ {
+ var starts = new List();
+ Keywords("obj"u8, starts, numbered: true);
+ Keywords("trailer"u8, starts, numbered: false);
+ starts.Sort();
+ foreach (var start in starts)
+ {
+ var (streamAt, hasN) = Read(file, start);
+ if (streamAt >= 0 && hasN)
+ ObjectStream(start, streamAt);
+ }
+ }
+
+ /// Every standing as a token of its own, with where the reading starts after it.
+ private void Keywords(ReadOnlySpan keyword, List starts, bool numbered)
+ {
+ for (var at = file.IndexOf(keyword, 0); at >= 0; at = file.IndexOf(keyword, at + 1))
+ {
+ if (!Ends(file[at - 1]) || !Ends(file[at + keyword.Length]))
+ continue;
+ var start = at + keyword.Length;
+ starts.Add(start);
+ if (numbered && Number(at) is { } number)
+ {
+ if (!_objects.TryGetValue(number, out var list))
+ _objects[number] = list = [];
+ list.Add(start);
+ }
+ if ((starts.Count & 0xFFF) == 0)
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+ }
+
+ /// The object number of "N G obj" whose keyword is at .
+ private long? Number(long keyword)
+ {
+ var at = keyword - 1;
+ return Digits(ref at, out _, out _) && Digits(ref at, out var from, out var to)
+ && long.TryParse(Text(file, from, to - from), NumberStyles.None, CultureInfo.InvariantCulture, out var number)
+ ? number
+ : null;
+ }
+
+ /// Steps back over white space and then up to 12 digits, which are at [from, to); false without any digit.
+ private bool Digits(ref long at, out long from, out long to)
+ {
+ while (at >= 0 && IsSpace(file[at]))
+ at--;
+ to = at + 1;
+ while (at >= 0 && file[at] is >= '0' and <= '9' && to - at <= 12)
+ at--;
+ from = at + 1;
+ return from < to;
+ }
+
+ ///
+ /// Reads one object as PDFsharp would from , refusing it when it nests too deeply. Returns
+ /// where its stream data begins (after "stream", else -1) and whether its dictionary has /N. An object after
+ /// "obj" ends at a keyword such as endobj; with (in an object stream) after its value.
+ ///
+ private (long StreamAt, bool HasN) Read(Source source, long at, bool oneValue = false)
+ {
+ var checkpoint = at;
+ var depth = 0;
+ var topIsDictionary = false;
+ var hasN = false;
+ while (true)
+ {
+ if (at - checkpoint > 1 << 20)
+ {
+ Spend(at - checkpoint);
+ checkpoint = at;
+ }
+ var kind = Next(source, ref at, out var start, out var length);
+ switch (kind)
+ {
+ case Kind.End:
+ Spend(at - checkpoint);
+ return (-1, hasN);
+ case Kind.DictionaryOpen or Kind.ArrayOpen:
+ if (++depth > MaxDepth)
+ throw TooDeep();
+ if (depth == 1)
+ topIsDictionary = kind == Kind.DictionaryOpen;
+ break;
+ case Kind.DictionaryClose or Kind.ArrayClose:
+ if (depth == 0)
+ {
+ Spend(at - checkpoint);
+ return (-1, hasN); // a stray closer: the parser stops with an error
+ }
+ depth--;
+ break;
+ case Kind.Name when depth == 1 && topIsDictionary && NameIs(source, start, length, "N"):
+ hasN = true;
+ break;
+ case Kind.Regular when depth == 0 && length <= 9:
+ var word = Text(source, start, length);
+ if (word is "stream" or "endobj" or "obj" or "endstream" or "trailer" or "xref" or "startxref")
+ {
+ Spend(at - checkpoint);
+ return (word == "stream" ? at : -1, hasN);
+ }
+ break;
+ }
+ if (oneValue && depth == 0)
+ {
+ Spend(at - checkpoint);
+ return (-1, hasN);
+ }
+ }
+ }
+
+ /// Counts bytes read; refuses a file that would be read too many times over.
+ private void Spend(long bytes)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _read += bytes;
+ if (_read > _allowed)
+ throw DocumentLimits.Exceeded("The PDF's objects overlap each other too often to be checked safely.");
+ }
+
+ // ───────────────────────── Object streams ─────────────────────────
+
+ /// Unpacks the stream of the object at and reads the objects its header lists.
+ private void ObjectStream(long start, long streamAt)
+ {
+ var at = start;
+ if (Value(file, ref at) is not Dictionary dictionary)
+ return;
+ var counts = Integers(dictionary.GetValueOrDefault("N"));
+ if (counts.Count == 0)
+ return; // no object can be looked up in it
+ // PDFsharp takes /N and /First only as integers in the dictionary itself (it fails on one by reference);
+ // references are followed here all the same.
+ var firsts = dictionary.TryGetValue("First", out var first) ? Integers(first) : [0];
+ if (firsts.Count == 0)
+ return;
+
+ if (Unpack(dictionary, streamAt) is not { } data)
+ return; // PDFsharp can't unpack it either, so it parses nothing of it
+ _allowed += (long)data.Length * MaxReadsPerByte;
+ var unpacked = new Source(data);
+
+ // The header: pairs of object number and offset (from /First), as many as /N says (and the data can hold).
+ var offsets = new List();
+ var pairs = Math.Min(counts.Max(), data.Length / 4 + 1);
+ long position = 0;
+ for (var i = 0L; i < pairs * 2; i++)
+ {
+ if (Next(unpacked, ref position, out var tokenStart, out var length) != Kind.Regular
+ || !long.TryParse(Text(unpacked, tokenStart, length), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
+ break;
+ if (i % 2 == 1)
+ offsets.Add(number);
+ }
+ foreach (var from in firsts)
+ {
+ foreach (var offset in offsets)
+ {
+ var objectAt = from + offset;
+ if (objectAt >= 0 && objectAt < data.Length)
+ Read(unpacked, objectAt, oneValue: true);
+ }
+ }
+ }
+
+ /// The stream's data unpacked with PDFsharp's filters, or null when they can't unpack it.
+ private byte[]? Unpack(Dictionary dictionary, long streamAt)
+ {
+ // The data starts after the end of line that follows "stream".
+ var dataAt = streamAt;
+ if (file[dataAt] == '\r')
+ dataAt++;
+ if (file[dataAt] == '\n')
+ dataAt++;
+ // Its end: the longest of /Length and the next "endstream" (PDFsharp's filters stop at the end of the
+ // packed data, so more bytes than it takes never unpack to less).
+ var end = file.IndexOf("endstream"u8, dataAt);
+ foreach (var length in Integers(dictionary.GetValueOrDefault("Length")))
+ {
+ if (length >= 0 && length <= file.Length - dataAt)
+ end = Math.Max(end, dataAt + length);
+ }
+ if (end < 0)
+ end = file.Length;
+ if (end - dataAt > DocumentLimits.Default.MaxPartBytes)
+ throw DocumentLimits.Exceeded($"An object stream of the PDF is larger than {DocumentLimits.Megabytes(DocumentLimits.Default.MaxPartBytes)}.");
+ var data = file.Read(dataAt, (int)(end - dataAt));
+
+ var filters = Resolve(dictionary.GetValueOrDefault("Filter")) switch
+ {
+ PdfNameValue name => [name.Value],
+ List