Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert office files without Office or LibreOffice

KnifeLemon9c0cc3364ab8
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e2bff27f..c1cece4e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,9 +6,12 @@ Thanks for helping! Filee is built to be easy to extend: most contributions touc
1. Install the .NET 10 SDK (the exact feature band is pinned in `global.json`, newer patches roll forward).
2. `pwsh build/fetch-fonts.ps1` (optional, for the Noto Sans UI fonts).
-3. `pwsh build/fetch-engines.ps1 -Only rhwp,pandoc` (optional, enables HWP/HWPX → PDF, HWP ↔ HWPX and
- HTML / Markdown ↔ Word; Markdown → HTML, TXT and HWPX work without it). Without `-Only` it also downloads LibreOffice with H2Orestart and Java (~420 MB). Engines in the
+3. `pwsh build/fetch-engines.ps1 -Only rhwp,pandoc` (optional: rhwp renders HWP/HWPX, and everything converted
+ through HWPX — DOCX, XLSX, CSV, PPTX, Markdown — to PDF, and converts HWP ↔ HWPX; Pandoc adds HTML / Markdown ↔
+ DOCX. XLSX ↔ CSV and anything → HWPX work without either). Without `-Only` it also downloads LibreOffice with
+ H2Orestart and Java (~420 MB), which only older formats such as DOC, XLS and PPT need. Engines in the
repository's `engines/` folder are picked up by debug builds; users download the large ones from the app.
+ Filee never uses programs installed on the system (Microsoft Office, a system LibreOffice, tools on `PATH`).
4. `dotnet run --project src/Filee.App`, `dotnet test`.
Any IDE works (Visual Studio 2022+, Rider, VS Code with C# Dev Kit).
@@ -28,7 +31,7 @@ Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short:
- Comments are in English so every contributor can read them.
- Every file starts with a short comment saying what it is for.
- Public types and members get `///` XML docs.
- - Explain *why* for anything non-obvious (workarounds, engine quirks) — see `WordComConverter.cs` for the tone.
+ - Explain *why* for anything non-obvious (workarounds, engine quirks) — see `LibreOfficeConverter.cs` for the tone.
- Keep UI strings out of code: add a key to all three `i18n/*.json` files (a test checks they match).
- Prefer small, focused pull requests.
@@ -36,8 +39,8 @@ Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short:
- `tests/Filee.Core.Tests` – pure logic (fast).
- `tests/Filee.Engines.Tests` – real conversions on generated input files. Tests needing an engine that is not
- installed skip automatically. Microsoft Word is only used when `FILEE_TEST_WORD=1` is set (it opens real Word
- windows).
+ installed skip automatically. XLSX and PPTX inputs are generated by `OfficeBuilders.cs`, DOCX by
+ `DocxBuilder.cs`.
- `tests/Filee.App.Tests` – gesture state machine, donut geometry, translations and headless UI rendering.
Screenshots of every page land in `tests/Filee.App.Tests/bin/<config>/net10.0/screenshots` — attach them to
UI pull requests.
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 78040e85..7fbcbe54 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -33,6 +33,7 @@
<PackageVersion Include="PDFtoImage" Version="5.2.1" />
<PackageVersion Include="Unhwp" Version="0.13.0" />
<PackageVersion Include="Markdig" Version="1.4.0" />
+ <PackageVersion Include="ExcelNumberFormat" Version="1.1.0" />
</ItemGroup>
<ItemGroup Label="Tests">
diff --git a/README.ko.md b/README.ko.md
index bb6abbc8..70dca7c5 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -43,7 +43,7 @@
- **커서 위치에 뜨는 도넛 툴바.** 수정키 + 파일 드래그(기본 <kbd>Ctrl</kbd>). 수정키 조합, 마우스 버튼, 드래그 거리,
길게 누르기, 선택한 파일용 키보드 단축키까지 모두 바꿀 수 있습니다.
-- **파일 종류별 툴바.** 이미지, PDF, 오피스 문서, HWP/HWPX, 혼합 파일용 프로필. 실제 도넛 위에서 드래그 앤 드롭으로
+- **파일 종류별 툴바.** 이미지, PDF, 문서, 스프레드시트, 프레젠테이션, HWP/HWPX, 텍스트, 혼합 파일용 프로필. 실제 도넛 위에서 드래그 앤 드롭으로
프리셋을 넣고, 빼고, 순서를 바꿉니다. 우클릭이나 ✎로 프리셋을 편집합니다.
- **프리셋.** 품질, 크기 조정, DPI, 메타데이터, TIFF 압축, ICO 크기, PDF 합치기·나누기, 페이지 범위,
저장 위치, 파일 이름 패턴, 이름 충돌 처리.
@@ -60,12 +60,14 @@
| **이미지**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, HEIC(읽기) | 모든 이미지 형식, PDF |
| **PDF** | PNG, JPG, TIFF, 합치기, 나누기, 페이지 범위 |
| **문서**: DOCX, DOC, ODT, RTF | PDF, HWPX, 서로 변환, TXT, HTML |
+| **스프레드시트**: XLSX, XLS, ODS, CSV | PDF, XLSX ↔ CSV, HWPX, HTML |
+| **프레젠테이션**: PPTX, PPT, ODP | PDF, PNG, JPG, HWPX |
| **한글**: HWP, HWPX | PDF, HWPX ↔ HWP, DOCX, TXT, 마크다운, HTML |
-| **스프레드시트·프레젠테이션**: XLSX, XLS, ODS, CSV, PPTX, PPT, ODP | PDF와 서로 변환 |
| **텍스트**: TXT, 마크다운, HTML | DOCX, HWPX, PDF |
-마크다운 → PDF·HWPX·HTML·TXT는 설치하자마자 됩니다. 오피스 문서는 LibreOffice, HTML과 마크다운 ↔ 워드는 Pandoc을
-쓰는데, 둘 다 처음 실행할 때 받을지 물어보는 추가 엔진입니다.
+DOCX·XLSX·CSV·PPTX → PDF, 한글 파일, 마크다운은 설치하자마자 변환됩니다. MS 오피스·한컴오피스·LibreOffice가 없어도
+되고, PC에 설치된 프로그램은 쓰지 않습니다. 오래된 형식(DOC·XLS·PPT·OpenDocument)과 DOCX·ODT로 저장하기는
+LibreOffice, HTML과 마크다운 ↔ 워드는 Pandoc을 쓰는데, 둘 다 처음 실행할 때 받을지 물어보는 추가 엔진입니다.
HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)에 있습니다.
## 스크린샷
@@ -94,8 +96,8 @@ HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md
**설치:** [`Filee-win-Setup.exe`](https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe)를 받으세요
(Windows 10/11, 64비트). 다른 버전은 [Releases](https://github.com/KnifeLemon/Filee/releases)에 있습니다.
-- **설치 파일은 가볍습니다.** 이미지, PDF, HWP/HWPX, DOCX → HWPX는 설치하자마자 바로 변환됩니다.
-- **큰 엔진은 골라서 설치합니다.** 처음 실행하면 LibreOffice(오피스 문서, 약 420MB)와 Pandoc(HTML·마크다운 ↔ 워드, 약 42MB)을 받을지 묻습니다. 나중에 설정 → 변환 엔진에서 언제든 설치하거나 지울 수 있습니다.
+- **설치 파일은 가볍습니다.** 이미지, PDF, HWP/HWPX, 마크다운, DOCX·XLSX·PPTX → PDF, XLSX ↔ CSV는 설치하자마자 바로 변환됩니다.
+- **큰 엔진은 골라서 설치합니다.** 처음 실행하면 LibreOffice(DOC·XLS·PPT 같은 오래된 오피스 형식, 약 420MB)와 Pandoc(HTML·마크다운 ↔ 워드, 약 42MB)을 받을지 묻습니다. 나중에 설정 → 변환 엔진에서 언제든 설치하거나 지울 수 있습니다.
- **업데이트는 알려 드려요.** 새 버전이 나오면 메뉴 하단, 알림, 트레이 메뉴에 표시되고 누르면 최신 릴리스 페이지가
열립니다. 새 설치 파일을 실행하면 설정은 그대로 유지돼요.
diff --git a/README.md b/README.md
index e202c0fe..273f687a 100644
--- a/README.md
+++ b/README.md
@@ -43,7 +43,8 @@
- **Donut toolbar at the cursor.** Modifier + drag files (default <kbd>Ctrl</kbd>). Everything is configurable: any modifier
combination, mouse button, drag distance, a hold gesture or a keyboard shortcut for the selected files.
-- **One toolbar per file type.** Images, PDF, office documents, HWP/HWPX and a fallback for mixed files.
+- **One toolbar per file type.** Images, PDF, documents, spreadsheets, presentations, HWP/HWPX, text and a fallback
+ for mixed files.
Arrange presets on a live donut by drag & drop; right-click or ✎ edits a preset.
- **Presets.** Quality, resizing, DPI, metadata, TIFF compression, ICO sizes, PDF merge and split, page ranges,
output folder, file name pattern and conflict handling.
@@ -63,12 +64,15 @@
| **Images**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, HEIC (read) | any image format, PDF |
| **PDF** | PNG, JPG, TIFF, merge, split, page ranges |
| **Documents**: DOCX, DOC, ODT, RTF | PDF, HWPX, each other, TXT, HTML |
+| **Spreadsheets**: XLSX, XLS, ODS, CSV | PDF, XLSX ↔ CSV, HWPX, HTML |
+| **Presentations**: PPTX, PPT, ODP | PDF, PNG, JPG, HWPX |
| **HWP**: HWP, HWPX | PDF, HWPX ↔ HWP, DOCX, TXT, Markdown, HTML |
-| **Spreadsheets & slides**: XLSX, XLS, ODS, CSV, PPTX, PPT, ODP | PDF and each other |
| **Text**: TXT, Markdown, HTML | DOCX, HWPX, PDF |
-Markdown → PDF, HWPX, HTML and TXT work out of the box. Office documents use LibreOffice, and HTML / Markdown ↔ Word use
-Pandoc: optional engines that Filee offers to download on first start.
+DOCX, XLSX, CSV and PPTX → PDF, everything HWP and Markdown work out of the box: no Microsoft Office, Hancom Office or
+LibreOffice needed, and Filee never uses programs installed on your PC. Older formats (DOC, XLS, PPT, OpenDocument)
+and saving as DOCX / ODT use LibreOffice, HTML / Markdown ↔ Word use Pandoc: optional engines that Filee offers to
+download on first start.
How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).
## Screenshots
@@ -97,8 +101,8 @@ How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).
**Install:** download [`Filee-win-Setup.exe`](https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe)
(Windows 10/11, 64-bit) or pick a version on the [Releases](https://github.com/KnifeLemon/Filee/releases) page.
-- **The installer is small.** Images, PDF, HWP/HWPX and DOCX → HWPX work right away.
-- **Large engines are optional.** On first start Filee offers LibreOffice for office documents (~420 MB) and Pandoc for HTML and Markdown ↔ Word (~42 MB). You can install or remove them any time in Settings → Engines.
+- **The installer is small.** Images, PDF, HWP/HWPX, Markdown, DOCX / XLSX / PPTX → PDF and XLSX ↔ CSV work right away.
+- **Large engines are optional.** On first start Filee offers LibreOffice for older office formats such as DOC, XLS and PPT (~420 MB) and Pandoc for HTML and Markdown ↔ Word (~42 MB). You can install or remove them any time in Settings → Engines.
- **You hear about updates.** When a new release is out, Filee says so at the bottom of the menu, in a notice and in
the tray menu, and opens the latest release to download it. Run the new installer; your settings are kept.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index f2adab56..6ff3096d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -43,7 +43,7 @@
- **光标处的格式圆环。** 按住修饰键拖动文件(默认 <kbd>Ctrl</kbd>)。修饰键组合、鼠标按键、拖动距离、长按手势,
以及对选中文件使用的快捷键都可以自定义。
-- **按文件类型的工具栏。** 图片、PDF、办公文档、HWP/HWPX,以及用于混合文件的通用配置。
+- **按文件类型的工具栏。** 图片、PDF、文档、电子表格、演示文稿、HWP/HWPX、文本,以及用于混合文件的通用配置。
直接在圆环上拖放来添加、移除和排序预设;右键或 ✎ 编辑预设。
- **预设。** 质量、缩放、DPI、元数据、TIFF 压缩、ICO 尺寸、PDF 合并与拆分、页码范围、
保存位置、文件名模板和重名处理。
@@ -60,12 +60,14 @@
| **图片**:JPG、PNG、WEBP、TIFF、BMP、GIF、ICO、AVIF、HEIC(读取) | 任意图片格式、PDF |
| **PDF** | PNG、JPG、TIFF、合并、拆分、页码范围 |
| **文档**:DOCX、DOC、ODT、RTF | PDF、HWPX、互相转换、TXT、HTML |
+| **电子表格**:XLSX、XLS、ODS、CSV | PDF、XLSX ↔ CSV、HWPX、HTML |
+| **演示文稿**:PPTX、PPT、ODP | PDF、PNG、JPG、HWPX |
| **HWP**:HWP、HWPX | PDF、HWPX ↔ HWP、DOCX、TXT、Markdown、HTML |
-| **表格与演示文稿**:XLSX、XLS、ODS、CSV、PPTX、PPT、ODP | PDF 及互相转换 |
| **文本**:TXT、Markdown、HTML | DOCX、HWPX、PDF |
-Markdown → PDF、HWPX、HTML、TXT 装好即用。办公文档使用 LibreOffice,HTML 与 Markdown ↔ Word 使用 Pandoc,
-这两个可选引擎会在首次启动时询问是否下载。
+DOCX、XLSX、CSV、PPTX → PDF,所有 HWP 转换和 Markdown 装好即用:无需 Microsoft Office、韩文办公软件或 LibreOffice,
+Filee 也从不调用电脑上已安装的程序。较旧的格式(DOC、XLS、PPT、OpenDocument)以及保存为 DOCX / ODT 使用 LibreOffice,
+HTML 与 Markdown ↔ Word 使用 Pandoc,这两个可选引擎会在首次启动时询问是否下载。
HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)。
## 截图
@@ -94,8 +96,8 @@ HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)
**安装:** 下载 [`Filee-win-Setup.exe`](https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe)
(Windows 10/11,64 位),或在 [Releases](https://github.com/KnifeLemon/Filee/releases) 页面选择其他版本。
-- **安装包很小。** 图片、PDF、HWP/HWPX 和 DOCX → HWPX 装好即用。
-- **大型引擎按需下载。** 首次启动时会询问是否下载 LibreOffice(办公文档,约 420 MB)和 Pandoc(HTML 与 Markdown ↔ Word,约 42 MB);之后可随时在“设置 → 转换引擎”中安装或删除。
+- **安装包很小。** 图片、PDF、HWP/HWPX、Markdown、DOCX / XLSX / PPTX → PDF 以及 XLSX ↔ CSV 装好即用。
+- **大型引擎按需下载。** 首次启动时会询问是否下载 LibreOffice(DOC、XLS、PPT 等旧版办公格式,约 420 MB)和 Pandoc(HTML 与 Markdown ↔ Word,约 42 MB);之后可随时在“设置 → 转换引擎”中安装或删除。
- **有更新会提醒你。** 新版本发布后,Filee 会在菜单底部、通知和托盘菜单中提示,点击即可打开最新发布页面下载。
运行新的安装程序即可更新,设置会保留。
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index ef80b2aa..05fb3bc0 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -19,6 +19,7 @@ Each component remains under its own license.
| SkiaSharp | MIT | https://github.com/mono/SkiaSharp |
| Unhwp | MIT | https://github.com/iyulab/unhwp |
| Markdig | BSD-2-Clause | https://github.com/xoofx/markdig |
+| ExcelNumberFormat | MIT | https://github.com/andersnm/ExcelNumberFormat |
| pypandoc-hwpx (Pandoc AST mapping and package layout in `Filee.Engines/Hwp/Hwpx`, incl. the `blank.hwpx` reference document) | MIT, Copyright (c) 2024 pypandoc-hwpx Contributors | https://github.com/msjang/pypandoc-hwpx |
| Microsoft.Extensions.* | MIT | https://github.com/dotnet/runtime |
@@ -48,8 +49,3 @@ These programs run as separate processes. Their source code is available from th
|---|---|---|
| Noto Sans, Noto Sans KR, Noto Sans SC | SIL Open Font License 1.1 | https://github.com/notofonts |
| Material Design Icons (Pictogrammers) | Apache-2.0 | https://pictogrammers.com |
-
-## Optional engines used when installed by the user
-
-Microsoft Word is a commercial product. Filee only automates a copy that is already installed on the user's
-computer and does not redistribute it.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4375e62d..d0f651b2 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -20,8 +20,9 @@
▼
┌──────────────────────────── Filee.Engines ────────────────────────────────────────┐
│ Magick (images) · PdfSharp (image→PDF, merge, split) · Pdfium (PDF→image) │
- │ LibreOffice (office, HWP via H2Orestart) · rhwp (HWP→PDF, HWP↔HWPX) · Unhwp │
- │ HwpxWriter (DOCX / Markdown / Pandoc AST → HWPX) · Markdig · Pandoc · Word COM │
+ │ LibreOffice (old formats, HWP via H2Orestart) · rhwp (HWP→PDF, HWP↔HWPX) · Unhwp │
+ │ HwpxWriter (DOCX / XLSX / PPTX / Markdown → HWPX) · Spreadsheet · Markdig │
+ │ Pandoc (HTML / ODT / RTF, Markdown ↔ DOCX) │
└────────────────────────────────────────────────────────────────────────────────────┘
```
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index cae324dc..15adb4d1 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -1,8 +1,7 @@
# Conversion engines
Filee chooses engines automatically. Settings → *Engines* shows their status, lets you change the priority
-(higher wins when two engines can do the same conversion), point an engine at a custom executable, and install
-or remove the optional engines.
+(higher wins when two engines can do the same conversion), and install or remove the optional engines.
| Engine | How it gets there | Handles |
|---|---|---|
@@ -11,14 +10,18 @@ or remove the optional engines.
| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |
-| **HWPX writer** | built in | **DOCX, TXT, Markdown → HWPX**; HTML, ODT, RTF → HWPX with Pandoc |
+| Spreadsheets | built in | **XLSX ↔ CSV** (one CSV per sheet) |
+| **HWPX writer** | built in | **DOCX, XLSX, CSV, PPTX, TXT, Markdown → HWPX** (and with rhwp → PDF and images); HTML, ODT, RTF → HWPX with Pandoc |
| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
-| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | DOCX/DOC/ODT/RTF/XLSX/PPTX… ↔ each other and → PDF; HWP/HWPX → DOCX/ODT |
+| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS; HWP/HWPX → DOCX/ODT |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT |
-| Microsoft Word | used if installed | best-fidelity DOCX → PDF, PDF → DOCX |
-Engines found on the system (an installed LibreOffice, `soffice`/`rhwp`/`pandoc` on PATH) are used when Filee's own
-copy is missing, e.g. when running from source.
+DOCX, XLSX and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
+and rendered by rhwp. LibreOffice's cost is set so the built-in route always wins where one exists.
+
+Filee never uses software installed on the system (Microsoft Office, an installed LibreOffice, programs on `PATH`):
+every engine is built in, bundled or downloaded into Filee's own folder, so a conversion behaves the same on every
+PC. Running from source, the repository's `engines/` folder (filled by `build/fetch-engines.ps1`) is used.
## Optional engines
@@ -55,6 +58,19 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an
- pictures inline and floating, text boxes, rectangles/ellipses/lines with solid or gradient fills, groups;
- footnotes, endnotes, bookmarks, hyperlinks (web and within the document, e.g. a table of contents);
- Word's document grid ("lines"), which 한글 does not have, as an "at least" line spacing.
+- **XLSX and CSV** (`Office/Sheets`): every visible sheet becomes a section with one table. Cells show what Excel
+ shows (number formats via ExcelNumberFormat, dates, percentages, cached formula results), with fonts, fills,
+ borders, alignment and merged cells; frozen top rows repeat on every page. The page is A4 with narrow margins,
+ landscape when the columns are much wider than portrait, and the table is scaled to the page width like
+ Excel's "Fit all columns on one page". CSV is read with its delimiter (comma, semicolon, tab) and encoding
+ (UTF-8 / UTF-16 with BOM, else CP949 as saved by Korean Excel). Not converted: charts, pictures, conditional
+ formatting, print areas and page breaks.
+- **PPTX** (`Hwp/Hwpx/Pptx`): one page per slide, sized like the slide, with every object floating at its place:
+ placeholders inherit position and text style from the layout and master, text with bullets and numbering,
+ shapes (rectangles, rounded rectangles, ellipses, lines) with solid or gradient fills and outlines, pictures,
+ tables with PowerPoint's default table style, groups, master decorations and the slide background. Not
+ converted: charts, SmartArt, rotation, effects (shadows, glow), picture cropping, animations, notes and hidden
+ slides.
- **TXT** needs no reader (one paragraph per line; UTF-8, UTF-16 or the Korean code page CP949).
- **Markdown** is parsed with Markdig (`MarkdownReader.cs`): headings, emphasis, code, lists (1. / a. / i. with
start numbers), task lists, quotes, tables with spans, links, images, footnotes and math. No Pandoc needed.
@@ -71,7 +87,8 @@ Element order and attribute values follow files saved by 한글 where the schema
- layout caches (table row heights, inline tab widths) are estimated, because simpler readers use them as-is.
Every generated file is checked in the tests with three independent readers: rhwp (renders it), Unhwp (reads the
-text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/DocxToHwpxTests.cs`.
+text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/DocxToHwpxTests.cs` and
+`OfficeTests.cs`.
Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 25b90768..728783c4 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -52,14 +52,15 @@
"error.conversion_failed": "The engine reported an error",
"engine.reason.not_installed": "Not installed",
- "engine.reason.windows_only": "Windows only",
"engine.reason.error": "Error while checking",
"engine.reason.unsupported_platform": "Not available on this platform",
"engine.reason.needs_package": "Needs {0} — install it in Settings → Engines",
"profile.images": "Images",
"profile.pdf": "PDF",
- "profile.office": "Office documents",
+ "profile.office": "Documents",
+ "profile.spreadsheets": "Spreadsheets",
+ "profile.presentations": "Presentations",
"profile.hwp": "HWP / HWPX",
"profile.text": "Text & Markdown",
"profile.mixed": "Mixed files",
@@ -221,15 +222,13 @@
"engines.unavailable": "Unavailable",
"engines.move_up": "Move up",
"engines.move_down": "Move down",
- "engines.custom_path": "Custom executable",
- "engines.browse": "Browse…",
"engines.recheck": "Check again",
"engines.conversions": "{0} conversions",
"engines.optional_title": "Optional engines",
"engines.optional_description": "Large engines are only downloaded when you want them. They are kept when Filee updates and removed when you uninstall it.",
"engines.all_title": "All engines",
- "engines.package.libreoffice.name": "LibreOffice (office documents)",
- "engines.package.libreoffice.description": "Word, Excel, PowerPoint and OpenDocument files to PDF and to each other, DOC ↔ DOCX, and HWP → DOCX (includes the H2Orestart filter and Java).",
+ "engines.package.libreoffice.name": "LibreOffice (older and rare formats)",
+ "engines.package.libreoffice.description": "Only needed for older and less common formats: DOC, XLS, PPT and OpenDocument files, conversions to DOCX, ODT and ODS, and HWP → DOCX (includes the H2Orestart filter and Java). DOCX, XLSX, PPTX and CSV convert without it.",
"engines.package.pandoc.name": "Pandoc (HTML and Markdown ↔ Word)",
"engines.package.pandoc.description": "Markdown ↔ DOCX, ODT and RTF, and HTML, ODT and RTF → HWPX. Markdown → PDF, HWPX, HTML and TXT, and DOCX → HWPX work without it.",
"engines.package.size": "Download {0} · {1} on disk",
@@ -260,7 +259,7 @@
"common.no": "No",
"setup.title": "Choose conversion engines",
- "setup.description": "Filee already converts images, PDF, HWP/HWPX and DOCX → HWPX. Choose the engines to download for more formats.",
+ "setup.description": "Filee already converts images, PDF, HWP/HWPX, Markdown, and DOCX, XLSX and PPTX to PDF. Download engines only for the formats you need.",
"setup.note": "You can install or remove engines at any time in Settings → Engines.",
"setup.install": "Install selected",
"setup.later": "Later",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index fb888ce6..faa3ce0c 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -52,14 +52,15 @@
"error.conversion_failed": "엔진에서 오류가 발생했어요",
"engine.reason.not_installed": "설치되지 않음",
- "engine.reason.windows_only": "Windows 전용",
"engine.reason.error": "확인 중 오류",
"engine.reason.unsupported_platform": "이 플랫폼에서는 사용할 수 없음",
"engine.reason.needs_package": "{0} 필요 — 설정 → 변환 엔진에서 설치",
"profile.images": "이미지",
"profile.pdf": "PDF",
- "profile.office": "오피스 문서",
+ "profile.office": "문서",
+ "profile.spreadsheets": "스프레드시트",
+ "profile.presentations": "프레젠테이션",
"profile.hwp": "HWP / HWPX",
"profile.text": "텍스트·마크다운",
"profile.mixed": "혼합 파일",
@@ -221,15 +222,13 @@
"engines.unavailable": "사용 불가",
"engines.move_up": "위로",
"engines.move_down": "아래로",
- "engines.custom_path": "실행 파일 직접 지정",
- "engines.browse": "찾아보기…",
"engines.recheck": "다시 확인",
"engines.conversions": "변환 {0}종",
"engines.optional_title": "선택 설치 엔진",
"engines.optional_description": "용량이 큰 엔진은 원할 때만 내려받습니다. Filee를 업데이트해도 유지되고, 제거하면 함께 지워집니다.",
"engines.all_title": "전체 엔진",
- "engines.package.libreoffice.name": "LibreOffice (오피스 문서)",
- "engines.package.libreoffice.description": "워드·엑셀·파워포인트·오픈오피스 문서를 PDF나 다른 형식으로 변환합니다. DOC ↔ DOCX, HWP → DOCX도 됩니다(H2Orestart 필터와 Java 포함).",
+ "engines.package.libreoffice.name": "LibreOffice (오래되었거나 드문 형식)",
+ "engines.package.libreoffice.description": "오래되었거나 흔하지 않은 형식에만 필요해요: DOC·XLS·PPT·OpenDocument 파일, DOCX·ODT·ODS로 변환, HWP → DOCX (H2Orestart 필터와 Java 포함). DOCX·XLSX·PPTX·CSV는 없어도 변환돼요.",
"engines.package.pandoc.name": "Pandoc (HTML·마크다운 ↔ 워드)",
"engines.package.pandoc.description": "마크다운 ↔ DOCX·ODT·RTF 변환과 HTML·ODT·RTF → HWPX 변환을 추가합니다. 마크다운 → PDF·HWPX·HTML·TXT와 DOCX → HWPX는 없어도 됩니다.",
"engines.package.size": "다운로드 {0} · 설치 후 {1}",
@@ -260,7 +259,7 @@
"common.no": "아니요",
"setup.title": "변환 엔진 선택",
- "setup.description": "Filee는 지금 바로 이미지, PDF, HWP/HWPX, DOCX → HWPX를 변환할 수 있습니다. 더 많은 형식이 필요하면 내려받을 엔진을 고르세요.",
+ "setup.description": "Filee는 지금 바로 이미지, PDF, HWP/HWPX, 마크다운, DOCX·XLSX·PPTX → PDF를 변환할 수 있습니다. 더 필요한 형식이 있을 때만 엔진을 내려받으세요.",
"setup.note": "엔진은 언제든 설정 → 변환 엔진에서 설치하거나 제거할 수 있습니다.",
"setup.install": "선택한 엔진 설치",
"setup.later": "나중에",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index f86ad0e4..0d581254 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -52,14 +52,15 @@
"error.conversion_failed": "引擎报告了错误",
"engine.reason.not_installed": "未安装",
- "engine.reason.windows_only": "仅限 Windows",
"engine.reason.error": "检查时出错",
"engine.reason.unsupported_platform": "此平台不可用",
"engine.reason.needs_package": "需要 {0} — 在 设置 → 转换引擎 中安装",
"profile.images": "图片",
"profile.pdf": "PDF",
- "profile.office": "办公文档",
+ "profile.office": "文档",
+ "profile.spreadsheets": "电子表格",
+ "profile.presentations": "演示文稿",
"profile.hwp": "HWP / HWPX",
"profile.text": "文本与 Markdown",
"profile.mixed": "混合文件",
@@ -221,15 +222,13 @@
"engines.unavailable": "不可用",
"engines.move_up": "上移",
"engines.move_down": "下移",
- "engines.custom_path": "自定义可执行文件",
- "engines.browse": "浏览…",
"engines.recheck": "重新检查",
"engines.conversions": "{0} 种转换",
"engines.optional_title": "可选引擎",
"engines.optional_description": "体积较大的引擎仅在需要时下载。更新 Filee 时会保留,卸载时一并删除。",
"engines.all_title": "全部引擎",
- "engines.package.libreoffice.name": "LibreOffice(办公文档)",
- "engines.package.libreoffice.description": "将 Word、Excel、PowerPoint 和 OpenDocument 文件转换为 PDF 或相互转换,支持 DOC ↔ DOCX 和 HWP → DOCX(含 H2Orestart 过滤器和 Java)。",
+ "engines.package.libreoffice.name": "LibreOffice(旧版和少见格式)",
+ "engines.package.libreoffice.description": "仅用于较旧或不常见的格式:DOC、XLS、PPT 和 OpenDocument 文件,转换为 DOCX、ODT 和 ODS,以及 HWP → DOCX(含 H2Orestart 过滤器和 Java)。DOCX、XLSX、PPTX 和 CSV 无需它即可转换。",
"engines.package.pandoc.name": "Pandoc(HTML 与 Markdown ↔ Word)",
"engines.package.pandoc.description": "支持 Markdown ↔ DOCX、ODT、RTF,以及 HTML、ODT、RTF → HWPX。Markdown → PDF、HWPX、HTML、TXT 和 DOCX → HWPX 无需此引擎。",
"engines.package.size": "下载 {0} · 占用 {1}",
@@ -260,7 +259,7 @@
"common.no": "否",
"setup.title": "选择转换引擎",
- "setup.description": "Filee 现在即可转换图片、PDF、HWP/HWPX 以及 DOCX → HWPX。如需更多格式,请选择要下载的引擎。",
+ "setup.description": "Filee 现在即可转换图片、PDF、HWP/HWPX、Markdown,以及 DOCX、XLSX、PPTX → PDF。仅在需要其他格式时才下载引擎。",
"setup.note": "可随时在 设置 → 转换引擎 中安装或删除引擎。",
"setup.install": "安装所选引擎",
"setup.later": "稍后",
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
index a9f22a35..1d7ae0e0 100644
--- a/src/Filee.App/Services/AppHost.cs
+++ b/src/Filee.App/Services/AppHost.cs
@@ -40,11 +40,7 @@ public static class AppHost
services.AddSingleton<ThemeService>();
// Conversion engines
- services.AddSingleton(sp =>
- {
- var store = sp.GetRequiredService<UserDataStore>();
- return new EngineEnvironment(id => store.Settings.EnginePaths.GetValueOrDefault(id), dataDir);
- });
+ services.AddSingleton(_ => new EngineEnvironment(dataDir));
services.AddSingleton(sp => EngineRegistry.CreateAll(sp.GetRequiredService<EngineEnvironment>()));
services.AddSingleton(sp => new ConverterCatalog(sp.GetRequiredService<IReadOnlyList<IConverter>>()));
services.AddSingleton(sp => new JobQueue(
diff --git a/src/Filee.App/ViewModels/EngineSetupViewModel.cs b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
index 51704fb8..04e564f6 100644
--- a/src/Filee.App/ViewModels/EngineSetupViewModel.cs
+++ b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
@@ -20,7 +20,9 @@ public sealed partial class EngineSetupViewModel : ObservableObject
_loc = loc;
foreach (var package in Packages)
{
- package.Selected = !package.IsInstalled;
+ // LibreOffice is large and only needed for older formats (DOC, XLS, PPT, OpenDocument): offered, not
+ // pre-selected.
+ package.Selected = !package.IsInstalled && package.Package.Id != "libreoffice";
package.PropertyChanged += OnPackageChanged;
}
}
diff --git a/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs b/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs
index 6d0430e7..27a0bb0e 100644
--- a/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs
+++ b/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs
@@ -1,4 +1,5 @@
-// Conversion engines: optional downloads, availability, priority order and custom executable paths.
+// Conversion engines: optional downloads, availability and priority order. Filee only uses its own engine copies,
+// so there are no paths to configure.
using System.Collections.ObjectModel;
using Avalonia.Threading;
@@ -11,35 +12,14 @@ using Filee.Core.Settings;
namespace Filee.App.ViewModels.Pages;
-public sealed partial class EngineItemViewModel : ObservableObject
+public sealed class EngineItemViewModel(IConverter converter, EngineStatus status, ILocalizer loc)
{
- private readonly Action<EngineItemViewModel, string> _pathChanged;
-
- public EngineItemViewModel(IConverter converter, EngineStatus status, string? customPath, ILocalizer loc,
- Action<EngineItemViewModel, string> pathChanged)
- {
- Converter = converter;
- _pathChanged = pathChanged;
- IsAvailable = status.IsAvailable;
- StatusText = status.IsAvailable ? loc["engines.available"] : loc[status.ReasonKey ?? "engines.unavailable"];
- Detail = status.Detail;
- Conversions = loc.Format("engines.conversions", converter.Edges.Count);
- _customPath = customPath ?? "";
- // Only command line engines can be pointed at a custom executable.
- SupportsCustomPath = converter.Id is "libreoffice" or "rhwp" or "pandoc";
- }
-
- public IConverter Converter { get; }
+ public IConverter Converter { get; } = converter;
public string Name => Converter.DisplayName;
- public bool IsAvailable { get; }
- public string StatusText { get; }
- public string? Detail { get; }
- public string Conversions { get; }
- public bool SupportsCustomPath { get; }
-
- [ObservableProperty] private string _customPath;
-
- partial void OnCustomPathChanged(string value) => _pathChanged(this, value);
+ public bool IsAvailable { get; } = status.IsAvailable;
+ public string StatusText { get; } = status.IsAvailable ? loc["engines.available"] : loc[status.ReasonKey ?? "engines.unavailable"];
+ public string? Detail { get; } = status.Detail;
+ public string Conversions { get; } = loc.Format("engines.conversions", converter.Edges.Count);
}
public sealed partial class EnginesPageViewModel : ObservableObject, IDisposable
@@ -82,8 +62,7 @@ public sealed partial class EnginesPageViewModel : ObservableObject, IDisposable
{
Engines.Clear();
foreach (var converter in _catalog.Ordered)
- Engines.Add(new EngineItemViewModel(converter, _catalog.StatusOf(converter),
- _store.Settings.EnginePaths.GetValueOrDefault(converter.Id), _loc, OnPathChanged));
+ Engines.Add(new EngineItemViewModel(converter, _catalog.StatusOf(converter), _loc));
}
[RelayCommand]
@@ -109,13 +88,4 @@ public sealed partial class EnginesPageViewModel : ObservableObject, IDisposable
_store.Settings.EnginePriority = Engines.Select(e => e.Converter.Id).ToList();
_store.SaveSettings();
}
-
- private void OnPathChanged(EngineItemViewModel item, string path)
- {
- if (string.IsNullOrWhiteSpace(path))
- _store.Settings.EnginePaths.Remove(item.Converter.Id);
- else
- _store.Settings.EnginePaths[item.Converter.Id] = path.Trim().Trim('"');
- _store.SaveSettings();
- }
}
diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml b/src/Filee.App/Views/Pages/EnginesPage.axaml
index 446ead46..01d395d5 100644
--- a/src/Filee.App/Views/Pages/EnginesPage.axaml
+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml
@@ -96,10 +96,6 @@
<TextBlock Classes="caption" Text="{Binding Detail}" TextTrimming="CharacterEllipsis" />
</StackPanel>
</DockPanel>
- <DockPanel IsVisible="{Binding SupportsCustomPath}">
- <Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{DynamicResource engines.browse}" Click="OnBrowse" />
- <TextBox Text="{Binding CustomPath}" PlaceholderText="{DynamicResource engines.custom_path}" />
- </DockPanel>
</StackPanel>
</Border>
</DataTemplate>
diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml.cs b/src/Filee.App/Views/Pages/EnginesPage.axaml.cs
index ef6d8921..7f15bfca 100644
--- a/src/Filee.App/Views/Pages/EnginesPage.axaml.cs
+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml.cs
@@ -1,6 +1,5 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
-using Avalonia.Platform.Storage;
using Filee.App.Services;
using Filee.App.ViewModels.Pages;
using Filee.Core.Localization;
@@ -22,13 +21,4 @@ public partial class EnginesPage : UserControl
if (!vm.Remove(package))
await AppHost.Get<WindowService>().MessageAsync(window, loc["engines.remove_failed"]);
}
-
- private async void OnBrowse(object? sender, RoutedEventArgs e)
- {
- if (sender is not Button { DataContext: EngineItemViewModel engine } || TopLevel.GetTopLevel(this) is not { } top)
- return;
- var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = false });
- if (files.FirstOrDefault()?.TryGetLocalPath() is { } path)
- engine.CustomPath = path;
- }
}
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index c977d04d..e8a53f83 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -59,6 +59,14 @@ public static class BuiltInData
new() { Id = "to-txt", Name = "TXT", TargetFormat = "txt" },
new() { Id = "to-md", Name = "Markdown", TargetFormat = "md" },
new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
+ .. SpreadsheetPresets(),
+ ];
+
+ /// <summary>Spreadsheet targets (added in settings schema 5, see SettingsMigrations).</summary>
+ public static List<Preset> SpreadsheetPresets() =>
+ [
+ new() { Id = "to-xlsx", Name = "XLSX", TargetFormat = "xlsx" },
+ new() { Id = "to-csv", Name = "CSV", TargetFormat = "csv" },
];
/// <summary>Creates the default toolbar profiles.</summary>
@@ -74,14 +82,16 @@ public static class BuiltInData
{
Id = "pdf", NameKey = "profile.pdf",
Extensions = ["pdf"],
- PresetIds = ["to-png", "to-jpg", "to-docx", "to-hwpx", "to-txt", "pdf-split", "merge-pdf"],
+ PresetIds = ["to-png", "to-jpg", "to-tiff", "pdf-split", "merge-pdf"],
},
new()
{
Id = "office", NameKey = "profile.office",
- Extensions = ["docx", "doc", "odt", "rtf", "xlsx", "xls", "ods", "csv", "pptx", "ppt", "odp"],
- PresetIds = ["to-pdf", "to-docx", "to-hwpx", "to-odt", "to-txt", "to-html", "merge-pdf"],
+ Extensions = ["docx", "doc", "odt", "rtf"],
+ PresetIds = ["to-pdf", "to-hwpx", "to-docx", "to-odt", "to-txt", "to-html", "merge-pdf"],
},
+ SpreadsheetProfile(),
+ PresentationProfile(),
new()
{
Id = "hwp", NameKey = "profile.hwp",
@@ -96,6 +106,24 @@ public static class BuiltInData
},
];
+ /// <summary>Excel, OpenDocument and CSV sheets (split from "office" in settings schema 5).</summary>
+ public static ToolbarProfile SpreadsheetProfile() => new()
+ {
+ Id = "spreadsheets",
+ NameKey = "profile.spreadsheets",
+ Extensions = ["xlsx", "xls", "ods", "csv"],
+ PresetIds = ["to-pdf", "to-xlsx", "to-csv", "to-hwpx", "to-html", "merge-pdf"],
+ };
+
+ /// <summary>PowerPoint and OpenDocument slides (split from "office" in settings schema 5).</summary>
+ public static ToolbarProfile PresentationProfile() => new()
+ {
+ Id = "presentations",
+ NameKey = "profile.presentations",
+ Extensions = ["pptx", "ppt", "odp"],
+ PresetIds = ["to-pdf", "to-png", "to-jpg", "to-hwpx", "merge-pdf"],
+ };
+
/// <summary>Markdown, plain text and HTML (added in settings schema 4, see SettingsMigrations).</summary>
public static ToolbarProfile TextProfile() => new()
{
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 12c48e54..2cfb645d 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -48,7 +48,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 4;
+ public const int CurrentSchemaVersion = 5;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
@@ -78,10 +78,7 @@ public sealed class AppSettings
public List<string> ExcludedProcesses { get; set; } = [];
/// <summary>Engine ids in preferred order (see <see cref="Conversion.ConverterCatalog.Priority"/>).</summary>
- public List<string> EnginePriority { get; set; } = ["magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "hwpx-writer", "word", "pandoc", "libreoffice"];
-
- /// <summary>User-provided executable paths per engine id, overriding auto-detection.</summary>
- public Dictionary<string, string> EnginePaths { get; set; } = [];
+ public List<string> EnginePriority { get; set; } = ["magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "spreadsheet", "hwpx-writer", "pandoc", "libreoffice"];
/// <summary>Set once the first-run welcome has been shown.</summary>
public bool FirstRunCompleted { get; set; }
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index a38365d6..cfc41477 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -231,6 +231,14 @@ internal static class SettingsMigrations
if (settings.SchemaVersion < 4)
InsertBefore(settings.EnginePriority, "markdown", "hwpx-writer");
+ // v5: Microsoft Word automation was removed (Filee no longer uses software installed on the system) and the
+ // built-in "spreadsheet" engine (XLSX <-> CSV) was added; profiles are split by ApplyToLibrary.
+ if (settings.SchemaVersion < 5)
+ {
+ settings.EnginePriority.Remove("word");
+ InsertBefore(settings.EnginePriority, "spreadsheet", "hwpx-writer");
+ }
+
if (settings.Triggers.Count == 0)
settings.Triggers = TriggerGesture.Defaults();
@@ -253,6 +261,38 @@ internal static class SettingsMigrations
profiles.Insert(fallback < 0 ? profiles.Count : fallback, text);
changed = true;
}
+
+ // v5: spreadsheets and presentations get their own donuts (with XLSX / CSV targets) instead of sharing the
+ // documents donut, and the PDF donut drops targets only Word could produce (PDF → DOCX / HWPX / TXT).
+ if (from < 5)
+ {
+ foreach (var preset in BuiltInData.SpreadsheetPresets().Where(p => presets.All(existing => existing.Id != p.Id)))
+ {
+ presets.Add(preset);
+ changed = true;
+ }
+
+ var office = profiles.FirstOrDefault(p => p.Id == "office");
+ var insertAt = office is null ? profiles.FindIndex(p => p.IsFallback) : profiles.IndexOf(office) + 1;
+ var ids = presets.Select(p => p.Id).ToHashSet();
+ foreach (var split in new[] { BuiltInData.SpreadsheetProfile(), BuiltInData.PresentationProfile() })
+ {
+ if (profiles.Any(p => p.Id == split.Id))
+ continue;
+ split.PresetIds = split.PresetIds.Where(ids.Contains).ToList();
+ // The new donut takes over these extensions from the built-in documents donut, but not from
+ // profiles the user made.
+ changed |= office?.Extensions.RemoveAll(split.Extensions.Contains) > 0;
+ if (profiles.Any(p => p.Extensions.Intersect(split.Extensions, StringComparer.OrdinalIgnoreCase).Any()))
+ continue;
+ insertAt = insertAt < 0 ? profiles.Count : insertAt;
+ profiles.Insert(insertAt++, split);
+ changed = true;
+ }
+
+ if (profiles.FirstOrDefault(p => p.Id == "pdf") is { } pdf)
+ changed |= pdf.PresetIds.RemoveAll(id => id is "to-docx" or "to-hwpx" or "to-txt") > 0;
+ }
return changed;
}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index a0122fa1..31b45a74 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -16,19 +16,20 @@ public static class EngineRegistry
{
/// <summary>
/// Instantiates all converters. Order only matters as a tie-breaker when no priority is set, so it mirrors
- /// AppSettings.EnginePriority: free, silent engines first; Word automation after them.
+ /// AppSettings.EnginePriority: built-in engines first, the optional downloads last. Software installed on the
+ /// system (Microsoft Office, a system-wide LibreOffice) is never used.
/// </summary>
public static IReadOnlyList<IConverter> CreateAll(EngineEnvironment env) =>
[
new MagickImageConverter(),
new PdfSharpConverter(),
new PdfiumConverter(),
- new RhwpConverter(env),
+ new RhwpConverter(),
new UnhwpConverter(),
new MarkdownConverter(),
- new HwpxConverter(env),
- new WordComConverter(),
- new PandocConverter(env),
+ new SpreadsheetConverter(),
+ new HwpxConverter(),
+ new PandocConverter(),
new LibreOfficeConverter(env),
];
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
index 6052b884..af7d20a6 100644
--- a/src/Filee.Engines/Filee.Engines.csproj
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -17,6 +17,7 @@
<PackageReference Include="PDFtoImage" />
<PackageReference Include="Unhwp" />
<PackageReference Include="Markdig" />
+ <PackageReference Include="ExcelNumberFormat" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
</ItemGroup>
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
index 186f3bba..4c0b2c3a 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
@@ -3,19 +3,23 @@
// * DOCX is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns, text boxes and formatting.
// * TXT needs no reader: one paragraph per line.
// * Markdown is parsed with Markdig (MarkdownReader), no external engine needed.
+// * XLSX and CSV are read directly (Office/Sheets); every sheet becomes a table (SheetDocument).
+// * PPTX is read directly (Pptx/PptxReader): one page per slide with the objects floating at their places.
// * HTML, ODT and RTF are parsed by Pandoc (optional engine) into its JSON AST (PandocAstReader).
using System.Text;
using System.Text.Json.Nodes;
using Filee.Core.Conversion;
using Filee.Engines.Hwp.Hwpx.Docx;
+using Filee.Engines.Hwp.Hwpx.Pptx;
using Filee.Engines.Infrastructure;
using Filee.Engines.Office;
+using Filee.Engines.Office.Sheets;
namespace Filee.Engines.Hwp.Hwpx;
/// <summary>Writes HWPX files with the built-in OWPML writer.</summary>
-public sealed class HwpxConverter(EngineEnvironment env) : IConverter
+public sealed class HwpxConverter : IConverter
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
@@ -33,14 +37,14 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter
public string DisplayName => "HWPX writer (built-in)";
public int MaxParallelism => 0;
- public IReadOnlyList<ConversionEdge> Edges => BuildEdges(_pandoc is not null || PandocConverter.Locate(env) is not null);
+ public IReadOnlyList<ConversionEdge> Edges => BuildEdges(_pandoc is not null || PandocConverter.Locate() is not null);
public EngineStatus GetStatus()
{
- _pandoc = PandocConverter.Locate(env);
+ _pandoc = PandocConverter.Locate();
return EngineStatus.Available(_pandoc is null
- ? "DOCX, TXT, Markdown → HWPX. HTML, ODT and RTF need Pandoc."
- : $"DOCX, TXT, Markdown; HTML, ODT, RTF with Pandoc ({_pandoc})");
+ ? "DOCX, XLSX, PPTX, CSV, TXT, Markdown → HWPX. HTML, ODT and RTF need Pandoc."
+ : $"DOCX, XLSX, PPTX, CSV, TXT, Markdown; HTML, ODT, RTF with Pandoc ({_pandoc})");
}
public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
@@ -53,6 +57,9 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter
"txt" => TextDocument(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),
"md" => MarkdownReader.Read(DecodeText(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),
Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!),
+ "xlsx" => SheetDocument.Build(XlsxReader.Read(step.InputPath)),
+ "csv" => SheetDocument.Build(CsvFormat.Read(step.InputPath)),
+ "pptx" => PptxReader.Read(step.InputPath, media),
_ => await ReadWithPandocAsync(step, media, cancellationToken),
};
progress?.Report(0.6);
@@ -67,7 +74,7 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter
private async Task<HDocument> ReadWithPandocAsync(ConversionStep step, string media, CancellationToken cancellationToken)
{
- var pandoc = _pandoc ?? PandocConverter.Locate(env) ?? throw new InvalidOperationException("Pandoc was not found.");
+ var pandoc = _pandoc ?? PandocConverter.Locate() ?? throw new InvalidOperationException("Pandoc was not found.");
var json = Path.Combine(step.WorkDirectory, $"ast-{Guid.NewGuid():N}.json");
// Working directory = the input's folder, so relative image paths in HTML resolve.
@@ -135,7 +142,7 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter
private static List<ConversionEdge> BuildEdges(bool pandoc)
{
- List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx")];
+ List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx"), new("xlsx", "hwpx"), new("csv", "hwpx"), new("pptx", "hwpx")];
if (pandoc)
edges.AddRange(PandocReaders.Keys.Select(from => new ConversionEdge(from, "hwpx")));
return edges;
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index bc5dbf74..4ec80293 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -255,7 +255,15 @@ internal sealed class HTextBox : HInline
public int Height { get; set; }
public HAnchor? Anchor { get; set; }
public string? Fill { get; set; }
+ public HGradient? Gradient { get; set; }
public HBorder Line { get; set; } = HBorder.Thin;
+
+ /// <summary>Outline of the box: <see cref="HShapeKind.Rectangle"/> (default) or <see cref="HShapeKind.Ellipse"/>.</summary>
+ public HShapeKind Shape { get; set; }
+
+ /// <summary>Corner rounding of a rectangular box in percent (0 = square).</summary>
+ public int CornerRatio { get; set; }
+
public HInsets Padding { get; set; } = new(283, 283, 283, 283);
public HVerticalAlign VerticalAlign { get; set; }
public List<HBlock> Blocks { get; } = [];
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
index 3e01461e..3fe3a7d9 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
@@ -132,33 +132,45 @@ internal sealed partial class HwpxWriter
_ => "TOP",
};
+ // Readers lay out (and align) the text within textWidth, so it is the box minus its margins.
var outerWidth = _width;
_width = Math.Max(1000, w - box.Padding.Left - box.Padding.Right);
- var content = SubList(box.Blocks, verticalAlign);
+ var content = SubList(box.Blocks, verticalAlign, _width, Math.Max(0, h - box.Padding.Top - box.Padding.Bottom));
_width = outerWidth;
+ var ellipse = box.Shape == HShapeKind.Ellipse;
+ var (element, extra) = ellipse
+ ? ("ellipse", " intervalDirty=\"0\" hasArcPr=\"0\" arcType=\"NORMAL\"")
+ : ("rect", $" ratio=\"{box.CornerRatio}\"");
var sb = new StringBuilder();
- sb.Append($"<hp:rect id=\"{id}\" zOrder=\"{_zOrder++}\" numberingType=\"NONE\" textWrap=\"{box.Anchor?.Wrap ?? "TOP_AND_BOTTOM"}\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" href=\"\" groupLevel=\"0\" instid=\"{id}\" ratio=\"0\">");
+ sb.Append($"<hp:{element} id=\"{id}\" zOrder=\"{_zOrder++}\" numberingType=\"NONE\" textWrap=\"{box.Anchor?.Wrap ?? "TOP_AND_BOTTOM"}\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" href=\"\" groupLevel=\"0\" instid=\"{id}\"{extra}>");
sb.Append("<hp:offset x=\"0\" y=\"0\"/>");
sb.Append($"<hp:orgSz width=\"{w}\" height=\"{h}\"/><hp:curSz width=\"0\" height=\"0\"/>");
sb.Append("<hp:flip horizontal=\"0\" vertical=\"0\"/>");
sb.Append($"<hp:rotationInfo angle=\"0\" centerX=\"{w / 2}\" centerY=\"{h / 2}\" rotateimage=\"1\"/>");
sb.Append(IdentityRendering);
sb.Append(LineShape(box.Line));
- sb.Append(FillBrush(box.Fill, null));
+ sb.Append(FillBrush(box.Fill, box.Gradient));
sb.Append("<hp:shadow type=\"NONE\" color=\"#B2B2B2\" offsetX=\"0\" offsetY=\"0\" alpha=\"0\"/>");
sb.Append($"<hp:drawText lastWidth=\"{w}\" name=\"\" editable=\"0\">");
sb.Append(content);
sb.Append($"<hp:textMargin left=\"{box.Padding.Left}\" right=\"{box.Padding.Right}\" top=\"{box.Padding.Top}\" bottom=\"{box.Padding.Bottom}\"/>");
sb.Append("</hp:drawText>");
- sb.Append($"<hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"{w}\" y=\"0\"/><hc:pt2 x=\"{w}\" y=\"{h}\"/><hc:pt3 x=\"0\" y=\"{h}\"/>");
+ sb.Append(ellipse ? EllipseGeometry(w, h) : RectangleGeometry(w, h));
sb.Append($"<hp:sz width=\"{w}\" widthRelTo=\"ABSOLUTE\" height=\"{h}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>");
sb.Append(Position(box.Anchor));
sb.Append("<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/>");
- sb.Append("</hp:rect>");
+ sb.Append($"</hp:{element}>");
return sb.ToString();
}
+ private static string RectangleGeometry(int w, int h) =>
+ $"<hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"{w}\" y=\"0\"/><hc:pt2 x=\"{w}\" y=\"{h}\"/><hc:pt3 x=\"0\" y=\"{h}\"/>";
+
+ private static string EllipseGeometry(int w, int h) =>
+ $"<hc:center x=\"{w / 2}\" y=\"{h / 2}\"/><hc:ax1 x=\"{w}\" y=\"{h / 2}\"/><hc:ax2 x=\"{w / 2}\" y=\"0\"/>" +
+ "<hc:start1 x=\"0\" y=\"0\"/><hc:end1 x=\"0\" y=\"0\"/><hc:start2 x=\"0\" y=\"0\"/><hc:end2 x=\"0\" y=\"0\"/>";
+
// ───────────────────────── Shapes ─────────────────────────
private string Shape(HShape shape)
@@ -195,11 +207,10 @@ internal sealed partial class HwpxWriter
break;
}
case HShapeKind.Ellipse:
- sb.Append($"<hc:center x=\"{w / 2}\" y=\"{h / 2}\"/><hc:ax1 x=\"{w}\" y=\"{h / 2}\"/><hc:ax2 x=\"{w / 2}\" y=\"0\"/>");
- sb.Append("<hc:start1 x=\"0\" y=\"0\"/><hc:end1 x=\"0\" y=\"0\"/><hc:start2 x=\"0\" y=\"0\"/><hc:end2 x=\"0\" y=\"0\"/>");
+ sb.Append(EllipseGeometry(w, h));
break;
default:
- sb.Append($"<hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"{w}\" y=\"0\"/><hc:pt2 x=\"{w}\" y=\"{h}\"/><hc:pt3 x=\"0\" y=\"{h}\"/>");
+ sb.Append(RectangleGeometry(w, h));
break;
}
sb.Append($"<hp:sz width=\"{w}\" widthRelTo=\"ABSOLUTE\" height=\"{h}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>");
diff --git a/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.Text.cs b/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.Text.cs
new file mode 100644
index 00000000..6c3c1ce5
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.Text.cs
@@ -0,0 +1,414 @@
+// Text of PPTX shapes and table cells. PowerPoint text inherits from a chain of level styles (lvlNpPr):
+// the paragraph itself → the shape's list style → the layout placeholder → the master placeholder → the master's
+// title / body / other text style → the presentation default. Every property is looked up along that chain.
+
+using System.Globalization;
+using System.Xml.Linq;
+using Filee.Engines.Office.Ooxml;
+
+namespace Filee.Engines.Hwp.Hwpx.Pptx;
+
+internal sealed partial class PptxReader
+{
+ private const int DefaultSize = 1800; // 18 pt, PowerPoint's default text size
+
+ private readonly record struct BodyLayout(HInsets Padding, HVerticalAlign Anchor);
+
+ /// <summary>Insets and vertical anchoring of a text body, inherited from the placeholders.</summary>
+ private static BodyLayout BodyProperties(XElement shape, XElement? layoutPh, XElement? masterPh)
+ {
+ var chain = new[] { shape, layoutPh, masterPh }.Select(e => e?.Element(P + "txBody")?.Element(A + "bodyPr")).OfType<XElement>().ToList();
+ string? Attr(string name) => chain.Select(b => (string?)b.Attribute(name)).FirstOrDefault(v => v is not null);
+ int Inset(string name, long fallback) => Hwp(long.TryParse(Attr(name), out var v) ? v : fallback);
+ return new BodyLayout(
+ new HInsets(Inset("lIns", 91440), Inset("rIns", 91440), Inset("tIns", 45720), Inset("bIns", 45720)),
+ Attr("anchor") switch
+ {
+ "ctr" => HVerticalAlign.Center,
+ "b" => HVerticalAlign.Bottom,
+ _ => HVerticalAlign.Top,
+ });
+ }
+
+ /// <summary>Paragraphs of a text body; an empty list when there is no visible text.</summary>
+ /// <param name="defaultColor">Text colour from the shape style (p:style/a:fontRef), if any.</param>
+ private List<HBlock> TextBody(SlideContext context, string partPath, XElement? body, XElement? ph, XElement? layoutPh,
+ XElement? masterPh, string? defaultColor)
+ {
+ var blocks = new List<HBlock>();
+ if (body is null || !body.Descendants(A + "t").Any(t => t.Value.Trim().Length > 0))
+ return blocks;
+
+ // "Shrink text on overflow" stores the scale PowerPoint applied.
+ var fontScale = double.TryParse((string?)body.Element(A + "bodyPr")?.Element(A + "normAutofit")?.Attribute("fontScale"),
+ NumberStyles.Integer, CultureInfo.InvariantCulture, out var scale) ? scale / 100000 : 1;
+ var counters = new int[10];
+ var lastNumbered = new bool[10];
+
+ foreach (var p in body.Elements(A + "p"))
+ {
+ var pPr = p.Element(A + "pPr");
+ var level = Math.Clamp(int.TryParse((string?)pPr?.Attribute("lvl"), out var l) ? l : 0, 0, 8);
+ var chain = StyleChain(context, body, ph, layoutPh, masterPh, level + 1);
+ var paragraphChain = new List<XElement>();
+ if (pPr is not null)
+ paragraphChain.Add(pPr);
+ paragraphChain.AddRange(chain.Specific);
+ paragraphChain.AddRange(chain.General);
+
+ string? Attr(string name) => paragraphChain.Select(e => (string?)e.Attribute(name)).FirstOrDefault(v => v is not null);
+ var paragraph = new HParagraph
+ {
+ Format = new HParaFormat(
+ Align: Attr("algn") switch
+ {
+ "ctr" => HAlign.Center,
+ "r" => HAlign.Right,
+ "just" => HAlign.Justify,
+ "dist" => HAlign.Distribute,
+ _ => HAlign.Left,
+ },
+ Left: long.TryParse(Attr("marL"), out var marL) ? Hwp(marL) : 0,
+ FirstLine: long.TryParse(Attr("indent"), out var indent) ? Hwp(indent) : 0,
+ Before: Spacing(paragraphChain, "spcBef"),
+ After: Spacing(paragraphChain, "spcAft"),
+ LineSpacing: LineSpacing(paragraphChain)),
+ };
+
+ var runs = p.Elements().Where(e => e.Name.LocalName is "r" or "br" or "fld").ToList();
+ var firstRun = runs.FirstOrDefault(r => r.Name.LocalName != "br");
+ var markFormat = RunFormat(context, p.Element(A + "endParaRPr") ?? firstRun?.Element(A + "rPr"), pPr, chain, defaultColor, fontScale);
+ paragraph.MarkFormat = markFormat with { Color = null };
+
+ // Bullet or number (not on empty paragraphs, as PowerPoint shows them).
+ var hasText = runs.Any(r => r.Element(A + "t")?.Value.Length > 0);
+ var bullet = hasText ? Bullet(paragraphChain) : null;
+ for (var deeper = level + 1; deeper < counters.Length; deeper++)
+ {
+ counters[deeper] = 0;
+ lastNumbered[deeper] = false;
+ }
+ if (bullet is { AutoNumber: { } scheme })
+ {
+ counters[level] = lastNumbered[level] ? counters[level] + 1 : bullet.Value.Start;
+ lastNumbered[level] = true;
+ paragraph.Inlines.Add(new HText(Number(scheme, counters[level]) + " ", markFormat));
+ }
+ else
+ {
+ lastNumbered[level] = false;
+ if (bullet is { Char: { } character })
+ paragraph.Inlines.Add(new HText(character + " ", markFormat with { Bold = null, Italic = null, Underline = null }));
+ }
+
+ foreach (var run in runs)
+ {
+ var format = RunFormat(context, run.Element(A + "rPr"), pPr, chain, defaultColor, fontScale);
+ if (run.Name.LocalName == "br")
+ {
+ paragraph.Inlines.Add(new HLineBreak(format));
+ continue;
+ }
+ var text = run.Element(A + "t")?.Value ?? "";
+ if (text.Length == 0)
+ continue;
+ var link = ExternalLink(partPath, (string?)run.Element(A + "rPr")?.Element(A + "hlinkClick")?.Attribute(R + "id"));
+ if (link is null)
+ {
+ paragraph.Inlines.Add(new HText(text, format));
+ }
+ else
+ {
+ var hLink = new HLink(link);
+ hLink.Content.Add(new HText(text, format));
+ paragraph.Inlines.Add(hLink);
+ }
+ }
+ blocks.Add(paragraph);
+ }
+ return blocks;
+ }
+
+ /// <summary>
+ /// Level styles for one paragraph level: specific ones (shape, layout and master placeholder list styles) and
+ /// general ones (master text style, presentation default). The shape style's text colour sits between them.
+ /// </summary>
+ private (List<XElement> Specific, List<XElement> General) StyleChain(SlideContext context, XElement body, XElement? ph,
+ XElement? layoutPh, XElement? masterPh, int level)
+ {
+ var name = A + $"lvl{level}pPr";
+ var specific = new[] { body, layoutPh?.Element(P + "txBody"), masterPh?.Element(P + "txBody") }
+ .Select(owner => owner?.Element(A + "lstStyle")?.Element(name))
+ .OfType<XElement>()
+ .ToList();
+
+ var general = new List<XElement>();
+ var textStyles = context.Master?.Element(P + "txStyles");
+ if (ph is not null)
+ {
+ var masterStyle = Normalize((string?)ph.Attribute("type")) switch
+ {
+ "title" => textStyles?.Element(P + "titleStyle"),
+ "body" => textStyles?.Element(P + "bodyStyle"),
+ _ => textStyles?.Element(P + "otherStyle"),
+ };
+ if (masterStyle?.Element(name) is { } fromMaster)
+ general.Add(fromMaster);
+ }
+ if (_defaultTextStyle?.Element(name) is { } fromPresentation)
+ general.Add(fromPresentation);
+ return (specific, general);
+ }
+
+ private HCharFormat RunFormat(SlideContext context, XElement? rPr, XElement? pPr,
+ (List<XElement> Specific, List<XElement> General) chain, string? defaultColor, double fontScale)
+ {
+ // Run → paragraph default → specific level styles → [shape style colour] → general level styles.
+ var properties = new List<XElement>();
+ if (rPr is not null)
+ properties.Add(rPr);
+ if (pPr?.Element(A + "defRPr") is { } paragraphDefault)
+ properties.Add(paragraphDefault);
+ properties.AddRange(chain.Specific.Select(s => s.Element(A + "defRPr")).OfType<XElement>());
+ var specificCount = properties.Count;
+ properties.AddRange(chain.General.Select(s => s.Element(A + "defRPr")).OfType<XElement>());
+
+ string? Attr(string attribute) => properties.Select(e => (string?)e.Attribute(attribute)).FirstOrDefault(v => v is not null);
+ string? color = null;
+ for (var i = 0; i < properties.Count && color is null; i++)
+ {
+ if (i == specificCount && defaultColor is not null)
+ color = defaultColor;
+ else if (properties[i].Element(A + "solidFill") is { } fill)
+ color = context.Colors.Drawing(fill);
+ }
+ color ??= defaultColor ?? context.Colors.Theme("tx1");
+
+ var size = int.TryParse(Attr("sz"), out var sz) ? sz : DefaultSize;
+ var latin = Typeface(context, properties.Select(e => (string?)e.Element(A + "latin")?.Attribute("typeface")).FirstOrDefault(v => v is not null));
+ var eastAsian = Typeface(context, properties.Select(e => (string?)e.Element(A + "ea")?.Attribute("typeface")).FirstOrDefault(v => v is not null));
+ var baseline = int.TryParse(Attr("baseline"), out var b) ? b : 0;
+ return new HCharFormat(
+ Bold: Attr("b") is "1" or "true" ? true : null,
+ Italic: Attr("i") is "1" or "true" ? true : null,
+ Underline: Attr("u") is { } u && u != "none" ? true : null,
+ Strike: Attr("strike") is { } s && s != "noStrike" ? true : null,
+ Superscript: baseline > 0 ? true : null,
+ Subscript: baseline < 0 ? true : null,
+ Size: Math.Max(100, (int)Math.Round(size * fontScale)),
+ Font: latin,
+ EastAsianFont: eastAsian,
+ Color: color);
+ }
+
+ /// <summary>Theme font references (+mj-lt, +mn-ea, ...) resolved against the theme's font scheme.</summary>
+ private static string? Typeface(SlideContext context, string? typeface) => typeface switch
+ {
+ null or "" => null,
+ "+mj-lt" => context.Fonts.MajorLatin,
+ "+mn-lt" => context.Fonts.MinorLatin,
+ "+mj-ea" => context.Fonts.MajorEastAsian,
+ "+mn-ea" => context.Fonts.MinorEastAsian,
+ _ when typeface.StartsWith('+') => null,
+ _ => typeface,
+ };
+
+ private readonly record struct BulletInfo(string? Char, string? AutoNumber, int Start);
+
+ private static BulletInfo? Bullet(List<XElement> chain)
+ {
+ foreach (var style in chain)
+ {
+ if (style.Element(A + "buNone") is not null)
+ return null;
+ if (style.Element(A + "buChar") is { } character)
+ return new BulletInfo((string?)character.Attribute("char") ?? "•", null, 1);
+ if (style.Element(A + "buAutoNum") is { } number)
+ return new BulletInfo(null, (string?)number.Attribute("type") ?? "arabicPeriod",
+ int.TryParse((string?)number.Attribute("startAt"), out var start) ? start : 1);
+ if (style.Element(A + "buBlip") is not null)
+ return new BulletInfo("•", null, 1);
+ }
+ return null;
+ }
+
+ /// <summary>The label of item <paramref name="n"/> in a PowerPoint auto-number scheme (arabicPeriod, alphaLcParenR, ...).</summary>
+ internal static string Number(string scheme, int n)
+ {
+ var value = scheme switch
+ {
+ _ when scheme.StartsWith("alphaLc", StringComparison.Ordinal) => Letters(n).ToLowerInvariant(),
+ _ when scheme.StartsWith("alphaUc", StringComparison.Ordinal) => Letters(n),
+ _ when scheme.StartsWith("romanLc", StringComparison.Ordinal) => Roman(n).ToLowerInvariant(),
+ _ when scheme.StartsWith("romanUc", StringComparison.Ordinal) => Roman(n),
+ _ when scheme.StartsWith("circleNum", StringComparison.Ordinal) && n is >= 1 and <= 20 => ((char)('①' + n - 1)).ToString(),
+ _ => n.ToString(CultureInfo.InvariantCulture),
+ };
+ return scheme switch
+ {
+ _ when scheme.EndsWith("ParenBoth", StringComparison.Ordinal) => $"({value})",
+ _ when scheme.EndsWith("ParenR", StringComparison.Ordinal) => value + ")",
+ _ when scheme.EndsWith("Plain", StringComparison.Ordinal) => value,
+ _ => value + ".",
+ };
+ }
+
+ private static string Letters(int n)
+ {
+ var text = "";
+ for (; n > 0; n = (n - 1) / 26)
+ text = (char)('A' + (n - 1) % 26) + text;
+ return text;
+ }
+
+ private static string Roman(int n)
+ {
+ var text = "";
+ foreach (var (value, symbol) in new[] { (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I") })
+ {
+ for (; n >= value; n -= value)
+ text += symbol;
+ }
+ return text;
+ }
+
+ /// <summary>Space before / after in HWPUNIT (1/100 pt = 1 HWPUNIT); percentages are taken of an 18 pt line.</summary>
+ private static int? Spacing(List<XElement> chain, string name)
+ {
+ foreach (var style in chain)
+ {
+ if (style.Element(A + name) is not { } spacing)
+ continue;
+ if (int.TryParse((string?)spacing.Element(A + "spcPts")?.Attribute("val"), out var points))
+ return points;
+ if (int.TryParse((string?)spacing.Element(A + "spcPct")?.Attribute("val"), out var percent))
+ return (int)(percent / 100000.0 * DefaultSize * 1.2);
+ }
+ return 0;
+ }
+
+ /// <summary>
+ /// PowerPoint's "single" line is about 1.2 × the font size, 한글's percentages count the font size itself.
+ /// </summary>
+ private static HLineSpacing LineSpacing(List<XElement> chain)
+ {
+ foreach (var style in chain)
+ {
+ if (style.Element(A + "lnSpc") is not { } spacing)
+ continue;
+ if (int.TryParse((string?)spacing.Element(A + "spcPct")?.Attribute("val"), out var percent))
+ return new HLineSpacing(HLineSpacingKind.Percent, Math.Max(60, (int)Math.Round(percent / 1000.0 * 1.2)));
+ if (int.TryParse((string?)spacing.Element(A + "spcPts")?.Attribute("val"), out var points))
+ return new HLineSpacing(HLineSpacingKind.Fixed, points);
+ }
+ return new HLineSpacing(HLineSpacingKind.Percent, 120);
+ }
+
+ private string? ExternalLink(string partPath, string? id) =>
+ id is not null && _package.Relationships(partPath).TryGetValue(id, out var rel) && rel.External ? rel.Target : null;
+
+ // ───────────────────────── Tables ─────────────────────────
+
+ private void Table(SlideContext context, string partPath, XElement frame, Transform transform, List<HInline> output)
+ {
+ var tbl = frame.Element(A + "graphic")?.Element(A + "graphicData")?.Element(A + "tbl");
+ if (tbl is null || Bounds(frame.Element(P + "xfrm"), transform) is not { } bounds)
+ return; // charts, SmartArt and embedded objects are not converted
+
+ var grid = tbl.Element(A + "tblGrid")?.Elements(A + "gridCol").Select(c => Math.Max(1, Hwp(Emu(c.Attribute("w"))))).ToArray() ?? [];
+ if (grid.Length == 0)
+ return;
+ var tablePr = tbl.Element(A + "tblPr");
+ var styled = tablePr?.Element(A + "tableStyleId") is not null;
+ var firstRow = (string?)tablePr?.Attribute("firstRow") is "1" or "true";
+ var banded = (string?)tablePr?.Attribute("bandRow") is "1" or "true";
+ // Without the style part, table styles are approximated by PowerPoint's default "Medium Style 2 – Accent 1".
+ var accent = context.Colors.Theme("accent1");
+ var gridLine = styled ? new HBorder(HBorderStyle.Solid, 0.35, "#FFFFFF") : HBorder.Thin;
+
+ var table = new HTable
+ {
+ ColumnCount = grid.Length,
+ ColumnWidths = grid,
+ CellMargin = new HInsets(720, 720, 360, 360),
+ Borders = new HBorders(gridLine, gridLine, gridLine, gridLine),
+ };
+ var rows = tbl.Elements(A + "tr").ToList();
+ for (var r = 0; r < rows.Count; r++)
+ {
+ var header = firstRow && r == 0;
+ var row = new HRow { Header = header, Height = Math.Max(1, Hwp(Emu(rows[r].Attribute("h")))) };
+ var column = 0;
+ foreach (var tc in rows[r].Elements(A + "tc"))
+ {
+ var colSpan = Math.Max(1, int.TryParse((string?)tc.Attribute("gridSpan"), out var gs) ? gs : 1);
+ if ((string?)tc.Attribute("hMerge") is "1" or "true" || (string?)tc.Attribute("vMerge") is "1" or "true")
+ {
+ column += colSpan;
+ continue; // covered by a merged cell
+ }
+ var tcPr = tc.Element(A + "tcPr");
+ string? fill = tcPr?.Element(A + "solidFill") is { } solid ? context.Colors.Drawing(solid) : null;
+ if (fill is null && styled && tcPr?.Element(A + "noFill") is null)
+ fill = header ? accent : banded && (r - (firstRow ? 1 : 0)) % 2 == 0 ? OoxmlColors.Tint(accent, 0.6) : OoxmlColors.Tint(accent, 0.8);
+
+ var cell = new HCell
+ {
+ Column = column,
+ ColSpan = colSpan,
+ RowSpan = Math.Max(1, int.TryParse((string?)tc.Attribute("rowSpan"), out var rs) ? rs : 1),
+ Fill = fill,
+ VerticalAlign = (string?)tcPr?.Attribute("anchor") switch
+ {
+ "ctr" => HVerticalAlign.Center,
+ "b" => HVerticalAlign.Bottom,
+ _ => HVerticalAlign.Top,
+ },
+ Borders = new HBorders(
+ CellLine(tcPr?.Element(A + "lnL"), context.Colors, gridLine),
+ CellLine(tcPr?.Element(A + "lnR"), context.Colors, gridLine),
+ CellLine(tcPr?.Element(A + "lnT"), context.Colors, gridLine),
+ CellLine(tcPr?.Element(A + "lnB"), context.Colors, gridLine)),
+ };
+ var text = TextBody(context, partPath, tc.Element(A + "txBody"), null, null, null,
+ styled && header ? context.Colors.Theme("lt1") : null);
+ if (styled && header)
+ Emphasize(text);
+ cell.Blocks.AddRange(text.Count > 0 ? text : [new HParagraph()]);
+ row.Cells.Add(cell);
+ column += colSpan;
+ }
+ table.Rows.Add(row);
+ }
+
+ var box = new HTextBox
+ {
+ Width = Math.Max(1, Hwp(bounds.W)),
+ Height = Math.Max(1, table.Rows.Sum(r => r.Height ?? 0)),
+ Anchor = Anchor(Hwp(bounds.X), Hwp(bounds.Y)),
+ Line = HBorder.None,
+ Padding = new HInsets(0, 0, 0, 0),
+ };
+ box.Blocks.Add(table);
+ output.Add(box);
+ }
+
+ private static HBorder CellLine(XElement? line, OoxmlColors colors, HBorder fallback)
+ {
+ if (line is null)
+ return fallback;
+ if (line.Element(A + "noFill") is not null)
+ return HBorder.None;
+ var color = line.Element(A + "solidFill") is { } solid ? colors.Drawing(solid) : null;
+ return color is null ? fallback : new HBorder(HBorderStyle.Solid, Math.Max(0.1, Emu(line.Attribute("w")) / 36000.0), color);
+ }
+
+ /// <summary>Header cells of styled tables are bold.</summary>
+ private static void Emphasize(List<HBlock> blocks)
+ {
+ foreach (var paragraph in blocks.OfType<HParagraph>())
+ for (var i = 0; i < paragraph.Inlines.Count; i++)
+ if (paragraph.Inlines[i] is HText text && text.Format.Bold is null)
+ paragraph.Inlines[i] = new HText(text.Text, text.Format with { Bold = true });
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.cs
new file mode 100644
index 00000000..b90aa8da
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Pptx/PptxReader.cs
@@ -0,0 +1,454 @@
+// PPTX (PresentationML) → HDocument without PowerPoint or LibreOffice: one page per slide, sized like the slide, with
+// every object floating at its place on the page: text boxes (placeholders inherit position and text style from the
+// layout and master), shapes with solid or gradient fills and outlines, pictures, tables, lines, groups and the slide
+// background. PPTX → PDF / PNG then goes through the HWPX writer and rhwp.
+//
+// Split over partial files: this one walks slides and objects, PptxReader.Text resolves text and its inherited styles.
+// Not converted: charts, SmartArt, rotation, effects (shadows, glow), picture cropping, animations, notes, hidden slides.
+
+using System.Globalization;
+using System.Xml.Linq;
+using Filee.Engines.Office.Ooxml;
+
+namespace Filee.Engines.Hwp.Hwpx.Pptx;
+
+internal sealed partial class PptxReader
+{
+ private static readonly XNamespace P = "http://schemas.openxmlformats.org/presentationml/2006/main";
+ private static readonly XNamespace A = OoxmlColors.A;
+ private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+
+ /// <summary>Picture formats the HWPX writer and 한글 readers display.</summary>
+ private static readonly HashSet<string> PictureTypes = new(StringComparer.OrdinalIgnoreCase) { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".tiff" };
+
+ private readonly OpcPackage _package;
+ private readonly string _mediaFolder;
+ private XElement? _defaultTextStyle;
+
+ private PptxReader(OpcPackage package, string mediaFolder)
+ {
+ _package = package;
+ _mediaFolder = mediaFolder;
+ }
+
+ /// <summary>Reads <paramref name="path"/>; pictures are extracted into <paramref name="mediaFolder"/>.</summary>
+ public static HDocument Read(string path, string mediaFolder)
+ {
+ using var package = new OpcPackage(path);
+ return new PptxReader(package, mediaFolder).ReadPresentation();
+ }
+
+ /// <summary>EMU (914400 per inch) → HWPUNIT (7200 per inch).</summary>
+ private static int Hwp(long emu) => (int)Math.Round(emu / 127.0);
+
+ private static long Emu(XAttribute? attribute) =>
+ long.TryParse((string?)attribute, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : 0;
+
+ // ───────────────────────── Presentation & slides ─────────────────────────
+
+ private HDocument ReadPresentation()
+ {
+ var presentationPath = _package.MainPartPath ?? "ppt/presentation.xml";
+ var presentation = _package.Part(presentationPath)?.Root
+ ?? throw new InvalidDataException("The file is not a PowerPoint presentation (no ppt/presentation.xml).");
+ _defaultTextStyle = presentation.Element(P + "defaultTextStyle");
+ var size = presentation.Element(P + "sldSz");
+ var width = Hwp(Emu(size?.Attribute("cx")) is > 0 and var cx ? cx : 12192000);
+ var height = Hwp(Emu(size?.Attribute("cy")) is > 0 and var cy ? cy : 6858000);
+
+ var section = new HSection { Page = new HPage(width, height, 0, 0, 0, 0, 0, 0, 0) };
+ foreach (var id in presentation.Element(P + "sldIdLst")?.Elements(P + "sldId") ?? [])
+ {
+ var slidePath = _package.Target(presentationPath, (string?)id.Attribute(R + "id"));
+ if (slidePath is null || _package.Part(slidePath)?.Root is not { } slide || (string?)slide.Attribute("show") is "0" or "false")
+ continue;
+ var page = new HParagraph { PageBreakBefore = section.Blocks.Count > 0 };
+ ReadSlide(slidePath, slide, width, height, page.Inlines);
+ section.Blocks.Add(page);
+ }
+ if (section.Blocks.Count == 0)
+ section.Blocks.Add(new HParagraph());
+
+ var document = new HDocument();
+ document.Sections.Add(section);
+ return document;
+ }
+
+ /// <summary>The parts one slide draws from, with the colours and placeholders they define.</summary>
+ /// <summary>Latin and East Asian fonts of the theme (what "+mj-lt", "+mn-ea" ... refer to).</summary>
+ private sealed record ThemeFonts(string? MajorLatin, string? MinorLatin, string? MajorEastAsian, string? MinorEastAsian)
+ {
+ public static ThemeFonts From(XDocument? theme)
+ {
+ var scheme = theme?.Descendants(A + "fontScheme").FirstOrDefault();
+ string? Latin(string kind) => NonEmpty((string?)scheme?.Element(A + kind)?.Element(A + "latin")?.Attribute("typeface"));
+ // Korean templates name the Hangul font in <a:font script="Hang">, often with an empty <a:ea>.
+ string? EastAsian(string kind) =>
+ NonEmpty((string?)scheme?.Element(A + kind)?.Element(A + "ea")?.Attribute("typeface"))
+ ?? NonEmpty((string?)scheme?.Element(A + kind)?.Elements(A + "font").FirstOrDefault(f => (string?)f.Attribute("script") == "Hang")?.Attribute("typeface"));
+ return new ThemeFonts(Latin("majorFont"), Latin("minorFont"), EastAsian("majorFont"), EastAsian("minorFont"));
+ }
+
+ private static string? NonEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value;
+ }
+
+ private sealed class SlideContext(string slidePath, XElement slide, XElement? layout, string? layoutPath, XElement? master, string? masterPath, OoxmlColors colors, ThemeFonts fonts)
+ {
+ public ThemeFonts Fonts { get; } = fonts;
+ public string SlidePath { get; } = slidePath;
+ public XElement Slide { get; } = slide;
+ public XElement? Layout { get; } = layout;
+ public string? LayoutPath { get; } = layoutPath;
+ public XElement? Master { get; } = master;
+ public string? MasterPath { get; } = masterPath;
+ public OoxmlColors Colors { get; } = colors;
+ }
+
+ private void ReadSlide(string slidePath, XElement slide, int width, int height, List<HInline> output)
+ {
+ var layoutPath = _package.TargetOfType(slidePath, "/slideLayout");
+ var layout = layoutPath is null ? null : _package.Part(layoutPath)?.Root;
+ var masterPath = layoutPath is null ? null : _package.TargetOfType(layoutPath, "/slideMaster");
+ var master = masterPath is null ? null : _package.Part(masterPath)?.Root;
+ var themePath = masterPath is null ? null : _package.TargetOfType(masterPath, "/theme");
+ var theme = themePath is null ? null : _package.Part(themePath);
+ // The master's colour map says which theme colours "text" and "background" are (dark templates swap them).
+ var colors = OoxmlColors.FromTheme(theme)
+ .WithMap(master?.Element(P + "clrMap")?.Attributes().ToDictionary(a => a.Name.LocalName, a => a.Value));
+ var context = new SlideContext(slidePath, slide, layout, layoutPath, master, masterPath, colors, ThemeFonts.From(theme));
+
+ if (Background(context) is { } background)
+ {
+ background.Width = width;
+ background.Height = height;
+ background.Anchor = Anchor(0, 0);
+ output.Add(background);
+ }
+
+ // Decorations of the master and the layout (logos, bars) lie under the slide's own objects.
+ var showMaster = (string?)slide.Attribute("showMasterSp") is not ("0" or "false")
+ && (string?)layout?.Attribute("showMasterSp") is not ("0" or "false");
+ if (showMaster && master is not null && masterPath is not null)
+ Objects(context, masterPath, Tree(master), Transform.Identity, output, decorationsOnly: true);
+ if (layout is not null && layoutPath is not null)
+ Objects(context, layoutPath, Tree(layout), Transform.Identity, output, decorationsOnly: true);
+ Objects(context, slidePath, Tree(slide), Transform.Identity, output, decorationsOnly: false);
+ }
+
+ private static XElement? Tree(XElement part) => part.Element(P + "cSld")?.Element(P + "spTree");
+
+ private static HAnchor Anchor(int x, int y) =>
+ new("PAPER", "LEFT", Math.Max(0, x), "PAPER", "TOP", Math.Max(0, y), "IN_FRONT_OF_TEXT", AllowOverlap: true);
+
+ /// <summary>The first background of slide, layout or master, as a full-page rectangle (null for plain white).</summary>
+ private HShape? Background(SlideContext context)
+ {
+ foreach (var part in new[] { context.Slide, context.Layout, context.Master })
+ {
+ var bg = part?.Element(P + "cSld")?.Element(P + "bg");
+ if (bg is null)
+ continue;
+ var properties = bg.Element(P + "bgPr");
+ string? fill = null;
+ HGradient? gradient = null;
+ if (properties is not null)
+ (fill, gradient) = Fill(properties, context.Colors, null);
+ else if (bg.Element(P + "bgRef") is { } reference)
+ fill = context.Colors.Drawing(reference);
+ if (gradient is null && (fill is null || fill.Equals("#FFFFFF", StringComparison.OrdinalIgnoreCase)))
+ return null;
+ return new HShape(HShapeKind.Rectangle) { Fill = fill, Gradient = gradient, Line = HBorder.None };
+ }
+ return null;
+ }
+
+ // ───────────────────────── Objects ─────────────────────────
+
+ /// <summary>Maps child coordinates of a group to slide coordinates (EMU).</summary>
+ private readonly record struct Transform(double ScaleX, double ScaleY, double OffsetX, double OffsetY)
+ {
+ public static readonly Transform Identity = new(1, 1, 0, 0);
+ public (long X, long Y, long W, long H) Apply(long x, long y, long w, long h) =>
+ ((long)(OffsetX + x * ScaleX), (long)(OffsetY + y * ScaleY), (long)(w * ScaleX), (long)(h * ScaleY));
+ }
+
+ private void Objects(SlideContext context, string partPath, XElement? tree, Transform transform, List<HInline> output, bool decorationsOnly)
+ {
+ foreach (var element in tree?.Elements() ?? [])
+ {
+ // Placeholders of the master / layout are only templates for the slide's own placeholders.
+ if (decorationsOnly && Placeholder(element) is not null)
+ continue;
+ switch (element.Name.LocalName)
+ {
+ case "sp":
+ Shape(context, partPath, element, transform, output);
+ break;
+ case "cxnSp":
+ Connector(context, element, transform, output);
+ break;
+ case "pic":
+ Picture(context, partPath, element, transform, output);
+ break;
+ case "graphicFrame":
+ Table(context, partPath, element, transform, output);
+ break;
+ case "grpSp":
+ Group(context, partPath, element, transform, output, decorationsOnly);
+ break;
+ case "AlternateContent":
+ // Newer object kinds come with a fallback that older readers understand.
+ var fallback = element.Elements().FirstOrDefault(e => e.Name.LocalName == "Fallback");
+ if (fallback is not null)
+ Objects(context, partPath, fallback, transform, output, decorationsOnly);
+ break;
+ }
+ }
+ }
+
+ private void Group(SlideContext context, string partPath, XElement group, Transform transform, List<HInline> output, bool decorationsOnly)
+ {
+ var xfrm = group.Element(P + "grpSpPr")?.Element(A + "xfrm");
+ var inner = transform;
+ if (xfrm is not null)
+ {
+ var (x, y, w, h) = (Emu(xfrm.Element(A + "off")?.Attribute("x")), Emu(xfrm.Element(A + "off")?.Attribute("y")),
+ Emu(xfrm.Element(A + "ext")?.Attribute("cx")), Emu(xfrm.Element(A + "ext")?.Attribute("cy")));
+ var (cx, cy, cw, ch) = (Emu(xfrm.Element(A + "chOff")?.Attribute("x")), Emu(xfrm.Element(A + "chOff")?.Attribute("y")),
+ Emu(xfrm.Element(A + "chExt")?.Attribute("cx")), Emu(xfrm.Element(A + "chExt")?.Attribute("cy")));
+ var sx = cw > 0 ? (double)w / cw : 1;
+ var sy = ch > 0 ? (double)h / ch : 1;
+ // child → group space → parent space
+ inner = new Transform(transform.ScaleX * sx, transform.ScaleY * sy,
+ transform.OffsetX + (x - cx * sx) * transform.ScaleX, transform.OffsetY + (y - cy * sy) * transform.ScaleY);
+ }
+ Objects(context, partPath, group, inner, output, decorationsOnly);
+ }
+
+ /// <summary>The p:ph element of a shape, picture or frame, if it is a placeholder.</summary>
+ private static XElement? Placeholder(XElement element) =>
+ element.Elements().FirstOrDefault(e => e.Name.LocalName.StartsWith("nv", StringComparison.Ordinal))?
+ .Element(P + "nvPr")?.Element(P + "ph");
+
+ /// <summary>
+ /// The layout's and master's version of placeholder <paramref name="ph"/>: matched by index, else by type
+ /// (ctrTitle ↔ title, subTitle / obj / untyped ↔ body).
+ /// </summary>
+ private static (XElement? Layout, XElement? Master) Inherited(SlideContext context, XElement? ph)
+ {
+ if (ph is null)
+ return (null, null);
+ var type = Normalize((string?)ph.Attribute("type"));
+ var index = (string?)ph.Attribute("idx");
+
+ XElement? Find(XElement? part, bool byIndex)
+ {
+ var candidates = Tree(part ?? new XElement("none"))?.Descendants().Where(e => e.Name.LocalName is "sp" or "pic" && Placeholder(e) is not null).ToList() ?? [];
+ if (byIndex && index is not null && candidates.FirstOrDefault(c => (string?)Placeholder(c)!.Attribute("idx") == index) is { } byIdx)
+ return byIdx;
+ return candidates.FirstOrDefault(c => Normalize((string?)Placeholder(c)!.Attribute("type")) == type);
+ }
+
+ var layout = Find(context.Layout, byIndex: true);
+ var master = Find(context.Master, byIndex: false);
+ return (layout, master);
+ }
+
+ private static string Normalize(string? type) => type switch
+ {
+ "ctrTitle" or "title" => "title",
+ null or "" or "obj" or "subTitle" or "body" => "body",
+ _ => type,
+ };
+
+ /// <summary>a:xfrm of the object, else of the placeholder it inherits from.</summary>
+ private static XElement? Geometry(XElement element, XElement? layoutPh, XElement? masterPh)
+ {
+ static XElement? Xfrm(XElement? e) => e?.Element(P + "spPr")?.Element(A + "xfrm") ?? e?.Element(P + "xfrm");
+ return Xfrm(element) ?? Xfrm(layoutPh) ?? Xfrm(masterPh);
+ }
+
+ private static (long X, long Y, long W, long H)? Bounds(XElement? xfrm, Transform transform)
+ {
+ if (xfrm is null)
+ return null;
+ var off = xfrm.Element(A + "off");
+ var ext = xfrm.Element(A + "ext");
+ return transform.Apply(Emu(off?.Attribute("x")), Emu(off?.Attribute("y")), Emu(ext?.Attribute("cx")), Emu(ext?.Attribute("cy")));
+ }
+
+ private void Shape(SlideContext context, string partPath, XElement shape, Transform transform, List<HInline> output)
+ {
+ var ph = Placeholder(shape);
+ var (layoutPh, masterPh) = partPath == context.SlidePath ? Inherited(context, ph) : (null, null);
+ if (Bounds(Geometry(shape, layoutPh, masterPh), transform) is not { } bounds || bounds.W <= 0 && bounds.H <= 0)
+ return;
+
+ var properties = shape.Element(P + "spPr");
+ var style = shape.Element(P + "style");
+ var (fill, gradient) = Fill(properties, context.Colors, style?.Element(A + "fillRef"));
+ var line = Line(properties, context.Colors, style?.Element(A + "lnRef"));
+ var geometry = (string?)properties?.Element(A + "prstGeom")?.Attribute("prst") ?? "rect";
+ var (x, y, w, h) = (Hwp(bounds.X), Hwp(bounds.Y), Math.Max(1, Hwp(bounds.W)), Math.Max(1, Hwp(bounds.H)));
+
+ var textColor = context.Colors.Drawing(style?.Element(A + "fontRef"));
+ var blocks = TextBody(context, partPath, shape.Element(P + "txBody"), ph, layoutPh, masterPh, textColor);
+ if (geometry is "line" or "straightConnector1")
+ {
+ AddLine(shape, bounds, line, output);
+ return;
+ }
+ var kind = geometry == "ellipse" ? HShapeKind.Ellipse : HShapeKind.Rectangle;
+ var corners = geometry == "roundRect" ? CornerRatio(properties) : 0;
+ if (blocks.Count > 0)
+ {
+ var body = BodyProperties(shape, layoutPh, masterPh);
+ var padding = body.Padding;
+ if (kind == HShapeKind.Ellipse)
+ {
+ // PowerPoint puts the text of an ellipse into the rectangle inscribed in it.
+ var (dx, dy) = ((int)(w * 0.146), (int)(h * 0.146));
+ padding = new HInsets(padding.Left + dx, padding.Right + dx, padding.Top + dy, padding.Bottom + dy);
+ }
+ output.Add(new HTextBox
+ {
+ Width = w,
+ Height = h,
+ Anchor = Anchor(x, y),
+ Fill = fill,
+ Gradient = gradient,
+ Line = line,
+ Shape = kind,
+ CornerRatio = corners,
+ Padding = padding,
+ VerticalAlign = body.Anchor,
+ }.With(blocks));
+ return;
+ }
+ if (fill is null && gradient is null && line.Style == HBorderStyle.None)
+ return; // an empty placeholder or an invisible box
+ output.Add(new HShape(kind)
+ {
+ Width = w,
+ Height = h,
+ Anchor = Anchor(x, y),
+ Fill = fill,
+ Gradient = gradient,
+ Line = line,
+ CornerRatio = corners,
+ });
+ }
+
+ /// <summary>
+ /// Corner radius of a rounded rectangle as a percentage of the shorter side: the "adj" guide in 1/1000 %,
+ /// 16 667 (a sixth) by default.
+ /// </summary>
+ private static int CornerRatio(XElement? properties)
+ {
+ var guide = properties?.Element(A + "prstGeom")?.Element(A + "avLst")?.Elements(A + "gd")
+ .FirstOrDefault(g => (string?)g.Attribute("name") == "adj");
+ var value = ((string?)guide?.Attribute("fmla"))?.Split(' ') is ["val", var number] && int.TryParse(number, out var v) ? v : 16667;
+ return Math.Clamp((int)Math.Round(value / 1000.0), 0, 50);
+ }
+
+ private void Connector(SlideContext context, XElement connector, Transform transform, List<HInline> output)
+ {
+ var properties = connector.Element(P + "spPr");
+ if (Bounds(properties?.Element(A + "xfrm"), transform) is not { } bounds)
+ return;
+ var line = Line(properties, context.Colors, connector.Element(P + "style")?.Element(A + "lnRef"));
+ AddLine(connector, bounds, line, output);
+ }
+
+ private static void AddLine(XElement element, (long X, long Y, long W, long H) bounds, HBorder line, List<HInline> output)
+ {
+ if (line.Style == HBorderStyle.None)
+ return;
+ var xfrm = element.Element(P + "spPr")?.Element(A + "xfrm");
+ output.Add(new HShape(HShapeKind.Line)
+ {
+ Width = Math.Max(1, Hwp(bounds.W)),
+ Height = Math.Max(1, Hwp(bounds.H)),
+ Anchor = Anchor(Hwp(bounds.X), Hwp(bounds.Y)),
+ Line = line,
+ FlipHorizontal = (string?)xfrm?.Attribute("flipH") is "1" or "true",
+ FlipVertical = (string?)xfrm?.Attribute("flipV") is "1" or "true",
+ });
+ }
+
+ private void Picture(SlideContext context, string partPath, XElement picture, Transform transform, List<HInline> output)
+ {
+ var (layoutPh, masterPh) = partPath == context.SlidePath ? Inherited(context, Placeholder(picture)) : (null, null);
+ if (Bounds(Geometry(picture, layoutPh, masterPh), transform) is not { } bounds)
+ return;
+ var embed = (string?)picture.Element(P + "blipFill")?.Element(A + "blip")?.Attribute(R + "embed");
+ var target = _package.Target(partPath, embed);
+ if (target is null || !PictureTypes.Contains(Path.GetExtension(target)) || _package.Extract(target, _mediaFolder) is not { } file)
+ return; // vector formats (EMF, WMF, SVG without a bitmap fallback) are left out
+ output.Add(new HImage(file)
+ {
+ Width = Math.Max(1, Hwp(bounds.W)),
+ Height = Math.Max(1, Hwp(bounds.H)),
+ Anchor = Anchor(Hwp(bounds.X), Hwp(bounds.Y)),
+ });
+ }
+
+ // ───────────────────────── Fills and lines ─────────────────────────
+
+ /// <summary>
+ /// Solid colour or gradient of a shape's properties; a style reference (p:style/a:fillRef) applies when the
+ /// properties say nothing, as for shapes drawn with PowerPoint's default style.
+ /// </summary>
+ private static (string? Fill, HGradient? Gradient) Fill(XElement? properties, OoxmlColors colors, XElement? styleRef)
+ {
+ if (properties?.Element(A + "noFill") is not null)
+ return (null, null);
+ if (properties?.Element(A + "solidFill") is { } solid)
+ return (colors.Drawing(solid), null);
+ if (properties?.Element(A + "gradFill") is { } gradFill)
+ {
+ var stops = gradFill.Element(A + "gsLst")?.Elements(A + "gs")
+ .OrderBy(gs => Emu(gs.Attribute("pos")))
+ .Select(gs => colors.Drawing(gs))
+ .OfType<string>()
+ .ToList() ?? [];
+ var angle = (int)(Emu(gradFill.Element(A + "lin")?.Attribute("ang")) / 60000);
+ return stops.Count >= 2 ? (stops[0], new HGradient(stops, angle)) : (stops.FirstOrDefault(), null);
+ }
+ if (properties?.Element(A + "blipFill") is not null || properties?.Element(A + "pattFill") is { })
+ return (null, null);
+ return styleRef is not null && Emu(styleRef.Attribute("idx")) > 0 ? (colors.Drawing(styleRef), null) : (null, null);
+ }
+
+ private static HBorder Line(XElement? properties, OoxmlColors colors, XElement? styleRef)
+ {
+ var ln = properties?.Element(A + "ln");
+ if (ln?.Element(A + "noFill") is not null)
+ return HBorder.None;
+ var width = Emu(ln?.Attribute("w")) is > 0 and var w ? w : 12700; // 1 pt
+ var color = ln?.Element(A + "solidFill") is { } solid ? colors.Drawing(solid)
+ : styleRef is not null && Emu(styleRef.Attribute("idx")) > 0 ? colors.Drawing(styleRef)
+ : null;
+ if (color is null)
+ return HBorder.None;
+ var dash = (string?)ln?.Element(A + "prstDash")?.Attribute("val");
+ var kind = dash switch
+ {
+ "dot" or "sysDot" => HBorderStyle.Dot,
+ "dash" or "sysDash" or "lgDash" => HBorderStyle.Dash,
+ "dashDot" or "lgDashDot" or "sysDashDot" => HBorderStyle.DashDot,
+ _ => HBorderStyle.Solid,
+ };
+ return new HBorder(kind, width / 36000.0, color);
+ }
+}
+
+internal static class HTextBoxExtensions
+{
+ /// <summary>Adds blocks to a text box built with an object initializer.</summary>
+ public static HTextBox With(this HTextBox box, IEnumerable<HBlock> blocks)
+ {
+ box.Blocks.AddRange(blocks);
+ return box;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
new file mode 100644
index 00000000..789fedf6
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/SheetDocument.cs
@@ -0,0 +1,195 @@
+// Workbook → HDocument: every non-empty sheet becomes a section with one table, so XLSX / CSV → HWPX works directly
+// and XLSX / CSV → PDF goes through the HWPX writer and rhwp, without Excel or LibreOffice.
+//
+// Layout choices, since a sheet has no page of its own: A4 with narrow margins, landscape when the columns are much
+// wider than a portrait page, columns (and text) scaled down to fit the width like "Fit all columns on one page",
+// light grey grid lines where cells have no border, frozen top rows repeated on every page.
+
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal static class SheetDocument
+{
+ /// <summary>Largest table written; bigger sheets are cut with a note (a PDF of 100 000 rows helps nobody).</summary>
+ private const int MaxRows = 5000;
+ private const int MaxColumns = 60;
+
+ private const int A4Short = 59528;
+ private const int A4Long = 84188;
+ private const int Margin = 2268; // 8 mm
+ private const double DefaultFontSize = 11; // Excel's default (Calibri / 맑은 고딕 11 pt)
+
+ private static readonly HBorder GridLine = new(HBorderStyle.Solid, 0.1, "#D9D9D9");
+
+ public static HDocument Build(Workbook book)
+ {
+ var document = new HDocument();
+ var sheets = book.Sheets.Where(s => s.UsedRange() is not null).ToList();
+ foreach (var sheet in sheets)
+ document.Sections.Add(Section(sheet, withTitle: sheets.Count > 1));
+ if (document.Sections.Count == 0)
+ {
+ var empty = new HSection();
+ empty.Blocks.Add(new HParagraph());
+ document.Sections.Add(empty);
+ }
+ return document;
+ }
+
+ private static HSection Section(Worksheet sheet, bool withTitle)
+ {
+ var range = sheet.UsedRange()!.Value;
+ var rows = Enumerable.Range(range.Top, range.Bottom - range.Top + 1).Where(r => !sheet.HiddenRows.Contains(r)).ToList();
+ var columns = Enumerable.Range(range.Left, range.Right - range.Left + 1).Where(c => !sheet.HiddenColumns.Contains(c)).ToList();
+ var cutRows = rows.Count > MaxRows;
+ var cutColumns = columns.Count > MaxColumns;
+ rows = rows.Take(MaxRows).ToList();
+ 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();
+ var total = Math.Max(1, widths.Sum());
+ var landscape = total > A4Short - 2 * Margin;
+ var page = landscape
+ ? new HPage(A4Long, A4Short, Margin, Margin, Margin / 2, Margin / 2, Margin / 2, Margin / 2, 0)
+ : new HPage(A4Short, A4Long, Margin, Margin, Margin / 2, Margin / 2, Margin / 2, Margin / 2, 0);
+ var scale = Math.Min(1.0, (double)page.TextWidth / total);
+ var fontScale = Math.Max(0.5, scale);
+
+ var section = new HSection { Page = page };
+ if (withTitle)
+ {
+ var title = new HParagraph { Format = new HParaFormat(After: 400), MarkFormat = new HCharFormat(Size: 1300) };
+ title.Inlines.Add(new HText(sheet.Name, new HCharFormat(Bold: true, Size: 1300)));
+ section.Blocks.Add(title);
+ }
+
+ var table = new HTable
+ {
+ ColumnCount = columns.Count,
+ ColumnWidths = widths.Select(w => Math.Max(300, (int)(w * scale))).ToArray(),
+ CellMargin = new HInsets(141, 141, 57, 57),
+ Borders = new HBorders(GridLine, GridLine, GridLine, GridLine),
+ };
+ var columnIndex = columns.Select((c, i) => (c, i)).ToDictionary(p => p.c, p => p.i);
+
+ // Merged areas: the top-left visible cell spans the visible rows and columns of the area; the rest are skipped.
+ var anchors = new Dictionary<(int, int), (int RowSpan, int ColSpan)>();
+ var covered = new HashSet<(int, int)>();
+ foreach (var merge in sheet.Merges)
+ {
+ var mergeRows = rows.Where(r => r >= merge.Top && r <= merge.Bottom).ToList();
+ var mergeColumns = columns.Where(c => c >= merge.Left && c <= merge.Right).ToList();
+ if (mergeRows.Count == 0 || mergeColumns.Count == 0)
+ continue;
+ anchors[(mergeRows[0], mergeColumns[0])] = (mergeRows.Count, mergeColumns.Count);
+ foreach (var r in mergeRows)
+ foreach (var c in mergeColumns)
+ if (r != mergeRows[0] || c != mergeColumns[0])
+ covered.Add((r, c));
+ }
+
+ var headerRows = sheet.FrozenRows is > 0 and <= 5 ? sheet.FrozenRows : 0;
+ foreach (var r in rows)
+ {
+ var row = new HRow
+ {
+ Header = r < headerRows,
+ Height = sheet.RowHeights.TryGetValue(r, out var points) ? (int)(points * 100 * fontScale) : null,
+ };
+ foreach (var c in columns)
+ {
+ if (covered.Contains((r, c)))
+ continue;
+ var (rowSpan, colSpan) = anchors.GetValueOrDefault((r, c), (1, 1));
+ row.Cells.Add(Cell(sheet, r, c, rowSpan, colSpan, columnIndex[c], fontScale));
+ }
+ table.Rows.Add(row);
+ }
+ section.Blocks.Add(table);
+
+ if (cutRows || cutColumns)
+ {
+ var note = new HParagraph();
+ note.Inlines.Add(new HText(
+ $"… {sheet.Name}: {(cutRows ? $"first {MaxRows} rows" : "")}{(cutRows && cutColumns ? ", " : "")}{(cutColumns ? $"first {MaxColumns} columns" : "")} shown",
+ new HCharFormat(Italic: true, Size: 900, Color: "#808080")));
+ section.Blocks.Add(note);
+ }
+ return section;
+ }
+
+ private static HCell Cell(Worksheet sheet, int r, int c, int rowSpan, int colSpan, int column, double fontScale)
+ {
+ var value = sheet.Get(r, c);
+ var style = value?.Style ?? CellStyle.Default;
+ var size = (int)Math.Round((style.FontSize ?? DefaultFontSize) * 100 * fontScale);
+ var format = new HCharFormat(
+ Bold: style.Bold ? true : null,
+ Italic: style.Italic ? true : null,
+ Underline: style.Underline ? true : null,
+ Strike: style.Strike ? true : null,
+ Size: size,
+ Color: style.Color is null or "#000000" ? null : style.Color);
+
+ var align = style.Align switch
+ {
+ CellAlign.Center => HAlign.Center,
+ CellAlign.Right => HAlign.Right,
+ CellAlign.Left => HAlign.Left,
+ _ => value?.IsNumber == true ? HAlign.Right : HAlign.Left,
+ };
+ var paragraph = new HParagraph { Format = new HParaFormat(Align: align), MarkFormat = new HCharFormat(Size: size) };
+ var lines = (value?.Text ?? "").Replace("\r\n", "\n").Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ {
+ if (i > 0)
+ paragraph.Inlines.Add(new HLineBreak(format));
+ if (lines[i].Length > 0)
+ paragraph.Inlines.Add(new HText(lines[i], format));
+ }
+
+ var cell = new HCell
+ {
+ Column = column,
+ RowSpan = rowSpan,
+ ColSpan = colSpan,
+ Fill = style.Fill,
+ VerticalAlign = style.VerticalAlign switch
+ {
+ CellVerticalAlign.Top => HVerticalAlign.Top,
+ CellVerticalAlign.Center => HVerticalAlign.Center,
+ _ => HVerticalAlign.Bottom,
+ },
+ // A border drawn by the neighbour counts too: in Excel both cells share the line.
+ Borders = new HBorders(
+ Border(style.Left, sheet.Get(r, c - 1)?.Style.Right),
+ Border(style.Right, sheet.Get(r, c + colSpan)?.Style.Left),
+ Border(style.Top, sheet.Get(r - 1, c)?.Style.Bottom),
+ Border(style.Bottom, sheet.Get(r + rowSpan, c)?.Style.Top)),
+ };
+ cell.Blocks.Add(paragraph);
+ return cell;
+ }
+
+ private static HBorder Border(CellBorder own, CellBorder? neighbour)
+ {
+ var side = own.IsVisible ? own : neighbour is { IsVisible: true } other ? other : CellBorder.None;
+ if (!side.IsVisible)
+ return GridLine;
+ var color = side.Color ?? "#000000";
+ return side.Style switch
+ {
+ "hair" => new HBorder(HBorderStyle.Solid, 0.1, color),
+ "medium" => new HBorder(HBorderStyle.Solid, 0.4, color),
+ "thick" => new HBorder(HBorderStyle.Solid, 0.7, color),
+ "double" => new HBorder(HBorderStyle.Double, 0.5, color),
+ "dotted" => new HBorder(HBorderStyle.Dot, 0.12, color),
+ "dashed" or "mediumDashed" => new HBorder(HBorderStyle.Dash, side.Style == "dashed" ? 0.12 : 0.4, color),
+ "dashDot" or "dashDotDot" or "mediumDashDot" or "mediumDashDotDot" or "slantDashDot" => new HBorder(HBorderStyle.DashDot, 0.12, color),
+ _ => new HBorder(HBorderStyle.Solid, 0.12, color),
+ };
+ }
+}
diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.cs
index 96894b26..2670875b 100644
--- a/src/Filee.Engines/Hwp/RhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs
@@ -7,7 +7,7 @@ using Filee.Engines.Infrastructure;
namespace Filee.Engines.Hwp;
/// <summary>Renders HWP and HWPX documents to PDF and converts between the two 한글 formats.</summary>
-public sealed class RhwpConverter(EngineEnvironment env) : IConverter
+public sealed class RhwpConverter : IConverter
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
private string? _exe;
@@ -58,13 +58,9 @@ public sealed class RhwpConverter(EngineEnvironment env) : IConverter
return [target];
}
- private string? Locate()
- {
- var exe = OperatingSystem.IsWindows() ? "rhwp.exe" : "rhwp";
- var bundled = EngineEnvironment.FindBundled("rhwp");
- return EngineEnvironment.FirstExisting(
- env.CustomPath(Id),
- bundled is null ? null : Path.Combine(bundled, exe),
- EngineEnvironment.FindOnPath("rhwp"));
- }
+ /// <summary>Filee's own copy (engines/rhwp), never one found elsewhere on the system.</summary>
+ private static string? Locate() =>
+ EngineEnvironment.FindBundled("rhwp") is { } bundled
+ ? EngineEnvironment.FirstExisting(Path.Combine(bundled, OperatingSystem.IsWindows() ? "rhwp.exe" : "rhwp"))
+ : null;
}
diff --git a/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs b/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs
deleted file mode 100644
index 2263dba9..00000000
--- a/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-// COM automation servers (Hwp.exe, WINWORD.EXE) sometimes hang on a hidden dialog or survive a failed Quit().
-// This guard remembers which processes existed before a conversion and kills only the hidden instances that
-// the conversion started, so a stuck conversion never leaves invisible Office processes behind.
-
-using System.Diagnostics;
-using System.Runtime.Versioning;
-
-namespace Filee.Engines.Infrastructure;
-
-[SupportedOSPlatform("windows")]
-internal sealed class AutomationProcessGuard
-{
- private readonly string _processName;
- private readonly HashSet<int> _existing;
- private readonly DateTime _startedAt = DateTime.Now.AddSeconds(-1);
-
- /// <param name="processName">Process name without ".exe", e.g. "Hwp" or "WINWORD".</param>
- public AutomationProcessGuard(string processName)
- {
- _processName = processName;
- _existing = Snapshot(processName);
- }
-
- /// <summary>
- /// Runs a COM conversion with a timeout. On timeout, cancellation or error, automation processes started by
- /// this conversion are killed (which also unblocks the COM call).
- /// </summary>
- public async Task RunAsync(Func<bool> work, TimeSpan timeout, CancellationToken cancellationToken)
- {
- var task = StaThread.RunAsync(work, cancellationToken);
- try
- {
- var finished = await Task.WhenAny(task, Task.Delay(timeout, cancellationToken));
- if (finished != task)
- {
- KillLeftovers();
- cancellationToken.ThrowIfCancellationRequested();
- throw new TimeoutException($"{_processName} did not finish within {timeout.TotalSeconds:0} s.");
- }
- await task;
- }
- catch
- {
- KillLeftovers();
- throw;
- }
- finally
- {
- // Quit() normally ends the server; give it a moment, then remove anything still hanging around.
- _ = Task.Delay(TimeSpan.FromSeconds(3)).ContinueWith(_ => KillLeftovers(), TaskScheduler.Default);
- }
- }
-
- /// <summary>Kills processes of this name that were started after the guard was created (i.e. by this conversion).</summary>
- public void KillLeftovers()
- {
- foreach (var process in Process.GetProcessesByName(_processName))
- {
- using (process)
- {
- try
- {
- if (!_existing.Contains(process.Id) && process.StartTime >= _startedAt)
- process.Kill();
- }
- catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException)
- {
- // Already gone or not accessible.
- }
- }
- }
- }
-
- private static HashSet<int> Snapshot(string name)
- {
- var processes = Process.GetProcessesByName(name);
- var ids = processes.Select(p => p.Id).ToHashSet();
- foreach (var p in processes)
- p.Dispose();
- return ids;
- }
-}
diff --git a/src/Filee.Engines/Infrastructure/EngineEnvironment.cs b/src/Filee.Engines/Infrastructure/EngineEnvironment.cs
index cf00ba7a..5c2b4939 100644
--- a/src/Filee.Engines/Infrastructure/EngineEnvironment.cs
+++ b/src/Filee.Engines/Infrastructure/EngineEnvironment.cs
@@ -1,23 +1,15 @@
-// Shared context for engines: where bundled tools live and which custom paths the user configured.
+// Shared context for engines: where Filee's own engine copies live and where engines keep their state.
+// Engines never use software installed on the system (Office, a system-wide LibreOffice, tools on the PATH): only
+// the copies that ship with the installer or that Filee downloaded, so every user gets the same, tested versions.
namespace Filee.Engines.Infrastructure;
/// <summary>Environment information passed to every engine.</summary>
-public sealed class EngineEnvironment
+/// <param name="dataDirectory">Filee's writable data directory (profiles, caches).</param>
+public sealed class EngineEnvironment(string dataDirectory)
{
- /// <param name="customPath">Returns a user-configured executable path for an engine id, or null.</param>
- /// <param name="dataDirectory">Filee's writable data directory (profiles, caches).</param>
- public EngineEnvironment(Func<string, string?> customPath, string dataDirectory)
- {
- CustomPath = customPath;
- DataDirectory = dataDirectory;
- }
-
- /// <summary>User override for an engine executable (engine id → path).</summary>
- public Func<string, string?> CustomPath { get; }
-
/// <summary>Writable directory for engine state (e.g. LibreOffice profiles).</summary>
- public string DataDirectory { get; }
+ public string DataDirectory { get; } = dataDirectory;
/// <summary>
/// Per-user folder for engines downloaded on demand (see <see cref="EngineInstaller"/>):
@@ -29,47 +21,25 @@ public sealed class EngineEnvironment
/// <summary>
/// Finds an engine directory (<c>engines/&lt;name&gt;</c>): next to the executable (bundled with the installer),
- /// in <see cref="DownloadRoot"/> (downloaded later), then up the directory tree so a developer running from
- /// <c>bin/Debug</c> can use engines fetched into the repository root.
+ /// in <see cref="DownloadRoot"/> (downloaded later), then in the Filee repository checkout the app runs from
+ /// (a folder with Filee.slnx), so a developer running from <c>bin/Debug</c> uses the engines fetched there.
/// </summary>
public static string? FindBundled(string name)
{
- var downloaded = Path.Combine(DownloadRoot, name);
var local = Path.Combine(AppContext.BaseDirectory, "engines", name);
if (Directory.Exists(local))
return local;
+ var downloaded = Path.Combine(DownloadRoot, name);
if (Directory.Exists(downloaded))
return downloaded;
var dir = new DirectoryInfo(AppContext.BaseDirectory);
for (var depth = 0; dir is not null && depth < 8; depth++, dir = dir.Parent)
{
+ if (!File.Exists(Path.Combine(dir.FullName, "Filee.slnx")))
+ continue;
var candidate = Path.Combine(dir.FullName, "engines", name);
- if (Directory.Exists(candidate))
- return candidate;
- }
- return null;
- }
-
- /// <summary>Searches the PATH for an executable.</summary>
- public static string? FindOnPath(string executable)
- {
- var names = OperatingSystem.IsWindows() && !executable.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
- ? new[] { executable + ".exe", executable }
- : [executable];
-
- foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator))
- {
- foreach (var name in names)
- {
- try
- {
- var full = Path.Combine(dir.Trim('"'), name);
- if (File.Exists(full))
- return full;
- }
- catch (ArgumentException) { /* malformed PATH entry */ }
- }
+ return Directory.Exists(candidate) ? candidate : null;
}
return null;
}
diff --git a/src/Filee.Engines/Infrastructure/StaThread.cs b/src/Filee.Engines/Infrastructure/StaThread.cs
deleted file mode 100644
index ce5afe7c..00000000
--- a/src/Filee.Engines/Infrastructure/StaThread.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-// COM automation (MS Word) must run on a single-threaded apartment thread.
-
-using System.Runtime.Versioning;
-
-namespace Filee.Engines.Infrastructure;
-
-/// <summary>Runs a delegate on a fresh STA thread and awaits the result.</summary>
-public static class StaThread
-{
- [SupportedOSPlatform("windows")]
- public static Task<T> RunAsync<T>(Func<T> work, CancellationToken cancellationToken)
- {
- var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously);
- var thread = new Thread(() =>
- {
- try
- {
- cancellationToken.ThrowIfCancellationRequested();
- tcs.TrySetResult(work());
- }
- catch (OperationCanceledException)
- {
- tcs.TrySetCanceled(cancellationToken);
- }
- catch (Exception ex)
- {
- tcs.TrySetException(ex);
- }
- })
- {
- IsBackground = true,
- Name = "Filee COM worker",
- };
- thread.SetApartmentState(ApartmentState.STA);
- thread.Start();
- return tcs.Task;
- }
-}
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index 370d75e9..6235e846 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -1,5 +1,6 @@
-// Office documents via LibreOffice in headless mode (MPL-2.0). LibreOffice is bundled with the installer
-// (engines/libreoffice); a system installation or a user-configured path is used as fallback.
+// Office documents via LibreOffice in headless mode (MPL-2.0): the optional fallback for formats the built-in engines
+// don't handle (DOC, XLS, PPT, OpenDocument, output as DOCX, ...). Filee downloads its own copy on request
+// (engines/libreoffice); a LibreOffice installed on the system is never used.
//
// Gotchas handled here:
// * Each concurrent soffice process needs its own user profile (-env:UserInstallation), otherwise
@@ -13,7 +14,6 @@
using Filee.Core.Conversion;
using Filee.Engines.Infrastructure;
-using Microsoft.Win32;
namespace Filee.Engines.Office;
@@ -213,31 +213,26 @@ public sealed class LibreOfficeConverter : IConverter
edges.Add(new ConversionEdge(s, t, cost));
}
- Add(Writer, [.. Writer, "pdf", "txt", "html"], 12);
- Add(Calc, [.. Calc, "pdf", "html"], 12);
- Add(Impress, [.. Impress, "pdf"], 12);
- Add(["txt", "html"], ["docx", "odt", "pdf"], 15);
+ // LibreOffice is the fallback: its costs make the built-in engines win wherever they can do the job
+ // (DOCX / XLSX / PPTX / TXT → PDF through the HWPX writer and rhwp, XLSX ↔ CSV, ...), so it is only used for
+ // what nothing else reads or writes (DOC, XLS, PPT, OpenDocument, DOCX output, ...).
+ const int Fallback = 25;
+ Add(Writer, [.. Writer, "pdf", "txt", "html"], Fallback);
+ Add(Calc, [.. Calc, "pdf", "html"], Fallback);
+ Add(Impress, [.. Impress, "pdf"], Fallback);
+ Add(["txt", "html"], ["docx", "odt", "pdf"], Fallback + 3);
if (hwp)
- Add(["hwp", "hwpx"], ["pdf", "docx", "odt", "rtf"], 18);
+ Add(["hwp", "hwpx"], ["pdf", "docx", "odt", "rtf"], Fallback + 6);
return edges;
}
- /// <summary>Finds soffice: user path → bundled copy → system installation.</summary>
+ /// <summary>Finds Filee's own copy (engines/libreoffice); a LibreOffice installed on the system is never used.</summary>
private void Locate()
{
var bundled = EngineEnvironment.FindBundled("libreoffice");
- var exe = OperatingSystem.IsWindows() ? "soffice.exe" : "soffice";
-
- _soffice = EngineEnvironment.FirstExisting(
- _env.CustomPath(Id),
- bundled is null ? null : Path.Combine(bundled, "program", exe),
- bundled is null ? null : Path.Combine(bundled, "Contents", "MacOS", "soffice"),
- RegistryInstallPath(),
- OperatingSystem.IsWindows() ? @"C:\Program Files\LibreOffice\program\soffice.exe" : null,
- OperatingSystem.IsWindows() ? @"C:\Program Files (x86)\LibreOffice\program\soffice.exe" : null,
- OperatingSystem.IsMacOS() ? "/Applications/LibreOffice.app/Contents/MacOS/soffice" : null,
- EngineEnvironment.FindOnPath("soffice"));
-
+ _soffice = bundled is null ? null : EngineEnvironment.FirstExisting(
+ Path.Combine(bundled, "program", OperatingSystem.IsWindows() ? "soffice.exe" : "soffice"),
+ Path.Combine(bundled, "Contents", "MacOS", "soffice"));
_hasHwpFilter = _soffice is not null && HasH2Orestart(_soffice);
}
@@ -259,20 +254,4 @@ public sealed class LibreOfficeConverter : IConverter
catch (UnauthorizedAccessException) { }
return false;
}
-
- private static string? RegistryInstallPath()
- {
- if (!OperatingSystem.IsWindows())
- return null;
- try
- {
- using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\LibreOffice\UNO\InstallPath");
- var dir = key?.GetValue(null) as string;
- return dir is null ? null : Path.Combine(dir, "soffice.exe");
- }
- catch (Exception ex) when (ex is System.Security.SecurityException or IOException or UnauthorizedAccessException)
- {
- return null;
- }
- }
}
diff --git a/src/Filee.Engines/Office/Ooxml/OoxmlColors.cs b/src/Filee.Engines/Office/Ooxml/OoxmlColors.cs
new file mode 100644
index 00000000..6ff3f249
--- /dev/null
+++ b/src/Filee.Engines/Office/Ooxml/OoxmlColors.cs
@@ -0,0 +1,210 @@
+// Colours in Office Open XML: theme colours (theme1.xml), Excel's tint and indexed palette, and DrawingML colour
+// elements with their modifiers (lumMod, lumOff, tint, shade).
+
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Office.Ooxml;
+
+/// <summary>Resolves colours to "#RRGGBB".</summary>
+internal sealed class OoxmlColors
+{
+ public static readonly XNamespace A = "http://schemas.openxmlformats.org/drawingml/2006/main";
+
+ /// <summary>Theme slots in clrScheme order.</summary>
+ private static readonly string[] Slots = ["dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"];
+
+ /// <summary>Office 2013+ default theme, used when a file has none.</summary>
+ private static readonly Dictionary<string, string> DefaultTheme = new()
+ {
+ ["dk1"] = "#000000",
+ ["lt1"] = "#FFFFFF",
+ ["dk2"] = "#44546A",
+ ["lt2"] = "#E7E6E6",
+ ["accent1"] = "#4472C4",
+ ["accent2"] = "#ED7D31",
+ ["accent3"] = "#A5A5A5",
+ ["accent4"] = "#FFC000",
+ ["accent5"] = "#5B9BD5",
+ ["accent6"] = "#70AD47",
+ ["hlink"] = "#0563C1",
+ ["folHlink"] = "#954F72",
+ };
+
+ /// <summary>Excel's legacy indexed colours 0-63 (8-63 is the default 56-colour palette).</summary>
+ private static readonly string[] Indexed =
+ [
+ "000000", "FFFFFF", "FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF",
+ "000000", "FFFFFF", "FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF",
+ "800000", "008000", "000080", "808000", "800080", "008080", "C0C0C0", "808080",
+ "9999FF", "993366", "FFFFCC", "CCFFFF", "660066", "FF8080", "0066CC", "CCCCFF",
+ "000080", "FF00FF", "FFFF00", "00FFFF", "800080", "800000", "008080", "0000FF",
+ "00CCFF", "CCFFFF", "CCFFCC", "FFFF99", "99CCFF", "FF99CC", "CC99FF", "FFCC99",
+ "3366FF", "33CCCC", "99CC00", "FFCC00", "FF9900", "FF6600", "666699", "969696",
+ "003366", "339966", "003300", "333300", "993300", "993366", "333399", "333333",
+ ];
+
+ private readonly Dictionary<string, string> _theme;
+ private readonly IReadOnlyDictionary<string, string>? _map;
+
+ private OoxmlColors(Dictionary<string, string> theme, IReadOnlyDictionary<string, string>? map = null)
+ {
+ _theme = theme;
+ _map = map;
+ }
+
+ /// <summary>
+ /// The same colours with a PresentationML colour map (p:clrMap bg1="lt1" tx1="dk1" ...), which decides what the
+ /// aliases tx1 / bg1 / tx2 / bg2 mean.
+ /// </summary>
+ public OoxmlColors WithMap(IReadOnlyDictionary<string, string>? map) => new(_theme, map);
+
+ /// <summary>Reads the colour scheme of a theme part (null = Office default colours).</summary>
+ public static OoxmlColors FromTheme(XDocument? theme)
+ {
+ var colors = new Dictionary<string, string>(DefaultTheme);
+ var scheme = theme?.Descendants(A + "clrScheme").FirstOrDefault();
+ foreach (var slot in Slots)
+ {
+ var element = scheme?.Element(A + slot);
+ var value = (string?)element?.Element(A + "srgbClr")?.Attribute("val")
+ ?? (string?)element?.Element(A + "sysClr")?.Attribute("lastClr");
+ if (value is { Length: 6 })
+ colors[slot] = "#" + value.ToUpperInvariant();
+ }
+ return new OoxmlColors(colors);
+ }
+
+ /// <summary>A theme slot or alias (tx1, bg1, ...) as "#RRGGBB".</summary>
+ public string Theme(string name) => _theme.GetValueOrDefault(
+ _map?.GetValueOrDefault(name) ?? name switch
+ {
+ "tx1" => "dk1",
+ "bg1" => "lt1",
+ "tx2" => "dk2",
+ "bg2" => "lt2",
+ _ => name,
+ }, "#000000");
+
+ /// <summary>
+ /// A SpreadsheetML colour element (&lt;color rgb="FFRRGGBB"/&gt;, theme="n" tint="x" or indexed="n"), or null
+ /// for "automatic".
+ /// </summary>
+ public string? Spreadsheet(XElement? color)
+ {
+ if (color is null || (string?)color.Attribute("auto") is "1" or "true")
+ return null;
+ string? hex = null;
+ if ((string?)color.Attribute("rgb") is { Length: >= 6 } argb)
+ hex = "#" + argb[^6..].ToUpperInvariant();
+ else if (int.TryParse((string?)color.Attribute("theme"), out var theme) && theme is >= 0 and < 12)
+ // SpreadsheetML swaps the first two pairs: 0 = lt1, 1 = dk1, 2 = lt2, 3 = dk2.
+ hex = Theme(theme switch { 0 => "lt1", 1 => "dk1", 2 => "lt2", 3 => "dk2", _ => Slots[theme] });
+ else if (int.TryParse((string?)color.Attribute("indexed"), out var index) && index is >= 0 and < 64)
+ hex = "#" + Indexed[index];
+ if (hex is null)
+ return null;
+ return double.TryParse((string?)color.Attribute("tint"), NumberStyles.Float, CultureInfo.InvariantCulture, out var tint) && tint != 0
+ ? Tint(hex, tint)
+ : hex;
+ }
+
+ /// <summary>
+ /// The first DrawingML colour child of <paramref name="parent"/> (srgbClr, schemeClr, sysClr, prstClr) with its
+ /// modifiers applied; <paramref name="placeholderColor"/> replaces schemeClr "phClr" (style references).
+ /// </summary>
+ public string? Drawing(XElement? parent, string? placeholderColor = null)
+ {
+ foreach (var element in parent?.Elements() ?? [])
+ {
+ string? hex = element.Name.LocalName switch
+ {
+ "srgbClr" => (string?)element.Attribute("val") is { Length: 6 } rgb ? "#" + rgb.ToUpperInvariant() : null,
+ "schemeClr" => (string?)element.Attribute("val") is "phClr" ? placeholderColor : Theme((string?)element.Attribute("val") ?? ""),
+ "sysClr" => (string?)element.Attribute("lastClr") is { Length: 6 } last ? "#" + last.ToUpperInvariant() : "#000000",
+ "prstClr" => PresetColor((string?)element.Attribute("val")),
+ _ => null,
+ };
+ if (element.Name.LocalName is not ("srgbClr" or "schemeClr" or "sysClr" or "prstClr" or "scrgbClr" or "hslClr"))
+ continue;
+ return hex is null ? null : Modify(hex, element);
+ }
+ return null;
+ }
+
+ private static string Modify(string hex, XElement color)
+ {
+ double Value(string name) => int.TryParse((string?)color.Element(A + name)?.Attribute("val"), out var v) ? v / 100000.0 : double.NaN;
+ var (h, s, l) = ToHsl(hex);
+ var lumMod = Value("lumMod");
+ var lumOff = Value("lumOff");
+ if (!double.IsNaN(lumMod) || !double.IsNaN(lumOff))
+ l = Math.Clamp(l * (double.IsNaN(lumMod) ? 1 : lumMod) + (double.IsNaN(lumOff) ? 0 : lumOff), 0, 1);
+ var result = FromHsl(h, s, l);
+ var (r, g, b) = Rgb(result);
+ var tint = Value("tint");
+ if (!double.IsNaN(tint))
+ (r, g, b) = (r + (1 - r) * (1 - tint), g + (1 - g) * (1 - tint), b + (1 - b) * (1 - tint));
+ var shade = Value("shade");
+ if (!double.IsNaN(shade))
+ (r, g, b) = (r * shade, g * shade, b * shade);
+ return Hex(r, g, b);
+ }
+
+ /// <summary>Excel's tint: lightens (tint &gt; 0) or darkens (tint &lt; 0) the luminance.</summary>
+ internal static string Tint(string hex, double tint)
+ {
+ var (h, s, l) = ToHsl(hex);
+ l = tint < 0 ? l * (1 + tint) : l * (1 - tint) + tint;
+ return FromHsl(h, s, Math.Clamp(l, 0, 1));
+ }
+
+ private static string? PresetColor(string? name) => name switch
+ {
+ "black" => "#000000",
+ "white" => "#FFFFFF",
+ "red" => "#FF0000",
+ "green" => "#008000",
+ "blue" => "#0000FF",
+ "yellow" => "#FFFF00",
+ "gray" or "grey" => "#808080",
+ "lightGray" => "#D3D3D3",
+ "darkGray" => "#A9A9A9",
+ "orange" => "#FFA500",
+ _ => null,
+ };
+
+ private static (double R, double G, double B) Rgb(string hex) =>
+ (Convert.ToInt32(hex[1..3], 16) / 255.0, Convert.ToInt32(hex[3..5], 16) / 255.0, Convert.ToInt32(hex[5..7], 16) / 255.0);
+
+ private static string Hex(double r, double g, double b) =>
+ $"#{(int)Math.Round(Math.Clamp(r, 0, 1) * 255):X2}{(int)Math.Round(Math.Clamp(g, 0, 1) * 255):X2}{(int)Math.Round(Math.Clamp(b, 0, 1) * 255):X2}";
+
+ private static (double H, double S, double L) ToHsl(string hex)
+ {
+ var (r, g, b) = Rgb(hex);
+ var max = Math.Max(r, Math.Max(g, b));
+ var min = Math.Min(r, Math.Min(g, b));
+ var l = (max + min) / 2;
+ if (max == min)
+ return (0, 0, l);
+ var d = max - min;
+ var s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ var h = max == r ? (g - b) / d + (g < b ? 6 : 0) : max == g ? (b - r) / d + 2 : (r - g) / d + 4;
+ return (h / 6, s, l);
+ }
+
+ private static string FromHsl(double h, double s, double l)
+ {
+ if (s == 0)
+ return Hex(l, l, l);
+ double Channel(double p, double q, double t)
+ {
+ t = t < 0 ? t + 1 : t > 1 ? t - 1 : t;
+ return t < 1 / 6.0 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2 / 3.0 ? p + (q - p) * (2 / 3.0 - t) * 6 : p;
+ }
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+ return Hex(Channel(p, q, h + 1 / 3.0), Channel(p, q, h), Channel(p, q, h - 1 / 3.0));
+ }
+}
diff --git a/src/Filee.Engines/Office/Ooxml/OpcPackage.cs b/src/Filee.Engines/Office/Ooxml/OpcPackage.cs
new file mode 100644
index 00000000..b53c26ad
--- /dev/null
+++ b/src/Filee.Engines/Office/Ooxml/OpcPackage.cs
@@ -0,0 +1,106 @@
+// Minimal reader for Office Open XML packages (.xlsx, .pptx): parts as XML, relationships resolved to zip paths.
+
+using System.IO.Compression;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Office.Ooxml;
+
+/// <summary>A relationship of a package part; <see cref="Target"/> is a zip path unless it is external.</summary>
+internal readonly record struct OpcRelationship(string Type, string Target, bool External);
+
+/// <summary>An open OPC zip package. Parts and relationships are cached.</summary>
+internal sealed class OpcPackage : IDisposable
+{
+ private static readonly XNamespace PackageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
+
+ private readonly ZipArchive _zip;
+ private readonly Dictionary<string, XDocument?> _parts = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Dictionary<string, Dictionary<string, OpcRelationship>> _relationships = new(StringComparer.OrdinalIgnoreCase);
+
+ public OpcPackage(string path) => _zip = ZipFile.OpenRead(path);
+
+ /// <summary>The main part (target of the package's officeDocument relationship), e.g. xl/workbook.xml.</summary>
+ public string? MainPartPath =>
+ Relationships("").Values.FirstOrDefault(r => r.Type.EndsWith("/officeDocument", StringComparison.Ordinal)).Target;
+
+ /// <summary>A part as XML (whitespace preserved), or null when it doesn't exist.</summary>
+ public XDocument? Part(string path)
+ {
+ if (_parts.TryGetValue(path, out var cached))
+ return cached;
+ XDocument? xml = null;
+ if (_zip.GetEntry(path) is { } entry)
+ {
+ using var stream = entry.Open();
+ xml = XDocument.Load(stream, LoadOptions.PreserveWhitespace);
+ }
+ _parts[path] = xml;
+ return xml;
+ }
+
+ /// <summary>Relationships of a part ("" = the package), by id.</summary>
+ public Dictionary<string, OpcRelationship> Relationships(string partPath)
+ {
+ if (_relationships.TryGetValue(partPath, out var cached))
+ return cached;
+ var folder = Folder(partPath);
+ var relsPath = partPath.Length == 0 ? "_rels/.rels" : $"{folder}/_rels/{partPath[(partPath.LastIndexOf('/') + 1)..]}.rels".TrimStart('/');
+ var result = new Dictionary<string, OpcRelationship>();
+ if (_zip.GetEntry(relsPath) is { } entry)
+ {
+ using var stream = entry.Open();
+ foreach (var rel in XDocument.Load(stream).Root?.Elements(PackageRelationships + "Relationship") ?? [])
+ {
+ var target = (string?)rel.Attribute("Target") ?? "";
+ var external = (string?)rel.Attribute("TargetMode") == "External";
+ result[(string?)rel.Attribute("Id") ?? ""] = new OpcRelationship(
+ (string?)rel.Attribute("Type") ?? "", external ? target : ResolvePath(folder, target), external);
+ }
+ }
+ _relationships[partPath] = result;
+ return result;
+ }
+
+ /// <summary>Zip path of the part that relationship <paramref name="id"/> of <paramref name="partPath"/> points to.</summary>
+ public string? Target(string partPath, string? id) =>
+ id is not null && Relationships(partPath).TryGetValue(id, out var rel) && !rel.External ? rel.Target : null;
+
+ /// <summary>The first relationship target of a type (matched on the end of the type URI, e.g. "/theme").</summary>
+ public string? TargetOfType(string partPath, string typeSuffix) =>
+ Relationships(partPath).Values.FirstOrDefault(r => !r.External && r.Type.EndsWith(typeSuffix, StringComparison.Ordinal)).Target;
+
+ /// <summary>Copies a binary part (a picture) to <paramref name="folder"/>; returns the file path, or null.</summary>
+ public string? Extract(string partPath, string folder)
+ {
+ if (_zip.GetEntry(partPath) is not { } entry)
+ return null;
+ Directory.CreateDirectory(folder);
+ var file = Path.Combine(folder, $"{Guid.NewGuid():N}{Path.GetExtension(partPath)}");
+ entry.ExtractToFile(file);
+ return file;
+ }
+
+ public void Dispose() => _zip.Dispose();
+
+ private static string Folder(string path) => path.Contains('/') ? path[..path.LastIndexOf('/')] : "";
+
+ private static string ResolvePath(string folder, string target)
+ {
+ if (target.StartsWith('/'))
+ return target.TrimStart('/');
+ var parts = new List<string>(folder.Length == 0 ? [] : folder.Split('/'));
+ foreach (var segment in Uri.UnescapeDataString(target).Split('/'))
+ {
+ if (segment == "..")
+ {
+ if (parts.Count > 0)
+ parts.RemoveAt(parts.Count - 1);
+ }
+ else if (segment is not ("." or ""))
+ {
+ parts.Add(segment);
+ }
+ }
+ return string.Join('/', parts);
+ }
+}
diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.cs
index 26421284..2fa7e8c8 100644
--- a/src/Filee.Engines/Office/PandocConverter.cs
+++ b/src/Filee.Engines/Office/PandocConverter.cs
@@ -1,5 +1,5 @@
// General document conversions with Pandoc (GPL-2.0-or-later, bundled as a separate program in engines/pandoc).
-// Mainly adds Markdown in and out, which no other engine offers; for office ↔ HTML LibreOffice/Word stay preferred.
+// Adds Markdown ↔ DOCX / ODT / RTF and HTML ↔ DOCX / ODT; Markdown → HTML / TXT / HWPX is built in (MarkdownConverter).
using Filee.Core.Conversion;
using Filee.Engines.Infrastructure;
@@ -7,7 +7,7 @@ using Filee.Engines.Infrastructure;
namespace Filee.Engines.Office;
/// <summary>Markdown, HTML, DOCX, ODT and RTF conversions through Pandoc.</summary>
-public sealed class PandocConverter(EngineEnvironment env) : IConverter
+public sealed class PandocConverter : IConverter
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
@@ -41,20 +41,20 @@ public sealed class PandocConverter(EngineEnvironment env) : IConverter
// Markdown in / out: only Pandoc does this.
.. new[] { "docx", "odt", "html", "rtf" }.Select(from => new ConversionEdge(from, "md")),
.. new[] { "docx", "odt", "html", "rtf", "txt" }.Select(to => new ConversionEdge("md", to)),
- // Overlaps with LibreOffice: slightly more expensive so LibreOffice / Word win by default.
+ // Overlaps with LibreOffice (the fallback engine, which costs more).
.. new[] { "docx", "odt" }.Select(to => new ConversionEdge("html", to, 14)),
.. new[] { "docx", "odt" }.Select(from => new ConversionEdge(from, "html", 14)),
];
public EngineStatus GetStatus()
{
- _pandoc = Locate(env);
+ _pandoc = Locate();
return _pandoc is null ? EngineStatus.Unavailable("engine.reason.not_installed") : EngineStatus.Available(_pandoc);
}
public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
{
- var pandoc = _pandoc ?? Locate(env) ?? throw new InvalidOperationException("Pandoc was not found.");
+ var pandoc = _pandoc ?? Locate() ?? throw new InvalidOperationException("Pandoc was not found.");
var output = step.Output.Allocate(step.To);
if (output is null)
return [];
@@ -76,14 +76,9 @@ public sealed class PandocConverter(EngineEnvironment env) : IConverter
return [output];
}
- /// <summary>pandoc executable: custom path, bundled engines/pandoc, then PATH.</summary>
- internal static string? Locate(EngineEnvironment env)
- {
- var bundled = EngineEnvironment.FindBundled("pandoc");
- var exe = OperatingSystem.IsWindows() ? "pandoc.exe" : "pandoc";
- return EngineEnvironment.FirstExisting(
- env.CustomPath("pandoc"),
- bundled is null ? null : Path.Combine(bundled, exe),
- EngineEnvironment.FindOnPath("pandoc"));
- }
+ /// <summary>Filee's own pandoc (engines/pandoc, downloaded on demand), never one found elsewhere on the system.</summary>
+ internal static string? Locate() =>
+ EngineEnvironment.FindBundled("pandoc") is { } bundled
+ ? EngineEnvironment.FirstExisting(Path.Combine(bundled, OperatingSystem.IsWindows() ? "pandoc.exe" : "pandoc"))
+ : null;
}
diff --git a/src/Filee.Engines/Office/Sheets/CsvFormat.cs b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
new file mode 100644
index 00000000..e9b98347
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/CsvFormat.cs
@@ -0,0 +1,159 @@
+// CSV ↔ Worksheet. Reading follows RFC 4180 (quotes, doubled quotes, line breaks inside quotes), detects the
+// delimiter (comma, semicolon or tab) and the encoding (UTF-8 / UTF-16 with BOM, else CP949 like Korean Excel).
+// Writing produces what Excel opens correctly everywhere: UTF-8 with BOM, CRLF line ends, quotes only when needed.
+
+using System.Globalization;
+using System.Text;
+using Filee.Engines.Hwp.Hwpx;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class CsvFormat
+{
+ /// <summary>Reads a CSV file into one sheet named after the file.</summary>
+ public static Workbook Read(string path)
+ {
+ var text = HwpxConverter.DecodeText(File.ReadAllBytes(path));
+ var sheet = new Worksheet(Path.GetFileNameWithoutExtension(path));
+ var rows = Parse(text, DetectDelimiter(text));
+ var widths = new Dictionary<int, double>();
+ for (var r = 0; r < rows.Count; r++)
+ {
+ for (var c = 0; c < rows[r].Count; c++)
+ {
+ var value = rows[r][c];
+ if (value.Length == 0)
+ continue;
+ sheet.Set(r, c, new SheetCell(value, CellStyle.Default, IsNumber(value)));
+ widths[c] = Math.Max(widths.GetValueOrDefault(c), DisplayWidth(value));
+ }
+ }
+ // CSV has no widths: size columns to their content like Excel's "AutoFit" would, within reason.
+ foreach (var (column, width) in widths)
+ sheet.ColumnWidths[column] = Math.Clamp(width + 1, 4, 50);
+ var book = new Workbook();
+ book.Sheets.Add(sheet);
+ return book;
+ }
+
+ /// <summary>Writes the used range of a sheet as CSV (UTF-8 with BOM, CRLF).</summary>
+ public static void Write(Worksheet sheet, string path)
+ {
+ var sb = new StringBuilder();
+ if (sheet.UsedRange() is { } range)
+ {
+ for (var r = 0; r <= range.Bottom; r++)
+ {
+ if (sheet.HiddenRows.Contains(r))
+ continue;
+ var fields = new List<string>();
+ for (var c = 0; c <= range.Right; c++)
+ {
+ if (!sheet.HiddenColumns.Contains(c))
+ fields.Add(Quote(sheet.Get(r, c)?.Text ?? ""));
+ }
+ // Excel omits trailing empty fields only for fully empty rows; keep the column count stable.
+ sb.Append(string.Join(',', fields)).Append("\r\n");
+ }
+ }
+ File.WriteAllText(path, sb.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
+ }
+
+ internal static List<List<string>> Parse(string text, char delimiter)
+ {
+ var rows = new List<List<string>>();
+ var row = new List<string>();
+ var field = new StringBuilder();
+ var quoted = false;
+ for (var i = 0; i < text.Length; i++)
+ {
+ var ch = text[i];
+ if (quoted)
+ {
+ if (ch == '"' && i + 1 < text.Length && text[i + 1] == '"')
+ {
+ field.Append('"');
+ i++;
+ }
+ else if (ch == '"')
+ {
+ quoted = false;
+ }
+ else
+ {
+ field.Append(ch);
+ }
+ }
+ else if (ch == '"' && field.Length == 0)
+ {
+ quoted = true;
+ }
+ else if (ch == delimiter)
+ {
+ row.Add(field.ToString());
+ field.Clear();
+ }
+ else if (ch is '\r' or '\n')
+ {
+ if (ch == '\r' && i + 1 < text.Length && text[i + 1] == '\n')
+ i++;
+ row.Add(field.ToString());
+ field.Clear();
+ rows.Add(row);
+ row = [];
+ }
+ else
+ {
+ field.Append(ch);
+ }
+ }
+ if (field.Length > 0 || row.Count > 0)
+ {
+ row.Add(field.ToString());
+ rows.Add(row);
+ }
+ return rows;
+ }
+
+ /// <summary>The most frequent of comma, semicolon and tab outside quotes in the first lines.</summary>
+ internal static char DetectDelimiter(string text)
+ {
+ var sample = text.Length > 4096 ? text[..4096] : text;
+ var counts = new Dictionary<char, int> { [','] = 0, [';'] = 0, ['\t'] = 0 };
+ var quoted = false;
+ foreach (var ch in sample)
+ {
+ if (ch == '"')
+ quoted = !quoted;
+ else if (!quoted && counts.ContainsKey(ch))
+ counts[ch]++;
+ }
+ return counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key == ',' ? 0 : 1).First().Key;
+ }
+
+ private static string Quote(string value) =>
+ value.IndexOfAny([',', '"', '\r', '\n']) >= 0 || value.StartsWith(' ') || value.EndsWith(' ')
+ ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\""
+ : value;
+
+ /// <summary>A plain number Excel would store as a number: "12", "-3.5", "1e3" (not "007" or "1,234").</summary>
+ internal static bool IsNumber(string value) =>
+ value.Length is > 0 and < 20
+ && !(value.Length > 1 && value[0] == '0' && value[1] != '.')
+ && !(value.Length > 2 && value[0] == '-' && value[1] == '0' && value[2] != '.')
+ && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _);
+
+ /// <summary>Width in "characters" as Excel counts them: wide (CJK) glyphs count twice.</summary>
+ internal static double DisplayWidth(string text)
+ {
+ var longest = 0.0;
+ foreach (var line in text.Split('\n'))
+ {
+ var width = 0.0;
+ foreach (var ch in line)
+ width += ch >= 0x1100 && (ch <= 0x115F || ch >= 0x2E80 && ch <= 0xA4CF || ch >= 0xAC00 && ch <= 0xD7A3 || ch >= 0xF900 && ch <= 0xFAFF || ch >= 0xFF00 && ch <= 0xFF60) ? 2 : 1;
+ longest = Math.Max(longest, width);
+ }
+ return longest;
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/Workbook.cs b/src/Filee.Engines/Office/Sheets/Workbook.cs
new file mode 100644
index 00000000..07a25b43
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/Workbook.cs
@@ -0,0 +1,167 @@
+// In-memory spreadsheet between the readers (XLSX, CSV) and the writers (CSV, XLSX, HWPX tables).
+// Cells hold the text as the spreadsheet shows it (numbers and dates already formatted).
+
+namespace Filee.Engines.Office.Sheets;
+
+internal sealed class Workbook
+{
+ public List<Worksheet> Sheets { get; } = [];
+}
+
+internal sealed class Worksheet(string name)
+{
+ /// <summary>Excel's default column width, in characters of the default font.</summary>
+ public const double StandardColumnWidth = 8.43;
+
+ public string Name { get; } = name;
+
+ /// <summary>Cells by 0-based row, then 0-based column. Only cells with a value or visible formatting.</summary>
+ public SortedDictionary<int, SortedDictionary<int, SheetCell>> Rows { get; } = [];
+
+ /// <summary>Column widths in characters, for columns that set one.</summary>
+ public Dictionary<int, double> ColumnWidths { get; } = [];
+
+ public double DefaultColumnWidth { get; set; } = StandardColumnWidth;
+
+ /// <summary>Row heights in points, for rows with a custom height.</summary>
+ public Dictionary<int, double> RowHeights { get; } = [];
+
+ public HashSet<int> HiddenRows { get; } = [];
+ public HashSet<int> HiddenColumns { get; } = [];
+ public List<CellRange> Merges { get; } = [];
+
+ /// <summary>Rows frozen at the top (usually headers): repeated on every printed page.</summary>
+ public int FrozenRows { get; set; }
+
+ public void Set(int row, int column, SheetCell cell)
+ {
+ if (!Rows.TryGetValue(row, out var cells))
+ Rows[row] = cells = [];
+ cells[column] = cell;
+ }
+
+ public SheetCell? Get(int row, int column) =>
+ Rows.TryGetValue(row, out var cells) && cells.TryGetValue(column, out var cell) ? cell : null;
+
+ public double ColumnWidth(int column) => ColumnWidths.TryGetValue(column, out var width) ? width : DefaultColumnWidth;
+
+ /// <summary>
+ /// The smallest range holding every cell with text, fill or borders (merged areas included); null for an empty
+ /// sheet.
+ /// </summary>
+ public CellRange? UsedRange()
+ {
+ int top = int.MaxValue, left = int.MaxValue, bottom = -1, right = -1;
+ foreach (var (row, cells) in Rows)
+ {
+ foreach (var (column, cell) in cells)
+ {
+ if (!cell.HasContent)
+ continue;
+ top = Math.Min(top, row);
+ bottom = Math.Max(bottom, row);
+ left = Math.Min(left, column);
+ right = Math.Max(right, column);
+ }
+ }
+ if (bottom < 0)
+ return null;
+ foreach (var merge in Merges.Where(m => m.Top <= bottom && m.Left <= right && m.Top >= top && m.Left >= left))
+ {
+ bottom = Math.Max(bottom, merge.Bottom);
+ right = Math.Max(right, merge.Right);
+ }
+ return new CellRange(top, left, bottom, right);
+ }
+}
+
+/// <summary>An inclusive, 0-based range of cells.</summary>
+internal readonly record struct CellRange(int Top, int Left, int Bottom, int Right)
+{
+ public bool Contains(int row, int column) => row >= Top && row <= Bottom && column >= Left && column <= Right;
+
+ /// <summary>Parses "B2" or "A1:C3".</summary>
+ public static CellRange? Parse(string? reference)
+ {
+ if (string.IsNullOrWhiteSpace(reference))
+ return null;
+ var parts = reference.Replace("$", "", StringComparison.Ordinal).Split(':');
+ if (!TryParseCell(parts[0], out var r1, out var c1))
+ return null;
+ if (parts.Length == 1)
+ return new CellRange(r1, c1, r1, c1);
+ return TryParseCell(parts[1], out var r2, out var c2)
+ ? new CellRange(Math.Min(r1, r2), Math.Min(c1, c2), Math.Max(r1, r2), Math.Max(c1, c2))
+ : null;
+ }
+
+ /// <summary>"AB12" → row 11, column 27.</summary>
+ public static bool TryParseCell(string reference, out int row, out int column)
+ {
+ row = column = -1;
+ var i = 0;
+ var col = 0;
+ while (i < reference.Length && char.IsAsciiLetter(reference[i]))
+ col = col * 26 + (char.ToUpperInvariant(reference[i++]) - 'A' + 1);
+ if (i == 0 || i == reference.Length || !int.TryParse(reference.AsSpan(i), out var r) || r < 1)
+ return false;
+ row = r - 1;
+ column = col - 1;
+ return true;
+ }
+}
+
+internal enum CellAlign
+{
+ General,
+ Left,
+ Center,
+ Right,
+}
+
+internal enum CellVerticalAlign
+{
+ Bottom,
+ Center,
+ Top,
+}
+
+/// <summary>One border side: Excel style name ("thin", "medium", "dashed", ...) and colour.</summary>
+internal readonly record struct CellBorder(string Style, string? Color)
+{
+ public static readonly CellBorder None = new("none", null);
+ public bool IsVisible => Style is not ("none" or "");
+}
+
+internal sealed record CellStyle
+{
+ public static readonly CellStyle Default = new();
+
+ public bool Bold { get; init; }
+ public bool Italic { get; init; }
+ public bool Underline { get; init; }
+ public bool Strike { get; init; }
+
+ /// <summary>Font size in points; null = the workbook default.</summary>
+ public double? FontSize { get; init; }
+
+ public string? Color { get; init; }
+ public string? Fill { get; init; }
+ public CellAlign Align { get; init; }
+ public CellVerticalAlign VerticalAlign { get; init; }
+ public bool Wrap { get; init; }
+ public CellBorder Left { get; init; } = CellBorder.None;
+ public CellBorder Right { get; init; } = CellBorder.None;
+ public CellBorder Top { get; init; } = CellBorder.None;
+ public CellBorder Bottom { get; init; } = CellBorder.None;
+
+ public bool HasBorders => Left.IsVisible || Right.IsVisible || Top.IsVisible || Bottom.IsVisible;
+}
+
+/// <summary>A cell as displayed: formatted text plus style.</summary>
+/// <param name="Text">What the cell shows ("1,234.50", "2026-10-01", "TRUE").</param>
+/// <param name="IsNumber">Numbers (and dates) align right under the General alignment.</param>
+internal sealed record SheetCell(string Text, CellStyle Style, bool IsNumber = false)
+{
+ public bool HasContent => Text.Length > 0 || Style.Fill is not null || Style.HasBorders;
+}
diff --git a/src/Filee.Engines/Office/Sheets/XlsxReader.cs b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
new file mode 100644
index 00000000..68334dd6
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/XlsxReader.cs
@@ -0,0 +1,306 @@
+// XLSX (SpreadsheetML) → Workbook, read directly (no Excel, no LibreOffice): cell values formatted the way Excel
+// shows them (number formats through ExcelNumberFormat, MIT), fonts, fills, borders, alignment, merged cells,
+// column widths, custom row heights, hidden rows / columns / sheets and frozen header rows.
+// Charts, pictures and conditional formatting are not read.
+
+using System.Globalization;
+using System.Text;
+using System.Xml.Linq;
+using ExcelNumberFormat;
+using Filee.Engines.Office.Ooxml;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal sealed class XlsxReader
+{
+ private static readonly XNamespace S = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
+ private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+
+ /// <summary>Built-in number formats (ECMA-376 18.8.30); 14 uses the ISO date order most locales read.</summary>
+ private static readonly Dictionary<int, string> BuiltInFormats = new()
+ {
+ [0] = "General",
+ [1] = "0",
+ [2] = "0.00",
+ [3] = "#,##0",
+ [4] = "#,##0.00",
+ [9] = "0%",
+ [10] = "0.00%",
+ [11] = "0.00E+00",
+ [12] = "# ?/?",
+ [13] = "# ??/??",
+ [14] = "yyyy-mm-dd",
+ [15] = "d-mmm-yy",
+ [16] = "d-mmm",
+ [17] = "mmm-yy",
+ [18] = "h:mm AM/PM",
+ [19] = "h:mm:ss AM/PM",
+ [20] = "h:mm",
+ [21] = "h:mm:ss",
+ [22] = "yyyy-mm-dd h:mm",
+ [37] = "#,##0 ;(#,##0)",
+ [38] = "#,##0 ;[Red](#,##0)",
+ [39] = "#,##0.00;(#,##0.00)",
+ [40] = "#,##0.00;[Red](#,##0.00)",
+ [45] = "mm:ss",
+ [46] = "[h]:mm:ss",
+ [47] = "mmss.0",
+ [48] = "##0.0E+0",
+ [49] = "@",
+ };
+
+ private readonly OpcPackage _package;
+ private readonly List<string> _sharedStrings = [];
+ private readonly List<(CellStyle Style, string Format)> _cellFormats = [];
+ private readonly Dictionary<string, NumberFormat> _numberFormats = [];
+ private bool _date1904;
+
+ private XlsxReader(OpcPackage package) => _package = package;
+
+ /// <summary>Reads every visible sheet of <paramref name="path"/>.</summary>
+ public static Workbook Read(string path)
+ {
+ using var package = new OpcPackage(path);
+ return new XlsxReader(package).ReadWorkbook();
+ }
+
+ private Workbook ReadWorkbook()
+ {
+ var workbookPath = _package.MainPartPath ?? "xl/workbook.xml";
+ var workbook = _package.Part(workbookPath)?.Root ?? throw new InvalidDataException("The file is not an Excel workbook (no xl/workbook.xml).");
+ _date1904 = (string?)workbook.Element(S + "workbookPr")?.Attribute("date1904") is "1" or "true";
+
+ var colors = OoxmlColors.FromTheme(_package.TargetOfType(workbookPath, "/theme") is { } theme ? _package.Part(theme) : null);
+ if (_package.TargetOfType(workbookPath, "/sharedStrings") is { } shared)
+ ReadSharedStrings(_package.Part(shared));
+ if (_package.TargetOfType(workbookPath, "/styles") is { } styles)
+ ReadStyles(_package.Part(styles), colors);
+
+ var result = new Workbook();
+ foreach (var sheet in workbook.Element(S + "sheets")?.Elements(S + "sheet") ?? [])
+ {
+ if ((string?)sheet.Attribute("state") is "hidden" or "veryHidden")
+ continue;
+ var target = _package.Target(workbookPath, (string?)sheet.Attribute(R + "id"));
+ if (target is null || _package.Part(target)?.Root is not { } xml || xml.Name != S + "worksheet")
+ continue; // chart sheets and dialog sheets have no cells
+ result.Sheets.Add(ReadSheet((string?)sheet.Attribute("name") ?? "Sheet", xml));
+ }
+ return result;
+ }
+
+ private void ReadSharedStrings(XDocument? xml)
+ {
+ foreach (var item in xml?.Root?.Elements(S + "si") ?? [])
+ _sharedStrings.Add(RichText(item));
+ }
+
+ /// <summary>Text of a shared or inline string: plain &lt;t&gt; or rich text runs; phonetic hints skipped.</summary>
+ private static string RichText(XElement item)
+ {
+ if (item.Element(S + "t") is { } plain)
+ return plain.Value;
+ var sb = new StringBuilder();
+ foreach (var run in item.Elements(S + "r"))
+ sb.Append(run.Element(S + "t")?.Value);
+ return sb.ToString();
+ }
+
+ // ───────────────────────── Styles ─────────────────────────
+
+ private void ReadStyles(XDocument? xml, OoxmlColors colors)
+ {
+ var root = xml?.Root;
+ if (root is null)
+ return;
+ var formats = root.Element(S + "numFmts")?.Elements(S + "numFmt")
+ .Where(f => int.TryParse((string?)f.Attribute("numFmtId"), out _))
+ .ToDictionary(f => int.Parse((string)f.Attribute("numFmtId")!, CultureInfo.InvariantCulture), f => (string?)f.Attribute("formatCode") ?? "General")
+ ?? [];
+
+ var fonts = (root.Element(S + "fonts")?.Elements(S + "font") ?? []).Select(f => new
+ {
+ Bold = On(f.Element(S + "b")),
+ Italic = On(f.Element(S + "i")),
+ Underline = f.Element(S + "u") is { } u && (string?)u.Attribute("val") != "none",
+ Strike = On(f.Element(S + "strike")),
+ Size = double.TryParse((string?)f.Element(S + "sz")?.Attribute("val"), NumberStyles.Float, CultureInfo.InvariantCulture, out var size) ? size : (double?)null,
+ Color = colors.Spreadsheet(f.Element(S + "color")),
+ }).ToList();
+
+ var fills = (root.Element(S + "fills")?.Elements(S + "fill") ?? []).Select(f =>
+ {
+ var pattern = f.Element(S + "patternFill");
+ var type = (string?)pattern?.Attribute("patternType");
+ return type is null or "none" or "gray125" ? null
+ : colors.Spreadsheet(pattern!.Element(S + "fgColor")) ?? colors.Spreadsheet(pattern.Element(S + "bgColor"));
+ }).ToList();
+
+ CellBorder Side(XElement? side) => side is null || (string?)side.Attribute("style") is not { } style
+ ? CellBorder.None
+ : new CellBorder(style, colors.Spreadsheet(side.Element(S + "color")));
+ var borders = (root.Element(S + "borders")?.Elements(S + "border") ?? []).Select(b => (
+ Left: Side(b.Element(S + "left") ?? b.Element(S + "start")),
+ Right: Side(b.Element(S + "right") ?? b.Element(S + "end")),
+ Top: Side(b.Element(S + "top")),
+ Bottom: Side(b.Element(S + "bottom")))).ToList();
+
+ foreach (var xf in root.Element(S + "cellXfs")?.Elements(S + "xf") ?? [])
+ {
+ var font = Index(xf, "fontId") is var fi && fi < fonts.Count ? fonts[fi] : null;
+ var fill = Index(xf, "fillId") is var fl && fl < fills.Count ? fills[fl] : null;
+ var border = Index(xf, "borderId") is var bi && bi < borders.Count ? borders[bi] : (CellBorder.None, CellBorder.None, CellBorder.None, CellBorder.None);
+ var alignment = xf.Element(S + "alignment");
+ var style = new CellStyle
+ {
+ Bold = font?.Bold ?? false,
+ Italic = font?.Italic ?? false,
+ Underline = font?.Underline ?? false,
+ Strike = font?.Strike ?? false,
+ FontSize = font?.Size,
+ Color = font?.Color,
+ Fill = fill,
+ Align = (string?)alignment?.Attribute("horizontal") switch
+ {
+ "left" => CellAlign.Left,
+ "center" or "centerContinuous" => CellAlign.Center,
+ "right" => CellAlign.Right,
+ _ => CellAlign.General,
+ },
+ VerticalAlign = (string?)alignment?.Attribute("vertical") switch
+ {
+ "top" => CellVerticalAlign.Top,
+ "center" => CellVerticalAlign.Center,
+ _ => CellVerticalAlign.Bottom,
+ },
+ Wrap = On(alignment?.Attribute("wrapText")),
+ Left = border.Item1,
+ Right = border.Item2,
+ Top = border.Item3,
+ Bottom = border.Item4,
+ };
+ var formatId = Index(xf, "numFmtId");
+ _cellFormats.Add((style, formats.GetValueOrDefault(formatId) ?? BuiltInFormats.GetValueOrDefault(formatId, "General")));
+ }
+ }
+
+ private static int Index(XElement element, string attribute) =>
+ int.TryParse((string?)element.Attribute(attribute), out var value) && value >= 0 ? value : 0;
+
+ /// <summary>A boolean element or attribute: present without val, or val="1"/"true".</summary>
+ private static bool On(XObject? node) => node switch
+ {
+ XElement element => (string?)element.Attribute("val") is null or "1" or "true",
+ XAttribute attribute => attribute.Value is "1" or "true",
+ _ => false,
+ };
+
+ // ───────────────────────── Sheets ─────────────────────────
+
+ private Worksheet ReadSheet(string name, XElement xml)
+ {
+ var sheet = new Worksheet(name);
+ if (double.TryParse((string?)xml.Element(S + "sheetFormatPr")?.Attribute("defaultColWidth"), NumberStyles.Float, CultureInfo.InvariantCulture, out var defaultWidth))
+ sheet.DefaultColumnWidth = defaultWidth;
+
+ var pane = xml.Element(S + "sheetViews")?.Elements(S + "sheetView").FirstOrDefault()?.Element(S + "pane");
+ if ((string?)pane?.Attribute("state") is "frozen" or "frozenSplit" && double.TryParse((string?)pane.Attribute("ySplit"), NumberStyles.Float, CultureInfo.InvariantCulture, out var frozen))
+ sheet.FrozenRows = (int)frozen;
+
+ foreach (var col in xml.Element(S + "cols")?.Elements(S + "col") ?? [])
+ {
+ var min = Index(col, "min");
+ var max = Math.Min(Index(col, "max"), min + 16384);
+ var hasWidth = double.TryParse((string?)col.Attribute("width"), NumberStyles.Float, CultureInfo.InvariantCulture, out var width);
+ for (var c = min; c <= max && c > 0; c++)
+ {
+ if (hasWidth)
+ sheet.ColumnWidths[c - 1] = width;
+ if (On(col.Attribute("hidden")) || hasWidth && width == 0)
+ sheet.HiddenColumns.Add(c - 1);
+ }
+ }
+
+ var nextRow = 0;
+ foreach (var row in xml.Element(S + "sheetData")?.Elements(S + "row") ?? [])
+ {
+ var r = int.TryParse((string?)row.Attribute("r"), out var number) ? number - 1 : nextRow;
+ nextRow = r + 1;
+ if (On(row.Attribute("hidden")))
+ sheet.HiddenRows.Add(r);
+ if (On(row.Attribute("customHeight")) && double.TryParse((string?)row.Attribute("ht"), NumberStyles.Float, CultureInfo.InvariantCulture, out var height))
+ sheet.RowHeights[r] = height;
+
+ var nextColumn = 0;
+ foreach (var cell in row.Elements(S + "c"))
+ {
+ var c = CellRange.TryParseCell((string?)cell.Attribute("r") ?? "", out _, out var column) ? column : nextColumn;
+ nextColumn = c + 1;
+ var (style, format) = Index(cell, "s") is var s && s < _cellFormats.Count ? _cellFormats[s] : (CellStyle.Default, "General");
+ var (text, isNumber) = Value(cell, format);
+ var value = new SheetCell(text, style, isNumber);
+ if (value.HasContent)
+ sheet.Set(r, c, value);
+ }
+ }
+
+ foreach (var merge in xml.Element(S + "mergeCells")?.Elements(S + "mergeCell") ?? [])
+ if (CellRange.Parse((string?)merge.Attribute("ref")) is { } range && (range.Bottom > range.Top || range.Right > range.Left))
+ sheet.Merges.Add(range);
+ return sheet;
+ }
+
+ /// <summary>The displayed text of a cell and whether it is a number (dates included).</summary>
+ private (string Text, bool IsNumber) Value(XElement cell, string format)
+ {
+ var type = (string?)cell.Attribute("t") ?? "n";
+ var raw = cell.Element(S + "v")?.Value;
+ switch (type)
+ {
+ case "s":
+ return (int.TryParse(raw, out var index) && index >= 0 && index < _sharedStrings.Count ? _sharedStrings[index] : "", false);
+ case "inlineStr":
+ return (cell.Element(S + "is") is { } inline ? RichText(inline) : raw ?? "", false);
+ case "str":
+ case "e":
+ return (raw ?? "", false);
+ case "b":
+ return (raw is "1" or "true" ? "TRUE" : "FALSE", false);
+ case "d":
+ return DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
+ ? (Format(date.ToOADate(), format), true)
+ : (raw ?? "", false);
+ default:
+ return double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ ? (Format(number, format), true)
+ : (raw ?? "", false);
+ }
+ }
+
+ private string Format(double value, string format)
+ {
+ if (format is "General" or "" || format.Equals("general", StringComparison.OrdinalIgnoreCase))
+ return General(value);
+ if (!_numberFormats.TryGetValue(format, out var parsed))
+ _numberFormats[format] = parsed = new NumberFormat(format);
+ if (!parsed.IsValid)
+ return General(value);
+ try
+ {
+ return parsed.Format(value, CultureInfo.InvariantCulture, _date1904);
+ }
+ catch (Exception ex) when (ex is ArgumentException or FormatException or OverflowException)
+ {
+ return General(value);
+ }
+ }
+
+ /// <summary>Excel's General format: up to 11 significant characters, no trailing zeros.</summary>
+ internal static string General(double value)
+ {
+ if (value == Math.Floor(value) && Math.Abs(value) < 1e11)
+ return value.ToString("0", CultureInfo.InvariantCulture);
+ var text = value.ToString("G10", CultureInfo.InvariantCulture);
+ return text.Contains('E') ? value.ToString("0.#####E+00", CultureInfo.InvariantCulture) : text;
+ }
+}
diff --git a/src/Filee.Engines/Office/Sheets/XlsxWriter.cs b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
new file mode 100644
index 00000000..a1402fbc
--- /dev/null
+++ b/src/Filee.Engines/Office/Sheets/XlsxWriter.cs
@@ -0,0 +1,93 @@
+// Worksheet → minimal XLSX package (one sheet, values only): numbers as numbers, everything else as inline strings,
+// column widths from the sheet. Used for CSV → XLSX; opens in Excel, LibreOffice and Google Sheets.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Security;
+using System.Text;
+
+namespace Filee.Engines.Office.Sheets;
+
+internal static class XlsxWriter
+{
+ public static void Write(Worksheet sheet, string path)
+ {
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ Add(zip, "[Content_Types].xml", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>
+ """);
+ Add(zip, "_rels/.rels", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>
+ """);
+ Add(zip, "xl/_rels/workbook.xml.rels", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>
+ """);
+ Add(zip, "xl/workbook.xml", $"""
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="{Escape(SheetName(sheet.Name))}" sheetId="1" r:id="rId1"/></sheets></workbook>
+ """);
+ Add(zip, "xl/styles.xml", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/><family val="2"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>
+ """);
+ Add(zip, "xl/worksheets/sheet1.xml", SheetXml(sheet));
+ }
+
+ private static string SheetXml(Worksheet sheet)
+ {
+ var sb = new StringBuilder("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>""");
+ sb.Append("""<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">""");
+ if (sheet.ColumnWidths.Count > 0)
+ {
+ sb.Append("<cols>");
+ foreach (var (column, width) in sheet.ColumnWidths.OrderBy(kv => kv.Key))
+ sb.Append(CultureInfo.InvariantCulture, $"<col min=\"{column + 1}\" max=\"{column + 1}\" width=\"{width:0.##}\" customWidth=\"1\"/>");
+ sb.Append("</cols>");
+ }
+ sb.Append("<sheetData>");
+ foreach (var (row, cells) in sheet.Rows)
+ {
+ sb.Append(CultureInfo.InvariantCulture, $"<row r=\"{row + 1}\">");
+ foreach (var (column, cell) in cells)
+ {
+ var reference = ColumnName(column) + (row + 1).ToString(CultureInfo.InvariantCulture);
+ if (cell.IsNumber && double.TryParse(cell.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out var number))
+ sb.Append(CultureInfo.InvariantCulture, $"<c r=\"{reference}\"><v>{number.ToString("R", CultureInfo.InvariantCulture)}</v></c>");
+ else
+ sb.Append($"<c r=\"{reference}\" t=\"inlineStr\"><is><t xml:space=\"preserve\">{Escape(cell.Text)}</t></is></c>");
+ }
+ sb.Append("</row>");
+ }
+ sb.Append("</sheetData></worksheet>");
+ return sb.ToString();
+ }
+
+ /// <summary>0 → "A", 26 → "AA".</summary>
+ internal static string ColumnName(int column)
+ {
+ var name = "";
+ for (var c = column + 1; c > 0; c = (c - 1) / 26)
+ name = (char)('A' + (c - 1) % 26) + name;
+ return name;
+ }
+
+ /// <summary>Excel sheet names: at most 31 characters, none of : \ / ? * [ ].</summary>
+ private static string SheetName(string name)
+ {
+ var clean = new string([.. name.Where(ch => ch is not (':' or '\\' or '/' or '?' or '*' or '[' or ']'))]).Trim('\'').Trim();
+ clean = clean.Length == 0 ? "Sheet1" : clean;
+ return clean.Length > 31 ? clean[..31] : clean;
+ }
+
+ private static string Escape(string text) =>
+ SecurityElement.Escape(new string([.. text.Where(ch => ch is '\t' or '\n' or '\r' || ch >= ' ')])) ?? "";
+
+ private static void Add(ZipArchive zip, string name, string content)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name, CompressionLevel.Optimal).Open(), new UTF8Encoding(false));
+ writer.Write(content);
+ }
+}
diff --git a/src/Filee.Engines/Office/SpreadsheetConverter.cs b/src/Filee.Engines/Office/SpreadsheetConverter.cs
new file mode 100644
index 00000000..e28cf16c
--- /dev/null
+++ b/src/Filee.Engines/Office/SpreadsheetConverter.cs
@@ -0,0 +1,62 @@
+// XLSX → CSV and CSV → XLSX without Excel or LibreOffice. XLSX / CSV → PDF, HWPX and HTML go through the HWPX
+// writer (sheets become 한글 tables), see HwpxConverter and SheetDocument.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Office.Sheets;
+
+namespace Filee.Engines.Office;
+
+/// <summary>Converts between spreadsheet formats in-process.</summary>
+public sealed class SpreadsheetConverter : IConverter
+{
+ public string Id => "spreadsheet";
+ public string DisplayName => "Spreadsheets (built-in)";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("xlsx", "csv"), new("csv", "xlsx")];
+
+ public EngineStatus GetStatus() => EngineStatus.Available("XLSX ↔ CSV");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ progress?.Report(0.1);
+ var book = step.From == "csv" ? CsvFormat.Read(step.InputPath) : XlsxReader.Read(step.InputPath);
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.6);
+
+ var outputs = new List<string>();
+ if (step.To == "xlsx")
+ {
+ if (step.Output.Allocate("xlsx") is { } path)
+ {
+ XlsxWriter.Write(book.Sheets[0], path);
+ outputs.Add(path);
+ }
+ }
+ else
+ {
+ // CSV holds one sheet: a workbook with several sheets becomes one file per sheet.
+ var sheets = book.Sheets.Where(s => s.UsedRange() is not null).ToList();
+ if (sheets.Count == 0 && book.Sheets.Count > 0)
+ sheets = [book.Sheets[0]];
+ foreach (var sheet in sheets)
+ {
+ var path = step.Output.Allocate("csv", sheets.Count > 1 ? "_" + SafeName(sheet.Name) : null);
+ if (path is null)
+ continue;
+ CsvFormat.Write(sheet, path);
+ outputs.Add(path);
+ }
+ }
+ progress?.Report(1);
+ return outputs;
+ }, cancellationToken);
+
+ private static string SafeName(string name)
+ {
+ var invalid = Path.GetInvalidFileNameChars();
+ var clean = new string([.. name.Select(ch => invalid.Contains(ch) ? '_' : ch)]).Trim();
+ return clean.Length == 0 ? "Sheet" : clean;
+ }
+}
diff --git a/src/Filee.Engines/Office/WordComConverter.cs b/src/Filee.Engines/Office/WordComConverter.cs
deleted file mode 100644
index fdd8508b..00000000
--- a/src/Filee.Engines/Office/WordComConverter.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-// Microsoft Word automation (Windows, only when Word is installed). Highest fidelity for DOCX → PDF and the
-// only reasonable PDF → DOCX path (Word's "PDF Reflow").
-
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using Filee.Core.Conversion;
-using Filee.Engines.Infrastructure;
-
-namespace Filee.Engines.Office;
-
-/// <summary>Converts documents by remote-controlling Microsoft Word through COM.</summary>
-public sealed class WordComConverter : IConverter
-{
- private const string ProgId = "Word.Application";
-
- // WdSaveFormat values (https://learn.microsoft.com/office/vba/api/word.wdsaveformat)
- private const int WdFormatDocument97 = 0;
- private const int WdFormatRtf = 6;
- private const int WdFormatEncodedText = 7;
- private const int WdFormatFilteredHtml = 10;
- private const int WdFormatDocumentDefault = 16;
- private const int WdFormatPdf = 17;
- private const int WdFormatOpenDocumentText = 23;
- private const int Utf8CodePage = 65001;
-
- private static readonly string[] Sources = ["docx", "doc", "rtf", "odt", "txt", "html"];
- private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(3);
-
- public string Id => "word";
- public string DisplayName => "Microsoft Word";
-
- /// <summary>One Word instance at a time keeps memory use and COM trouble low.</summary>
- public int MaxParallelism => 1;
-
- public IReadOnlyList<ConversionEdge> Edges { get; } =
- [
- .. from s in Sources
- from t in new[] { "pdf", "docx", "doc", "rtf", "odt", "txt", "html" }
- where s != t
- select new ConversionEdge(s, t),
- new("pdf", "docx", 20), // PDF reflow: works, but layout fidelity varies
- ];
-
- public EngineStatus GetStatus()
- {
- if (!OperatingSystem.IsWindows())
- return EngineStatus.Unavailable("engine.reason.windows_only");
- return Type.GetTypeFromProgID(ProgId) is null
- ? EngineStatus.Unavailable("engine.reason.not_installed")
- : EngineStatus.Available();
- }
-
- public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
- {
- if (!OperatingSystem.IsWindows())
- throw new PlatformNotSupportedException();
-
- var target = step.Output.Allocate(step.To);
- if (target is null)
- return [];
-
- progress?.Report(0.1);
-#pragma warning disable CA1416 // guarded by the OperatingSystem.IsWindows() check above; the analyzer does not see into lambdas
- using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(4)))
- await new AutomationProcessGuard("WINWORD").RunAsync(() => Convert(step.InputPath, target, step.To), Timeout, cancellationToken);
-#pragma warning restore CA1416
- progress?.Report(1);
- return [target];
- }
-
- [SupportedOSPlatform("windows")]
- private static bool Convert(string input, string output, string to)
- {
- var type = Type.GetTypeFromProgID(ProgId) ?? throw new InvalidOperationException("Word is not installed.");
- dynamic? word = null;
- dynamic? document = null;
- try
- {
- word = Activator.CreateInstance(type)!;
- word.Visible = false;
- word.DisplayAlerts = 0; // wdAlertsNone
- document = word.Documents.Open(input, ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, Visible: false);
-
- if (to == "pdf")
- {
- document.ExportAsFixedFormat(output, WdFormatPdf);
- }
- else
- {
- var format = to switch
- {
- "docx" => WdFormatDocumentDefault,
- "doc" => WdFormatDocument97,
- "rtf" => WdFormatRtf,
- "odt" => WdFormatOpenDocumentText,
- "html" => WdFormatFilteredHtml,
- "txt" => WdFormatEncodedText,
- _ => throw new NotSupportedException(to),
- };
- if (to == "txt")
- document.SaveAs2(output, format, Encoding: Utf8CodePage);
- else
- document.SaveAs2(output, format);
- }
- return true;
- }
- finally
- {
- try { document?.Close(false); } catch (COMException) { }
- try { word?.Quit(false); } catch (COMException) { }
- if (document is not null) Marshal.FinalReleaseComObject(document);
- if (word is not null) Marshal.FinalReleaseComObject(word);
- }
- }
-}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 177028ac..6810f317 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -66,9 +66,9 @@ public class RenderTests
window.Show();
Pump();
- // Everything not installed is offered, pre-selected.
- Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.True(p.Selected));
- Assert.Equal(vm.Packages.Any(p => p.CanInstall), vm.InstallCommand.CanExecute(null));
+ // Everything not installed is offered; all but the large LibreOffice pre-selected.
+ Assert.All(vm.Packages.Where(p => !p.IsInstalled), p => Assert.Equal(p.Package.Id != "libreoffice", p.Selected));
+ Assert.Equal(vm.Packages.Any(p => p.Selected && p.CanInstall), vm.InstallCommand.CanExecute(null));
Save(window, $"engine-setup-{language}.png");
window.Close();
}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index d428c4d8..742bece3 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -1,4 +1,5 @@
using Filee.Core.Presets;
+using Filee.Core.Profiles;
using Filee.Core.Settings;
namespace Filee.Core.Tests;
@@ -39,7 +40,7 @@ public class UserDataStoreTests
var store = new UserDataStore(dir.Path);
store.Load();
- Assert.Equal(["magick", "word", "markdown", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(["magick", "markdown", "spreadsheet", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);
Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
}
@@ -72,6 +73,48 @@ public class UserDataStoreTests
Assert.Equal(AppSettings.CurrentSchemaVersion, next.Settings.SchemaVersion);
}
+ [Fact]
+ public void Version_4_libraries_get_spreadsheet_and_presentation_profiles()
+ {
+ using var dir = new TempDir();
+ var old = new UserDataStore(dir.Path);
+ old.Load();
+ // As written by 1.0.1: one documents donut for Word, Excel and PowerPoint files, Word-only PDF targets.
+ old.Profiles.RemoveAll(p => p.Id is "spreadsheets" or "presentations");
+ old.Profiles.Single(p => p.Id == "office").Extensions.AddRange(["xlsx", "xls", "ods", "csv", "pptx", "ppt", "odp"]);
+ old.Profiles.Single(p => p.Id == "pdf").PresetIds.AddRange(["to-docx", "to-hwpx"]);
+ old.Presets.RemoveAll(p => p.Id is "to-xlsx" or "to-csv");
+ old.Settings.SchemaVersion = 4;
+ old.Settings.EnginePriority = ["magick", "word", "markdown", "hwpx-writer", "pandoc", "libreoffice"];
+ old.SaveSettings();
+ old.SaveLibrary();
+
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+
+ Assert.Equal(["magick", "markdown", "spreadsheet", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ var ids = store.Profiles.Select(p => p.Id).ToList();
+ Assert.Equal(ids.IndexOf("office") + 1, ids.IndexOf("spreadsheets"));
+ Assert.Equal(ids.IndexOf("office") + 2, ids.IndexOf("presentations"));
+ Assert.DoesNotContain("xlsx", store.Profiles.Single(p => p.Id == "office").Extensions);
+ Assert.Contains("to-csv", store.Profiles.Single(p => p.Id == "spreadsheets").PresetIds);
+ Assert.NotNull(store.FindPreset("to-xlsx"));
+ Assert.DoesNotContain("to-docx", store.Profiles.Single(p => p.Id == "pdf").PresetIds);
+ }
+
+ [Fact]
+ public void Spreadsheet_profile_is_not_added_when_a_user_profile_takes_spreadsheets()
+ {
+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id is not ("spreadsheets" or "presentations")).ToList();
+ profiles.Insert(0, new ToolbarProfile { Id = "mine", Name = "Mine", Extensions = ["xlsx"] });
+
+ SettingsMigrations.ApplyToLibrary(4, BuiltInData.CreatePresets(), profiles);
+
+ Assert.DoesNotContain(profiles, p => p.Id == "spreadsheets");
+ Assert.Contains(profiles, p => p.Id == "presentations");
+ Assert.Equal(["xlsx"], profiles[0].Extensions);
+ }
+
[Fact]
public void Text_profile_is_not_added_when_a_profile_already_takes_markdown()
{
diff --git a/tests/Filee.Engines.Tests/DocumentEngineTests.cs b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
index fd9f4aea..ba730b34 100644
--- a/tests/Filee.Engines.Tests/DocumentEngineTests.cs
+++ b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
@@ -1,4 +1,4 @@
-// Tests for engines that depend on external software (LibreOffice, rhwp, Word).
+// Tests for engines that are downloaded or bundled separately (LibreOffice, rhwp).
// They skip automatically when the engine is not available, so CI stays green without them.
using Filee.Core.Conversion;
@@ -9,11 +9,11 @@ namespace Filee.Engines.Tests;
public class DocumentEngineTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
- /// <summary>The engine with this id; skips the test when it is excluded (Office automation is opt-in).</summary>
+ /// <summary>The engine with this id; skips the test when it is not registered.</summary>
private IConverter Engine(string id)
{
var engine = fx.Converters.SingleOrDefault(c => c.Id == id);
- Assert.SkipUnless(engine is not null, $"{id} excluded from tests (see EngineFixture)");
+ Assert.SkipUnless(engine is not null, $"{id} not registered");
return engine!;
}
diff --git a/tests/Filee.Engines.Tests/EngineFixture.cs b/tests/Filee.Engines.Tests/EngineFixture.cs
index 516394a1..9d1242f3 100644
--- a/tests/Filee.Engines.Tests/EngineFixture.cs
+++ b/tests/Filee.Engines.Tests/EngineFixture.cs
@@ -13,11 +13,8 @@ public sealed class EngineFixture : IDisposable
public EngineFixture()
{
Directory.CreateDirectory(Root);
- var env = new EngineEnvironment(_ => null, Path.Combine(Root, "data"));
- // Word automation starts real Word windows: opt-in only.
- Converters = EngineRegistry.CreateAll(env)
- .Where(c => c.Id != "word" || Environment.GetEnvironmentVariable("FILEE_TEST_WORD") == "1")
- .ToList();
+ var env = new EngineEnvironment(Path.Combine(Root, "data"));
+ Converters = EngineRegistry.CreateAll(env);
Catalog = new ConverterCatalog(Converters) { Priority = new AppSettings().EnginePriority };
}
diff --git a/tests/Filee.Engines.Tests/HwpxWriterTests.cs b/tests/Filee.Engines.Tests/HwpxWriterTests.cs
index d53c41e2..28a10fef 100644
--- a/tests/Filee.Engines.Tests/HwpxWriterTests.cs
+++ b/tests/Filee.Engines.Tests/HwpxWriterTests.cs
@@ -51,7 +51,7 @@ public class HwpxWriterTests(EngineFixture fx) : IClassFixture<EngineFixture>
""";
private void SkipUnlessPandoc() =>
- Assert.SkipUnless(PandocConverter.Locate(new Infrastructure.EngineEnvironment(_ => null, fx.Root)) is not null,
+ Assert.SkipUnless(PandocConverter.Locate() is not null,
"Pandoc not found (pwsh build/fetch-engines.ps1 -Only pandoc)");
private async Task<string> ConvertAsync(string input, string target = "hwpx")
diff --git a/tests/Filee.Engines.Tests/MarkdownTests.cs b/tests/Filee.Engines.Tests/MarkdownTests.cs
index 33ee3d10..8f7d52f5 100644
--- a/tests/Filee.Engines.Tests/MarkdownTests.cs
+++ b/tests/Filee.Engines.Tests/MarkdownTests.cs
@@ -31,8 +31,8 @@ public class MarkdownTests(EngineFixture fx) : IClassFixture<EngineFixture>
- [ ] 남은 일
""";
- /// <summary>Only engines that ship with the app (or run in-process): no Pandoc, LibreOffice or Word.</summary>
- private static readonly string[] OptionalEngines = ["pandoc", "libreoffice", "word"];
+ /// <summary>Only engines that ship with the app (or run in-process): no Pandoc or LibreOffice.</summary>
+ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice"];
private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>
new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }
@@ -169,7 +169,7 @@ public class MarkdownTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task LibreOffice_warm_up_prepares_every_profile_once()
{
- var env = new EngineEnvironment(_ => null, Path.Combine(fx.NewFolder(), "data"));
+ var env = new EngineEnvironment(Path.Combine(fx.NewFolder(), "data"));
var libreOffice = new LibreOfficeConverter(env);
Assert.SkipUnless(libreOffice.GetStatus().IsAvailable, "LibreOffice not found");
diff --git a/tests/Filee.Engines.Tests/OfficeBuilders.cs b/tests/Filee.Engines.Tests/OfficeBuilders.cs
new file mode 100644
index 00000000..b23376d5
--- /dev/null
+++ b/tests/Filee.Engines.Tests/OfficeBuilders.cs
@@ -0,0 +1,287 @@
+// Builds small .xlsx and .pptx files for tests, so the built-in spreadsheet and presentation readers can be tested
+// without sample documents (see DocxBuilder for .docx).
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Security;
+using System.Text;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>Writes the parts of an OPC package (the zip format of DOCX, XLSX and PPTX).</summary>
+internal static class OpcWriter
+{
+ public const string Declaration = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
+
+ public static void Save(string path, IReadOnlyDictionary<string, string> parts, IReadOnlyDictionary<string, byte[]> media)
+ {
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ foreach (var (name, xml) in parts)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name).Open(), new UTF8Encoding(false));
+ writer.Write(Declaration + xml);
+ }
+ foreach (var (name, bytes) in media)
+ {
+ using var stream = zip.CreateEntry(name).Open();
+ stream.Write(bytes);
+ }
+ }
+
+ public static string Relationships(IEnumerable<(string Id, string Type, string Target)> relationships) =>
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
+ string.Concat(relationships.Select(r => $"<Relationship Id=\"{r.Id}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/{r.Type}\" Target=\"{r.Target}\"/>")) +
+ "</Relationships>";
+
+ public static string ContentTypes(IEnumerable<(string Part, string Type)> overrides) =>
+ "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">" +
+ "<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/>" +
+ "<Default Extension=\"png\" ContentType=\"image/png\"/>" +
+ string.Concat(overrides.Select(o => $"<Override PartName=\"/{o.Part}\" ContentType=\"application/vnd.openxmlformats-officedocument.{o.Type}+xml\"/>")) +
+ "</Types>";
+
+ public static string Escape(string text) => SecurityElement.Escape(text);
+}
+
+/// <summary>A workbook with shared strings, a fixed style sheet and any number of sheets.</summary>
+internal sealed class XlsxBuilder
+{
+ private const string Namespaces = "xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"";
+
+ // Styles (cellXfs index):
+ public const int Plain = 0;
+ public const int Header = 1; // bold white text on #1F4E79, thin borders, centered
+ public const int Won = 2; // #,##0"원"
+ public const int Date = 3; // built-in 14
+ public const int Percent = 4; // 0.0%
+ public const int Total = 5; // bold red, thin top border, #,##0"원"
+
+ private const string StyleSheet =
+ "<numFmts count=\"2\"><numFmt numFmtId=\"164\" formatCode=\"#,##0&quot;원&quot;\"/><numFmt numFmtId=\"165\" formatCode=\"0.0%\"/></numFmts>" +
+ "<fonts count=\"3\"><font><sz val=\"11\"/><name val=\"맑은 고딕\"/></font><font><b/><sz val=\"11\"/><color rgb=\"FFFFFFFF\"/><name val=\"맑은 고딕\"/></font>" +
+ "<font><b/><sz val=\"11\"/><color rgb=\"FFC00000\"/><name val=\"맑은 고딕\"/></font></fonts>" +
+ "<fills count=\"3\"><fill><patternFill patternType=\"none\"/></fill><fill><patternFill patternType=\"gray125\"/></fill>" +
+ "<fill><patternFill patternType=\"solid\"><fgColor rgb=\"FF1F4E79\"/><bgColor indexed=\"64\"/></patternFill></fill></fills>" +
+ "<borders count=\"3\"><border><left/><right/><top/><bottom/><diagonal/></border>" +
+ "<border><left style=\"thin\"><color indexed=\"64\"/></left><right style=\"thin\"><color indexed=\"64\"/></right><top style=\"thin\"><color indexed=\"64\"/></top><bottom style=\"thin\"><color indexed=\"64\"/></bottom><diagonal/></border>" +
+ "<border><left/><right/><top style=\"thin\"><color auto=\"1\"/></top><bottom/><diagonal/></border></borders>" +
+ "<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>" +
+ "<cellXfs count=\"6\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\"/>" +
+ "<xf numFmtId=\"0\" fontId=\"1\" fillId=\"2\" borderId=\"1\" xfId=\"0\" applyFont=\"1\" applyFill=\"1\" applyBorder=\"1\" applyAlignment=\"1\"><alignment horizontal=\"center\" vertical=\"center\"/></xf>" +
+ "<xf numFmtId=\"164\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyNumberFormat=\"1\"/>" +
+ "<xf numFmtId=\"14\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyNumberFormat=\"1\"/>" +
+ "<xf numFmtId=\"165\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyNumberFormat=\"1\"/>" +
+ "<xf numFmtId=\"164\" fontId=\"2\" fillId=\"0\" borderId=\"2\" xfId=\"0\" applyNumberFormat=\"1\" applyFont=\"1\" applyBorder=\"1\"/></cellXfs>";
+
+ private readonly List<(string Name, string Xml, bool Hidden)> _sheets = [];
+ private readonly List<string> _strings = [];
+
+ /// <summary>A shared-string cell.</summary>
+ public string Text(string reference, string text, int style = Plain)
+ {
+ var index = _strings.IndexOf(text);
+ if (index < 0)
+ {
+ index = _strings.Count;
+ _strings.Add(text);
+ }
+ return $"<c r=\"{reference}\" s=\"{style}\" t=\"s\"><v>{index}</v></c>";
+ }
+
+ public static string Number(string reference, double value, int style = Plain) =>
+ $"<c r=\"{reference}\" s=\"{style}\"><v>{value.ToString(CultureInfo.InvariantCulture)}</v></c>";
+
+ /// <summary>A row element; <paramref name="cells"/> from <see cref="Text"/> and <see cref="Number"/>.</summary>
+ public static string Row(int number, params string[] cells) => $"<row r=\"{number}\">{string.Concat(cells)}</row>";
+
+ /// <param name="rows">Rows of sheetData.</param>
+ /// <param name="before">Elements before sheetData (sheetViews, cols).</param>
+ /// <param name="after">Elements after sheetData (mergeCells).</param>
+ public XlsxBuilder Sheet(string name, string rows, string before = "", string after = "", bool hidden = false)
+ {
+ _sheets.Add((name, $"<worksheet {Namespaces}>{before}<sheetData>{rows}</sheetData>{after}</worksheet>", hidden));
+ return this;
+ }
+
+ public string Save(string path)
+ {
+ var parts = new Dictionary<string, string>
+ {
+ ["_rels/.rels"] = OpcWriter.Relationships([("rId1", "officeDocument", "xl/workbook.xml")]),
+ ["xl/workbook.xml"] = $"<workbook {Namespaces}><sheets>" +
+ string.Concat(_sheets.Select((s, i) => $"<sheet name=\"{OpcWriter.Escape(s.Name)}\" sheetId=\"{i + 1}\"{(s.Hidden ? " state=\"hidden\"" : "")} r:id=\"rId{i + 1}\"/>")) +
+ "</sheets></workbook>",
+ ["xl/_rels/workbook.xml.rels"] = OpcWriter.Relationships(
+ _sheets.Select((_, i) => ($"rId{i + 1}", "worksheet", $"worksheets/sheet{i + 1}.xml"))
+ .Append(("rIdS", "sharedStrings", "sharedStrings.xml"))
+ .Append(("rIdT", "styles", "styles.xml"))),
+ ["xl/sharedStrings.xml"] = $"<sst {Namespaces} count=\"{_strings.Count}\" uniqueCount=\"{_strings.Count}\">" +
+ string.Concat(_strings.Select(s => $"<si><t xml:space=\"preserve\">{OpcWriter.Escape(s)}</t></si>")) + "</sst>",
+ ["xl/styles.xml"] = $"<styleSheet {Namespaces}>{StyleSheet}</styleSheet>",
+ };
+ for (var i = 0; i < _sheets.Count; i++)
+ parts[$"xl/worksheets/sheet{i + 1}.xml"] = _sheets[i].Xml;
+ parts["[Content_Types].xml"] = OpcWriter.ContentTypes(
+ _sheets.Select((_, i) => ($"xl/worksheets/sheet{i + 1}.xml", "spreadsheetml.worksheet"))
+ .Append(("xl/workbook.xml", "spreadsheetml.sheet.main"))
+ .Append(("xl/sharedStrings.xml", "spreadsheetml.sharedStrings"))
+ .Append(("xl/styles.xml", "spreadsheetml.styles")));
+ OpcWriter.Save(path, parts, new Dictionary<string, byte[]>());
+ return path;
+ }
+}
+
+/// <summary>
+/// A 16:9 presentation with one master (title / body placeholders, centred title style, bullet body style and a
+/// decorative bar), one layout and a theme; slides are added as p:spTree content.
+/// </summary>
+internal sealed class PptxBuilder
+{
+ public const string Namespaces =
+ "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " +
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " +
+ "xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\"";
+
+ public const long Width = 12192000;
+ public const long Height = 6858000;
+
+ /// <summary>Colour of the master's decorative bar (theme accent2).</summary>
+ public const string BarColor = "#ED7D31";
+
+ private const string TreeStart = "<p:nvGrpSpPr><p:cNvPr id=\"1\" name=\"\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/>";
+
+ private const string Master =
+ "<p:cSld><p:spTree>" + TreeStart +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"2\" name=\"Title\"/><p:cNvSpPr/><p:nvPr><p:ph type=\"title\"/></p:nvPr></p:nvSpPr>" +
+ "<p:spPr><a:xfrm><a:off x=\"838200\" y=\"365125\"/><a:ext cx=\"10515600\" cy=\"1325563\"/></a:xfrm></p:spPr><p:txBody><a:bodyPr anchor=\"ctr\"/><a:lstStyle/><a:p/></p:txBody></p:sp>" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"3\" name=\"Body\"/><p:cNvSpPr/><p:nvPr><p:ph type=\"body\" idx=\"1\"/></p:nvPr></p:nvSpPr>" +
+ "<p:spPr><a:xfrm><a:off x=\"838200\" y=\"1825625\"/><a:ext cx=\"10515600\" cy=\"4351338\"/></a:xfrm></p:spPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"4\" name=\"Bar\"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>" +
+ "<p:spPr><a:xfrm><a:off x=\"0\" y=\"6705600\"/><a:ext cx=\"12192000\" cy=\"152400\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom>" +
+ "<a:solidFill><a:schemeClr val=\"accent2\"/></a:solidFill><a:ln><a:noFill/></a:ln></p:spPr></p:sp>" +
+ "</p:spTree></p:cSld>" +
+ "<p:clrMap bg1=\"lt1\" tx1=\"dk1\" bg2=\"lt2\" tx2=\"dk2\" accent1=\"accent1\" accent2=\"accent2\" accent3=\"accent3\" accent4=\"accent4\" accent5=\"accent5\" accent6=\"accent6\" hlink=\"hlink\" folHlink=\"folHlink\"/>" +
+ "<p:sldLayoutIdLst><p:sldLayoutId id=\"2147483649\" r:id=\"rId1\"/></p:sldLayoutIdLst>" +
+ "<p:txStyles>" +
+ "<p:titleStyle><a:lvl1pPr algn=\"ctr\"><a:buNone/><a:defRPr sz=\"4400\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill><a:latin typeface=\"+mj-lt\"/><a:ea typeface=\"+mj-ea\"/></a:defRPr></a:lvl1pPr></p:titleStyle>" +
+ "<p:bodyStyle><a:lvl1pPr marL=\"228600\" indent=\"-228600\"><a:buChar char=\"•\"/><a:defRPr sz=\"2800\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill></a:defRPr></a:lvl1pPr>" +
+ "<a:lvl2pPr marL=\"685800\" indent=\"-228600\"><a:buChar char=\"–\"/><a:defRPr sz=\"2400\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill></a:defRPr></a:lvl2pPr></p:bodyStyle>" +
+ "<p:otherStyle><a:lvl1pPr><a:defRPr sz=\"1800\"><a:solidFill><a:schemeClr val=\"tx1\"/></a:solidFill></a:defRPr></a:lvl1pPr></p:otherStyle>" +
+ "</p:txStyles>";
+
+ private const string Layout =
+ "<p:cSld name=\"Title and Content\"><p:spTree>" + TreeStart +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"2\" name=\"Title\"/><p:cNvSpPr/><p:nvPr><p:ph type=\"title\"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>" +
+ "<p:sp><p:nvSpPr><p:cNvPr id=\"3\" name=\"Content\"/><p:cNvSpPr/><p:nvPr><p:ph idx=\"1\"/></p:nvPr></p:nvSpPr><p:spPr/><p:txBody><a:bodyPr/><a:lstStyle/><a:p/></p:txBody></p:sp>" +
+ "</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>";
+
+ private const string Theme =
+ "<a:themeElements><a:clrScheme name=\"Office\">" +
+ "<a:dk1><a:sysClr val=\"windowText\" lastClr=\"000000\"/></a:dk1><a:lt1><a:sysClr val=\"window\" lastClr=\"FFFFFF\"/></a:lt1>" +
+ "<a:dk2><a:srgbClr val=\"44546A\"/></a:dk2><a:lt2><a:srgbClr val=\"E7E6E6\"/></a:lt2>" +
+ "<a:accent1><a:srgbClr val=\"4472C4\"/></a:accent1><a:accent2><a:srgbClr val=\"ED7D31\"/></a:accent2><a:accent3><a:srgbClr val=\"A5A5A5\"/></a:accent3>" +
+ "<a:accent4><a:srgbClr val=\"FFC000\"/></a:accent4><a:accent5><a:srgbClr val=\"5B9BD5\"/></a:accent5><a:accent6><a:srgbClr val=\"70AD47\"/></a:accent6>" +
+ "<a:hlink><a:srgbClr val=\"0563C1\"/></a:hlink><a:folHlink><a:srgbClr val=\"954F72\"/></a:folHlink></a:clrScheme>" +
+ "<a:fontScheme name=\"Office\"><a:majorFont><a:latin typeface=\"Calibri Light\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/><a:font script=\"Hang\" typeface=\"맑은 고딕\"/></a:majorFont>" +
+ "<a:minorFont><a:latin typeface=\"Calibri\"/><a:ea typeface=\"\"/><a:cs typeface=\"\"/><a:font script=\"Hang\" typeface=\"맑은 고딕\"/></a:minorFont></a:fontScheme>" +
+ "<a:fmtScheme name=\"Office\"><a:fillStyleLst/><a:lnStyleLst/><a:effectStyleLst/><a:bgFillStyleLst/></a:fmtScheme></a:themeElements>";
+
+ private readonly List<string> _slides = [];
+ private readonly List<byte[]> _images = [];
+ private int _nextId = 10;
+
+ /// <summary>Adds a PNG; every slide can refer to it by the returned relationship id.</summary>
+ public string Image(byte[] png)
+ {
+ _images.Add(png);
+ return $"rIdImg{_images.Count}";
+ }
+
+ /// <summary>Adds a slide from p:spTree children; <paramref name="background"/> is an optional hex colour.</summary>
+ public PptxBuilder Slide(string shapes, string? background = null)
+ {
+ var bg = background is null ? "" : $"<p:bg><p:bgPr><a:solidFill><a:srgbClr val=\"{background.TrimStart('#')}\"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>";
+ _slides.Add($"<p:sld {Namespaces}><p:cSld>{bg}<p:spTree>{TreeStart}{shapes}</p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>");
+ return this;
+ }
+
+ /// <summary>The title placeholder (position and style come from the layout and master).</summary>
+ public string Title(string text) =>
+ $"<p:sp><p:nvSpPr><p:cNvPr id=\"{_nextId++}\" name=\"Title\"/><p:cNvSpPr/><p:nvPr><p:ph type=\"title\"/></p:nvPr></p:nvSpPr><p:spPr/>" +
+ $"<p:txBody><a:bodyPr/><a:lstStyle/>{Paragraph(text)}</p:txBody></p:sp>";
+
+ /// <summary>The content placeholder with one paragraph per item (level 0 or 1).</summary>
+ public string Body(params (string Text, int Level)[] items) =>
+ $"<p:sp><p:nvSpPr><p:cNvPr id=\"{_nextId++}\" name=\"Content\"/><p:cNvSpPr/><p:nvPr><p:ph idx=\"1\"/></p:nvPr></p:nvSpPr><p:spPr/>" +
+ $"<p:txBody><a:bodyPr/><a:lstStyle/>{string.Concat(items.Select(i => Paragraph(i.Text, i.Level > 0 ? $"<a:pPr lvl=\"{i.Level}\"/>" : "")))}</p:txBody></p:sp>";
+
+ /// <summary>An auto shape (rect, roundRect, ellipse, ...) with a solid fill and optional centred white text.</summary>
+ public string Shape(string geometry, long x, long y, long cx, long cy, string fill, string? text = null) =>
+ $"<p:sp><p:nvSpPr><p:cNvPr id=\"{_nextId++}\" name=\"Shape\"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>" +
+ $"<p:spPr>{Xfrm(x, y, cx, cy)}<a:prstGeom prst=\"{geometry}\"><a:avLst/></a:prstGeom><a:solidFill><a:srgbClr val=\"{fill.TrimStart('#')}\"/></a:solidFill><a:ln><a:noFill/></a:ln></p:spPr>" +
+ (text is null ? "" : $"<p:txBody><a:bodyPr anchor=\"ctr\"/><a:lstStyle/>{Paragraph(text, "<a:pPr algn=\"ctr\"/>", "<a:rPr lang=\"ko-KR\" sz=\"2000\" b=\"1\"><a:solidFill><a:srgbClr val=\"FFFFFF\"/></a:solidFill></a:rPr>")}</p:txBody>") +
+ "</p:sp>";
+
+ public string Picture(string relationshipId, long x, long y, long cx, long cy) =>
+ $"<p:pic><p:nvPicPr><p:cNvPr id=\"{_nextId++}\" name=\"Picture\"/><p:cNvPicPr/><p:nvPr/></p:nvPicPr>" +
+ $"<p:blipFill><a:blip r:embed=\"{relationshipId}\"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>" +
+ $"<p:spPr>{Xfrm(x, y, cx, cy)}<a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></p:spPr></p:pic>";
+
+ /// <summary>A table with PowerPoint's default style: header row and banded rows.</summary>
+ public string Table(long x, long y, long columnWidth, long rowHeight, params string[][] rows) =>
+ $"<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id=\"{_nextId++}\" name=\"Table\"/><p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>" +
+ $"<p:xfrm><a:off x=\"{x}\" y=\"{y}\"/><a:ext cx=\"{columnWidth * rows[0].Length}\" cy=\"{rowHeight * rows.Length}\"/></p:xfrm>" +
+ "<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/table\"><a:tbl>" +
+ "<a:tblPr firstRow=\"1\" bandRow=\"1\"><a:tableStyleId>{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}</a:tableStyleId></a:tblPr>" +
+ $"<a:tblGrid>{string.Concat(rows[0].Select(_ => $"<a:gridCol w=\"{columnWidth}\"/>"))}</a:tblGrid>" +
+ string.Concat(rows.Select(row => $"<a:tr h=\"{rowHeight}\">" +
+ string.Concat(row.Select(cell => $"<a:tc><a:txBody><a:bodyPr/><a:lstStyle/>{Paragraph(cell)}</a:txBody><a:tcPr/></a:tc>")) + "</a:tr>")) +
+ "</a:tbl></a:graphicData></a:graphic></p:graphicFrame>";
+
+ /// <summary>A group whose child coordinates are scaled by <paramref name="scale"/> into the slide.</summary>
+ public string Group(long x, long y, long cx, long cy, double scale, string children) =>
+ $"<p:grpSp><p:nvGrpSpPr><p:cNvPr id=\"{_nextId++}\" name=\"Group\"/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>" +
+ $"<p:grpSpPr><a:xfrm><a:off x=\"{x}\" y=\"{y}\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/><a:chOff x=\"0\" y=\"0\"/><a:chExt cx=\"{(long)(cx / scale)}\" cy=\"{(long)(cy / scale)}\"/></a:xfrm></p:grpSpPr>" +
+ children + "</p:grpSp>";
+
+ private static string Xfrm(long x, long y, long cx, long cy) => $"<a:xfrm><a:off x=\"{x}\" y=\"{y}\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm>";
+
+ private static string Paragraph(string text, string pPr = "", string rPr = "<a:rPr lang=\"ko-KR\"/>") =>
+ $"<a:p>{pPr}<a:r>{rPr}<a:t>{OpcWriter.Escape(text)}</a:t></a:r></a:p>";
+
+ public string Save(string path)
+ {
+ var presentationRels = new List<(string, string, string)> { ("rId1", "slideMaster", "slideMasters/slideMaster1.xml"), ("rId2", "theme", "theme/theme1.xml") };
+ presentationRels.AddRange(_slides.Select((_, i) => ($"rId{i + 10}", "slide", $"slides/slide{i + 1}.xml")));
+ var slideRels = new List<(string, string, string)> { ("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml") };
+ slideRels.AddRange(_images.Select((_, i) => ($"rIdImg{i + 1}", "image", $"../media/image{i + 1}.png")));
+
+ var parts = new Dictionary<string, string>
+ {
+ ["_rels/.rels"] = OpcWriter.Relationships([("rId1", "officeDocument", "ppt/presentation.xml")]),
+ ["ppt/presentation.xml"] = $"<p:presentation {Namespaces}>" +
+ "<p:sldMasterIdLst><p:sldMasterId id=\"2147483648\" r:id=\"rId1\"/></p:sldMasterIdLst>" +
+ $"<p:sldIdLst>{string.Concat(_slides.Select((_, i) => $"<p:sldId id=\"{256 + i}\" r:id=\"rId{i + 10}\"/>"))}</p:sldIdLst>" +
+ $"<p:sldSz cx=\"{Width}\" cy=\"{Height}\"/><p:notesSz cx=\"6858000\" cy=\"9144000\"/></p:presentation>",
+ ["ppt/_rels/presentation.xml.rels"] = OpcWriter.Relationships(presentationRels),
+ ["ppt/slideMasters/slideMaster1.xml"] = $"<p:sldMaster {Namespaces}>{Master}</p:sldMaster>",
+ ["ppt/slideMasters/_rels/slideMaster1.xml.rels"] = OpcWriter.Relationships([("rId1", "slideLayout", "../slideLayouts/slideLayout1.xml"), ("rId2", "theme", "../theme/theme1.xml")]),
+ ["ppt/slideLayouts/slideLayout1.xml"] = $"<p:sldLayout {Namespaces}>{Layout}</p:sldLayout>",
+ ["ppt/slideLayouts/_rels/slideLayout1.xml.rels"] = OpcWriter.Relationships([("rId1", "slideMaster", "../slideMasters/slideMaster1.xml")]),
+ ["ppt/theme/theme1.xml"] = $"<a:theme {Namespaces} name=\"Office\">{Theme}</a:theme>",
+ };
+ for (var i = 0; i < _slides.Count; i++)
+ {
+ parts[$"ppt/slides/slide{i + 1}.xml"] = _slides[i];
+ parts[$"ppt/slides/_rels/slide{i + 1}.xml.rels"] = OpcWriter.Relationships(slideRels);
+ }
+ parts["[Content_Types].xml"] = OpcWriter.ContentTypes(
+ _slides.Select((_, i) => ($"ppt/slides/slide{i + 1}.xml", "presentationml.slide"))
+ .Append(("ppt/presentation.xml", "presentationml.presentation.main"))
+ .Append(("ppt/slideMasters/slideMaster1.xml", "presentationml.slideMaster"))
+ .Append(("ppt/slideLayouts/slideLayout1.xml", "presentationml.slideLayout"))
+ .Append(("ppt/theme/theme1.xml", "theme")));
+ OpcWriter.Save(path, parts, _images.Select((png, i) => ($"ppt/media/image{i + 1}.png", png)).ToDictionary(p => p.Item1, p => p.png));
+ return path;
+ }
+}
diff --git a/tests/Filee.Engines.Tests/OfficeTests.cs b/tests/Filee.Engines.Tests/OfficeTests.cs
new file mode 100644
index 00000000..378e53db
--- /dev/null
+++ b/tests/Filee.Engines.Tests/OfficeTests.cs
@@ -0,0 +1,292 @@
+// Spreadsheets and presentations without Excel, PowerPoint or LibreOffice: XLSX / CSV are read in-process (values
+// displayed like Excel shows them), converted to each other, and XLSX / CSV / PPTX become HWPX (and through rhwp,
+// PDF and images). Test files are generated by XlsxBuilder and PptxBuilder.
+
+using System.Text;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Office.Sheets;
+using ImageMagick;
+using static Filee.Engines.Tests.HwpxAssert;
+using static Filee.Engines.Tests.XlsxBuilder;
+
+namespace Filee.Engines.Tests;
+
+public class OfficeTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ /// <summary>Only engines that ship with the app (or run in-process): no Pandoc or LibreOffice.</summary>
+ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice"];
+
+ private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>
+ new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }
+ .CreatePlanner(assumeInstalled);
+
+ private async Task<IReadOnlyList<string>> ConvertAsync(string input, string target)
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return [.. job.Outputs];
+ }
+
+ /// <summary>
+ /// "매출": merged title, frozen header rows, number / date / percent formats, a formula, a boolean and an inline
+ /// string; "메모": a line break and a General number; "넓은 표": too wide for a portrait page; plus a hidden sheet.
+ /// </summary>
+ private string SalesWorkbook(string folder)
+ {
+ var xlsx = new XlsxBuilder();
+ var date = new DateTime(2026, 10, 1).ToOADate();
+ xlsx.Sheet("매출",
+ Row(1, xlsx.Text("A1", "지점별 매출", Header)) +
+ Row(2, xlsx.Text("A2", "지점", Header), xlsx.Text("B2", "매출", Header), xlsx.Text("C2", "일자", Header), xlsx.Text("D2", "성장률", Header)) +
+ Row(3, xlsx.Text("A3", "서울 강남"), Number("B3", 1350000, Won), Number("C3", date, Date), Number("D3", 0.128, Percent)) +
+ Row(4, xlsx.Text("A4", "부산 서면"), Number("B4", 870000, Won), Number("C4", date + 1, Date), Number("D4", 0.09, Percent)) +
+ Row(5, xlsx.Text("A5", "합계"), $"<c r=\"B5\" s=\"{Total}\"><f>SUM(B3:B4)</f><v>2220000</v></c>",
+ "<c r=\"C5\" t=\"b\"><v>1</v></c>", "<c r=\"D5\" t=\"inlineStr\"><is><t>메모, \"따옴표\"</t></is></c>"),
+ before: "<sheetViews><sheetView workbookViewId=\"0\"><pane ySplit=\"2\" topLeftCell=\"A3\" activePane=\"bottomLeft\" state=\"frozen\"/></sheetView></sheetViews>" +
+ "<cols><col min=\"1\" max=\"1\" width=\"14\" customWidth=\"1\"/><col min=\"2\" max=\"4\" width=\"12\" customWidth=\"1\"/></cols>",
+ after: "<mergeCells count=\"1\"><mergeCell ref=\"A1:D1\"/></mergeCells>");
+ xlsx.Sheet("메모", Row(1, xlsx.Text("A1", "첫 줄\n둘째 줄")) + Row(2, Number("A2", 3.5)));
+ xlsx.Sheet("비밀", Row(1, xlsx.Text("A1", "보이면 안 됨")), hidden: true);
+ xlsx.Sheet("넓은 표",
+ Row(1, [.. Enumerable.Range(0, 12).Select(c => xlsx.Text($"{(char)('A' + c)}1", $"항목 {c + 1}"))]),
+ before: "<cols><col min=\"1\" max=\"12\" width=\"12\" customWidth=\"1\"/></cols>");
+ return xlsx.Save(Path.Combine(folder, "매출보고.xlsx"));
+ }
+
+ // ───────────────────────── Spreadsheets ─────────────────────────
+
+ [Fact]
+ public void Xlsx_values_and_styles_are_read_like_excel_shows_them()
+ {
+ var book = XlsxReader.Read(SalesWorkbook(fx.NewFolder()));
+
+ Assert.Equal(["매출", "메모", "넓은 표"], book.Sheets.Select(s => s.Name)); // the hidden sheet is left out
+ var sales = book.Sheets[0];
+ Assert.Equal("1,350,000원", sales.Get(2, 1)!.Text);
+ Assert.True(sales.Get(2, 1)!.IsNumber);
+ Assert.Equal("2026-10-01", sales.Get(2, 2)!.Text);
+ Assert.Equal("12.8%", sales.Get(2, 3)!.Text);
+ Assert.Equal("2,220,000원", sales.Get(4, 1)!.Text); // cached formula result
+ Assert.Equal("TRUE", sales.Get(4, 2)!.Text);
+ Assert.Equal("메모, \"따옴표\"", sales.Get(4, 3)!.Text);
+
+ var header = sales.Get(1, 0)!.Style;
+ Assert.True(header.Bold);
+ Assert.Equal("#FFFFFF", header.Color);
+ Assert.Equal("#1F4E79", header.Fill);
+ Assert.Equal(CellAlign.Center, header.Align);
+ Assert.Equal("thin", header.Bottom.Style);
+ var total = sales.Get(4, 1)!.Style;
+ Assert.Equal("#C00000", total.Color);
+ Assert.True(total.Top.IsVisible);
+
+ Assert.Equal(new CellRange(0, 0, 0, 3), Assert.Single(sales.Merges));
+ Assert.Equal(2, sales.FrozenRows);
+ Assert.Equal(14, sales.ColumnWidth(0));
+ Assert.Equal(12, sales.ColumnWidth(3));
+
+ var memo = book.Sheets[1];
+ Assert.Equal("첫 줄\n둘째 줄", memo.Get(0, 0)!.Text);
+ Assert.Equal("3.5", memo.Get(1, 0)!.Text);
+ }
+
+ [Fact]
+ public async Task Xlsx_to_csv_writes_one_file_per_sheet_for_excel()
+ {
+ var outputs = await ConvertAsync(SalesWorkbook(fx.NewFolder()), "csv");
+
+ Assert.Equal(["매출보고_매출.csv", "매출보고_메모.csv", "매출보고_넓은 표.csv"], outputs.Select(Path.GetFileName));
+ var bytes = await File.ReadAllBytesAsync(outputs[0], TestContext.Current.CancellationToken);
+ Assert.Equal([0xEF, 0xBB, 0xBF], bytes[..3]); // Excel needs the BOM to read UTF-8
+ Assert.Equal(
+ "지점별 매출,,,\r\n" +
+ "지점,매출,일자,성장률\r\n" +
+ "서울 강남,\"1,350,000원\",2026-10-01,12.8%\r\n" +
+ "부산 서면,\"870,000원\",2026-10-02,9.0%\r\n" +
+ "합계,\"2,220,000원\",TRUE,\"메모, \"\"따옴표\"\"\"\r\n",
+ Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3));
+ }
+
+ [Fact]
+ public async Task Csv_to_xlsx_and_back_keeps_every_value()
+ {
+ var dir = fx.NewFolder();
+ const string Csv = "이름,금액,메모\r\n김민지,1200,\"줄\n바꿈\"\r\n\"Lee, J\",3.5,\"\"\"인용\"\"\"\r\n";
+ var csv = Path.Combine(dir, "명단.csv");
+ await File.WriteAllTextAsync(csv, Csv, TestContext.Current.CancellationToken);
+
+ var xlsx = Assert.Single(await ConvertAsync(csv, "xlsx"));
+ var sheet = Assert.Single(XlsxReader.Read(xlsx).Sheets);
+ Assert.Equal("김민지", sheet.Get(1, 0)!.Text);
+ Assert.Equal("1200", sheet.Get(1, 1)!.Text);
+ Assert.True(sheet.Get(1, 1)!.IsNumber); // stored as a number, so Excel can calculate with it
+ Assert.Equal("줄\n바꿈", sheet.Get(1, 2)!.Text);
+ Assert.Equal("Lee, J", sheet.Get(2, 0)!.Text);
+
+ File.Move(xlsx, Path.Combine(dir, "사본.xlsx"));
+ var back = Assert.Single(await ConvertAsync(Path.Combine(dir, "사본.xlsx"), "csv"));
+ Assert.Equal(Csv, (await File.ReadAllTextAsync(back, TestContext.Current.CancellationToken)).TrimStart(''));
+ }
+
+ [Fact]
+ public async Task Csv_from_korean_excel_is_read_as_cp949_with_its_delimiter()
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ var csv = Path.Combine(fx.NewFolder(), "점수.csv");
+ await File.WriteAllBytesAsync(csv, Encoding.GetEncoding(949).GetBytes("이름;점수\r\n홍길동;90\r\n"), TestContext.Current.CancellationToken);
+
+ var sheet = Assert.Single(CsvFormat.Read(csv).Sheets);
+
+ Assert.Equal("홍길동", sheet.Get(1, 0)!.Text);
+ Assert.Equal("90", sheet.Get(1, 1)!.Text);
+ }
+
+ [Fact]
+ public async Task Xlsx_to_hwpx_makes_a_table_per_sheet()
+ {
+ var hwpx = Assert.Single(await ConvertAsync(SalesWorkbook(fx.NewFolder()), "hwpx"));
+
+ ValidPackage(hwpx, expectImages: 0);
+ Assert.Equal(3, (int)Xml(hwpx, "Contents/header.xml").Attribute("secCnt")!);
+ var sales = Xml(hwpx);
+ var table = sales.Descendants(Hp + "tbl").Single();
+ Assert.Equal(("5", "4", "1"), ((string?)table.Attribute("rowCnt"), (string?)table.Attribute("colCnt"), (string?)table.Attribute("repeatHeader")));
+ var title = sales.Descendants(Hp + "tc").First(c => c.Value.Contains("지점별 매출"));
+ Assert.Equal("4", (string?)title.Element(Hp + "cellSpan")!.Attribute("colSpan"));
+ // Frozen rows repeat on every page.
+ Assert.Equal(2, sales.Descendants(Hp + "tr").Count(r => r.Elements(Hp + "tc").All(c => (string?)c.Attribute("header") == "1")));
+ Assert.Contains("2,220,000원", sales.Value);
+ Assert.Contains("faceColor=\"#1F4E79\"", Xml(hwpx, "Contents/header.xml").ToString());
+
+ // Portrait for the narrow sheets, landscape for the wide one.
+ string Orientation(int section) => (string)Xml(hwpx, $"Contents/section{section}.xml").Descendants(Hp + "pagePr").Single().Attribute("landscape")!;
+ Assert.Equal(["WIDELY", "WIDELY", "NARROWLY"], new[] { 0, 1, 2 }.Select(Orientation));
+ Assert.DoesNotContain("보이면 안 됨", string.Concat(new[] { 0, 1, 2 }.Select(i => Xml(hwpx, $"Contents/section{i}.xml").Value)));
+
+ RenderWithRhwp(fx, hwpx, "xlsx-sales");
+ }
+
+ // ───────────────────────── Presentations ─────────────────────────
+
+ private static byte[] Png()
+ {
+ using var image = new MagickImage(MagickColors.MediumPurple, 160, 90);
+ return image.ToByteArray(MagickFormat.Png);
+ }
+
+ [Fact]
+ public async Task Pptx_slides_become_pages_with_their_objects_in_place()
+ {
+ var pptx = new PptxBuilder();
+ var chart = pptx.Image(Png());
+ pptx.Slide(pptx.Title("2026년 사업 보고"));
+ pptx.Slide(
+ pptx.Title("다음 분기 계획") +
+ pptx.Body(("매출 증가", 0), ("지점 확대", 1)) +
+ pptx.Shape("roundRect", 838200, 4400000, 3000000, 1500000, "#7F77DD", "강조") +
+ pptx.Picture(chart, 8000000, 1900000, 3000000, 1687500) +
+ pptx.Table(4000000, 4400000, 1200000, 370840, ["지점", "매출"], ["강남", "16.2억"], ["서면", "8.7억"]) +
+ pptx.Group(6000000, 4000000, 2000000, 1000000, 0.5, pptx.Shape("ellipse", 0, 0, 4000000, 2000000, "#1D9E75", "단계 1")),
+ background: "#1F1E2D");
+ var path = pptx.Save(Path.Combine(fx.NewFolder(), "계획.pptx"));
+
+ var hwpx = Assert.Single(await ConvertAsync(path, "hwpx"));
+
+ ValidPackage(hwpx, expectImages: 1);
+ var section = Xml(hwpx);
+ // The page is the slide (EMU / 127 = HWPUNIT), one page per slide; 한글 stores it as a turned portrait sheet.
+ var pagePr = section.Descendants(Hp + "pagePr").Single();
+ Assert.Equal((54000, 96000, "NARROWLY"), ((int)pagePr.Attribute("width")!, (int)pagePr.Attribute("height")!, (string?)pagePr.Attribute("landscape")));
+ Assert.Single(section.Elements(Hp + "p"), p => (string?)p.Attribute("pageBreak") == "1");
+
+ // Title placeholders take position from the master and centring from its title style.
+ var titleBox = section.Descendants(Hp + "rect").First(r => r.Value.Contains("2026년 사업 보고"));
+ var position = titleBox.Element(Hp + "pos")!;
+ Assert.Equal(("6600", "2875"), ((string?)position.Attribute("horzOffset"), (string?)position.Attribute("vertOffset")));
+ var titleParagraph = ParagraphWith(section, "2026년 사업 보고");
+ Assert.Equal("CENTER", (string?)HeadItem(hwpx, "paraPr", (string)titleParagraph.Attribute("paraPrIDRef")!).Element(Hh + "align")!.Attribute("horizontal"));
+
+ // Body placeholders get the master's bullets per level.
+ Assert.StartsWith("• ", ParagraphWith(section, "매출 증가").Value);
+ Assert.StartsWith("– ", ParagraphWith(section, "지점 확대").Value);
+
+ // Shapes keep their outline around the text; group children are scaled into the slide.
+ Assert.Equal("17", (string?)section.Descendants(Hp + "rect").Single(r => r.Element(Hp + "drawText")?.Value.Contains("강조") == true).Attribute("ratio"));
+ var ellipse = section.Descendants(Hp + "ellipse").Single();
+ Assert.Contains("단계 1", ellipse.Element(Hp + "drawText")!.Value);
+ Assert.Equal("15748", (string?)ellipse.Element(Hp + "sz")!.Attribute("width"));
+ Assert.Equal("47244", (string?)ellipse.Element(Hp + "pos")!.Attribute("horzOffset"));
+
+ // Table with the default style: accent 1 header row.
+ var table = section.Descendants(Hp + "tbl").Single();
+ Assert.Equal("3", (string?)table.Attribute("rowCnt"));
+ Assert.Contains("faceColor=\"#4472C4\"", Xml(hwpx, "Contents/header.xml").ToString());
+
+ // Master decoration on both slides, background on the second.
+ var xml = section.ToString(SaveOptions.DisableFormatting);
+ Assert.Equal(2, CountOf(xml, $"faceColor=\"{PptxBuilder.BarColor}\""));
+ Assert.Equal(1, CountOf(xml, "faceColor=\"#1F1E2D\""));
+
+ if (RenderWithRhwp(fx, hwpx, "pptx-slides") is { } pages)
+ Assert.Equal(2, pages);
+ }
+
+ private static int CountOf(string text, string value)
+ {
+ var count = 0;
+ for (var i = text.IndexOf(value, StringComparison.Ordinal); i >= 0; i = text.IndexOf(value, i + 1, StringComparison.Ordinal))
+ count++;
+ return count;
+ }
+
+ [Fact]
+ public async Task Pptx_to_pdf_without_powerpoint()
+ {
+ Assert.SkipUnless(fx.Converters.Any(c => c.Id == "rhwp" && fx.Catalog.StatusOf(c).IsAvailable), "rhwp not found");
+ var pptx = new PptxBuilder();
+ pptx.Slide(pptx.Title("첫 장"));
+ pptx.Slide(pptx.Title("둘째 장"));
+ pptx.Slide(pptx.Title("셋째 장"));
+ var path = pptx.Save(Path.Combine(fx.NewFolder(), "세 장.pptx"));
+
+ var pdf = Assert.Single(await ConvertAsync(path, "pdf"));
+
+ // PDFium (for counting pages) is only known to the platform analyzer on desktop and mobile systems.
+ if (OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() || OperatingSystem.IsLinux())
+ Assert.Equal(3, PDFtoImage.Conversion.GetPageCount(await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken)));
+ }
+
+ // ───────────────────────── Routes ─────────────────────────
+
+ [Theory]
+ [InlineData("xlsx", "csv", "spreadsheet")]
+ [InlineData("csv", "xlsx", "spreadsheet")]
+ [InlineData("xlsx", "hwpx", "hwpx-writer")]
+ [InlineData("csv", "hwpx", "hwpx-writer")]
+ [InlineData("pptx", "hwpx", "hwpx-writer")]
+ [InlineData("xlsx", "pdf", "hwpx-writer,rhwp")]
+ [InlineData("csv", "pdf", "hwpx-writer,rhwp")]
+ [InlineData("pptx", "pdf", "hwpx-writer,rhwp")]
+ [InlineData("docx", "pdf", "hwpx-writer,rhwp")]
+ public void Office_files_convert_without_optional_engines(string from, string to, string engines)
+ {
+ Assert.Equal(engines.Split(','), BuiltInPlanner("rhwp").Plan(from, to)!.Steps.Select(s => s.Converter.Id));
+ // Built-in conversions win even when LibreOffice is installed.
+ Assert.DoesNotContain(fx.Catalog.CreatePlanner(["libreoffice", "rhwp"]).Plan(from, to)!.Steps, s => s.Converter.Id == "libreoffice");
+ }
+
+ [Theory]
+ [InlineData("doc", "pdf")]
+ [InlineData("xls", "xlsx")]
+ [InlineData("ppt", "pdf")]
+ [InlineData("ods", "pdf")]
+ [InlineData("docx", "odt")]
+ public void Rare_formats_need_libreoffice(string from, string to)
+ {
+ Assert.Null(BuiltInPlanner("rhwp").Plan(from, to));
+ if (fx.Catalog.CreatePlanner(["libreoffice", "rhwp"]).Plan(from, to) is { } route)
+ Assert.Contains(route.Steps, s => s.Converter.Id == "libreoffice");
+ }
+}