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.

Initial commit: Filee drag & drop file converter

KnifeLemon49961742c2aa
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 00000000..fbb1e15a
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,46 @@
+root = true
+
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 4
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.{json,yml,yaml,axaml,xml,csproj,props,targets,slnx}]
+indent_size = 2
+
+[*.md]
+trim_trailing_whitespace = false
+
+[*.cs]
+# Namespaces and usings
+csharp_style_namespace_declarations = file_scoped:warning
+dotnet_sort_system_directives_first = true
+csharp_using_directive_placement = outside_namespace
+
+# var usage
+csharp_style_var_for_built_in_types = true:suggestion
+csharp_style_var_when_type_is_apparent = true:suggestion
+csharp_style_var_elsewhere = true:suggestion
+
+# Expression-level preferences
+csharp_prefer_braces = when_multiline:suggestion
+csharp_style_expression_bodied_methods = when_on_single_line:suggestion
+csharp_style_expression_bodied_properties = true:suggestion
+dotnet_style_prefer_conditional_expression_over_return = false
+
+# Naming: private fields are _camelCase
+dotnet_naming_rule.private_fields_underscore.symbols = private_fields
+dotnet_naming_rule.private_fields_underscore.style = underscore_camel
+dotnet_naming_rule.private_fields_underscore.severity = suggestion
+dotnet_naming_symbols.private_fields.applicable_kinds = field
+dotnet_naming_symbols.private_fields.applicable_accessibilities = private
+dotnet_naming_style.underscore_camel.required_prefix = _
+dotnet_naming_style.underscore_camel.capitalization = camel_case
+
+# Newlines
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..39743c82
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,18 @@
+* text=auto
+
+*.cs text diff=csharp
+*.axaml text
+*.json text
+*.md text
+*.ps1 text eol=crlf
+*.sh text eol=lf
+
+*.ttf binary
+*.otf binary
+*.ico binary
+*.png binary
+*.jpg binary
+*.pdf binary
+*.docx binary
+*.hwpx binary
+*.hwp binary
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..9916a50d
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,22 @@
+---
+name: Bug report
+about: Something doesn't convert or behaves wrongly
+labels: bug
+---
+
+**What happened?**
+
+**What did you expect?**
+
+**Steps to reproduce**
+1.
+2.
+
+**Files involved** (formats, sizes — attach a sample if you can share it)
+
+**Environment**
+- Filee version (Settings → About):
+- Windows version:
+- Engines page status (screenshot helps):
+
+**Log** – `%APPDATA%\Filee\logs\filee-<date>.log` (last lines)
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 00000000..31a3b620
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,11 @@
+---
+name: Feature request
+about: A new format, preset option or idea
+labels: enhancement
+---
+
+**What would you like Filee to do?**
+
+**Why / when would you use it?**
+
+**Ideas for how it could work** (optional — engine or library suggestions welcome)
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..7c215f8e
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,18 @@
+## What does this change?
+
+<!-- One or two sentences. Link the issue if there is one: Fixes #123 -->
+
+## How was it tested?
+
+- [ ] `dotnet format --verify-no-changes`
+- [ ] `dotnet test`
+- [ ] Tried it in the app (describe):
+
+## Screenshots (UI changes)
+
+<!-- Rendered pages are in tests/Filee.App.Tests/bin/<config>/net10.0/screenshots -->
+
+## Checklist
+
+- [ ] New UI strings are in all `src/Filee.App/Assets/i18n/*.json` files
+- [ ] New third-party code or binaries are listed in `THIRD-PARTY-NOTICES.md`
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..32745737
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,45 @@
+# Build, test and style check on every push and pull request.
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ global-json-file: global.json
+
+ - name: Restore
+ run: dotnet restore Filee.slnx
+
+ - name: Check formatting
+ run: dotnet format Filee.slnx --verify-no-changes --no-restore --severity warn
+
+ - name: Build
+ run: dotnet build Filee.slnx --no-restore -c Release
+
+ # rhwp + Pandoc are small; with them the HWP/HWPX engine tests run too (LibreOffice is skipped to save time).
+ - name: Fetch rhwp and Pandoc for engine tests
+ shell: pwsh
+ run: ./build/fetch-engines.ps1 -Only rhwp,pandoc
+
+ - name: Test
+ run: dotnet test Filee.slnx --no-build -c Release --logger "trx" --results-directory TestResults
+
+ - name: Upload UI screenshots
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: ui-screenshots
+ path: tests/Filee.App.Tests/bin/Release/net10.0/screenshots/
+ if-no-files-found: ignore
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..eb5dfa0e
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,71 @@
+# Builds the Windows installer and publishes it to GitHub Releases.
+# Trigger: push a tag like v0.1.0 (git tag v0.1.0 && git push origin v0.1.0)
+#
+# Output (Velopack): Filee-win-Setup.exe, Filee-win-Portable.zip, full + delta .nupkg for in-app updates.
+# Large engines are not in the installer; the app offers them on first run and in Settings > Engines.
+name: Release
+
+on:
+ push:
+ tags: ['v*']
+
+permissions:
+ contents: write
+
+jobs:
+ windows:
+ runs-on: windows-latest
+ env:
+ PUBLISH_DIR: publish/win-x64
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v4
+ with:
+ global-json-file: global.json
+
+ - name: Version from tag
+ id: version
+ shell: pwsh
+ run: |
+ $version = '${{ github.ref_name }}'.TrimStart('v')
+ "value=$version" >> $env:GITHUB_OUTPUT
+
+ - name: Fonts
+ shell: pwsh
+ run: ./build/fetch-fonts.ps1
+
+ - name: Test
+ run: dotnet test Filee.slnx -c Release
+
+ - name: Publish
+ run: >
+ dotnet publish src/Filee.App/Filee.App.csproj -c Release -r win-x64 --self-contained
+ -p:Version=${{ steps.version.outputs.value }}
+ -p:PublishReadyToRun=true
+ -o ${{ env.PUBLISH_DIR }}
+
+ # Only the small rhwp is bundled. LibreOffice (+ H2Orestart, Java) and Pandoc are large and are downloaded by
+ # the app when the user picks them (first-run setup or Settings > Engines), see engines.json.
+ - name: Bundle conversion engines (rhwp)
+ shell: pwsh
+ run: ./build/fetch-engines.ps1 -Only rhwp -Destination "${{ env.PUBLISH_DIR }}/engines"
+
+ - name: Install Velopack CLI
+ run: dotnet tool install -g vpk
+
+ - name: Download previous release (for delta updates)
+ run: vpk download github --repoUrl ${{ github.server_url }}/${{ github.repository }} --token ${{ secrets.GITHUB_TOKEN }} -o Releases
+ continue-on-error: true
+
+ - name: Pack
+ run: >
+ vpk pack --packId Filee --packVersion ${{ steps.version.outputs.value }}
+ --packDir ${{ env.PUBLISH_DIR }} --mainExe Filee.exe --packTitle Filee
+ --icon src/Filee.App/Assets/Icons/filee.ico -o Releases
+
+ - name: Upload to GitHub Releases
+ run: >
+ vpk upload github --repoUrl ${{ github.server_url }}/${{ github.repository }}
+ --token ${{ secrets.GITHUB_TOKEN }} --publish
+ --releaseName "Filee ${{ steps.version.outputs.value }}" --tag ${{ github.ref_name }} -o Releases
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..1c3b65ea
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,32 @@
+# Build output
+bin/
+obj/
+artifacts/
+publish/
+Releases/
+
+# Downloaded conversion engines (see build/fetch-engines.ps1)
+engines/
+build/.cache/
+
+# IDE
+.vs/
+.vscode/*
+!.vscode/extensions.json
+.idea/
+*.user
+*.suo
+*.DotSettings.user
+
+# Test results
+TestResults/
+*.trx
+coverage*/
+
+# OS
+Thumbs.db
+.DS_Store
+
+# Fonts are downloaded by build/fetch-fonts.ps1
+src/Filee.App/Assets/Fonts/*.ttf
+src/Filee.App/Assets/Fonts/*.otf
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 00000000..ac004e1a
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,54 @@
+# Contributing to Filee
+
+Thanks for helping! Filee is built to be easy to extend: most contributions touch one file plus a test.
+
+## Setup
+
+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
+ Markdown/HTML). Without `-Only` it also downloads LibreOffice with H2Orestart and Java (~420 MB). Engines in the
+ repository's `engines/` folder are picked up by debug builds; users download the large ones from the app.
+4. `dotnet run --project src/Filee.App`, `dotnet test`.
+
+Any IDE works (Visual Studio 2022+, Rider, VS Code with C# Dev Kit).
+
+## Where things live
+
+Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short:
+
+- **New file format or engine** → `src/Filee.Engines`, see [docs/ADDING-A-CONVERTER.md](docs/ADDING-A-CONVERTER.md).
+- **New language** → `src/Filee.App/Assets/i18n`, see [docs/ADDING-A-LANGUAGE.md](docs/ADDING-A-LANGUAGE.md).
+- **UI** → `src/Filee.App/Views` (XAML) + `ViewModels` (CommunityToolkit.Mvvm).
+- **Domain rules** (routes, output names, settings) → `src/Filee.Core` — no UI or OS code here.
+
+## Code style
+
+- `dotnet format` must pass (CI runs `dotnet format --verify-no-changes`). `.editorconfig` has the rules.
+- 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.
+- 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.
+
+## Tests
+
+- `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).
+- `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.
+
+## Pull requests
+
+1. Fork, create a branch, make your change with tests.
+2. `dotnet format && dotnet test`.
+3. Open a PR and fill in the template. Screenshots for UI changes, please.
+
+## Releasing (maintainers)
+
+Push a tag `vX.Y.Z`. `.github/workflows/release.yml` builds, bundles the engines, packs with Velopack and publishes
+the installer and update packages to GitHub Releases.
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 00000000..9604d18e
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,26 @@
+<!--
+ Shared MSBuild settings for every project in the repository.
+ Keep project files small: anything common belongs here.
+-->
+<Project>
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <LangVersion>latest</LangVersion>
+ <EnableNETAnalyzers>true</EnableNETAnalyzers>
+ <GenerateDocumentationFile>true</GenerateDocumentationFile>
+ <!-- Missing XML docs are reported by review, not by the compiler; documenting only the non-obvious
+ parameters of a member is fine (CS1573). -->
+ <NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>
+
+ <Version>0.1.0</Version>
+ <Product>Filee</Product>
+ <Authors>Filee contributors</Authors>
+ <Copyright>Copyright (c) Filee contributors</Copyright>
+
+ <!-- Single source of truth for the GitHub repository (used by the updater and the About page). -->
+ <FileeRepositoryUrl>https://github.com/KnifeLemon/Filee</FileeRepositoryUrl>
+ <RepositoryUrl>$(FileeRepositoryUrl)</RepositoryUrl>
+ </PropertyGroup>
+</Project>
diff --git a/Directory.Packages.props b/Directory.Packages.props
new file mode 100644
index 00000000..78040e85
--- /dev/null
+++ b/Directory.Packages.props
@@ -0,0 +1,43 @@
+<!--
+ Central package management: every NuGet version lives here.
+ Project files reference packages without a Version attribute.
+-->
+<Project>
+ <PropertyGroup>
+ <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
+ <AvaloniaVersion>12.1.3</AvaloniaVersion>
+ </PropertyGroup>
+
+ <ItemGroup Label="UI">
+ <PackageVersion Include="Avalonia" Version="$(AvaloniaVersion)" />
+ <PackageVersion Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
+ <PackageVersion Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
+ <PackageVersion Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
+ <PackageVersion Include="Avalonia.Headless.XUnit" Version="$(AvaloniaVersion)" />
+ <PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
+ <PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
+ </ItemGroup>
+
+ <ItemGroup Label="Infrastructure">
+ <PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.12" />
+ <PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.12" />
+ <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.12" />
+ <PackageVersion Include="SharpHook" Version="8.0.0" />
+ <PackageVersion Include="Velopack" Version="1.2.161" />
+ </ItemGroup>
+
+ <ItemGroup Label="Conversion engines">
+ <PackageVersion Include="Magick.NET-Q8-AnyCPU" Version="14.17.2" />
+ <PackageVersion Include="PDFsharp" Version="6.2.4" />
+ <!-- 5.3+ requires SkiaSharp 4, which conflicts with Avalonia 12.1 (SkiaSharp 3.119). -->
+ <PackageVersion Include="PDFtoImage" Version="5.2.1" />
+ <PackageVersion Include="Unhwp" Version="0.13.0" />
+ <PackageVersion Include="Markdig" Version="1.4.0" />
+ </ItemGroup>
+
+ <ItemGroup Label="Tests">
+ <PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.10.1" />
+ <PackageVersion Include="xunit.v3" Version="3.2.2" />
+ <PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
+ </ItemGroup>
+</Project>
diff --git a/Filee.slnx b/Filee.slnx
new file mode 100644
index 00000000..a95bd263
--- /dev/null
+++ b/Filee.slnx
@@ -0,0 +1,19 @@
+<Solution>
+ <Folder Name="/src/">
+ <Project Path="src/Filee.Core/Filee.Core.csproj" />
+ <Project Path="src/Filee.Engines/Filee.Engines.csproj" />
+ <Project Path="src/Filee.Platform.Windows/Filee.Platform.Windows.csproj" />
+ <Project Path="src/Filee.App/Filee.App.csproj" />
+ </Folder>
+ <Folder Name="/tests/">
+ <Project Path="tests/Filee.Core.Tests/Filee.Core.Tests.csproj" />
+ <Project Path="tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj" />
+ <Project Path="tests/Filee.App.Tests/Filee.App.Tests.csproj" />
+ </Folder>
+ <Folder Name="/Solution Items/">
+ <File Path="Directory.Build.props" />
+ <File Path="Directory.Packages.props" />
+ <File Path="global.json" />
+ <File Path=".editorconfig" />
+ </Folder>
+</Solution>
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..211f671b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Filee contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.ko.md b/README.ko.md
new file mode 100644
index 00000000..93dd9f92
--- /dev/null
+++ b/README.ko.md
@@ -0,0 +1,149 @@
+<p align="center">
+ <a href="https://filee.sh/ko/"><img src="docs/media/banner-ko.jpg" alt="Filee: 끌어서 놓으면, 변환 끝." width="100%"></a>
+</p>
+
+<p align="center">
+ <b>드래그로 쓰는 무료 오픈소스 Windows 파일 변환기.</b><br>
+ <kbd>Ctrl</kbd>을 누른 채 파일을 끌면 커서 위치에 도넛이 열립니다. 원하는 형식 위에 놓으면 끝.
+</p>
+
+<p align="center">
+ <a href="https://filee.sh/ko/"><b>웹사이트</b></a> ·
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe"><b>다운로드</b></a> ·
+ <a href="#시작하기">시작하기</a> ·
+ <a href="#문서">문서</a>
+</p>
+
+<p align="center">
+ <a href="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml"><img src="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest"><img src="https://img.shields.io/github/v/release/KnifeLemon/Filee?color=7F77DD&label=release" alt="최신 릴리스"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases"><img src="https://img.shields.io/github/downloads/KnifeLemon/Filee/total?color=1D9E75" alt="다운로드 수"></a>
+ <img src="https://img.shields.io/badge/Windows-10%20%7C%2011-3C3489" alt="Windows 10 | 11">
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-6A62C9" alt="MIT 라이선스"></a>
+</p>
+
+<p align="center"><a href="README.md">English</a> · <b>한국어</b> · <a href="README.zh-CN.md">简体中文</a></p>
+
+<table>
+ <tr>
+ <td width="33%" valign="top"><b>커서 바로 옆에서</b><br>프로그램 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 커서 위치에 나타납니다.</td>
+ <td width="33%" valign="top"><b>한컴오피스 없이 HWP·HWPX</b><br>내장 HWPX 작성기가 워드 문서의 레이아웃을 유지하고, rhwp가 HWP ↔ HWPX, PDF, PNG를 변환합니다.</td>
+ <td width="33%" valign="top"><b>내 PC 안에서만</b><br>아무것도 업로드하지 않아요. 인터넷 없이도 동작하고 결과는 원본 바로 옆에 저장됩니다.</td>
+ </tr>
+</table>
+
+## 이렇게 동작해요
+
+<p align="center">
+ <a href="https://filee.sh/ko/"><img src="docs/media/demo-ko.webp" alt="Ctrl을 누른 채 여행사진.jpg를 끌면 커서 위치에 형식 도넛이 열리고, PNG에 놓으면 진행률 링이 차오른 뒤 여행사진.png가 생깁니다" width="820"></a><br>
+ <sub>27초 영상과 직접 해보는 데모는 <a href="https://filee.sh/ko/">filee.sh</a>에서</sub>
+</p>
+
+## 기능
+
+- **커서 위치에 뜨는 도넛 툴바.** 수정키 + 파일 드래그(기본 <kbd>Ctrl</kbd>). 수정키 조합, 마우스 버튼, 드래그 거리,
+ 길게 누르기, 선택한 파일용 키보드 단축키까지 모두 바꿀 수 있습니다.
+- **파일 종류별 툴바.** 이미지, PDF, 오피스 문서, HWP/HWPX, 혼합 파일용 프로필. 실제 도넛 위에서 드래그 앤 드롭으로
+ 프리셋을 넣고, 빼고, 순서를 바꿉니다. 우클릭이나 ✎로 프리셋을 편집합니다.
+- **프리셋.** 품질, 크기 조정, DPI, 메타데이터, TIFF 압축, ICO 크기, PDF 합치기·나누기, 페이지 범위,
+ 저장 위치, 파일 이름 패턴, 이름 충돌 처리.
+- **일괄 변환.** 1개든 100개든 동시에 변환하고, 하나가 실패해도 나머지는 계속됩니다.
+- **경로 자동 계획.** 여러 단계 변환도 알아서 찾습니다(예: HWPX → PDF → PNG). 단계마다 가장 잘하는 엔진을 씁니다.
+- **네 가지 사용 방법.** 드래그 동작, 탐색기 우클릭과 보내기, 탐색기에서 선택한 파일 + 단축키, 메인 창 드롭 영역.
+- **말랑한 애니메이션 UI.** 라이트·다크·시스템 테마, 강조색, 모서리 둥글기, 저사양 PC를 위한 *애니메이션 줄이기*.
+- **한국어, English, 简体中文.** 기본값은 Windows 언어를 따릅니다.
+
+## 지원 형식
+
+| 원본 | 변환 대상 |
+|---|---|
+| **이미지**: JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, HEIC(읽기) | 모든 이미지 형식, PDF |
+| **PDF** | PNG, JPG, TIFF, 합치기, 나누기, 페이지 범위 |
+| **문서**: DOCX, DOC, ODT, RTF | PDF, HWPX, 서로 변환, TXT, HTML |
+| **한글**: HWP, HWPX | PDF, HWPX ↔ HWP, DOCX, TXT, 마크다운, HTML |
+| **스프레드시트·프레젠테이션**: XLSX, XLS, ODS, CSV, PPTX, PPT, ODP | PDF와 서로 변환 |
+| **텍스트**: TXT, 마크다운, HTML | DOCX, HWPX, PDF |
+
+오피스 문서와 마크다운은 추가 엔진(LibreOffice, Pandoc)을 씁니다. 처음 실행할 때 받을지 물어봐요.
+HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)에 있습니다.
+
+## 스크린샷
+
+<table>
+ <tr>
+ <td width="50%"><img src="docs/media/page-toolbar-ko.png" alt="프로필과 프리셋으로 도넛 툴바를 편집하는 화면"></td>
+ <td width="50%"><img src="docs/media/page-home-ko.png" alt="드롭 영역과 최근 변환 기록이 있는 홈 화면"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>파일 종류마다 도넛을 드래그 앤 드롭으로 배치</sub></td>
+ <td align="center"><sub>홈: 드롭 영역과 최근 변환 기록</sub></td>
+ </tr>
+ <tr>
+ <td width="50%" align="center"><img src="docs/media/preset-popup-ko.png" alt="품질과 저장 위치를 고르는 프리셋 편집 창" width="70%"></td>
+ <td width="50%" align="center"><img src="docs/media/engine-setup-ko.png" alt="처음 실행할 때 추가 엔진을 고르는 창" width="80%"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>프리셋 편집: 품질, 크기, 저장 위치, 파일 이름</sub></td>
+ <td align="center"><sub>큰 엔진은 처음 실행할 때 골라서 설치</sub></td>
+ </tr>
+</table>
+
+## 시작하기
+
+**설치:** [`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)을 받을지 묻습니다. 나중에 설정 → 변환 엔진에서 언제든 설치하거나 지울 수 있습니다.
+- **업데이트는 자동입니다.** Filee는 GitHub Releases에서 스스로 업데이트합니다.
+
+macOS 지원은 계획 중입니다.
+
+<details>
+<summary><b>소스에서 빌드</b></summary>
+
+필요: .NET 10 SDK, Windows 10/11.
+
+```bash
+git clone https://github.com/KnifeLemon/Filee.git
+cd Filee
+pwsh build/fetch-fonts.ps1 # 선택: Noto Sans 글꼴
+pwsh build/fetch-engines.ps1 -Only rhwp,pandoc # 선택: 개발용 엔진 (전체는 -Only 생략, 약 475MB)
+dotnet run --project src/Filee.App
+dotnet test
+```
+
+설정은 `%APPDATA%\Filee`에 저장됩니다. 디버그 빌드는 탐색기 우클릭 메뉴나 자동 시작을 건드리지 않습니다.
+
+| 프로젝트 | 설명 |
+|---|---|
+| `src/Filee.Core` | 형식, 프리셋, 툴바 프로필, 설정, 경로 계획, 작업 큐. UI·OS API 없음. |
+| `src/Filee.Engines` | 변환 엔진마다 클래스 하나(`IConverter`). HWPX 작성기 포함. |
+| `src/Filee.Platform.Windows` | 탐색기 연동, 우클릭 메뉴, 자동 시작. |
+| `src/Filee.App` | Avalonia UI: 도넛 툴바, 설정 창, 트레이, 알림. |
+| `tests/*` | xUnit v3 테스트(헤드리스 UI 렌더링 포함). |
+
+</details>
+
+## 문서
+
+| 하고 싶은 일 | 여기서 시작 |
+|---|---|
+| 앱 구조 이해하기 | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) |
+| 어떤 엔진이 무엇을 변환하는지, 라이선스 | [docs/ENGINES.md](docs/ENGINES.md) |
+| 새 변환 추가하기 | [docs/ADDING-A-CONVERTER.md](docs/ADDING-A-CONVERTER.md) |
+| 새 언어로 번역하기 | [docs/ADDING-A-LANGUAGE.md](docs/ADDING-A-LANGUAGE.md) |
+| PR 보내기 | [CONTRIBUTING.md](CONTRIBUTING.md) |
+
+## 기여
+
+PR 환영합니다. 시작하기 좋은 작업은 [변환기 추가](docs/ADDING-A-CONVERTER.md)와 [언어 추가](docs/ADDING-A-LANGUAGE.md)입니다.
+Filee가 쓸만하다면 ⭐ 하나가 다른 사람들이 찾는 데 큰 도움이 됩니다.
+
+## 라이선스
+
+MIT. 포함된 서드파티 구성요소는 각자의 라이선스를 따릅니다: [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
+
+<p align="center">
+ <a href="https://star-history.com/#KnifeLemon/Filee&Date"><img src="https://api.star-history.com/svg?repos=KnifeLemon/Filee&type=Date" alt="Star history" width="600"></a>
+</p>
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..ee12705d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,152 @@
+<p align="center">
+ <a href="https://filee.sh"><img src="docs/media/banner-en.jpg" alt="Filee: Drag. Drop. Converted." width="100%"></a>
+</p>
+
+<p align="center">
+ <b>A free, open-source file converter for Windows that you use by dragging.</b><br>
+ Hold <kbd>Ctrl</kbd>, drag files and drop them on a format in the donut that opens right at your cursor.
+</p>
+
+<p align="center">
+ <a href="https://filee.sh"><b>Website</b></a> ·
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe"><b>Download</b></a> ·
+ <a href="#get-started">Get started</a> ·
+ <a href="#documentation">Docs</a>
+</p>
+
+<p align="center">
+ <a href="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml"><img src="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest"><img src="https://img.shields.io/github/v/release/KnifeLemon/Filee?color=7F77DD&label=release" alt="Latest release"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases"><img src="https://img.shields.io/github/downloads/KnifeLemon/Filee/total?color=1D9E75" alt="Downloads"></a>
+ <img src="https://img.shields.io/badge/Windows-10%20%7C%2011-3C3489" alt="Windows 10 | 11">
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-6A62C9" alt="MIT license"></a>
+</p>
+
+<p align="center"><b>English</b> · <a href="README.ko.md">한국어</a> · <a href="README.zh-CN.md">简体中文</a></p>
+
+<table>
+ <tr>
+ <td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>
+ <td width="33%" valign="top"><b>HWP & HWPX without Hancom Office</b><br>A built-in HWPX writer keeps the layout of Word documents; rhwp converts HWP ↔ HWPX, PDF and PNG.</td>
+ <td width="33%" valign="top"><b>Stays on your PC</b><br>Nothing is uploaded. Filee works offline and saves the result right next to the original.</td>
+ </tr>
+</table>
+
+## See it in action
+
+<p align="center">
+ <a href="https://filee.sh"><img src="docs/media/demo-en.webp" alt="Dragging trip.jpg with Ctrl held: a donut of formats opens at the cursor, the file is dropped on PNG, a progress ring completes and trip.png appears" width="820"></a><br>
+ <sub>Watch the 27-second video and try the interactive demo on <a href="https://filee.sh">filee.sh</a></sub>
+</p>
+
+## Features
+
+- **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.
+ 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.
+- **Batch conversion.** 1 file or 100, converted in parallel; one failure never stops the rest.
+- **Planned routes.** Multi-step conversions are found automatically (e.g. HWPX → PDF → PNG), each step with the engine
+ that does it best.
+- **Four ways in.** The drag gesture, Explorer right-click and Send To, a keyboard shortcut on the Explorer selection,
+ and the drop zone in the main window.
+- **Soft, animated UI.** Light, dark or system theme, your accent colour, adjustable roundness and a *Reduce animations*
+ switch for older PCs.
+- **English, 한국어, 简体中文**, following your Windows language by default.
+
+## Formats
+
+| From | To |
+|---|---|
+| **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 |
+| **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 |
+
+Office documents and Markdown use optional engines (LibreOffice, Pandoc) that Filee offers to download on first start.
+How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).
+
+## Screenshots
+
+<table>
+ <tr>
+ <td width="50%"><img src="docs/media/page-toolbar-en.png" alt="Donut toolbar editor with profiles and presets"></td>
+ <td width="50%"><img src="docs/media/page-home-en.png" alt="Home screen with the drop zone and recent conversions"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>Arrange the donut by drag & drop, one profile per file type</sub></td>
+ <td align="center"><sub>Home: drop zone and recent conversions</sub></td>
+ </tr>
+ <tr>
+ <td width="50%"><img src="docs/media/page-presets-en.png" alt="Preset editor with quality and output options"></td>
+ <td width="50%"><img src="docs/media/page-toolbar-dark.png" alt="Donut toolbar editor in the dark theme"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>Presets: quality, size, PDF pages, output folder and file names</sub></td>
+ <td align="center"><sub>Dark theme</sub></td>
+ </tr>
+</table>
+
+## Get started
+
+**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 Markdown/HTML (~42 MB). You can install or remove them any time in Settings → Engines.
+- **Updates are automatic.** Filee updates itself from GitHub Releases.
+
+macOS support is planned.
+
+<details>
+<summary><b>Build from source</b></summary>
+
+Requirements: .NET 10 SDK, Windows 10/11.
+
+```bash
+git clone https://github.com/KnifeLemon/Filee.git
+cd Filee
+pwsh build/fetch-fonts.ps1 # optional: Noto Sans UI fonts
+pwsh build/fetch-engines.ps1 -Only rhwp,pandoc # optional engines for development (all: omit -Only, ~475 MB)
+dotnet run --project src/Filee.App
+dotnet test
+```
+
+Settings live in `%APPDATA%\Filee`. Debug builds never touch the Explorer context menu or auto-start.
+
+| Project | What it is |
+|---|---|
+| `src/Filee.Core` | Formats, presets, toolbar profiles, settings, route planner, job queue. No UI, no OS APIs. |
+| `src/Filee.Engines` | One class per conversion engine (`IConverter`), including the HWPX writer. |
+| `src/Filee.Platform.Windows` | Explorer integration, context menu, auto-start. |
+| `src/Filee.App` | Avalonia UI: donut toolbar, settings window, tray, toasts. |
+| `tests/*` | xUnit v3 tests, including headless UI rendering. |
+
+</details>
+
+## Documentation
+
+| I want to… | Start here |
+|---|---|
+| Understand how the app fits together | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) |
+| Know which engine converts what, and their licenses | [docs/ENGINES.md](docs/ENGINES.md) |
+| Add a new conversion | [docs/ADDING-A-CONVERTER.md](docs/ADDING-A-CONVERTER.md) |
+| Translate Filee into my language | [docs/ADDING-A-LANGUAGE.md](docs/ADDING-A-LANGUAGE.md) |
+| Send a pull request | [CONTRIBUTING.md](CONTRIBUTING.md) |
+
+## Contributing
+
+Pull requests are welcome. Good first steps are [adding a converter](docs/ADDING-A-CONVERTER.md) and
+[adding a language](docs/ADDING-A-LANGUAGE.md). If Filee saves you some clicks, a ⭐ helps other people find it.
+
+## License
+
+MIT. Bundled third-party components keep their own licenses: see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
+
+<p align="center">
+ <a href="https://star-history.com/#KnifeLemon/Filee&Date"><img src="https://api.star-history.com/svg?repos=KnifeLemon/Filee&type=Date" alt="Star history" width="600"></a>
+</p>
diff --git a/README.zh-CN.md b/README.zh-CN.md
new file mode 100644
index 00000000..342a632d
--- /dev/null
+++ b/README.zh-CN.md
@@ -0,0 +1,149 @@
+<p align="center">
+ <a href="https://filee.sh/zh-cn/"><img src="docs/media/banner-zh-CN.jpg" alt="Filee:拖一下,放一下,转好了。" width="100%"></a>
+</p>
+
+<p align="center">
+ <b>用拖放操作的免费开源 Windows 文件格式转换器。</b><br>
+ 按住 <kbd>Ctrl</kbd> 拖动文件,光标处会弹出格式圆环,放到想要的格式上即可。
+</p>
+
+<p align="center">
+ <a href="https://filee.sh/zh-cn/"><b>官网</b></a> ·
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest/download/Filee-win-Setup.exe"><b>下载</b></a> ·
+ <a href="#快速开始">快速开始</a> ·
+ <a href="#文档">文档</a>
+</p>
+
+<p align="center">
+ <a href="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml"><img src="https://github.com/KnifeLemon/Filee/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases/latest"><img src="https://img.shields.io/github/v/release/KnifeLemon/Filee?color=7F77DD&label=release" alt="最新版本"></a>
+ <a href="https://github.com/KnifeLemon/Filee/releases"><img src="https://img.shields.io/github/downloads/KnifeLemon/Filee/total?color=1D9E75" alt="下载次数"></a>
+ <img src="https://img.shields.io/badge/Windows-10%20%7C%2011-3C3489" alt="Windows 10 | 11">
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-6A62C9" alt="MIT 许可证"></a>
+</p>
+
+<p align="center"><a href="README.md">English</a> · <a href="README.ko.md">한국어</a> · <b>简体中文</b></p>
+
+<table>
+ <tr>
+ <td width="33%" valign="top"><b>就在光标旁边</b><br>无需打开程序窗口。只显示适合当前拖动文件的格式,就在你的光标处。</td>
+ <td width="33%" valign="top"><b>无需韩文办公软件处理 HWP/HWPX</b><br>内置 HWPX 写入器保留 Word 文档的版式;rhwp 负责 HWP ↔ HWPX、PDF 和 PNG。</td>
+ <td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何内容。离线也能使用,结果保存在原文件旁边。</td>
+ </tr>
+</table>
+
+## 实际效果
+
+<p align="center">
+ <a href="https://filee.sh/zh-cn/"><img src="docs/media/demo-zh-CN.webp" alt="按住 Ctrl 拖动 旅行.jpg,光标处弹出格式圆环,放到 PNG 上,进度环走完后生成 旅行.png" width="820"></a><br>
+ <sub>27 秒视频和可交互演示请访问 <a href="https://filee.sh/zh-cn/">filee.sh</a></sub>
+</p>
+
+## 功能
+
+- **光标处的格式圆环。** 按住修饰键拖动文件(默认 <kbd>Ctrl</kbd>)。修饰键组合、鼠标按键、拖动距离、长按手势,
+ 以及对选中文件使用的快捷键都可以自定义。
+- **按文件类型的工具栏。** 图片、PDF、办公文档、HWP/HWPX,以及用于混合文件的通用配置。
+ 直接在圆环上拖放来添加、移除和排序预设;右键或 ✎ 编辑预设。
+- **预设。** 质量、缩放、DPI、元数据、TIFF 压缩、ICO 尺寸、PDF 合并与拆分、页码范围、
+ 保存位置、文件名模板和重名处理。
+- **批量转换。** 1 个或 100 个文件并行转换,某个文件失败也不影响其余文件。
+- **自动规划路径。** 自动找到多步转换路径(例如 HWPX → PDF → PNG),每一步使用最擅长的引擎。
+- **四种使用方式。** 拖动手势、资源管理器右键和“发送到”、对资源管理器中选中的文件按快捷键、主窗口拖放区。
+- **柔和的动画界面。** 浅色、深色或跟随系统,自定义强调色和圆角,旧电脑可开启“减少动画”。
+- **简体中文、English、한국어**,默认跟随 Windows 语言。
+
+## 支持格式
+
+| 源格式 | 目标格式 |
+|---|---|
+| **图片**:JPG、PNG、WEBP、TIFF、BMP、GIF、ICO、AVIF、HEIC(读取) | 任意图片格式、PDF |
+| **PDF** | PNG、JPG、TIFF、合并、拆分、页码范围 |
+| **文档**:DOCX、DOC、ODT、RTF | PDF、HWPX、互相转换、TXT、HTML |
+| **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 使用可选引擎(LibreOffice、Pandoc),Filee 会在首次启动时询问是否下载。
+HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)。
+
+## 截图
+
+<table>
+ <tr>
+ <td width="50%"><img src="docs/media/page-toolbar-zh-CN.png" alt="用配置文件和预设编辑圆环工具栏"></td>
+ <td width="50%"><img src="docs/media/page-home-zh-CN.png" alt="带拖放区和最近转换记录的主页"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>拖放排列圆环,每种文件类型一个配置</sub></td>
+ <td align="center"><sub>主页:拖放区和最近转换记录</sub></td>
+ </tr>
+ <tr>
+ <td width="50%"><img src="docs/media/page-presets-zh-CN.png" alt="设置质量和输出选项的预设编辑器"></td>
+ <td width="50%"><img src="docs/media/page-toolbar-dark.png" alt="深色主题下的圆环工具栏编辑器"></td>
+ </tr>
+ <tr>
+ <td align="center"><sub>预设:质量、尺寸、PDF 页码、保存位置和文件名</sub></td>
+ <td align="center"><sub>深色主题</sub></td>
+ </tr>
+</table>
+
+## 快速开始
+
+**安装:** 下载 [`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(Markdown/HTML,约 42 MB);之后可随时在“设置 → 转换引擎”中安装或删除。
+- **自动更新。** Filee 会通过 GitHub Releases 自动更新。
+
+macOS 版本正在计划中。
+
+<details>
+<summary><b>从源码构建</b></summary>
+
+需要:.NET 10 SDK、Windows 10/11。
+
+```bash
+git clone https://github.com/KnifeLemon/Filee.git
+cd Filee
+pwsh build/fetch-fonts.ps1 # 可选:Noto Sans 字体
+pwsh build/fetch-engines.ps1 -Only rhwp,pandoc # 可选:开发用引擎(全部下载请省略 -Only,约 475 MB)
+dotnet run --project src/Filee.App
+dotnet test
+```
+
+设置保存在 `%APPDATA%\Filee`。调试版本不会修改资源管理器右键菜单和开机自启动。
+
+| 项目 | 说明 |
+|---|---|
+| `src/Filee.Core` | 格式、预设、工具栏配置、设置、路径规划、任务队列。不依赖 UI 和系统 API。 |
+| `src/Filee.Engines` | 每个转换引擎一个类(`IConverter`),包括 HWPX 写入器。 |
+| `src/Filee.Platform.Windows` | 资源管理器集成、右键菜单、开机自启动。 |
+| `src/Filee.App` | Avalonia 界面:圆环工具栏、设置窗口、托盘、通知。 |
+| `tests/*` | xUnit v3 测试,包括无头 UI 渲染。 |
+
+</details>
+
+## 文档
+
+| 我想要… | 从这里开始 |
+|---|---|
+| 了解应用的整体结构 | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) |
+| 了解各引擎负责哪些转换及其许可证 | [docs/ENGINES.md](docs/ENGINES.md) |
+| 添加新的转换 | [docs/ADDING-A-CONVERTER.md](docs/ADDING-A-CONVERTER.md) |
+| 把 Filee 翻译成我的语言 | [docs/ADDING-A-LANGUAGE.md](docs/ADDING-A-LANGUAGE.md) |
+| 提交 Pull Request | [CONTRIBUTING.md](CONTRIBUTING.md) |
+
+## 参与贡献
+
+欢迎提交 Pull Request。适合入门的任务:[添加转换器](docs/ADDING-A-CONVERTER.md)和[添加语言](docs/ADDING-A-LANGUAGE.md)。
+如果 Filee 帮你省了时间,点个 ⭐ 能让更多人发现它。
+
+## 许可证
+
+MIT。随附的第三方组件遵循各自的许可证,详见 [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md)。
+
+<p align="center">
+ <a href="https://star-history.com/#KnifeLemon/Filee&Date"><img src="https://api.star-history.com/svg?repos=KnifeLemon/Filee&type=Date" alt="Star history" width="600"></a>
+</p>
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
new file mode 100644
index 00000000..ef80b2aa
--- /dev/null
+++ b/THIRD-PARTY-NOTICES.md
@@ -0,0 +1,55 @@
+# Third-party notices
+
+Filee is MIT-licensed. It uses and redistributes the following third-party software.
+Each component remains under its own license.
+
+## Libraries (NuGet)
+
+| Component | License | Project |
+|---|---|---|
+| Avalonia UI | MIT | https://github.com/AvaloniaUI/Avalonia |
+| CommunityToolkit.Mvvm | MIT | https://github.com/CommunityToolkit/dotnet |
+| SharpHook (libuiohook) | MIT (libuiohook: GPL-3.0 with linking exception / LGPL-3.0) | https://github.com/TolikPylypchuk/SharpHook |
+| Velopack | MIT | https://github.com/velopack/velopack |
+| Magick.NET / ImageMagick | Apache-2.0 / ImageMagick License | https://github.com/dlemstra/Magick.NET |
+| ImageMagick delegate libraries (libheif, libde265, libwebp, libjpeg-turbo, libpng, libtiff, zlib, …) | Various (LGPL-2.1+, BSD, zlib) | bundled inside Magick.NET |
+| PDFsharp | MIT | https://github.com/empira/PDFsharp |
+| PDFtoImage | MIT | https://github.com/sungaila/PDFtoImage |
+| PDFium (bblanchon.PDFium) | BSD-3-Clause / Apache-2.0 | https://pdfium.googlesource.com/pdfium |
+| SkiaSharp | MIT | https://github.com/mono/SkiaSharp |
+| Unhwp | MIT | https://github.com/iyulab/unhwp |
+| Markdig | BSD-2-Clause | https://github.com/xoofx/markdig |
+| 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 |
+
+## Engines
+
+Bundled with the installer:
+
+| Component | License | Project |
+|---|---|---|
+| rhwp | MIT | https://github.com/edwardkim/rhwp |
+
+Downloaded from their official release pages when the user chooses to install them
+(pinned in `src/Filee.Engines/Infrastructure/engines.json`):
+
+| Component | License | Project |
+|---|---|---|
+| LibreOffice | MPL-2.0 | https://www.libreoffice.org |
+| H2Orestart (HWP/HWPX import for LibreOffice) | GPL-3.0 | https://github.com/ebandal/H2Orestart |
+| Eclipse Temurin JRE (for H2Orestart) | GPL-2.0 with Classpath Exception | https://adoptium.net |
+| Pandoc | GPL-2.0-or-later | https://github.com/jgm/pandoc |
+
+These programs run as separate processes. Their source code is available from the linked projects.
+
+## Fonts and icons
+
+| Component | License | Project |
+|---|---|---|
+| 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/build/fetch-engines.ps1 b/build/fetch-engines.ps1
new file mode 100644
index 00000000..932fa812
--- /dev/null
+++ b/build/fetch-engines.ps1
@@ -0,0 +1,158 @@
+<#
+.SYNOPSIS
+ Downloads and prepares conversion engines for development and for the installer (which bundles rhwp only;
+ the app downloads the large engines on demand, see src/Filee.Engines/Infrastructure/EngineInstaller.cs).
+
+.DESCRIPTION
+ Produces this layout (next to Filee.exe in a published build, or in the repo root for development):
+
+ engines/
+ libreoffice/ LibreOffice (MPL-2.0), extracted from the official MSI via an administrative install
+ + H2Orestart (GPL-3.0) unpacked into share/extensions for HWP/HWPX import
+ jre/ Eclipse Temurin JRE 21 (GPLv2 + Classpath Exception), used by H2Orestart
+ rhwp/ rhwp command line (MIT), HWP/HWPX -> PDF
+ pandoc/ Pandoc (GPL-2.0-or-later, separate program), Markdown/HTML and MD/HTML/ODT/RTF -> HWPX
+
+ Every download is pinned to a version and verified with SHA-256 (src/Filee.Engines/Infrastructure/engines.json,
+ shared with the app). Downloads are cached in build/.cache.
+
+.PARAMETER Destination
+ Target "engines" folder. Default: <repo>/engines (picked up automatically by debug builds).
+
+.PARAMETER Only
+ Restrict to some engines, e.g. -Only rhwp,pandoc (LibreOffice is large: ~356 MB download).
+
+.EXAMPLE
+ pwsh build/fetch-engines.ps1
+ pwsh build/fetch-engines.ps1 -Only rhwp
+ pwsh build/fetch-engines.ps1 -Destination publish/win-x64/engines
+#>
+[CmdletBinding()]
+param(
+ [string]$Destination = (Join-Path $PSScriptRoot '..\engines'),
+ # Accepts an array (-Only rhwp,jre from PowerShell) or one comma-separated string (pwsh -File ... -Only rhwp,jre).
+ [string[]]$Only
+)
+
+$ErrorActionPreference = 'Stop'
+$ProgressPreference = 'SilentlyContinue' # Invoke-WebRequest is ~10x faster without the progress bar
+
+# Versions, URLs and hashes come from the same list the app uses for on-demand downloads.
+$manifest = Get-Content (Join-Path $PSScriptRoot '..\src\Filee.Engines\Infrastructure\engines.json') -Raw | ConvertFrom-Json
+$engines = [ordered]@{}
+foreach ($component in $manifest.components.PSObject.Properties) {
+ $engines[$component.Name] = @{ Url = $component.Value.url; Sha256 = $component.Value.sha256 }
+}
+
+$cache = Join-Path $PSScriptRoot '.cache'
+New-Item -ItemType Directory -Force -Path $cache, $Destination | Out-Null
+$Destination = (Resolve-Path $Destination).Path
+
+function Get-Engine([string]$name) {
+ $info = $engines[$name]
+ $file = Join-Path $cache ([Uri]::UnescapeDataString(($info.Url -split '/')[-1]))
+ if ((Test-Path $file) -and (Get-FileHash $file -Algorithm SHA256).Hash -eq $info.Sha256) {
+ Write-Host "ok $name (cached)"
+ return $file
+ }
+ Write-Host "get $name $($info.Url)"
+ Invoke-WebRequest -Uri $info.Url -OutFile $file -UseBasicParsing
+ $hash = (Get-FileHash $file -Algorithm SHA256).Hash
+ if ($hash -ne $info.Sha256) {
+ Remove-Item $file
+ throw "Checksum mismatch for $name. Expected $($info.Sha256), got $hash."
+ }
+ return $file
+}
+
+function Reset-Folder([string]$path) {
+ if (Test-Path $path) { Remove-Item $path -Recurse -Force }
+ New-Item -ItemType Directory -Force -Path $path | Out-Null
+}
+
+# Moves the content of the single top-level folder of an extracted archive up one level.
+function Expand-Flat([string]$zip, [string]$target) {
+ $tmp = Join-Path $cache ('x-' + [Guid]::NewGuid().ToString('N').Substring(0, 8))
+ Expand-Archive -Path $zip -DestinationPath $tmp
+ $items = Get-ChildItem $tmp
+ $root = if ($items.Count -eq 1 -and $items[0].PSIsContainer) { $items[0].FullName } else { $tmp }
+ Reset-Folder $target
+ Get-ChildItem $root -Force | Move-Item -Destination $target
+ Remove-Item $tmp -Recurse -Force
+}
+
+# Removes parts of LibreOffice that headless conversion never uses (~500 MB):
+# help, readmes, the MSI stub copied by the admin install, the gallery, and spell-check dictionaries except
+# English and Korean (their hyphenation patterns can affect page layout when exporting PDFs).
+function Optimize-LibreOffice([string]$root) {
+ $remove = @('help', 'readmes', 'share\gallery') | ForEach-Object { Join-Path $root $_ }
+ $remove += Get-ChildItem $root -Filter '*.msi' | ForEach-Object FullName
+ $remove += Get-ChildItem (Join-Path $root 'share\extensions') -Directory -Filter 'dict-*' |
+ Where-Object { $_.Name -notin @('dict-en', 'dict-ko') } | ForEach-Object FullName
+ foreach ($path in $remove) { Remove-Item $path -Recurse -Force -ErrorAction SilentlyContinue }
+}
+
+$selected = if ($Only) { @($Only -split ',' | ForEach-Object { $_.Trim().ToLowerInvariant() } | Where-Object { $_ }) } else { @($engines.Keys) }
+foreach ($name in $selected) {
+ if (-not $engines.Contains($name)) { throw "Unknown engine '$name'. Valid: $($engines.Keys -join ', ')" }
+}
+
+if ('rhwp' -in $selected) {
+ $zip = Get-Engine 'rhwp'
+ Expand-Flat $zip (Join-Path $Destination 'rhwp')
+ if (-not (Get-ChildItem (Join-Path $Destination 'rhwp') -Recurse -Filter 'rhwp.exe')) { throw 'rhwp.exe not found in the archive.' }
+ # Keep rhwp.exe directly in engines/rhwp.
+ $exe = Get-ChildItem (Join-Path $Destination 'rhwp') -Recurse -Filter 'rhwp.exe' | Select-Object -First 1
+ if ($exe.DirectoryName -ne (Join-Path $Destination 'rhwp')) {
+ Get-ChildItem $exe.DirectoryName -Force | Move-Item -Destination (Join-Path $Destination 'rhwp') -Force
+ }
+}
+
+if ('pandoc' -in $selected) {
+ $zip = Get-Engine 'pandoc'
+ Expand-Flat $zip (Join-Path $Destination 'pandoc')
+ if (-not (Test-Path (Join-Path $Destination 'pandoc\pandoc.exe'))) { throw 'pandoc.exe not found in the archive.' }
+}
+
+if ('jre' -in $selected) {
+ $zip = Get-Engine 'jre'
+ Expand-Flat $zip (Join-Path $Destination 'jre')
+}
+
+if ('libreoffice' -in $selected) {
+ $msi = Get-Engine 'libreoffice'
+ $tmp = Join-Path $cache 'lo-admin'
+ Reset-Folder $tmp
+ Write-Host 'unpack LibreOffice (administrative install, no system changes)'
+ $proc = Start-Process msiexec.exe -ArgumentList @('/a', "`"$msi`"", '/qn', "TARGETDIR=`"$tmp`"") -Wait -PassThru
+ if ($proc.ExitCode -ne 0) { throw "msiexec /a failed with exit code $($proc.ExitCode)." }
+
+ $soffice = Get-ChildItem $tmp -Recurse -Filter 'soffice.exe' | Select-Object -First 1
+ if (-not $soffice) { throw 'soffice.exe not found after extracting the MSI.' }
+ $root = Split-Path $soffice.DirectoryName -Parent # folder containing program/, share/, ...
+ $target = Join-Path $Destination 'libreoffice'
+ Reset-Folder $target
+ Get-ChildItem $root -Force | Move-Item -Destination $target
+ Remove-Item $tmp -Recurse -Force
+
+ Optimize-LibreOffice $target
+}
+
+if ('h2orestart' -in $selected) {
+ $oxt = Get-Engine 'h2orestart'
+ $lo = Join-Path $Destination 'libreoffice'
+ if (-not (Test-Path (Join-Path $lo 'program\soffice.exe'))) {
+ Write-Warning 'H2Orestart skipped: LibreOffice is not in the destination folder.'
+ }
+ else {
+ # Bundled extensions are plain folders under share/extensions; LibreOffice registers them on start-up.
+ $target = Join-Path $lo 'share\extensions\H2Orestart'
+ Reset-Folder $target
+ $zipCopy = Join-Path $cache 'H2Orestart.zip'
+ Copy-Item $oxt $zipCopy -Force
+ Expand-Archive -Path $zipCopy -DestinationPath $target -Force
+ Remove-Item $zipCopy
+ }
+}
+
+Write-Host "Engines ready in $Destination"
diff --git a/build/fetch-fonts.ps1 b/build/fetch-fonts.ps1
new file mode 100644
index 00000000..66dc7e95
--- /dev/null
+++ b/build/fetch-fonts.ps1
@@ -0,0 +1,58 @@
+<#
+.SYNOPSIS
+ Downloads the Noto Sans fonts (SIL Open Font License 1.1) used by the Filee UI.
+
+.DESCRIPTION
+ Fonts are not committed to git (≈27 MB). Run this once after cloning, and CI runs it before publishing.
+ Without the fonts the app still works and falls back to system fonts (Malgun Gothic, Microsoft YaHei, ...).
+
+ Static font files are used because Avalonia does not support variable fonts.
+ Every file is pinned to a tag/commit and verified with SHA-256.
+
+.EXAMPLE
+ pwsh build/fetch-fonts.ps1
+#>
+[CmdletBinding()]
+param(
+ [string]$Destination = (Join-Path $PSScriptRoot '..\src\Filee.App\Assets\Fonts')
+)
+
+$ErrorActionPreference = 'Stop'
+$latin = 'https://raw.githubusercontent.com/notofonts/notofonts.github.io/28b15b4b43b7bed62b5cf6e6b0b5ff5846270535/fonts/NotoSans/hinted/ttf'
+$cjk = 'https://raw.githubusercontent.com/notofonts/noto-cjk/Sans2.004/Sans/SubsetOTF'
+
+# File name => (URL, SHA-256). Update both together when bumping a version.
+$fonts = [ordered]@{
+ 'NotoSans-Regular.ttf' = @("$latin/NotoSans-Regular.ttf", '478C558EA716033CD60C03438F628DFA75694DCF6B5F6D505A2F05FD2B4F3823')
+ 'NotoSans-Medium.ttf' = @("$latin/NotoSans-Medium.ttf", '635D93D1131D791F2576DE90B3BB0F7CDF61929906E8420A61B5F7F8E76420BB')
+ 'NotoSans-Bold.ttf' = @("$latin/NotoSans-Bold.ttf", '1DF075A380FC7CB898ACF64C1F7B3B4DD780DE3CAA860178BF929DE35817A913')
+ 'NotoSansKR-Regular.otf' = @("$cjk/KR/NotoSansKR-Regular.otf", '69975A0AC8472717870AEFEAB0A4D52739308D90856B9955313B2AD5E0148D68')
+ 'NotoSansKR-Bold.otf' = @("$cjk/KR/NotoSansKR-Bold.otf", '5A6CEB287ED2FC6CFC6213144EBEA68CBD94B20FC9EB873D8486493BF02D9BDA')
+ 'NotoSansSC-Regular.otf' = @("$cjk/SC/NotoSansSC-Regular.otf", 'FAA6C9DF652116DDE789D351359F3D7E5D2285A2B2A1F04A2D7244DF706D5EA9')
+ 'NotoSansSC-Bold.otf' = @("$cjk/SC/NotoSansSC-Bold.otf", 'C6CB5A93ABAA9EDC8EE7463B7EBB7F42D618D40E6ED2F7A5371C97B0B64767C0')
+}
+
+New-Item -ItemType Directory -Force -Path $Destination | Out-Null
+
+foreach ($name in $fonts.Keys) {
+ $url, $expected = $fonts[$name]
+ $target = Join-Path $Destination $name
+
+ if (Test-Path $target) {
+ $actual = (Get-FileHash $target -Algorithm SHA256).Hash
+ if ($actual -eq $expected) {
+ Write-Host "ok $name (cached)"
+ continue
+ }
+ }
+
+ Write-Host "get $name"
+ Invoke-WebRequest -Uri $url -OutFile $target -UseBasicParsing
+ $actual = (Get-FileHash $target -Algorithm SHA256).Hash
+ if ($actual -ne $expected) {
+ Remove-Item $target
+ throw "Checksum mismatch for $name. Expected $expected, got $actual."
+ }
+}
+
+Write-Host "Fonts ready in $Destination"
diff --git a/build/tools/make-icon.cs b/build/tools/make-icon.cs
new file mode 100644
index 00000000..2bf9e3cf
--- /dev/null
+++ b/build/tools/make-icon.cs
@@ -0,0 +1,51 @@
+// Generates src/Filee.App/Assets/Icons/filee.ico and filee.png (the donut logo).
+// Run from the repository root: dotnet run build/tools/make-icon.cs
+#:package Magick.NET-Q8-AnyCPU
+
+using System.Globalization;
+using System.Text;
+using ImageMagick;
+
+const int Size = 512;
+const double C = Size / 2.0;
+const double R2 = 236, R1 = 104;
+const int Segments = 6;
+string[] colors = ["#7F77DD", "#6A62C9", "#7F77DD", "#6A62C9", "#7F77DD", "#6A62C9"];
+const int Highlight = 1; // this slice pops out in teal
+
+string F(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
+(double X, double Y) P(double r, double a) => (C + r * Math.Cos(a), C + r * Math.Sin(a));
+
+var svg = new StringBuilder($"<svg xmlns='http://www.w3.org/2000/svg' width='{Size}' height='{Size}' viewBox='0 0 {Size} {Size}'>");
+var span = 2 * Math.PI / Segments;
+const double Gap = 0.07; // radians between slices
+for (var i = 0; i < Segments; i++)
+{
+ var mid = -Math.PI / 2 + i * span;
+ var s = mid - span / 2 + Gap / 2;
+ var e = mid + span / 2 - Gap / 2;
+ var push = i == Highlight ? 16 : 0;
+ var (dx, dy) = (Math.Cos(mid) * push, Math.Sin(mid) * push);
+ var r2 = i == Highlight ? R2 - 14 : R2 - 20;
+ var (x1, y1) = P(r2, s); var (x2, y2) = P(r2, e);
+ var (x3, y3) = P(R1, e); var (x4, y4) = P(R1, s);
+ var fill = i == Highlight ? "#1D9E75" : colors[i];
+ svg.Append($"<path transform='translate({F(dx)},{F(dy)})' fill='{fill}' d='M{F(x1)} {F(y1)} A{F(r2)} {F(r2)} 0 0 1 {F(x2)} {F(y2)} L{F(x3)} {F(y3)} A{R1} {R1} 0 0 0 {F(x4)} {F(y4)} Z'/>");
+}
+// Centre: a small "file" glyph.
+svg.Append($"<path fill='#3C3489' d='M{F(C - 34)} {F(C - 44)} h44 l24 24 v64 h-68 z'/>");
+svg.Append($"<path fill='#AFA9EC' d='M{F(C + 10)} {F(C - 44)} v24 h24 z'/>");
+svg.Append("</svg>");
+
+var outDir = Path.Combine("src", "Filee.App", "Assets", "Icons");
+Directory.CreateDirectory(outDir);
+File.WriteAllText(Path.Combine(outDir, "filee.svg"), svg.ToString());
+
+var settings = new MagickReadSettings { BackgroundColor = MagickColors.Transparent, Format = MagickFormat.Svg };
+using var master = new MagickImage(Encoding.UTF8.GetBytes(svg.ToString()), settings);
+master.Write(Path.Combine(outDir, "filee.png"), MagickFormat.Png);
+
+// One image + "auto-resize" makes ImageMagick embed every size into a single .ico file.
+master.Settings.SetDefine(MagickFormat.Icon, "auto-resize", "256,64,48,32,24,16");
+master.Write(Path.Combine(outDir, "filee.ico"), MagickFormat.Icon);
+Console.WriteLine($"Icons written to {outDir}");
diff --git a/docs/ADDING-A-CONVERTER.md b/docs/ADDING-A-CONVERTER.md
new file mode 100644
index 00000000..aabe7aad
--- /dev/null
+++ b/docs/ADDING-A-CONVERTER.md
@@ -0,0 +1,88 @@
+# Adding a converter
+
+A converter is one class implementing `IConverter` (`src/Filee.Core/Conversion/IConverter.cs`).
+The route planner combines converters automatically, so a new edge can unlock many conversions at once
+(for example, adding `epub → pdf` also gives `epub → png` through PDFium).
+
+## 1. New format? Register it
+
+If the format is new, add one line to `FormatRegistry.Known` (`src/Filee.Core/Formats/FormatRegistry.cs`):
+
+```csharp
+new("epub", "EPUB", FormatCategory.Document, ["epub"]),
+```
+
+## 2. Write the converter
+
+Create `src/Filee.Engines/<Area>/<Name>Converter.cs`:
+
+```csharp
+// EPUB → PDF with the (hypothetical) SuperEpub library (MIT).
+
+using Filee.Core.Conversion;
+
+namespace Filee.Engines.Documents;
+
+public sealed class SuperEpubConverter : IConverter
+{
+ public string Id => "superepub"; // stable, used in settings
+ public string DisplayName => "SuperEpub";
+ public int MaxParallelism => 0; // 0 = one per CPU core; 1 for non thread-safe engines
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("epub", "pdf"), // cost 10 = normal; higher for lossy/slow paths
+ ];
+
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken ct) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var output = step.Output.Allocate("pdf"); // null = skip (file exists + "skip" policy)
+ if (output is null)
+ return [];
+ SuperEpub.Convert(step.InputPath, output); // honour ct in long loops
+ progress?.Report(1);
+ return [output];
+ }, ct);
+}
+```
+
+Rules:
+
+- Never modify `step.InputPath`.
+- Write outputs only to paths from `step.Output.Allocate(...)`. For several outputs from one input
+ (pages), pass a suffix: `Allocate("png", $"_p{page}")`.
+- Scratch files go to `step.WorkDirectory` (deleted after the job).
+- External programs: use `ProcessRunner.RunAsync` (timeout + cancellation + no shell) and find them with
+ `EngineEnvironment.FindBundled/FindOnPath`. Let users override the path via `env.CustomPath(Id)`.
+- Return `EngineStatus.Unavailable("engine.reason.not_installed")` when a dependency is missing; the UI then greys
+ out affected slices with a reason.
+
+## 3. Register it
+
+Add one line to `EngineRegistry.CreateAll` (`src/Filee.Engines/EngineRegistry.cs`).
+If it should be preferred over existing engines by default, add its id to `AppSettings.EnginePriority`.
+
+## 4. Test it
+
+Add a test to `tests/Filee.Engines.Tests`. Generate the input files in the test (see `EngineFixture`) so the test
+runs everywhere without sample documents, and skip when the engine is not available:
+
+```csharp
+[Fact]
+public async Task Epub_to_pdf()
+{
+ var job = await fx.ConvertAsync([MakeEpub()], new Preset { TargetFormat = "pdf" });
+ Assert.Equal(JobState.Completed, job.State);
+}
+```
+
+## 5. Ship it (optional)
+
+Command line tools are pinned in `src/Filee.Engines/Infrastructure/engines.json` (URL, SHA-256, size, archive kind),
+which both `build/fetch-engines.ps1` and the app read. Small tools can be bundled with the installer (add the id to
+the `fetch-engines.ps1 -Only` list in `.github/workflows/release.yml`); large ones become an optional download by
+adding an `EnginePackage` to `EngineDownloads.Packages` plus its name and description in the three `i18n/*.json`
+files. Either way, add a line to `THIRD-PARTY-NOTICES.md`.
diff --git a/docs/ADDING-A-LANGUAGE.md b/docs/ADDING-A-LANGUAGE.md
new file mode 100644
index 00000000..6d70a6e3
--- /dev/null
+++ b/docs/ADDING-A-LANGUAGE.md
@@ -0,0 +1,24 @@
+# Adding a language
+
+1. Copy `src/Filee.App/Assets/i18n/en.json` to `<code>.json` (e.g. `ja.json`, `de.json`, `zh-TW.json`).
+ The file is a flat list of `"key": "text"` pairs.
+2. Translate the values. Keep `{0}`, `{1}` placeholders — a test checks they match English.
+ Keep the text short where English is short (buttons, donut labels).
+3. Register the language in `LocalizationService.Languages`
+ (`src/Filee.App/Services/LocalizationService.cs`) with its native name, e.g. `("ja", "日本語")`.
+ If the OS culture should pick it automatically, extend `LocalizationService.Resolve`.
+4. Add the code to `LocalizationTests.Languages` (`tests/Filee.App.Tests/LocalizationTests.cs`).
+5. If the script needs another font (Japanese, Arabic, …), add a static Noto font to `build/fetch-fonts.ps1`
+ and to the font list in `ThemeService` (variable fonts are not supported by Avalonia).
+6. Run `dotnet test` and look at the screenshots in `tests/Filee.App.Tests/bin/.../screenshots`
+ (add your language to `RenderTests.Pages` to render a few pages).
+
+Missing keys fall back to English at runtime, but the test suite requires every language to be complete.
+
+Optional, but welcome in the same or a later pull request: a translated README. Add `README.<code>.md` and link
+it from the language line at the top of the other READMEs.
+
+## Adding a UI string
+
+Add the key to **all** language files in the same pull request. In XAML use
+`Text="{DynamicResource my.key}"`; in code use `ILocalizer["my.key"]` or `ILocalizer.Format("my.key", arg)`.
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
new file mode 100644
index 00000000..47f1b5e7
--- /dev/null
+++ b/docs/ARCHITECTURE.md
@@ -0,0 +1,67 @@
+# Architecture
+
+```
+ ┌──────────────────────────── Filee.App (Avalonia) ─────────────────────────────┐
+ global │ TriggerService ──► GestureDetector ──► RadialController ──► RadialWindow/DonutMenu │
+ mouse/keys │ (SharpHook) (pure state (drag / click (transparent, │
+ ─────────► │ machine) mode) topmost window) │
+ │ │ drop / click │
+ Explorer │ SingleInstance (pipe) ── --convert files ──►│ │
+ context │ Home drop zone ─────────────────────────────┘ │
+ menu │ ▼ │
+ │ ConversionService ──► ToastWindow (progress) │
+ │ MainWindow (settings pages) ◄──► UserDataStore (JSON in %APPDATA%\Filee) │
+ └──────────────────────────────────────────────┬──────────────────────────────────────┘
+ ▼
+ ┌──────────────────────────── Filee.Core ───────────────────────────────────────────┐
+ │ JobQueue ──► RoutePlanner (Dijkstra over converter edges) ──► IConverter steps │
+ │ FormatRegistry · Preset · OutputPathResolver · ToolbarProfile · ProfileSelector │
+ └──────────────────────────────────────────────┬──────────────────────────────────────┘
+ ▼
+ ┌──────────────────────────── 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 / Pandoc AST → HWPX) · Pandoc · Word COM · EngineInstaller │
+ └────────────────────────────────────────────────────────────────────────────────────┘
+```
+
+## Flow of a conversion
+
+1. **Trigger** – `TriggerService` receives global input from SharpHook and feeds `GestureDetector`.
+ A drag gesture (modifier + drag past the threshold) opens the donut *before* files are known.
+2. **Donut** – `RadialWindow` is transparent, topmost and not activated, so Explorer's drag continues.
+ The first `DragEnter` delivers the file list; `RadialViewModel` picks a `ToolbarProfile` by extension
+ (`ProfileSelector`) and asks `PresetAvailability` which presets can run (disabled slices get a reason).
+3. **Drop** – the slice under the cursor is a preset. `ConversionService.Start` enqueues a `ConversionJob`.
+ The drop is always reported as *Copy* so Explorer never deletes the source files.
+4. **Plan** – for every file, `RoutePlanner` finds the cheapest chain of converter edges from the source format to
+ the target (at most 3 hops). Engine priority (Settings → Engines) breaks ties.
+5. **Run** – `JobQueue` runs steps with per-engine concurrency limits. Intermediate files live in a temp folder;
+ final outputs are named by `OutputPathResolver` (pattern, folder, conflict policy; the source is never overwritten).
+ "Merge into one PDF" converts each file to PDF and merges with PDFsharp.
+6. **Report** – progress and results appear in the toast window and in Home → Recent conversions.
+
+## Donut control
+
+`Controls/DonutMenu.cs` draws the ring itself (no child controls) for speed. `DonutGeometry.cs` holds the pure math
+(slice angles, hit testing) and is unit tested. The same control is the live toolbar and, with `IsEditMode`, the
+editor on the *Donut toolbar* settings page (drag to reorder, ✎ / right-click to edit).
+Animations are small springs advanced per frame; `Motion.Enabled == false` (*Reduce animations*) snaps them.
+
+## Settings and data
+
+`UserDataStore` owns `settings.json`, `presets.json`, `profiles.json` and `history.json`
+(System.Text.Json source generation, atomic writes, broken files are kept as `*.broken`).
+Bump `AppSettings.CurrentSchemaVersion` and add a step to `SettingsMigrations` when the format changes.
+
+## Localization and theming
+
+- `LocalizationService` loads `Assets/i18n/<lang>.json` into `Application.Resources`; XAML uses
+ `{DynamicResource key}`, so switching language updates the UI live.
+- `ThemeService` writes the accent colour, corner radii, fonts and Fluent's `SystemAccentColor*` into
+ application resources. Light/dark surface colours are theme dictionaries in `Styles/Soft.axaml`.
+
+## Platform code
+
+Everything OS-specific goes through `IPlatformServices` (`Filee.Core/Platform`). Windows lives in
+`Filee.Platform.Windows`; macOS will get its own project. Global input uses SharpHook on both.
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
new file mode 100644
index 00000000..ac54550e
--- /dev/null
+++ b/docs/ENGINES.md
@@ -0,0 +1,85 @@
+# 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.
+
+| Engine | How it gets there | Handles |
+|---|---|---|
+| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF ↔ each other; HEIC read |
+| PDFsharp | built in (library) | images → PDF, merge, split, page ranges |
+| PDFium | built in (library) | PDF → images (multi-page TIFF/GIF supported) |
+| Unhwp | built in (library) | HWP/HWPX → TXT, Markdown, HTML |
+| **HWPX writer** | built in | **DOCX, TXT → HWPX**; Markdown, 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 |
+| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/HTML/RTF, 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.
+
+## Optional engines
+
+The installer contains only the small engines. On first start Filee asks which of the large ones to download;
+they can be installed or removed later in Settings → *Engines*. A conversion that needs a missing engine shows
+"Needs LibreOffice …" on its donut slice.
+
+- Downloads are pinned in `src/Filee.Engines/Infrastructure/engines.json` (URL, SHA-256, size). The same file is
+ read by `build/fetch-engines.ps1`, so development and the app always use the same versions.
+- `EngineInstaller` verifies the SHA-256 before unpacking and unpacks into a staging folder that replaces the
+ engine folder only when complete. Redirects to mirrors (even plain HTTP) are followed, because the hash decides.
+- Engines go to `%LOCALAPPDATA%\Filee\engines`: outside the app folder, so updates keep them, and inside Filee's
+ install root, so uninstalling removes them.
+- LibreOffice comes as an MSI and is unpacked with an administrative install (`msiexec /a`): files only, no
+ registry entries, no admin rights. Help, gallery and most dictionaries are removed afterwards (~500 MB).
+
+To bump a version, change `url`, `sha256` and `size` in engines.json together, run
+`pwsh build/fetch-engines.ps1`, test, and update `THIRD-PARTY-NOTICES.md`. When the LibreOffice team retires a
+version from `download.documentfoundation.org/libreoffice/stable/`, its URL stops working: keep the pinned version
+current.
+
+## HWPX writer
+
+Filee writes OWPML (HWPX) itself, so saving as HWPX needs no Hancom Office and shows no approval dialog.
+Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) and `HwpxWriter` writes the package:
+
+- **DOCX** is read directly (`Hwp/Hwpx/Docx/DocxReader*.cs`) so the layout survives:
+ - page size, orientation and margins per section; columns, also when they change mid-page;
+ - headers and footers (odd/even pages, hidden on the first page) with page numbers and page counts;
+ - paragraph formatting (alignment, indents, spacing, line spacing, tab stops, keep with next);
+ - character formatting (fonts incl. theme fonts, size, colour, highlight and shading, bold/italic/underline/strike, super/subscript, spacing);
+ - lists with Word's numbering formats (1., 가., ①, i., bullets);
+ - tables with merged cells, column widths, borders and shading from the table style and cells, repeated header rows;
+ - 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.
+- **TXT** needs no reader (one paragraph per line; UTF-8, UTF-16 or the Korean code page CP949).
+- **Markdown, HTML, ODT, RTF** are parsed by Pandoc into its JSON AST (`PandocAstReader.cs`, following
+ [pypandoc-hwpx](https://github.com/msjang/pypandoc-hwpx)). Pandoc keeps structure only, so page setup comes from
+ the built-in template (A4).
+
+Element order and attribute values follow files saved by 한글 where the schema and 한글 disagree, for example:
+
+- `hp:default` repeats paragraph margins and fixed line spacing doubled (`hp:case` holds the real values);
+- page width/height are always those of the portrait sheet, `landscape="NARROWLY"` turns it;
+- 한글 keeps a hanging paragraph's first line at `left` and indents the other lines;
+- object offsets are unsigned: objects reaching into the margin are anchored to the paper instead;
+- 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`.
+
+Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+
+## HWP ↔ HWPX
+
+rhwp converts between the two 한글 formats without Hancom Office (`export-hwpx` and `convert`). Anything → HWP goes
+through the HWPX writer and then rhwp.
+
+## LibreOffice
+
+- Each parallel worker gets its own profile under `%APPDATA%\Filee\libreoffice-profiles` (LibreOffice silently
+ fails when two conversions share a profile).
+- HWP/HWPX import comes from the H2Orestart extension, which is written in Java; Filee points LibreOffice at the
+ downloaded JRE (`-env:UNO_JAVA_JFW_JREHOME`).
diff --git a/docs/design/mockup.html b/docs/design/mockup.html
new file mode 100644
index 00000000..4e77719c
--- /dev/null
+++ b/docs/design/mockup.html
@@ -0,0 +1,133 @@
+<!DOCTYPE html>
+<!--
+ Filee UI mockup (design reference for contributors).
+ Interactive: switch profiles, drag chips onto the donut / slices back to the palette / slices onto each other,
+ right-click or ✎ a slice for the preset popup, toggle "reduce animations".
+ The real implementation: src/Filee.App/Controls/DonutMenu.cs and Views/Pages/ToolbarPage.axaml.
+-->
+<html lang="ko">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Filee mockup</title>
+<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3/dist/tabler-icons.min.css">
+<style>
+:root{--surface-0:#F6F5F1;--surface-1:#EFEDE6;--surface-2:#FFFFFF;--text-primary:#1F1E1D;--text-secondary:#6B6A66;--text-muted:#9C9A92;
+--border:rgba(0,0,0,.09);--border-strong:rgba(0,0,0,.18);--bg-accent:#E3E1FA;--text-accent:#3C3489;--border-accent:#7F77DD;
+--bg-success:#DDF3EA;--text-success:#0F6E56;--text-warning:#854F0B;--text-danger:#A32D2D;--radius:10px;
+font-family:"Noto Sans KR","Noto Sans",system-ui,sans-serif}
+@media (prefers-color-scheme:dark){:root{--surface-0:#1B1B19;--surface-1:#232321;--surface-2:#2C2C2A;--text-primary:#F1EFE8;--text-secondary:#B4B2A9;
+--text-muted:#888780;--border:rgba(255,255,255,.1);--border-strong:rgba(255,255,255,.2);--bg-accent:#3C3489;--text-accent:#CECBF6;--border-accent:#AFA9EC;
+--bg-success:#085041;--text-success:#9FE1CB}}
+body{margin:0;padding:24px;background:var(--surface-0);color:var(--text-primary)}
+button,select,input{font:inherit;color:inherit;background:var(--surface-2);border:1px solid var(--border-strong);border-radius:var(--radius);padding:5px 10px}
+button{cursor:pointer}
+.fxA{transform-origin:160px 160px;animation:fxin .55s cubic-bezier(.34,1.56,.64,1) both}
+@keyframes fxin{from{opacity:0;transform:scale(.55) rotate(-25deg)}to{opacity:1;transform:none}}
+.fxS{transition:transform .35s cubic-bezier(.34,1.56,.64,1);cursor:grab;touch-action:none}
+.fxS path{fill:var(--surface-2);stroke:var(--surface-1);stroke-width:2.5;transition:fill .2s}
+.fxS text{fill:var(--text-primary);font-size:12px;font-weight:600;pointer-events:none;user-select:none}
+.fxS.hot path{fill:var(--bg-accent)}.fxS.hot text{fill:var(--text-accent)}
+.fxS.drop path{fill:var(--bg-success)}.fxS.drop text{fill:var(--text-success)}.fxS.dim{opacity:.35}
+#fx.red .fxA{animation:none}#fx.red .fxS,#fx.red .fxS path{transition:none}
+.fxchip{display:inline-flex;align-items:center;gap:4px;padding:4px 10px;margin:3px;border-radius:999px;border:1px solid var(--border-strong);background:var(--surface-2);font-size:12px;cursor:grab;user-select:none;touch-action:none}
+.fxpf{display:block;width:100%;text-align:left;font-size:13px;padding:6px 8px;margin-bottom:4px}
+.fxpf.on{background:var(--bg-accent);color:var(--text-accent);border-color:var(--border-accent)}
+.fxf{display:flex;flex-direction:column;gap:3px;font-size:12px;color:var(--text-secondary)}
+</style>
+</head>
+<body>
+<div id="fx" style="position:relative;max-width:760px;margin:0 auto">
+<div style="border:1px solid var(--border);border-radius:14px;overflow:hidden;background:var(--surface-2)">
+ <div style="display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid var(--border);background:var(--surface-1);flex-wrap:wrap">
+ <i class="ti ti-circle-dashed"></i><span style="font-size:13px;font-weight:600">Filee 설정 · 원형 툴바</span>
+ <span style="margin-left:auto;display:flex;gap:8px;align-items:center">
+ <label style="font-size:12px;color:var(--text-secondary)"><input type="checkbox" id="fxred"> 애니메이션 줄이기</label>
+ <button id="fxplay" style="font-size:12px"><i class="ti ti-player-play"></i> 열기 재생</button>
+ </span>
+ </div>
+ <div id="fxed" style="position:relative;display:grid;grid-template-columns:130px 320px minmax(0,1fr);gap:14px;padding:14px;min-height:440px;background:var(--surface-1)">
+ <div>
+ <p style="font-size:12px;color:var(--text-secondary);margin:0 0 6px">1. 프로필 선택</p>
+ <div id="fxprof"></div>
+ <button id="fxadd" class="fxpf" style="border-style:dashed;color:var(--text-secondary)"><i class="ti ti-plus"></i> 새 프로필</button>
+ </div>
+ <div>
+ <p style="font-size:12px;color:var(--text-secondary);margin:0 0 6px">2. 프리셋 배치 (실제 툴바와 동일한 모양)</p>
+ <div id="fxw" style="position:relative;width:320px;height:320px">
+ <svg id="fxsvg" width="320" height="320" viewBox="0 0 320 320" style="overflow:visible"></svg>
+ <button id="fxpen" aria-label="프리셋 편집" style="position:absolute;width:28px;height:28px;padding:0;border-radius:50%;visibility:hidden;display:flex;align-items:center;justify-content:center"><i class="ti ti-pencil" style="font-size:15px"></i></button>
+ </div>
+ <p id="fxext" style="font-size:12px;color:var(--text-secondary);margin:6px 0 0"></p>
+ <p id="fxmsg" style="font-size:12px;color:var(--text-warning);margin:2px 0 0;min-height:16px"></p>
+ </div>
+ <div>
+ <p style="font-size:12px;color:var(--text-secondary);margin:0 0 6px">사용 가능한 프리셋</p>
+ <div id="fxpal" style="min-height:120px;padding:4px;border-radius:var(--radius);border:1px dashed var(--border-strong);background:var(--surface-2)"></div>
+ <div style="font-size:12px;color:var(--text-secondary);line-height:1.7;margin-top:10px">
+ <div><i class="ti ti-drag-drop"></i> 칩을 도넛으로 끌면 추가</div>
+ <div><i class="ti ti-arrow-back-up"></i> 세그먼트를 여기로 끌면 빼기</div>
+ <div><i class="ti ti-arrows-sort"></i> 세그먼트끼리 끌면 순서 변경</div>
+ <div><i class="ti ti-pencil"></i> 우클릭 또는 연필 = 프리셋 편집</div>
+ </div>
+ </div>
+ </div>
+</div>
+<div id="fxgh" style="position:absolute;pointer-events:none;visibility:hidden;z-index:9" class="fxchip"></div>
+</div>
+<script>
+const P={image:{name:'이미지',ext:'jpg, jpeg, png, bmp, tiff, webp, gif, heic',on:['PNG','WEBP','PDF','TIFF','BMP','ICO','JPG 70%','50% 축소'],off:['GIF','AVIF','흑백 PNG','300dpi TIFF']},pdf:{name:'PDF',ext:'pdf',on:['PNG','JPG','DOCX','HWPX','TXT','PDF 분할','PDF 압축'],off:['TIFF','PDF/A','JPG 150dpi']},doc:{name:'오피스 문서',ext:'docx, doc, odt, rtf, xlsx, pptx',on:['PDF','ODT','HWPX','TXT','HTML'],off:['RTF','DOC','PDF/A']},hwp:{name:'HWP/HWPX',ext:'hwp, hwpx',on:['PDF','DOCX','PNG','TXT','HWPX'],off:['ODT','HTML','Markdown']}};
+const DET={},FM=['PNG','JPG','WEBP','TIFF','BMP','ICO','GIF','AVIF','PDF','DOCX','ODT','HWPX','TXT','HTML','RTF','DOC','MARKDOWN'];
+let cur='image',hov=-1,pd=null,nid=0;
+const NS='http://www.w3.org/2000/svg',C=160,R2=152,R1=62,$=i=>document.getElementById(i);
+const svg=$('fxsvg'),pen=$('fxpen'),pal=$('fxpal'),gh=$('fxgh'),root=$('fx'),wrap=$('fxw');
+const pt=(r,a)=>[C+r*Math.cos(a),C+r*Math.sin(a)];
+function seg(i,n){if(n===1)return `M${C-R2} ${C}A${R2} ${R2} 0 1 0 ${C+R2} ${C}A${R2} ${R2} 0 1 0 ${C-R2} ${C}M${C-R1} ${C}A${R1} ${R1} 0 1 1 ${C+R1} ${C}A${R1} ${R1} 0 1 1 ${C-R1} ${C}Z`;const sp=2*Math.PI/n,s=-Math.PI/2+i*sp-sp/2,e=s+sp,[a,b]=pt(R2,s),[c,d]=pt(R2,e),[f,g]=pt(R1,e),[h,k]=pt(R1,s);return `M${a} ${b}A${R2} ${R2} 0 0 1 ${c} ${d}L${f} ${g}A${R1} ${R1} 0 0 0 ${h} ${k}Z`}
+function el(t,a){const e=document.createElementNS(NS,t);for(const k in a)e.setAttribute(k,a[k]);return e}
+function render(anim){const p=P[cur],n=p.on.length;svg.innerHTML='';
+if(!n)svg.append(el('circle',{cx:C,cy:C,r:(R1+R2)/2,fill:'none','stroke-width':R2-R1,style:'stroke:var(--surface-2)'}));
+p.on.forEach((t,i)=>{const A=el('g',{class:'fxA'});A.style.animationDelay=(i*30)+'ms';if(!anim)A.style.animation='none';const S=el('g',{class:'fxS','data-seg':i});const pa=el('path',{d:seg(i,n)});if(n===1)pa.setAttribute('fill-rule','evenodd');const m=-Math.PI/2+i*2*Math.PI/n,[x,y]=n===1?[C,C-(R1+R2)/2]:pt(102,m);const tx=el('text',{x,y,'text-anchor':'middle','dominant-baseline':'central'});tx.textContent=t;S.append(pa,tx);A.append(S);svg.append(A);
+S.addEventListener('pointerenter',()=>setHov(i));S.addEventListener('pointerdown',e=>{if(e.button)return;e.preventDefault();pd={from:'on',idx:i,val:t,x:e.clientX,y:e.clientY,act:false}});S.addEventListener('contextmenu',e=>{e.preventDefault();openPop(i)})});
+const t1=el('text',{x:C,y:C-8,'text-anchor':'middle',style:'fill:var(--text-primary);font-size:14px;font-weight:600'});t1.textContent=p.name;const t2=el('text',{x:C,y:C+14,'text-anchor':'middle',style:'fill:var(--text-secondary);font-size:12px'});t2.textContent=n?n+' / 12':'여기로 끌어 놓기';svg.append(t1,t2);
+$('fxext').textContent='매칭 확장자: '+p.ext;
+$('fxprof').innerHTML='';Object.keys(P).forEach(k=>{const b=document.createElement('button');b.className='fxpf'+(k===cur?' on':'');b.textContent=P[k].name;b.onclick=()=>{cur=k;render(true)};$('fxprof').append(b)});
+pal.innerHTML='';p.off.forEach((t,i)=>{const c=document.createElement('span');c.className='fxchip';c.innerHTML='<i class="ti ti-grip-vertical"></i>'+t;c.onpointerdown=e=>{if(e.button)return;e.preventDefault();pd={from:'off',idx:i,val:t,x:e.clientX,y:e.clientY,act:false}};pal.append(c)});
+hov=-1;pen.style.visibility='hidden'}
+function clearHot(){svg.querySelectorAll('.fxS').forEach(s=>{s.classList.remove('hot');s.style.transform=''})}
+function setHov(i){if(pd&&pd.act)return;hov=i;const n=P[cur].on.length;clearHot();const s=svg.querySelector(`[data-seg="${i}"]`);s.classList.add('hot');const m=-Math.PI/2+i*2*Math.PI/n;if(n>1)s.style.transform=`translate(${Math.cos(m)*6}px,${Math.sin(m)*6}px)`;const [x,y]=n===1?[C,C-138]:pt(140,m);pen.style.left=(x-14)+'px';pen.style.top=(y-14)+'px';pen.style.visibility='visible'}
+wrap.addEventListener('pointerleave',()=>{if(pd&&pd.act)return;hov=-1;clearHot();pen.style.visibility='hidden'});
+pen.addEventListener('pointerdown',e=>e.stopPropagation());pen.onclick=()=>openPop(hov);
+function flash(t){$('fxmsg').textContent=t;setTimeout(()=>$('fxmsg').textContent='',1600)}
+document.addEventListener('pointermove',e=>{if(!pd)return;if(!pd.act&&Math.hypot(e.clientX-pd.x,e.clientY-pd.y)>5){pd.act=true;gh.textContent=pd.val;gh.style.visibility='visible';pen.style.visibility='hidden';clearHot();if(pd.from==='on')svg.querySelector(`[data-seg="${pd.idx}"]`).classList.add('dim')}if(!pd.act)return;const r=root.getBoundingClientRect();gh.style.left=(e.clientX-r.left+10)+'px';gh.style.top=(e.clientY-r.top+10)+'px';svg.querySelectorAll('.fxS').forEach(s=>s.classList.remove('drop'));const t=document.elementFromPoint(e.clientX,e.clientY),g=t&&t.closest('[data-seg]');if(g)g.classList.add('drop');pal.style.borderColor=(t&&t.closest('#fxpal')&&pd.from==='on')?'var(--border-accent)':''});
+document.addEventListener('pointerup',e=>{if(!pd)return;const d=pd;pd=null;gh.style.visibility='hidden';pal.style.borderColor='';if(!d.act)return;const t=document.elementFromPoint(e.clientX,e.clientY),g=t&&t.closest('[data-seg]'),inPal=t&&t.closest('#fxpal'),inD=t&&t.closest('#fxw'),p=P[cur];
+if(d.from==='on'){if(inPal){p.on.splice(d.idx,1);p.off.push(d.val)}else if(g){const ti=+g.dataset.seg;p.on.splice(d.idx,1);p.on.splice(ti,0,d.val)}}
+else if(g||inD){if(p.on.length>=12)flash('최대 12개까지 넣을 수 있어요');else{p.off.splice(d.idx,1);p.on.splice(g?+g.dataset.seg:p.on.length,0,d.val)}}
+render(false)});
+function openPop(i){if(i<0)return;const p=P[cur],nm=p.on[i],u=nm.toUpperCase(),d=DET[nm]||{fmt:FM.find(f=>u.includes(f))||'PNG',q:80,size:'원본',loc:'원본 폴더',pat:'{name}_{preset}',cf:'번호 붙이기',exif:true};
+const sel=(id,arr,v)=>`<select id="${id}" style="font-size:12px;width:100%">${arr.map(o=>`<option${o===v?' selected':''}>${o}</option>`).join('')}</select>`;
+const ov=document.createElement('div');ov.style.cssText='position:absolute;inset:0;background:rgba(0,0,0,.35);display:flex;align-items:center;justify-content:center;z-index:5';
+ov.innerHTML=`<div style="background:var(--surface-2);border:1px solid var(--border);border-radius:14px;padding:14px 16px;width:380px;font-size:13px">
+<div style="display:flex;align-items:center;gap:6px;font-weight:600;margin-bottom:10px"><i class="ti ti-pencil"></i>프리셋 편집<span style="margin-left:auto;font-size:11px;font-weight:400;color:var(--text-muted)">프리셋 화면과 같은 편집기</span></div>
+<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
+<label class="fxf" style="grid-column:1/3">이름<input id="fpN" value="${nm}" style="width:100%;box-sizing:border-box"><span id="fpE" style="font-size:12px;color:var(--text-danger)"></span></label>
+<label class="fxf">대상 형식${sel('fpF',FM,d.fmt)}</label>
+<label class="fxf">크기${sel('fpZ',['원본','50%','긴 변 1920px','긴 변 1280px'],d.size)}</label>
+<label class="fxf" style="grid-column:1/3">품질 <span style="display:flex;gap:8px;align-items:center"><input type="range" id="fpQ" min="10" max="100" step="1" value="${d.q}" style="flex:1"><span id="fpQo" style="min-width:28px;color:var(--text-primary)">${d.q}</span></span></label>
+<label class="fxf">저장 위치${sel('fpL',['원본 폴더','하위 converted','지정 폴더…'],d.loc)}</label>
+<label class="fxf">이름 충돌 시${sel('fpC2',['번호 붙이기','덮어쓰기','건너뛰기'],d.cf)}</label>
+<label class="fxf" style="grid-column:1/3">파일명 패턴<input id="fpP" value="${d.pat}" style="width:100%;box-sizing:border-box"></label>
+<label style="grid-column:1/3;font-size:12px;color:var(--text-secondary)"><input type="checkbox" id="fpX"${d.exif?' checked':''}> 메타데이터(EXIF) 유지</label>
+</div>
+<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px"><button id="fpCa">취소</button><button id="fpSv">저장</button></div></div>`;
+$('fxed').append(ov);const close=()=>ov.remove();
+ov.addEventListener('pointerdown',e=>{if(e.target===ov)close()});$('fpCa').onclick=close;
+$('fpQ').oninput=e=>$('fpQo').textContent=e.target.value;$('fpN').oninput=()=>$('fpE').textContent='';
+$('fpSv').onclick=()=>{const v=$('fpN').value.trim();if(!v){$('fpE').textContent='이름을 입력하세요';return}if(p.on.some((x,j)=>x===v&&j!==i)){$('fpE').textContent='이미 있는 프리셋 이름이에요';return}
+DET[v]={fmt:$('fpF').value,q:+$('fpQ').value,size:$('fpZ').value,loc:$('fpL').value,pat:$('fpP').value,cf:$('fpC2').value,exif:$('fpX').checked};p.on[i]=v;close();render(false)}}
+$('fxadd').onclick=()=>{const k='c'+(++nid);P[k]={name:'새 프로필 '+nid,ext:'(편집 가능)',on:[],off:['PNG','JPG','PDF','WEBP','TXT','DOCX']};cur=k;render(true)};
+$('fxplay').onclick=()=>render(true);
+$('fxred').onchange=e=>root.classList.toggle('red',e.target.checked);
+render(true);
+</script>
+</body>
+</html>
diff --git a/docs/media/banner-en.jpg b/docs/media/banner-en.jpg
new file mode 100644
index 00000000..1eae52fb
Binary files /dev/null and b/docs/media/banner-en.jpg differ
diff --git a/docs/media/banner-ko.jpg b/docs/media/banner-ko.jpg
new file mode 100644
index 00000000..2d979e3b
Binary files /dev/null and b/docs/media/banner-ko.jpg differ
diff --git a/docs/media/banner-zh-CN.jpg b/docs/media/banner-zh-CN.jpg
new file mode 100644
index 00000000..3b070d4b
Binary files /dev/null and b/docs/media/banner-zh-CN.jpg differ
diff --git a/docs/media/demo-en.webp b/docs/media/demo-en.webp
new file mode 100644
index 00000000..3b5f905d
Binary files /dev/null and b/docs/media/demo-en.webp differ
diff --git a/docs/media/demo-ko.webp b/docs/media/demo-ko.webp
new file mode 100644
index 00000000..d7bfa0b5
Binary files /dev/null and b/docs/media/demo-ko.webp differ
diff --git a/docs/media/demo-zh-CN.webp b/docs/media/demo-zh-CN.webp
new file mode 100644
index 00000000..a3831ff9
Binary files /dev/null and b/docs/media/demo-zh-CN.webp differ
diff --git a/docs/media/engine-setup-en.png b/docs/media/engine-setup-en.png
new file mode 100644
index 00000000..6e2876d2
Binary files /dev/null and b/docs/media/engine-setup-en.png differ
diff --git a/docs/media/engine-setup-ko.png b/docs/media/engine-setup-ko.png
new file mode 100644
index 00000000..0c5b83d6
Binary files /dev/null and b/docs/media/engine-setup-ko.png differ
diff --git a/docs/media/page-home-en.png b/docs/media/page-home-en.png
new file mode 100644
index 00000000..87cb5a6a
Binary files /dev/null and b/docs/media/page-home-en.png differ
diff --git a/docs/media/page-home-ko.png b/docs/media/page-home-ko.png
new file mode 100644
index 00000000..7a3d1fe5
Binary files /dev/null and b/docs/media/page-home-ko.png differ
diff --git a/docs/media/page-home-zh-CN.png b/docs/media/page-home-zh-CN.png
new file mode 100644
index 00000000..54c34844
Binary files /dev/null and b/docs/media/page-home-zh-CN.png differ
diff --git a/docs/media/page-presets-en.png b/docs/media/page-presets-en.png
new file mode 100644
index 00000000..90dbfeaf
Binary files /dev/null and b/docs/media/page-presets-en.png differ
diff --git a/docs/media/page-presets-zh-CN.png b/docs/media/page-presets-zh-CN.png
new file mode 100644
index 00000000..099bbcfe
Binary files /dev/null and b/docs/media/page-presets-zh-CN.png differ
diff --git a/docs/media/page-toolbar-dark.png b/docs/media/page-toolbar-dark.png
new file mode 100644
index 00000000..4e996544
Binary files /dev/null and b/docs/media/page-toolbar-dark.png differ
diff --git a/docs/media/page-toolbar-en.png b/docs/media/page-toolbar-en.png
new file mode 100644
index 00000000..2c15a170
Binary files /dev/null and b/docs/media/page-toolbar-en.png differ
diff --git a/docs/media/page-toolbar-ko.png b/docs/media/page-toolbar-ko.png
new file mode 100644
index 00000000..e55c383a
Binary files /dev/null and b/docs/media/page-toolbar-ko.png differ
diff --git a/docs/media/page-toolbar-zh-CN.png b/docs/media/page-toolbar-zh-CN.png
new file mode 100644
index 00000000..4533e515
Binary files /dev/null and b/docs/media/page-toolbar-zh-CN.png differ
diff --git a/docs/media/preset-popup-ko.png b/docs/media/preset-popup-ko.png
new file mode 100644
index 00000000..8f5af23e
Binary files /dev/null and b/docs/media/preset-popup-ko.png differ
diff --git a/docs/media/social-preview.jpg b/docs/media/social-preview.jpg
new file mode 100644
index 00000000..1eae52fb
Binary files /dev/null and b/docs/media/social-preview.jpg differ
diff --git a/global.json b/global.json
new file mode 100644
index 00000000..512142d2
--- /dev/null
+++ b/global.json
@@ -0,0 +1,6 @@
+{
+ "sdk": {
+ "version": "10.0.100",
+ "rollForward": "latestFeature"
+ }
+}
diff --git a/src/Filee.App/App.axaml b/src/Filee.App/App.axaml
new file mode 100644
index 00000000..5fd35174
--- /dev/null
+++ b/src/Filee.App/App.axaml
@@ -0,0 +1,25 @@
+<Application xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:local="using:Filee.App"
+ x:Class="Filee.App.App"
+ Name="Filee"
+ RequestedThemeVariant="Default">
+
+ <Application.DataTemplates>
+ <!-- Maps FooPageViewModel → FooPage view (see ViewLocator.cs). -->
+ <local:ViewLocator />
+ </Application.DataTemplates>
+
+ <Application.Resources>
+ <ResourceDictionary>
+ <ResourceDictionary.MergedDictionaries>
+ <ResourceInclude Source="avares://Filee/Styles/Icons.axaml" />
+ </ResourceDictionary.MergedDictionaries>
+ </ResourceDictionary>
+ </Application.Resources>
+
+ <Application.Styles>
+ <FluentTheme />
+ <StyleInclude Source="avares://Filee/Styles/Soft.axaml" />
+ </Application.Styles>
+</Application>
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.cs
new file mode 100644
index 00000000..832513c8
--- /dev/null
+++ b/src/Filee.App/App.axaml.cs
@@ -0,0 +1,158 @@
+// Application start-up: builds services, applies settings, wires global gestures to the donut toolbar.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Markup.Xaml;
+using Avalonia.Threading;
+using Filee.App.Services;
+using Filee.App.Services.Triggers;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App;
+
+public partial class App : Application
+{
+ private readonly List<string> _pendingConvertFiles = [];
+ private IDisposable? _convertDebounce;
+
+ public override void Initialize() => AvaloniaXamlLoader.Load(this);
+
+ public override void OnFrameworkInitializationCompleted()
+ {
+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
+ {
+ AppHost.Build();
+ Start(desktop);
+ }
+ base.OnFrameworkInitializationCompleted();
+ }
+
+ private void Start(IClassicDesktopStyleApplicationLifetime desktop)
+ {
+ var log = AppHost.Get<ILogger<App>>();
+ var store = AppHost.Get<UserDataStore>();
+ store.Load();
+
+ var loc = AppHost.Get<LocalizationService>();
+ loc.Attach(this);
+ ApplySettings(store.Settings);
+
+ // Global gestures → donut toolbar
+ var triggers = AppHost.Get<TriggerService>();
+ var radial = AppHost.Get<RadialController>();
+ var platform = AppHost.Get<IPlatformServices>();
+ triggers.DragStarted += (_, e) => radial.ShowForDrag(e.X, e.Y);
+ triggers.DragEnded += (_, _) => radial.OnDragGestureEnded();
+ triggers.SelectionGesture += (_, e) =>
+ {
+ var files = platform.GetFileManagerSelection();
+ if (files.Count > 0)
+ radial.ShowForFiles(e.X, e.Y, files);
+ };
+ triggers.Start();
+ log.LogInformation("Filee {Version} started", UpdateService.CurrentVersion);
+
+ store.SettingsChanged += (_, _) => ApplySettings(store.Settings);
+
+ AppHost.Get<TrayService>().Create(this);
+ AppHost.Get<WindowService>().EnsureToast();
+
+ // Later launches (context menu, Send To, double-clicking the exe) forward their arguments here.
+ if (Program.Instance is { } instance)
+ {
+ instance.ArgumentsReceived += args => Dispatcher.UIThread.Post(() => HandleCommandLine(CommandLine.Parse(args)));
+ instance.StartListening();
+ }
+
+ desktop.Exit += (_, _) =>
+ {
+ AppHost.Get<TriggerService>().Dispose();
+ AppHost.Get<TrayService>().Dispose();
+ };
+
+ HandleCommandLine(Program.Options, firstLaunch: true);
+ _ = CheckForUpdatesAsync(store.Settings);
+ }
+
+ /// <summary>Applies everything derived from settings. Called at start-up and whenever settings are saved.</summary>
+ private static void ApplySettings(AppSettings settings)
+ {
+ var loc = AppHost.Get<LocalizationService>();
+ if (loc.NeedsUpdate(settings.Language))
+ loc.SetLanguage(settings.Language);
+
+ AppHost.Get<ThemeService>().Apply(settings.Theme, loc.Language);
+ AppHost.Get<TriggerService>().Apply(settings);
+ AppHost.Get<ConverterCatalog>().Priority = settings.EnginePriority;
+ ApplySystemIntegration(settings, loc);
+ }
+
+ /// <summary>Keeps registry entries in sync with settings (idempotent; paths follow updates).</summary>
+ private static void ApplySystemIntegration(AppSettings settings, ILocalizer loc)
+ {
+ var exe = Environment.ProcessPath;
+ if (exe is null || !OperatingSystem.IsWindows())
+ return;
+ // When running from the IDE (bin\Debug) don't touch the user's Explorer / startup settings.
+ if (!AppHost.Get<UpdateService>().IsInstalled)
+ return;
+ try
+ {
+ var platform = AppHost.Get<IPlatformServices>();
+ platform.SetStartWithSystem(settings.StartWithSystem, exe);
+ platform.SetContextMenu(settings.ContextMenuEnabled, exe, loc["general.context_menu_label"]);
+ }
+ catch (Exception ex)
+ {
+ AppHost.Get<ILogger<App>>().LogWarning(ex, "Could not update system integration");
+ }
+ }
+
+ private void HandleCommandLine(CommandLine options, bool firstLaunch = false)
+ {
+ if (options.ConvertFiles.Count > 0)
+ {
+ // Explorer may start one process per selected file: collect them for a moment, then open once.
+ _pendingConvertFiles.AddRange(options.ConvertFiles);
+ _convertDebounce?.Dispose();
+ _convertDebounce = DispatcherTimer.RunOnce(OpenPendingFiles, TimeSpan.FromMilliseconds(350));
+ return;
+ }
+
+ var store = AppHost.Get<UserDataStore>();
+ if (!options.Background || options.ShowSettings || !firstLaunch)
+ AppHost.Get<WindowService>().ShowMain(store.Settings.FirstRunCompleted ? null : "home");
+
+ if (!store.Settings.FirstRunCompleted)
+ {
+ // The installer only contains the small engines: offer the large ones right after installing.
+ if (AppHost.Get<EngineDownloadService>().Packages.Any(p => !p.IsInstalled))
+ AppHost.Get<WindowService>().ShowEngineSetup();
+ store.Settings.FirstRunCompleted = true;
+ store.SaveSettings();
+ }
+ }
+
+ private void OpenPendingFiles()
+ {
+ var files = _pendingConvertFiles.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
+ _pendingConvertFiles.Clear();
+ var (x, y) = AppHost.Get<TriggerService>().LastCursor;
+ if (x == 0 && y == 0 && AppHost.Get<WindowService>().Main is { } main)
+ (x, y) = (main.Position.X + 200, main.Position.Y + 200);
+ AppHost.Get<RadialController>().ShowForFiles(x, y, files);
+ }
+
+ private static async Task CheckForUpdatesAsync(AppSettings settings)
+ {
+ if (!settings.CheckForUpdates)
+ return;
+ await Task.Delay(TimeSpan.FromSeconds(20));
+ await AppHost.Get<UpdateService>().CheckAsync();
+ }
+}
diff --git a/src/Filee.App/Assets/Icons/filee.ico b/src/Filee.App/Assets/Icons/filee.ico
new file mode 100644
index 00000000..83a3d183
Binary files /dev/null and b/src/Filee.App/Assets/Icons/filee.ico differ
diff --git a/src/Filee.App/Assets/Icons/filee.png b/src/Filee.App/Assets/Icons/filee.png
new file mode 100644
index 00000000..6948299c
Binary files /dev/null and b/src/Filee.App/Assets/Icons/filee.png differ
diff --git a/src/Filee.App/Assets/Icons/filee.svg b/src/Filee.App/Assets/Icons/filee.svg
new file mode 100644
index 00000000..be4afebd
--- /dev/null
+++ b/src/Filee.App/Assets/Icons/filee.svg
@@ -0,0 +1 @@
+<svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path transform='translate(0,-0)' fill='#7F77DD' d='M154.61 65.27 A216 216 0 0 1 357.39 65.27 L304.82 164.17 A104 104 0 0 0 207.18 164.17 Z'/><path transform='translate(13.86,-8)' fill='#1D9E75' d='M373.66 67.74 A222 222 0 0 1 477.86 248.23 L359.94 252.36 A104 104 0 0 0 311.12 167.81 Z'/><path transform='translate(0,0)' fill='#7F77DD' d='M471.87 263.56 A216 216 0 0 1 370.48 439.17 L311.12 344.19 A104 104 0 0 0 359.94 259.64 Z'/><path transform='translate(0,0)' fill='#6A62C9' d='M357.39 446.73 A216 216 0 0 1 154.61 446.73 L207.18 347.83 A104 104 0 0 0 304.82 347.83 Z'/><path transform='translate(-0,0)' fill='#7F77DD' d='M141.52 439.17 A216 216 0 0 1 40.13 263.56 L152.06 259.64 A104 104 0 0 0 200.88 344.19 Z'/><path transform='translate(-0,-0)' fill='#6A62C9' d='M40.13 248.44 A216 216 0 0 1 141.52 72.83 L200.88 167.81 A104 104 0 0 0 152.06 252.36 Z'/><path fill='#3C3489' d='M222 212 h44 l24 24 v64 h-68 z'/><path fill='#AFA9EC' d='M266 212 v24 h24 z'/></svg>
\ No newline at end of file
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
new file mode 100644
index 00000000..5c15a081
--- /dev/null
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -0,0 +1,266 @@
+{
+ "app.name": "Filee",
+ "app.tagline": "Drag, drop, converted.",
+
+ "nav.home": "Home",
+ "nav.general": "General",
+ "nav.triggers": "Shortcuts",
+ "nav.toolbar": "Donut toolbar",
+ "nav.presets": "Presets",
+ "nav.theme": "Theme",
+ "nav.engines": "Engines",
+ "nav.about": "About",
+
+ "tray.open": "Open Filee",
+ "tray.pause": "Pause shortcuts",
+ "tray.resume": "Resume shortcuts",
+ "tray.quit": "Quit",
+ "tray.tooltip": "Filee — hold {0} and drag files",
+
+ "home.title": "Home",
+ "home.drop_title": "Drop files here",
+ "home.drop_hint": "Or hold {0} while dragging files in Explorer — the donut toolbar opens at your cursor.",
+ "home.recent": "Recent conversions",
+ "home.recent_empty": "Your converted files will show up here.",
+ "home.open_folder": "Open folder",
+ "home.clear_history": "Clear",
+ "home.files": "{0} files",
+
+ "donut.center_drag": "Bring files here",
+ "donut.files_same": "{0} × {1}",
+ "donut.files_mixed": "{0} files",
+ "donut.drop_to": "Drop → {0}",
+ "donut.click_to": "Click → {0}",
+ "donut.cancel": "Drop here to cancel",
+ "donut.close_hint": "Esc to close",
+ "donut.edit": "Edit preset",
+ "donut.empty": "Drag presets here",
+ "donut.same_format": "Same format",
+
+ "toast.converting": "{0} → {1}",
+ "toast.done": "Done",
+ "toast.done_errors": "{0} of {1} failed",
+ "toast.failed": "Conversion failed",
+ "toast.cancelled": "Cancelled",
+ "toast.skipped": "Skipped (file exists)",
+ "toast.open_folder": "Show",
+ "toast.cancel": "Cancel",
+
+ "error.unsupported_source": "This file type isn't supported",
+ "error.no_route": "No engine can do this conversion",
+ "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.hwp": "HWP / HWPX",
+ "profile.mixed": "Mixed files",
+
+ "preset.half_size": "Half size",
+ "preset.grayscale": "Grayscale",
+ "preset.merge_pdf": "Merge PDF",
+ "preset.split_pdf": "Split PDF",
+
+ "general.title": "General",
+ "general.language": "Language",
+ "general.language_auto": "System default",
+ "general.start_with_system": "Start Filee when I sign in",
+ "general.context_menu": "Show “Convert with Filee” in the Explorer context menu",
+ "general.context_menu_label": "Convert with Filee",
+ "general.check_updates": "Check for updates automatically",
+ "general.check_now": "Check now",
+ "general.update_available": "Version {0} is available",
+ "general.update_none": "You're up to date",
+ "general.update_dev": "Updates are available in installed builds only",
+ "general.update_install": "Update and restart",
+ "general.data_folder": "Settings folder",
+ "general.open_data_folder": "Open",
+ "general.library": "Presets and toolbars",
+ "general.export": "Export…",
+ "general.import": "Import…",
+ "general.reset_library": "Reset to defaults",
+ "general.reset_confirm": "Replace all presets and toolbar profiles with the defaults?",
+ "general.imported": "Imported {0} items",
+
+ "triggers.title": "Shortcuts",
+ "triggers.description": "Choose how the donut toolbar opens. You can add as many gestures as you like.",
+ "triggers.add": "Add gesture",
+ "triggers.remove": "Remove",
+ "triggers.enabled": "On",
+ "triggers.kind": "Gesture",
+ "triggers.kind.Drag": "Modifier + drag files",
+ "triggers.kind.Hold": "Modifier + press and hold",
+ "triggers.kind.KeyChord": "Keyboard shortcut (selected files)",
+ "triggers.modifiers": "Modifier keys",
+ "triggers.button": "Mouse button",
+ "triggers.button.None": "None",
+ "triggers.button.Left": "Left",
+ "triggers.button.Right": "Right",
+ "triggers.button.Middle": "Middle",
+ "triggers.button.X1": "Back (X1)",
+ "triggers.button.X2": "Forward (X2)",
+ "triggers.key": "Key",
+ "triggers.record": "Record",
+ "triggers.recording": "Press a key combination…",
+ "triggers.clear": "Clear",
+ "triggers.threshold": "Drag distance",
+ "triggers.threshold_system": "System default",
+ "triggers.hold_ms": "Hold time",
+ "triggers.scope": "Active in",
+ "triggers.scope.FileManager": "Explorer and desktop",
+ "triggers.scope.Anywhere": "Everywhere",
+ "triggers.excluded": "Never trigger in these apps",
+ "triggers.excluded_hint": "Process names separated by commas, e.g. photoshop, code",
+ "triggers.paused": "Shortcuts are paused",
+
+ "toolbar.title": "Donut toolbar",
+ "toolbar.step_profile": "1. Choose a profile",
+ "toolbar.step_arrange": "2. Arrange presets",
+ "toolbar.add_profile": "New profile",
+ "toolbar.profile_new": "New profile",
+ "toolbar.delete_profile": "Delete profile",
+ "toolbar.name": "Name",
+ "toolbar.extensions": "Used for these extensions",
+ "toolbar.extensions_hint": "jpg, png, webp",
+ "toolbar.fallback_note": "Used when files match no other profile or several profiles.",
+ "toolbar.available": "Available presets",
+ "toolbar.hint_add": "Drag a chip onto the donut to add it",
+ "toolbar.hint_remove": "Drag a slice back here to remove it",
+ "toolbar.hint_reorder": "Drag slices onto each other to reorder",
+ "toolbar.hint_edit": "Right-click a slice or use ✎ to edit",
+ "toolbar.max_reached": "A donut holds up to {0} presets",
+ "toolbar.appearance": "Appearance",
+ "toolbar.size": "Size",
+ "toolbar.hole": "Hole",
+ "toolbar.opacity": "Opacity",
+ "toolbar.new_preset": "New preset",
+
+ "presets.title": "Presets",
+ "presets.add": "New",
+ "presets.duplicate": "Duplicate",
+ "presets.delete": "Delete",
+ "presets.save": "Save",
+ "presets.revert": "Revert",
+ "presets.name": "Name",
+ "presets.target": "Convert to",
+ "presets.same_as_source": "Same format as the source",
+ "presets.group.image": "Image",
+ "presets.quality": "Quality",
+ "presets.resize": "Resize",
+ "presets.resize.None": "Original size",
+ "presets.resize.Percent": "Scale by percent",
+ "presets.resize.LongEdge": "Limit the long edge",
+ "presets.percent": "Percent",
+ "presets.long_edge": "Long edge (px)",
+ "presets.dpi": "DPI",
+ "presets.dpi_keep": "Keep",
+ "presets.keep_metadata": "Keep metadata (EXIF)",
+ "presets.grayscale": "Grayscale",
+ "presets.background": "Background for transparency",
+ "presets.tiff_compression": "TIFF compression",
+ "presets.webp_lossless": "Lossless WEBP",
+ "presets.ico_sizes": "Icon sizes",
+ "presets.group.pdf": "PDF",
+ "presets.merge": "Merge all files into one PDF",
+ "presets.page_size": "Page size",
+ "presets.page_size.FitImage": "Fit to image",
+ "presets.page_size.A4": "A4",
+ "presets.page_size.Letter": "Letter",
+ "presets.margin": "Margin (mm)",
+ "presets.render_dpi": "Render DPI (PDF → image)",
+ "presets.page_range": "Pages",
+ "presets.page_range_hint": "All pages, or e.g. 1-3, 5",
+ "presets.split": "One file per page",
+ "presets.group.document": "Documents",
+ "presets.pdfa": "PDF/A (archival)",
+ "presets.group.output": "Output",
+ "presets.location": "Save to",
+ "presets.location.SameFolder": "Same folder as the source",
+ "presets.location.Subfolder": "A subfolder",
+ "presets.location.CustomFolder": "A fixed folder",
+ "presets.subfolder": "Subfolder name",
+ "presets.custom_folder": "Folder",
+ "presets.browse": "Browse…",
+ "presets.pattern": "File name",
+ "presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
+ "presets.conflict": "If the file exists",
+ "presets.conflict.Rename": "Add a number",
+ "presets.conflict.Overwrite": "Replace it",
+ "presets.conflict.Skip": "Skip",
+ "presets.editor_title": "Edit preset",
+ "presets.delete_confirm": "Delete “{0}”? It will also be removed from every toolbar.",
+ "presets.name_required": "Enter a name",
+ "presets.select": "Select a preset to edit it",
+
+ "theme.title": "Theme",
+ "theme.mode": "Appearance",
+ "theme.mode.System": "System",
+ "theme.mode.Light": "Light",
+ "theme.mode.Dark": "Dark",
+ "theme.accent": "Accent colour",
+ "theme.custom_color": "Custom",
+ "theme.corner_radius": "Softness",
+ "theme.reduce_motion": "Reduce animations",
+ "theme.reduce_motion_hint": "Recommended for older PCs. Turns off transitions and the donut's bounce.",
+ "theme.preview": "Preview",
+
+ "engines.title": "Conversion engines",
+ "engines.description": "Filee picks the best available engine for each conversion. Engines higher in the list win when several can do the same job.",
+ "engines.available": "Ready",
+ "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.pandoc.name": "Pandoc (Markdown and HTML)",
+ "engines.package.pandoc.description": "Markdown and HTML conversions, and Markdown, HTML, ODT and RTF → HWPX. DOCX → HWPX works without it.",
+ "engines.package.size": "Download {0} · {1} on disk",
+ "engines.install": "Install",
+ "engines.cancel": "Cancel",
+ "engines.remove": "Remove",
+ "engines.remove_confirm": "Remove {0}? You can download it again later.",
+ "engines.remove_failed": "The engine is in use. Try again after the running conversions have finished.",
+ "engines.state.not_installed": "Not installed",
+ "engines.state.queued": "Waiting…",
+ "engines.state.downloading": "Downloading {0}%",
+ "engines.state.unpacking": "Installing…",
+ "engines.state.installed": "Installed",
+ "engines.state.failed": "Failed: {0}",
+
+ "about.title": "About",
+ "about.version": "Version {0}",
+ "about.license": "Filee is free software under the MIT license.",
+ "about.notices": "Third-party notices",
+ "about.github": "GitHub repository",
+
+ "common.ok": "OK",
+ "common.cancel": "Cancel",
+ "common.save": "Save",
+ "common.close": "Close",
+ "common.delete": "Delete",
+ "common.yes": "Yes",
+ "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.note": "You can install or remove engines at any time in Settings → Engines.",
+ "setup.install": "Install selected",
+ "setup.later": "Later",
+ "setup.background": "Continue in the background",
+ "setup.done": "Done",
+ "setup.selection": "Download: {0}",
+ "setup.nothing_selected": "Nothing selected"
+}
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
new file mode 100644
index 00000000..edb6d09b
--- /dev/null
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -0,0 +1,266 @@
+{
+ "app.name": "Filee",
+ "app.tagline": "끌어서 놓으면, 변환 끝.",
+
+ "nav.home": "홈",
+ "nav.general": "일반",
+ "nav.triggers": "단축키",
+ "nav.toolbar": "원형 툴바",
+ "nav.presets": "프리셋",
+ "nav.theme": "테마",
+ "nav.engines": "변환 엔진",
+ "nav.about": "정보",
+
+ "tray.open": "Filee 열기",
+ "tray.pause": "단축키 일시 중지",
+ "tray.resume": "단축키 다시 사용",
+ "tray.quit": "종료",
+ "tray.tooltip": "Filee — {0} 누른 채 파일 드래그",
+
+ "home.title": "홈",
+ "home.drop_title": "여기에 파일을 놓으세요",
+ "home.drop_hint": "또는 탐색기에서 {0} 키를 누른 채 파일을 드래그하면 커서 위치에 원형 툴바가 열립니다.",
+ "home.recent": "최근 변환",
+ "home.recent_empty": "변환한 파일이 여기에 표시됩니다.",
+ "home.open_folder": "폴더 열기",
+ "home.clear_history": "지우기",
+ "home.files": "파일 {0}개",
+
+ "donut.center_drag": "파일을 이쪽으로",
+ "donut.files_same": "{1} {0}개",
+ "donut.files_mixed": "파일 {0}개",
+ "donut.drop_to": "놓으면 {0}(으)로",
+ "donut.click_to": "클릭하면 {0}(으)로",
+ "donut.cancel": "여기에 놓으면 취소",
+ "donut.close_hint": "Esc로 닫기",
+ "donut.edit": "프리셋 편집",
+ "donut.empty": "프리셋을 끌어다 놓으세요",
+ "donut.same_format": "같은 형식",
+
+ "toast.converting": "{0} → {1}",
+ "toast.done": "완료",
+ "toast.done_errors": "{1}개 중 {0}개 실패",
+ "toast.failed": "변환 실패",
+ "toast.cancelled": "취소됨",
+ "toast.skipped": "건너뜀 (파일이 이미 있음)",
+ "toast.open_folder": "보기",
+ "toast.cancel": "취소",
+
+ "error.unsupported_source": "지원하지 않는 파일 형식이에요",
+ "error.no_route": "이 변환을 할 수 있는 엔진이 없어요",
+ "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.hwp": "HWP / HWPX",
+ "profile.mixed": "혼합 파일",
+
+ "preset.half_size": "50% 축소",
+ "preset.grayscale": "흑백",
+ "preset.merge_pdf": "PDF 병합",
+ "preset.split_pdf": "PDF 분할",
+
+ "general.title": "일반",
+ "general.language": "언어",
+ "general.language_auto": "시스템 기본값",
+ "general.start_with_system": "로그인할 때 Filee 시작",
+ "general.context_menu": "탐색기 우클릭 메뉴에 “Filee로 변환” 표시",
+ "general.context_menu_label": "Filee로 변환",
+ "general.check_updates": "자동으로 업데이트 확인",
+ "general.check_now": "지금 확인",
+ "general.update_available": "{0} 버전을 사용할 수 있어요",
+ "general.update_none": "최신 버전이에요",
+ "general.update_dev": "업데이트는 설치된 버전에서만 사용할 수 있어요",
+ "general.update_install": "업데이트 후 다시 시작",
+ "general.data_folder": "설정 폴더",
+ "general.open_data_folder": "열기",
+ "general.library": "프리셋과 툴바",
+ "general.export": "내보내기…",
+ "general.import": "가져오기…",
+ "general.reset_library": "기본값으로 초기화",
+ "general.reset_confirm": "모든 프리셋과 툴바 프로필을 기본값으로 바꿀까요?",
+ "general.imported": "{0}개 항목을 가져왔어요",
+
+ "triggers.title": "단축키",
+ "triggers.description": "원형 툴바를 여는 방법을 정하세요. 제스처는 원하는 만큼 추가할 수 있어요.",
+ "triggers.add": "제스처 추가",
+ "triggers.remove": "삭제",
+ "triggers.enabled": "사용",
+ "triggers.kind": "제스처",
+ "triggers.kind.Drag": "수정키 + 파일 드래그",
+ "triggers.kind.Hold": "수정키 + 길게 누르기",
+ "triggers.kind.KeyChord": "키보드 단축키 (선택한 파일)",
+ "triggers.modifiers": "수정키",
+ "triggers.button": "마우스 버튼",
+ "triggers.button.None": "없음",
+ "triggers.button.Left": "왼쪽",
+ "triggers.button.Right": "오른쪽",
+ "triggers.button.Middle": "가운데",
+ "triggers.button.X1": "뒤로 (X1)",
+ "triggers.button.X2": "앞으로 (X2)",
+ "triggers.key": "키",
+ "triggers.record": "녹화",
+ "triggers.recording": "키 조합을 누르세요…",
+ "triggers.clear": "지우기",
+ "triggers.threshold": "드래그 거리",
+ "triggers.threshold_system": "시스템 기본값",
+ "triggers.hold_ms": "누르는 시간",
+ "triggers.scope": "동작 범위",
+ "triggers.scope.FileManager": "탐색기와 바탕화면",
+ "triggers.scope.Anywhere": "모든 곳",
+ "triggers.excluded": "이 앱에서는 동작하지 않기",
+ "triggers.excluded_hint": "프로세스 이름을 쉼표로 구분, 예: photoshop, code",
+ "triggers.paused": "단축키가 일시 중지되었어요",
+
+ "toolbar.title": "원형 툴바",
+ "toolbar.step_profile": "1. 프로필 선택",
+ "toolbar.step_arrange": "2. 프리셋 배치",
+ "toolbar.add_profile": "새 프로필",
+ "toolbar.profile_new": "새 프로필",
+ "toolbar.delete_profile": "프로필 삭제",
+ "toolbar.name": "이름",
+ "toolbar.extensions": "적용할 확장자",
+ "toolbar.extensions_hint": "jpg, png, webp",
+ "toolbar.fallback_note": "다른 프로필에 맞지 않거나 여러 프로필에 걸친 파일에 사용돼요.",
+ "toolbar.available": "사용 가능한 프리셋",
+ "toolbar.hint_add": "칩을 도넛으로 끌면 추가",
+ "toolbar.hint_remove": "세그먼트를 여기로 끌면 빼기",
+ "toolbar.hint_reorder": "세그먼트끼리 끌면 순서 변경",
+ "toolbar.hint_edit": "우클릭 또는 ✎로 프리셋 편집",
+ "toolbar.max_reached": "도넛에는 최대 {0}개까지 넣을 수 있어요",
+ "toolbar.appearance": "모양",
+ "toolbar.size": "크기",
+ "toolbar.hole": "구멍",
+ "toolbar.opacity": "불투명도",
+ "toolbar.new_preset": "새 프리셋",
+
+ "presets.title": "프리셋",
+ "presets.add": "새로 만들기",
+ "presets.duplicate": "복제",
+ "presets.delete": "삭제",
+ "presets.save": "저장",
+ "presets.revert": "되돌리기",
+ "presets.name": "이름",
+ "presets.target": "변환 형식",
+ "presets.same_as_source": "원본과 같은 형식",
+ "presets.group.image": "이미지",
+ "presets.quality": "품질",
+ "presets.resize": "크기 조정",
+ "presets.resize.None": "원본 크기",
+ "presets.resize.Percent": "비율로 조정",
+ "presets.resize.LongEdge": "긴 변 제한",
+ "presets.percent": "비율 (%)",
+ "presets.long_edge": "긴 변 (px)",
+ "presets.dpi": "DPI",
+ "presets.dpi_keep": "유지",
+ "presets.keep_metadata": "메타데이터(EXIF) 유지",
+ "presets.grayscale": "흑백으로",
+ "presets.background": "투명 영역 배경색",
+ "presets.tiff_compression": "TIFF 압축",
+ "presets.webp_lossless": "무손실 WEBP",
+ "presets.ico_sizes": "아이콘 크기",
+ "presets.group.pdf": "PDF",
+ "presets.merge": "모든 파일을 하나의 PDF로 합치기",
+ "presets.page_size": "페이지 크기",
+ "presets.page_size.FitImage": "이미지에 맞춤",
+ "presets.page_size.A4": "A4",
+ "presets.page_size.Letter": "Letter",
+ "presets.margin": "여백 (mm)",
+ "presets.render_dpi": "렌더링 DPI (PDF → 이미지)",
+ "presets.page_range": "페이지",
+ "presets.page_range_hint": "전체, 또는 예: 1-3, 5",
+ "presets.split": "페이지마다 파일 하나",
+ "presets.group.document": "문서",
+ "presets.pdfa": "PDF/A (장기 보존용)",
+ "presets.group.output": "출력",
+ "presets.location": "저장 위치",
+ "presets.location.SameFolder": "원본과 같은 폴더",
+ "presets.location.Subfolder": "하위 폴더",
+ "presets.location.CustomFolder": "지정한 폴더",
+ "presets.subfolder": "하위 폴더 이름",
+ "presets.custom_folder": "폴더",
+ "presets.browse": "찾아보기…",
+ "presets.pattern": "파일 이름",
+ "presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
+ "presets.conflict": "같은 파일이 있으면",
+ "presets.conflict.Rename": "번호 붙이기",
+ "presets.conflict.Overwrite": "덮어쓰기",
+ "presets.conflict.Skip": "건너뛰기",
+ "presets.editor_title": "프리셋 편집",
+ "presets.delete_confirm": "“{0}”을(를) 삭제할까요? 모든 툴바에서도 빠져요.",
+ "presets.name_required": "이름을 입력하세요",
+ "presets.select": "편집할 프리셋을 선택하세요",
+
+ "theme.title": "테마",
+ "theme.mode": "모드",
+ "theme.mode.System": "시스템",
+ "theme.mode.Light": "라이트",
+ "theme.mode.Dark": "다크",
+ "theme.accent": "강조색",
+ "theme.custom_color": "직접 선택",
+ "theme.corner_radius": "말랑함",
+ "theme.reduce_motion": "애니메이션 줄이기",
+ "theme.reduce_motion_hint": "저사양 PC에 권장해요. 전환 효과와 도넛의 튕김 효과를 끕니다.",
+ "theme.preview": "미리보기",
+
+ "engines.title": "변환 엔진",
+ "engines.description": "Filee는 변환마다 사용할 수 있는 가장 좋은 엔진을 고릅니다. 같은 작업을 여러 엔진이 할 수 있으면 목록 위쪽 엔진이 우선이에요.",
+ "engines.available": "사용 가능",
+ "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.pandoc.name": "Pandoc (마크다운·HTML)",
+ "engines.package.pandoc.description": "마크다운·HTML 변환과 마크다운·HTML·ODT·RTF → HWPX 변환을 추가합니다. DOCX → HWPX는 없어도 됩니다.",
+ "engines.package.size": "다운로드 {0} · 설치 후 {1}",
+ "engines.install": "설치",
+ "engines.cancel": "취소",
+ "engines.remove": "제거",
+ "engines.remove_confirm": "{0}을(를) 제거할까요? 나중에 다시 내려받을 수 있습니다.",
+ "engines.remove_failed": "엔진이 사용 중입니다. 진행 중인 변환이 끝난 뒤 다시 시도하세요.",
+ "engines.state.not_installed": "설치 안 됨",
+ "engines.state.queued": "대기 중…",
+ "engines.state.downloading": "내려받는 중 {0}%",
+ "engines.state.unpacking": "설치하는 중…",
+ "engines.state.installed": "설치됨",
+ "engines.state.failed": "실패: {0}",
+
+ "about.title": "정보",
+ "about.version": "버전 {0}",
+ "about.license": "Filee는 MIT 라이선스의 무료 소프트웨어입니다.",
+ "about.notices": "서드파티 고지",
+ "about.github": "GitHub 저장소",
+
+ "common.ok": "확인",
+ "common.cancel": "취소",
+ "common.save": "저장",
+ "common.close": "닫기",
+ "common.delete": "삭제",
+ "common.yes": "예",
+ "common.no": "아니요",
+
+ "setup.title": "변환 엔진 선택",
+ "setup.description": "Filee는 지금 바로 이미지, PDF, HWP/HWPX, DOCX → HWPX를 변환할 수 있습니다. 더 많은 형식이 필요하면 내려받을 엔진을 고르세요.",
+ "setup.note": "엔진은 언제든 설정 → 변환 엔진에서 설치하거나 제거할 수 있습니다.",
+ "setup.install": "선택한 엔진 설치",
+ "setup.later": "나중에",
+ "setup.background": "백그라운드에서 계속",
+ "setup.done": "완료",
+ "setup.selection": "다운로드: {0}",
+ "setup.nothing_selected": "선택한 엔진 없음"
+}
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
new file mode 100644
index 00000000..de34fa45
--- /dev/null
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -0,0 +1,266 @@
+{
+ "app.name": "Filee",
+ "app.tagline": "拖一拖,放一放,转换完成。",
+
+ "nav.home": "首页",
+ "nav.general": "常规",
+ "nav.triggers": "快捷方式",
+ "nav.toolbar": "环形工具栏",
+ "nav.presets": "预设",
+ "nav.theme": "主题",
+ "nav.engines": "转换引擎",
+ "nav.about": "关于",
+
+ "tray.open": "打开 Filee",
+ "tray.pause": "暂停快捷方式",
+ "tray.resume": "恢复快捷方式",
+ "tray.quit": "退出",
+ "tray.tooltip": "Filee — 按住 {0} 拖动文件",
+
+ "home.title": "首页",
+ "home.drop_title": "将文件拖放到这里",
+ "home.drop_hint": "或在资源管理器中按住 {0} 拖动文件,环形工具栏会在光标处打开。",
+ "home.recent": "最近的转换",
+ "home.recent_empty": "转换后的文件会显示在这里。",
+ "home.open_folder": "打开文件夹",
+ "home.clear_history": "清除",
+ "home.files": "{0} 个文件",
+
+ "donut.center_drag": "把文件拖到这里",
+ "donut.files_same": "{0} 个 {1}",
+ "donut.files_mixed": "{0} 个文件",
+ "donut.drop_to": "松开 → {0}",
+ "donut.click_to": "点击 → {0}",
+ "donut.cancel": "拖到这里取消",
+ "donut.close_hint": "按 Esc 关闭",
+ "donut.edit": "编辑预设",
+ "donut.empty": "把预设拖到这里",
+ "donut.same_format": "同格式",
+
+ "toast.converting": "{0} → {1}",
+ "toast.done": "完成",
+ "toast.done_errors": "{1} 个中有 {0} 个失败",
+ "toast.failed": "转换失败",
+ "toast.cancelled": "已取消",
+ "toast.skipped": "已跳过(文件已存在)",
+ "toast.open_folder": "查看",
+ "toast.cancel": "取消",
+
+ "error.unsupported_source": "不支持此文件类型",
+ "error.no_route": "没有引擎可以完成此转换",
+ "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.hwp": "HWP / HWPX",
+ "profile.mixed": "混合文件",
+
+ "preset.half_size": "缩小 50%",
+ "preset.grayscale": "灰度",
+ "preset.merge_pdf": "合并 PDF",
+ "preset.split_pdf": "拆分 PDF",
+
+ "general.title": "常规",
+ "general.language": "语言",
+ "general.language_auto": "跟随系统",
+ "general.start_with_system": "登录时启动 Filee",
+ "general.context_menu": "在资源管理器右键菜单中显示“用 Filee 转换”",
+ "general.context_menu_label": "用 Filee 转换",
+ "general.check_updates": "自动检查更新",
+ "general.check_now": "立即检查",
+ "general.update_available": "有新版本 {0}",
+ "general.update_none": "已是最新版本",
+ "general.update_dev": "仅安装版支持更新",
+ "general.update_install": "更新并重启",
+ "general.data_folder": "设置文件夹",
+ "general.open_data_folder": "打开",
+ "general.library": "预设与工具栏",
+ "general.export": "导出…",
+ "general.import": "导入…",
+ "general.reset_library": "恢复默认",
+ "general.reset_confirm": "要将所有预设和工具栏配置恢复为默认吗?",
+ "general.imported": "已导入 {0} 项",
+
+ "triggers.title": "快捷方式",
+ "triggers.description": "选择打开环形工具栏的方式。可以添加任意多个手势。",
+ "triggers.add": "添加手势",
+ "triggers.remove": "删除",
+ "triggers.enabled": "启用",
+ "triggers.kind": "手势",
+ "triggers.kind.Drag": "修饰键 + 拖动文件",
+ "triggers.kind.Hold": "修饰键 + 长按",
+ "triggers.kind.KeyChord": "键盘快捷键(选中的文件)",
+ "triggers.modifiers": "修饰键",
+ "triggers.button": "鼠标按键",
+ "triggers.button.None": "无",
+ "triggers.button.Left": "左键",
+ "triggers.button.Right": "右键",
+ "triggers.button.Middle": "中键",
+ "triggers.button.X1": "后退 (X1)",
+ "triggers.button.X2": "前进 (X2)",
+ "triggers.key": "按键",
+ "triggers.record": "录制",
+ "triggers.recording": "请按下组合键…",
+ "triggers.clear": "清除",
+ "triggers.threshold": "拖动距离",
+ "triggers.threshold_system": "系统默认",
+ "triggers.hold_ms": "按住时间",
+ "triggers.scope": "生效范围",
+ "triggers.scope.FileManager": "资源管理器和桌面",
+ "triggers.scope.Anywhere": "所有位置",
+ "triggers.excluded": "在这些应用中不触发",
+ "triggers.excluded_hint": "进程名,用逗号分隔,例如 photoshop, code",
+ "triggers.paused": "快捷方式已暂停",
+
+ "toolbar.title": "环形工具栏",
+ "toolbar.step_profile": "1. 选择配置",
+ "toolbar.step_arrange": "2. 排列预设",
+ "toolbar.add_profile": "新建配置",
+ "toolbar.profile_new": "新配置",
+ "toolbar.delete_profile": "删除配置",
+ "toolbar.name": "名称",
+ "toolbar.extensions": "适用的扩展名",
+ "toolbar.extensions_hint": "jpg, png, webp",
+ "toolbar.fallback_note": "当文件不匹配其他配置或跨多个配置时使用。",
+ "toolbar.available": "可用预设",
+ "toolbar.hint_add": "将标签拖到圆环上即可添加",
+ "toolbar.hint_remove": "将扇区拖回这里即可移除",
+ "toolbar.hint_reorder": "扇区之间互相拖动可调整顺序",
+ "toolbar.hint_edit": "右键扇区或点击 ✎ 编辑",
+ "toolbar.max_reached": "圆环最多容纳 {0} 个预设",
+ "toolbar.appearance": "外观",
+ "toolbar.size": "大小",
+ "toolbar.hole": "内圈",
+ "toolbar.opacity": "不透明度",
+ "toolbar.new_preset": "新预设",
+
+ "presets.title": "预设",
+ "presets.add": "新建",
+ "presets.duplicate": "复制",
+ "presets.delete": "删除",
+ "presets.save": "保存",
+ "presets.revert": "还原",
+ "presets.name": "名称",
+ "presets.target": "转换为",
+ "presets.same_as_source": "与源文件相同的格式",
+ "presets.group.image": "图片",
+ "presets.quality": "质量",
+ "presets.resize": "调整大小",
+ "presets.resize.None": "原始大小",
+ "presets.resize.Percent": "按百分比缩放",
+ "presets.resize.LongEdge": "限制长边",
+ "presets.percent": "百分比",
+ "presets.long_edge": "长边 (px)",
+ "presets.dpi": "DPI",
+ "presets.dpi_keep": "保持",
+ "presets.keep_metadata": "保留元数据 (EXIF)",
+ "presets.grayscale": "转为灰度",
+ "presets.background": "透明区域背景色",
+ "presets.tiff_compression": "TIFF 压缩",
+ "presets.webp_lossless": "无损 WEBP",
+ "presets.ico_sizes": "图标尺寸",
+ "presets.group.pdf": "PDF",
+ "presets.merge": "将所有文件合并为一个 PDF",
+ "presets.page_size": "页面大小",
+ "presets.page_size.FitImage": "适应图片",
+ "presets.page_size.A4": "A4",
+ "presets.page_size.Letter": "Letter",
+ "presets.margin": "边距 (mm)",
+ "presets.render_dpi": "渲染 DPI(PDF → 图片)",
+ "presets.page_range": "页面",
+ "presets.page_range_hint": "全部,或如 1-3, 5",
+ "presets.split": "每页一个文件",
+ "presets.group.document": "文档",
+ "presets.pdfa": "PDF/A(长期存档)",
+ "presets.group.output": "输出",
+ "presets.location": "保存到",
+ "presets.location.SameFolder": "与源文件相同的文件夹",
+ "presets.location.Subfolder": "子文件夹",
+ "presets.location.CustomFolder": "指定文件夹",
+ "presets.subfolder": "子文件夹名称",
+ "presets.custom_folder": "文件夹",
+ "presets.browse": "浏览…",
+ "presets.pattern": "文件名",
+ "presets.pattern_hint": "{name} {ext} {preset} {date} {time} {index}",
+ "presets.conflict": "文件已存在时",
+ "presets.conflict.Rename": "添加编号",
+ "presets.conflict.Overwrite": "覆盖",
+ "presets.conflict.Skip": "跳过",
+ "presets.editor_title": "编辑预设",
+ "presets.delete_confirm": "删除“{0}”?它也会从所有工具栏中移除。",
+ "presets.name_required": "请输入名称",
+ "presets.select": "选择一个预设进行编辑",
+
+ "theme.title": "主题",
+ "theme.mode": "外观",
+ "theme.mode.System": "跟随系统",
+ "theme.mode.Light": "浅色",
+ "theme.mode.Dark": "深色",
+ "theme.accent": "强调色",
+ "theme.custom_color": "自定义",
+ "theme.corner_radius": "柔和度",
+ "theme.reduce_motion": "减少动画",
+ "theme.reduce_motion_hint": "推荐低配置电脑使用。关闭过渡效果和圆环的弹跳效果。",
+ "theme.preview": "预览",
+
+ "engines.title": "转换引擎",
+ "engines.description": "Filee 会为每次转换选择最合适的可用引擎。多个引擎能完成同一任务时,列表中靠前的优先。",
+ "engines.available": "可用",
+ "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.pandoc.name": "Pandoc(Markdown 与 HTML)",
+ "engines.package.pandoc.description": "支持 Markdown 与 HTML 转换,以及 Markdown、HTML、ODT、RTF → HWPX。DOCX → HWPX 无需此引擎。",
+ "engines.package.size": "下载 {0} · 占用 {1}",
+ "engines.install": "安装",
+ "engines.cancel": "取消",
+ "engines.remove": "删除",
+ "engines.remove_confirm": "删除 {0}?以后可以重新下载。",
+ "engines.remove_failed": "引擎正在使用中。请在当前转换完成后重试。",
+ "engines.state.not_installed": "未安装",
+ "engines.state.queued": "等待中…",
+ "engines.state.downloading": "下载中 {0}%",
+ "engines.state.unpacking": "安装中…",
+ "engines.state.installed": "已安装",
+ "engines.state.failed": "失败:{0}",
+
+ "about.title": "关于",
+ "about.version": "版本 {0}",
+ "about.license": "Filee 是基于 MIT 许可证的免费软件。",
+ "about.notices": "第三方声明",
+ "about.github": "GitHub 仓库",
+
+ "common.ok": "确定",
+ "common.cancel": "取消",
+ "common.save": "保存",
+ "common.close": "关闭",
+ "common.delete": "删除",
+ "common.yes": "是",
+ "common.no": "否",
+
+ "setup.title": "选择转换引擎",
+ "setup.description": "Filee 现在即可转换图片、PDF、HWP/HWPX 以及 DOCX → HWPX。如需更多格式,请选择要下载的引擎。",
+ "setup.note": "可随时在 设置 → 转换引擎 中安装或删除引擎。",
+ "setup.install": "安装所选引擎",
+ "setup.later": "稍后",
+ "setup.background": "在后台继续",
+ "setup.done": "完成",
+ "setup.selection": "下载:{0}",
+ "setup.nothing_selected": "未选择引擎"
+}
diff --git a/src/Filee.App/Controls/DonutGeometry.cs b/src/Filee.App/Controls/DonutGeometry.cs
new file mode 100644
index 00000000..a80a77c0
--- /dev/null
+++ b/src/Filee.App/Controls/DonutGeometry.cs
@@ -0,0 +1,72 @@
+// Pure math for the donut: slice angles, hit testing and slice outlines. Unit tested (DonutGeometryTests).
+//
+// Angles are measured clockwise from 12 o'clock, in radians. Slice i is centred on i·span,
+// so the first preset sits at the top and the rest follow clockwise.
+
+using Avalonia;
+
+namespace Filee.App.Controls;
+
+/// <summary>What is under a point of the donut.</summary>
+public enum DonutHitKind
+{
+ /// <summary>Outside the donut.</summary>
+ Outside,
+ /// <summary>The hole in the middle (cancel / close).</summary>
+ Center,
+ /// <summary>A slice; <see cref="DonutHit.Index"/> is valid.</summary>
+ Segment,
+ /// <summary>The ring of a donut without slices (drop target for the first preset).</summary>
+ EmptyRing,
+ /// <summary>The ✎ edit button of the hovered slice (edit mode only).</summary>
+ EditButton,
+ /// <summary>The progress ring shown after a drop.</summary>
+ ProgressRing,
+ /// <summary>The × (cancel) button on the progress ring.</summary>
+ ProgressCancel,
+}
+
+public readonly record struct DonutHit(DonutHitKind Kind, int Index = -1);
+
+/// <summary>Geometry helpers.</summary>
+public static class DonutGeometry
+{
+ /// <summary>Angle covered by one of <paramref name="count"/> slices.</summary>
+ public static double Span(int count) => count <= 0 ? 2 * Math.PI : 2 * Math.PI / count;
+
+ /// <summary>Centre angle of slice <paramref name="index"/>.</summary>
+ public static double MidAngle(int index, int count) => index * Span(count);
+
+ /// <summary>Converts a clockwise-from-top angle and radius into a point relative to <paramref name="center"/>.</summary>
+ public static Point PointAt(Point center, double radius, double angle) =>
+ new(center.X + radius * Math.Sin(angle), center.Y - radius * Math.Cos(angle));
+
+ /// <summary>Clockwise-from-top angle (0..2π) of <paramref name="p"/> around <paramref name="center"/>.</summary>
+ public static double AngleOf(Point center, Point p)
+ {
+ var a = Math.Atan2(p.X - center.X, center.Y - p.Y);
+ return a < 0 ? a + 2 * Math.PI : a;
+ }
+
+ /// <summary>Index of the slice containing the given angle.</summary>
+ public static int IndexAt(double angle, int count)
+ {
+ if (count <= 0)
+ return -1;
+ var span = Span(count);
+ return (int)Math.Floor((angle + span / 2) / span) % count;
+ }
+
+ /// <summary>Classifies a point. <paramref name="slack"/> extends the outer radius to include popped-out slices.</summary>
+ public static DonutHit HitTest(Point center, Point p, double innerRadius, double outerRadius, int count, double slack = 0)
+ {
+ var distance = Math.Sqrt(Math.Pow(p.X - center.X, 2) + Math.Pow(p.Y - center.Y, 2));
+ if (distance < innerRadius)
+ return new DonutHit(DonutHitKind.Center);
+ if (distance > outerRadius + slack)
+ return new DonutHit(DonutHitKind.Outside);
+ if (count == 0)
+ return new DonutHit(DonutHitKind.EmptyRing);
+ return new DonutHit(DonutHitKind.Segment, IndexAt(AngleOf(center, p), count));
+ }
+}
diff --git a/src/Filee.App/Controls/DonutMenu.Progress.cs b/src/Filee.App/Controls/DonutMenu.Progress.cs
new file mode 100644
index 00000000..638d695d
--- /dev/null
+++ b/src/Filee.App/Controls/DonutMenu.Progress.cs
@@ -0,0 +1,462 @@
+// Progress mode of the donut: after a drop the slices are sucked into the centre, the hole turns into a small
+// progress ring with the percentage in the middle, and on completion a check mark pops up in the centre.
+//
+// BeginProgress() → slices collapse (≈0.3 s) → ring springs in
+// SetProgress(x) → arc follows smoothly
+// CompleteProgress → arc fills (success colour) → ✓ / ! pops in the centre → hold → fade → callback
+// HandOffProgress → ring shrinks away quickly (the toast window takes over) → callback
+//
+// The ring stays visible for at least MinRingSeconds so very fast conversions still show their ✓ instead of
+// flashing. With Motion.Enabled == false everything snaps; only the hold time remains.
+
+using Avalonia;
+using Avalonia.Input;
+using Avalonia.Media;
+using Filee.App.Services;
+
+namespace Filee.App.Controls;
+
+/// <summary>How a conversion shown by the progress ring ended.</summary>
+public enum DonutProgressOutcome
+{
+ Succeeded,
+ Failed,
+ Cancelled,
+}
+
+public sealed partial class DonutMenu
+{
+ public static readonly StyledProperty<IBrush?> SuccessBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(SuccessBrush), Brushes.SeaGreen);
+
+ /// <summary>Radius of the progress ring (centre of the stroke).</summary>
+ public const double RingRadius = 36;
+
+ private const double RingStroke = 6;
+ private const double CollapseSeconds = 0.28;
+ private const double CollapseStagger = 0.02;
+ private const double MinRingSeconds = 0.6;
+ private const double HoldSuccessSeconds = 0.9;
+ private const double HoldFailureSeconds = 1.4;
+ private const double FadeSeconds = 0.25;
+ private const double HandOffSeconds = 0.22;
+
+ // Material "close" icon (24×24) for the cancel button.
+ private static readonly Geometry CloseIcon = Geometry.Parse(
+ "M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z");
+
+ private bool _progressMode;
+ private double _collapseClock; // seconds since BeginProgress
+ private double _ringClock = -1; // seconds since the ring became visible (-1 = not yet)
+ private Spring _ring; // ring "pop in" scale 0..1
+ private double _shownProgress; // what the arc shows (smoothed)
+ private double _targetProgress; // latest real progress 0..1
+ private DonutProgressOutcome? _pendingOutcome;
+ private DonutProgressOutcome? _outcome; // shown outcome (badge visible)
+ private Spring _badge; // ✓ / ! pop scale
+ private double _holdClock = -1;
+ private double _fadeClock = -1;
+ private double _handOffClock = -1;
+ private Action? _progressDone;
+ private bool _ringHover;
+
+ public IBrush? SuccessBrush { get => GetValue(SuccessBrushProperty); set => SetValue(SuccessBrushProperty, value); }
+
+ /// <summary>True while the donut shows a conversion's progress instead of presets.</summary>
+ public bool IsInProgressMode => _progressMode;
+
+ /// <summary>Outcome badge currently visible (null while running). For tests.</summary>
+ internal DonutProgressOutcome? ShownOutcome => _outcome;
+
+ /// <summary>The × on the ring was clicked while a conversion was running.</summary>
+ public event EventHandler? ProgressCancelRequested;
+
+ /// <summary>The ring was clicked (e.g. to open the output folder).</summary>
+ public event EventHandler? ProgressClicked;
+
+ /// <summary>Switches to progress mode: collapses the slices into the centre and shows the progress ring.</summary>
+ public void BeginProgress()
+ {
+ ResetProgress();
+ _progressMode = true;
+ _closing = false;
+ _closeCallback = null;
+ _openClock = double.MaxValue;
+ if (!Motion.Enabled)
+ {
+ _collapseClock = CollapseEnd;
+ _ring.Value = 1;
+ _ringClock = 0;
+ }
+ StartAnimation();
+ }
+
+ /// <summary>Updates the progress (0..1). The arc animates towards it.</summary>
+ public void SetProgress(double value)
+ {
+ _targetProgress = Math.Clamp(value, 0, 1);
+ StartAnimation();
+ }
+
+ /// <summary>
+ /// Ends the conversion: shows the outcome badge in the centre, holds, fades and then calls <paramref name="done"/>.
+ /// </summary>
+ public void CompleteProgress(DonutProgressOutcome outcome, Action done)
+ {
+ if (!_progressMode)
+ {
+ done();
+ return;
+ }
+ if (outcome == DonutProgressOutcome.Succeeded)
+ _targetProgress = 1;
+ _pendingOutcome = outcome;
+ _progressDone = done;
+ StartAnimation();
+ }
+
+ /// <summary>Quickly shrinks the ring away (the toast window takes over), then calls <paramref name="done"/>.</summary>
+ public void HandOffProgress(Action done)
+ {
+ if (!_progressMode)
+ {
+ done();
+ return;
+ }
+ _progressDone = done;
+ _pendingOutcome = null;
+ if (!Motion.Enabled)
+ {
+ FinishProgress();
+ return;
+ }
+ _handOffClock = 0;
+ StartAnimation();
+ }
+
+ private double CollapseEnd => CollapseSeconds + CollapseStagger * Math.Max(0, Count - 1);
+
+ private void ResetProgress()
+ {
+ _progressMode = false;
+ _collapseClock = 0;
+ _ringClock = -1;
+ _ring = default;
+ _shownProgress = 0;
+ _targetProgress = 0;
+ _pendingOutcome = null;
+ _outcome = null;
+ _badge = default;
+ _holdClock = -1;
+ _fadeClock = -1;
+ _handOffClock = -1;
+ _progressDone = null;
+ _ringHover = false;
+ }
+
+ private void FinishProgress()
+ {
+ var done = _progressDone;
+ _progressDone = null;
+ done?.Invoke();
+ }
+
+ /// <summary>Advances all progress-mode animations. Returns true while another frame is needed.</summary>
+ private bool StepProgress(double dt)
+ {
+ if (!_progressMode)
+ return false;
+
+ var animate = Motion.Enabled;
+ var active = false;
+
+ // 1. Slices collapse into the centre, then the ring appears.
+ if (_collapseClock < CollapseEnd)
+ {
+ _collapseClock = animate ? _collapseClock + dt : CollapseEnd;
+ active = true;
+ }
+ else if (_ringClock < 0)
+ {
+ _ringClock = 0;
+ _ring.Velocity = animate ? 2 : 0;
+ if (!animate)
+ _ring.Value = 1;
+ }
+ if (_ringClock >= 0)
+ {
+ _ringClock += dt;
+ active |= animate ? _ring.Step(1, dt, 300, 16) : false;
+ }
+
+ // 2. The arc follows the real progress smoothly (exponential approach).
+ var gap = _targetProgress - _shownProgress;
+ _shownProgress = animate ? _shownProgress + gap * Math.Min(1, dt * 9) : _targetProgress;
+ if (Math.Abs(_targetProgress - _shownProgress) < 0.002)
+ _shownProgress = _targetProgress;
+ else
+ active = true;
+
+ // 3. Show the outcome once the ring has been visible long enough and the arc caught up.
+ if (_pendingOutcome is { } pending && _outcome is null && _ringClock >= MinRingSeconds &&
+ (pending != DonutProgressOutcome.Succeeded || _shownProgress >= 0.999))
+ {
+ _outcome = pending;
+ _holdClock = 0;
+ if (animate)
+ _badge.Velocity = 9; // kick → overshoot "pop"
+ else
+ _badge.Value = 1;
+ }
+ if (_pendingOutcome is not null)
+ active = true;
+
+ if (_outcome is { } outcome)
+ {
+ active |= animate && _badge.Step(1, dt, 420, 14);
+ if (_fadeClock < 0)
+ {
+ _holdClock += dt;
+ var hold = outcome switch
+ {
+ DonutProgressOutcome.Failed => HoldFailureSeconds,
+ DonutProgressOutcome.Cancelled => 0.2,
+ _ => HoldSuccessSeconds,
+ };
+ if (_holdClock >= hold)
+ _fadeClock = 0;
+ active = true;
+ }
+ else
+ {
+ _fadeClock = animate ? _fadeClock + dt : FadeSeconds;
+ if (_fadeClock >= FadeSeconds)
+ {
+ FinishProgress();
+ return false;
+ }
+ active = true;
+ }
+ }
+
+ // 4. Hand-off to the toast window.
+ if (_handOffClock >= 0)
+ {
+ _handOffClock += dt;
+ if (_handOffClock >= HandOffSeconds)
+ {
+ FinishProgress();
+ return false;
+ }
+ active = true;
+ }
+
+ return active;
+ }
+
+ // ───────────────────────── Rendering ─────────────────────────
+
+ private void RenderProgress(DrawingContext context, Point center, double r1, double r2, Typeface bold, Typeface regular)
+ {
+ var n = Count;
+ var collapseAll = CollapseEnd <= 0 ? 1 : Math.Clamp(_collapseClock / CollapseEnd, 0, 1);
+
+ // Slices shrink towards the centre with a slight stagger ("sucked in").
+ if (collapseAll < 1)
+ {
+ using (context.PushOpacity(1 - collapseAll))
+ DrawSoftShadow(context, center, r2);
+
+ for (var i = 0; i < n; i++)
+ {
+ var t = Math.Clamp((_collapseClock - i * CollapseStagger) / CollapseSeconds, 0, 1);
+ var c = EaseInCubic(t);
+ if (c >= 0.999)
+ continue;
+ var scale = 1 - 0.8 * c;
+ var transform =
+ Matrix.CreateTranslation(-center.X, -center.Y) *
+ Matrix.CreateRotation(c * 0.25) *
+ Matrix.CreateScale(scale, scale) *
+ Matrix.CreateTranslation(center.X, center.Y);
+ using (context.PushTransform(transform))
+ using (context.PushOpacity(1 - c))
+ {
+ var wedge = CreateWedge(center, r1, r2, i, n);
+ context.DrawGeometry(WithOpacity(SliceBrush, SliceOpacity), BorderPen(), wedge);
+ var hot = i == ActiveIndex;
+ if (hot)
+ context.DrawGeometry(WithOpacity(AccentBrush, 0.8), null, wedge);
+ // Labels shrink with their slice instead of vanishing when the collapse starts.
+ DrawLabel(context, Items![i], center, (r1 + r2) / 2, DonutGeometry.MidAngle(i, n),
+ DonutGeometry.Span(n) * (r1 + r2) / 2 - 10, r2 - r1 - 16, bold, regular, hot);
+ }
+ }
+
+ // The hole shrinks to the size of the ring's plate.
+ var plate = RingRadius + RingStroke + 2;
+ var holeRadius = Lerp(r1 - 6, plate, EaseInCubic(collapseAll));
+ context.DrawEllipse(CenterBrush, BorderPen(), center, holeRadius, holeRadius);
+ return;
+ }
+
+ // Ring: plate, track, arc, percentage or outcome badge.
+ var fade = _fadeClock >= 0 ? Math.Clamp(_fadeClock / FadeSeconds, 0, 1) : 0;
+ var handOff = _handOffClock >= 0 ? Math.Clamp(_handOffClock / HandOffSeconds, 0, 1) : 0;
+ var ringScale = Math.Max(0, _ring.Value) * (1 - 0.15 * fade) * (1 - 0.7 * EaseInCubic(handOff));
+ var opacity = (1 - fade) * (1 - handOff);
+ if (ringScale <= 0.01 || opacity <= 0.01)
+ return;
+
+ var ringTransform = Matrix.CreateTranslation(-center.X, -center.Y) * Matrix.CreateScale(ringScale, ringScale) *
+ Matrix.CreateTranslation(center.X, center.Y);
+ using var _ = context.PushTransform(ringTransform);
+ using var __ = context.PushOpacity(opacity);
+
+ var plateRadius = RingRadius + RingStroke + 2;
+ DrawPlateShadow(context, center, plateRadius);
+ context.DrawEllipse(CenterBrush, BorderPen(), center, plateRadius, plateRadius);
+ context.DrawEllipse(null, new Pen(WithOpacity(SecondaryForeground, 0.22), RingStroke), center, RingRadius, RingRadius);
+
+ var arcBrush = _outcome switch
+ {
+ DonutProgressOutcome.Succeeded => SuccessBrush,
+ DonutProgressOutcome.Failed => DangerBrush,
+ _ => AccentBrush,
+ };
+ var sweep = _outcome == DonutProgressOutcome.Failed ? Math.Max(_shownProgress, 0.02) : _shownProgress;
+ DrawArc(context, center, RingRadius, sweep, new Pen(arcBrush, RingStroke, lineCap: PenLineCap.Round));
+
+ var badge = _outcome is null ? 0 : Math.Max(0, _badge.Value);
+ if (badge < 0.98)
+ {
+ using (context.PushOpacity(1 - Math.Clamp(badge, 0, 1)))
+ {
+ var percent = MakeText($"{Math.Round(_shownProgress * 100):0}%", bold, 15, Foreground, RingRadius * 1.6);
+ DrawCentered(context, percent, center.X, center.Y - percent.Height / 2);
+ }
+ }
+
+ if (_outcome is { } outcome && outcome != DonutProgressOutcome.Cancelled && badge > 0.01)
+ DrawOutcomeBadge(context, center, outcome, badge, bold);
+
+ if (_ringHover && _outcome is null && _handOffClock < 0)
+ DrawCancelButton(context, CancelButtonCenter(center));
+ }
+
+ /// <summary>✓ (success) or ! (failure) popping in the centre of the ring.</summary>
+ private void DrawOutcomeBadge(DrawingContext context, Point center, DonutProgressOutcome outcome, double scale, Typeface bold)
+ {
+ var radius = 22 * scale;
+ var fill = outcome == DonutProgressOutcome.Succeeded ? SuccessBrush : DangerBrush;
+ context.DrawEllipse(fill, null, center, radius, radius);
+
+ var transform = Matrix.CreateTranslation(-center.X, -center.Y) * Matrix.CreateScale(scale, scale) *
+ Matrix.CreateTranslation(center.X, center.Y);
+ using var _ = context.PushTransform(transform);
+ if (outcome == DonutProgressOutcome.Succeeded)
+ {
+ var check = new StreamGeometry();
+ using (var g = check.Open())
+ {
+ g.BeginFigure(new Point(center.X - 9, center.Y + 0.5), false);
+ g.LineTo(new Point(center.X - 2.5, center.Y + 7));
+ g.LineTo(new Point(center.X + 10, center.Y - 6.5));
+ g.EndFigure(false);
+ }
+ context.DrawGeometry(null, new Pen(OnAccentBrush, 3.6, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), check);
+ }
+ else
+ {
+ var mark = MakeText("!", bold, 22, OnAccentBrush, 30);
+ DrawCentered(context, mark, center.X, center.Y - mark.Height / 2);
+ }
+ }
+
+ private Point CancelButtonCenter(Point center) =>
+ DonutGeometry.PointAt(center, RingRadius + RingStroke, Math.PI / 4);
+
+ private void DrawCancelButton(DrawingContext context, Point at)
+ {
+ context.DrawEllipse(Foreground, new Pen(CenterBrush, 2), at, 10, 10);
+ var bounds = CloseIcon.Bounds;
+ var s = 10 / Math.Max(bounds.Width, bounds.Height);
+ var matrix = Matrix.CreateTranslation(-bounds.Center.X, -bounds.Center.Y) * Matrix.CreateScale(s, s) *
+ Matrix.CreateTranslation(at.X, at.Y);
+ using (context.PushTransform(matrix))
+ context.DrawGeometry(CenterBrush, null, CloseIcon);
+ }
+
+ private static void DrawPlateShadow(DrawingContext context, Point center, double radius)
+ {
+ var outer = radius + 10;
+ var brush = new RadialGradientBrush
+ {
+ GradientStops =
+ {
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), 0),
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), (radius - 8) / outer),
+ new GradientStop(Color.FromArgb(52, 0, 0, 0), radius / outer),
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), 1),
+ },
+ };
+ context.DrawEllipse(brush, null, new Point(center.X, center.Y + 3), outer, outer);
+ }
+
+ /// <summary>Clockwise arc from 12 o'clock covering <paramref name="fraction"/> of the circle.</summary>
+ private static void DrawArc(DrawingContext context, Point center, double radius, double fraction, Pen pen)
+ {
+ if (fraction <= 0.001)
+ return;
+ if (fraction >= 0.999)
+ {
+ context.DrawEllipse(null, pen, center, radius, radius);
+ return;
+ }
+ var sweep = fraction * 2 * Math.PI;
+ var geometry = new StreamGeometry();
+ using (var g = geometry.Open())
+ {
+ g.BeginFigure(DonutGeometry.PointAt(center, radius, 0), false);
+ g.ArcTo(DonutGeometry.PointAt(center, radius, sweep), new Size(radius, radius), 0, sweep > Math.PI, SweepDirection.Clockwise);
+ g.EndFigure(false);
+ }
+ context.DrawGeometry(null, pen, geometry);
+ }
+
+ // ───────────────────────── Input ─────────────────────────
+
+ /// <summary>Hit test in progress mode.</summary>
+ private DonutHit HitTestProgress(Point p)
+ {
+ if (_ringHover && _outcome is null && Distance(p, CancelButtonCenter(Center)) <= 11)
+ return new DonutHit(DonutHitKind.ProgressCancel);
+ return Distance(p, Center) <= RingRadius + RingStroke + 2
+ ? new DonutHit(DonutHitKind.ProgressRing)
+ : new DonutHit(DonutHitKind.Outside);
+ }
+
+ private void OnProgressPointerMoved(Point p)
+ {
+ var over = Distance(p, Center) <= RingRadius + RingStroke + 14;
+ if (over == _ringHover)
+ return;
+ _ringHover = over;
+ StartAnimation();
+ }
+
+ private void OnProgressPointerReleased(Point p)
+ {
+ switch (HitTestProgress(p).Kind)
+ {
+ case DonutHitKind.ProgressCancel:
+ ProgressCancelRequested?.Invoke(this, EventArgs.Empty);
+ break;
+ case DonutHitKind.ProgressRing:
+ ProgressClicked?.Invoke(this, EventArgs.Empty);
+ break;
+ }
+ }
+
+ private static double Lerp(double a, double b, double t) => a + (b - a) * t;
+}
diff --git a/src/Filee.App/Controls/DonutMenu.cs b/src/Filee.App/Controls/DonutMenu.cs
new file mode 100644
index 00000000..a16e6000
--- /dev/null
+++ b/src/Filee.App/Controls/DonutMenu.cs
@@ -0,0 +1,699 @@
+// The donut toolbar: a ring completely divided into equal slices, one per preset.
+// Used both as the live toolbar (RadialWindow) and as the editor in Settings → Donut toolbar (IsEditMode).
+//
+// Drawn by hand (no child controls) so it stays fast on low-end PCs and so every slice can be hit-tested by
+// its exact wedge shape. Animations are tiny springs advanced on each rendered frame; with
+// Motion.Enabled == false every value jumps straight to its target.
+//
+// After a drop the donut turns into a progress ring: see DonutMenu.Progress.cs.
+
+using System.Globalization;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Documents;
+using Avalonia.Input;
+using Avalonia.Media;
+using Filee.App.Services;
+
+namespace Filee.App.Controls;
+
+/// <summary>One slice of the donut.</summary>
+public sealed class DonutItem
+{
+ public required string Id { get; init; }
+ public required string Label { get; init; }
+
+ /// <summary>Small second line, e.g. the target format. Hidden when equal to <see cref="Label"/>.</summary>
+ public string? Caption { get; init; }
+
+ public bool IsEnabled { get; init; } = true;
+
+ /// <summary>Tooltip shown for disabled slices.</summary>
+ public string? DisabledReason { get; init; }
+}
+
+/// <summary>Donut-shaped menu control.</summary>
+public sealed partial class DonutMenu : Control
+{
+ public static readonly StyledProperty<IReadOnlyList<DonutItem>?> ItemsProperty =
+ AvaloniaProperty.Register<DonutMenu, IReadOnlyList<DonutItem>?>(nameof(Items));
+ public static readonly StyledProperty<double> OuterRadiusProperty =
+ AvaloniaProperty.Register<DonutMenu, double>(nameof(OuterRadius), 150);
+ public static readonly StyledProperty<double> HoleRatioProperty =
+ AvaloniaProperty.Register<DonutMenu, double>(nameof(HoleRatio), 0.42);
+ public static readonly StyledProperty<double> SliceOpacityProperty =
+ AvaloniaProperty.Register<DonutMenu, double>(nameof(SliceOpacity), 0.96);
+ public static readonly StyledProperty<string?> CenterTitleProperty =
+ AvaloniaProperty.Register<DonutMenu, string?>(nameof(CenterTitle));
+ public static readonly StyledProperty<string?> CenterSubtitleProperty =
+ AvaloniaProperty.Register<DonutMenu, string?>(nameof(CenterSubtitle));
+ public static readonly StyledProperty<bool> IsEditModeProperty =
+ AvaloniaProperty.Register<DonutMenu, bool>(nameof(IsEditMode));
+ public static readonly StyledProperty<bool> AllowContextEditProperty =
+ AvaloniaProperty.Register<DonutMenu, bool>(nameof(AllowContextEdit));
+
+ public static readonly StyledProperty<IBrush?> SliceBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(SliceBrush), Brushes.White);
+ public static readonly StyledProperty<IBrush?> SliceBorderBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(SliceBorderBrush));
+ public static readonly StyledProperty<IBrush?> CenterBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(CenterBrush), Brushes.White);
+ public static readonly StyledProperty<IBrush?> AccentBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(AccentBrush), Brushes.MediumPurple);
+ public static readonly StyledProperty<IBrush?> OnAccentBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(OnAccentBrush), Brushes.White);
+ public static readonly StyledProperty<IBrush?> ForegroundProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(Foreground), Brushes.Black);
+ public static readonly StyledProperty<IBrush?> SecondaryForegroundProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(SecondaryForeground), Brushes.Gray);
+ public static readonly StyledProperty<IBrush?> DangerBrushProperty =
+ AvaloniaProperty.Register<DonutMenu, IBrush?>(nameof(DangerBrush), Brushes.IndianRed);
+
+ /// <summary>Gap between slices in pixels (keeps the donut "full" while separating slices).</summary>
+ private const double GapPixels = 3;
+ private const double PopOut = 7;
+ private const double OpenDuration = 0.42;
+ private const double OpenStagger = 0.028;
+ private const double DragStartDistance = 5;
+
+ // Pencil (Material "edit") path in a 24×24 box.
+ private static readonly Geometry PencilIcon = Geometry.Parse(
+ "M3,17.25V21h3.75L17.81,9.94l-3.75-3.75L3,17.25z M20.71,7.04c0.39-0.39,0.39-1.02,0-1.41l-2.34-2.34c-0.39-0.39-1.02-0.39-1.41,0l-1.83,1.83l3.75,3.75L20.71,7.04z");
+
+ private Spring[] _hover = [];
+ private double[] _open = [];
+ private Spring _centerPulse;
+ private double _openClock = double.MaxValue;
+ private TimeSpan? _lastFrame;
+ private bool _animating;
+ private Action? _closeCallback;
+ private bool _closing;
+
+ private int _hoverIndex = -1;
+ private int _externalHighlight = -1;
+ private bool _externalCenterHot;
+ private int _dimmedIndex = -1;
+ private int _dropTargetIndex = -1;
+ private (int Index, Point Start, PointerPressedEventArgs Args)? _press;
+
+ static DonutMenu()
+ {
+ AffectsMeasure<DonutMenu>(OuterRadiusProperty);
+ AffectsRender<DonutMenu>(HoleRatioProperty, SliceOpacityProperty, CenterTitleProperty, CenterSubtitleProperty,
+ IsEditModeProperty, SliceBrushProperty, SliceBorderBrushProperty, CenterBrushProperty, AccentBrushProperty,
+ OnAccentBrushProperty, ForegroundProperty, SecondaryForegroundProperty, SuccessBrushProperty);
+ ItemsProperty.Changed.AddClassHandler<DonutMenu>((d, _) => d.OnItemsChanged());
+ }
+
+ public DonutMenu()
+ {
+ ClipToBounds = false;
+ Cursor = new Cursor(StandardCursorType.Hand);
+ }
+
+ public IReadOnlyList<DonutItem>? Items { get => GetValue(ItemsProperty); set => SetValue(ItemsProperty, value); }
+ public double OuterRadius { get => GetValue(OuterRadiusProperty); set => SetValue(OuterRadiusProperty, value); }
+ public double HoleRatio { get => GetValue(HoleRatioProperty); set => SetValue(HoleRatioProperty, value); }
+ public double SliceOpacity { get => GetValue(SliceOpacityProperty); set => SetValue(SliceOpacityProperty, value); }
+ public string? CenterTitle { get => GetValue(CenterTitleProperty); set => SetValue(CenterTitleProperty, value); }
+ public string? CenterSubtitle { get => GetValue(CenterSubtitleProperty); set => SetValue(CenterSubtitleProperty, value); }
+
+ /// <summary>Settings editor mode: shows ✎ on hover, raises drag and edit events instead of invoking slices.</summary>
+ public bool IsEditMode { get => GetValue(IsEditModeProperty); set => SetValue(IsEditModeProperty, value); }
+
+ /// <summary>Live toolbar in click mode: right-click on a slice raises <see cref="SegmentContextRequested"/>.</summary>
+ public bool AllowContextEdit { get => GetValue(AllowContextEditProperty); set => SetValue(AllowContextEditProperty, value); }
+
+ public IBrush? SliceBrush { get => GetValue(SliceBrushProperty); set => SetValue(SliceBrushProperty, value); }
+ public IBrush? SliceBorderBrush { get => GetValue(SliceBorderBrushProperty); set => SetValue(SliceBorderBrushProperty, value); }
+ public IBrush? CenterBrush { get => GetValue(CenterBrushProperty); set => SetValue(CenterBrushProperty, value); }
+ public IBrush? AccentBrush { get => GetValue(AccentBrushProperty); set => SetValue(AccentBrushProperty, value); }
+ public IBrush? OnAccentBrush { get => GetValue(OnAccentBrushProperty); set => SetValue(OnAccentBrushProperty, value); }
+ public IBrush? Foreground { get => GetValue(ForegroundProperty); set => SetValue(ForegroundProperty, value); }
+ public IBrush? SecondaryForeground { get => GetValue(SecondaryForegroundProperty); set => SetValue(SecondaryForegroundProperty, value); }
+ public IBrush? DangerBrush { get => GetValue(DangerBrushProperty); set => SetValue(DangerBrushProperty, value); }
+
+ /// <summary>True while an external drag hovers the hole (drop = cancel).</summary>
+ public bool IsCenterHot => _externalCenterHot;
+
+ /// <summary>Currently emphasised slice (pointer hover or external highlight), or -1.</summary>
+ public int ActiveIndex => _externalHighlight >= 0 ? _externalHighlight : _hoverIndex;
+
+ /// <summary>A slice was clicked (live toolbar, click mode).</summary>
+ public event EventHandler<int>? SegmentInvoked;
+
+ /// <summary>Right-click or ✎ on a slice.</summary>
+ public event EventHandler<int>? SegmentContextRequested;
+
+ /// <summary>The hole was clicked.</summary>
+ public event EventHandler? CenterInvoked;
+
+ /// <summary>Edit mode: the user started dragging slice <c>Index</c>.</summary>
+ public event EventHandler<(int Index, PointerEventArgs Args)>? SegmentDragStarted;
+
+ /// <summary>The emphasised slice changed (-1 = none). Useful to update the centre text.</summary>
+ public event EventHandler<int>? ActiveIndexChanged;
+
+ private int Count => Items?.Count ?? 0;
+ private Point Center => new(Bounds.Width / 2, Bounds.Height / 2);
+ private double InnerRadius => OuterRadius * Math.Clamp(HoleRatio, 0.2, 0.75);
+
+ // ───────────────────────── Public API ─────────────────────────
+
+ /// <summary>Plays the "pop out from the centre" animation.</summary>
+ public void PlayOpenAnimation()
+ {
+ ResetProgress();
+ _closing = false;
+ _closeCallback = null;
+ if (!Motion.Enabled)
+ {
+ Array.Fill(_open, 1);
+ InvalidateVisual();
+ return;
+ }
+ Array.Fill(_open, 0);
+ _openClock = 0;
+ StartAnimation();
+ }
+
+ /// <summary>Shrinks the donut back into the centre, then calls <paramref name="done"/>.</summary>
+ public void PlayCloseAnimation(Action done)
+ {
+ if (!Motion.Enabled || Count == 0)
+ {
+ done();
+ return;
+ }
+ _closing = true;
+ _closeCallback = done;
+ _openClock = 0;
+ StartAnimation();
+ }
+
+ /// <summary>Short "boing" of the centre, e.g. after a drop.</summary>
+ public void PulseCenter()
+ {
+ if (!Motion.Enabled)
+ return;
+ _centerPulse.Velocity = 6;
+ StartAnimation();
+ }
+
+ /// <summary>Highlights a slice from outside (drag-over in the live toolbar). -1 clears.</summary>
+ public void SetExternalHighlight(int index, bool centerHot = false)
+ {
+ if (_externalHighlight == index && _externalCenterHot == centerHot)
+ return;
+ _externalHighlight = index;
+ _externalCenterHot = centerHot;
+ ActiveIndexChanged?.Invoke(this, ActiveIndex);
+ StartAnimation();
+ }
+
+ /// <summary>Edit mode: the slice being dragged is drawn faded.</summary>
+ public void SetDimmedIndex(int index)
+ {
+ _dimmedIndex = index;
+ InvalidateVisual();
+ }
+
+ /// <summary>Edit mode: highlights where a dragged item would land (-1 none, Count = empty ring).</summary>
+ public void SetDropTarget(int index)
+ {
+ if (_dropTargetIndex == index)
+ return;
+ _dropTargetIndex = index;
+ InvalidateVisual();
+ }
+
+ /// <summary>Hit-tests a point in this control's coordinates.</summary>
+ public DonutHit HitTest(Point p)
+ {
+ if (_progressMode)
+ return HitTestProgress(p);
+ if (IsEditMode && _hoverIndex >= 0 && _hoverIndex < Count &&
+ Distance(p, EditButtonCenter(_hoverIndex)) <= 13)
+ return new DonutHit(DonutHitKind.EditButton, _hoverIndex);
+ return DonutGeometry.HitTest(Center, p, InnerRadius, OuterRadius, Count, PopOut);
+ }
+
+ // ───────────────────────── Layout ─────────────────────────
+
+ protected override Size MeasureOverride(Size availableSize)
+ {
+ var side = 2 * (OuterRadius + PopOut + 14);
+ return new Size(side, side);
+ }
+
+ private void OnItemsChanged()
+ {
+ var n = Count;
+ _hover = new Spring[n];
+ _open = Enumerable.Repeat(1.0, n).ToArray();
+ _hoverIndex = -1;
+ _externalHighlight = -1;
+ _dimmedIndex = -1;
+ _dropTargetIndex = -1;
+ InvalidateVisual();
+ }
+
+ // ───────────────────────── Input ─────────────────────────
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ var p = e.GetPosition(this);
+ if (_progressMode)
+ {
+ OnProgressPointerMoved(p);
+ return;
+ }
+
+ if (_press is { } press && IsEditMode && Distance(p, press.Start) > DragStartDistance && press.Index >= 0)
+ {
+ _press = null;
+ SegmentDragStarted?.Invoke(this, (press.Index, e));
+ return;
+ }
+
+ var hit = HitTest(p);
+ SetHover(hit.Kind switch
+ {
+ DonutHitKind.Segment or DonutHitKind.EditButton => hit.Index,
+ _ => -1,
+ });
+ ToolTip.SetTip(this, _hoverIndex >= 0 && Items![_hoverIndex] is { IsEnabled: false } item ? item.DisabledReason : null);
+ }
+
+ protected override void OnPointerExited(PointerEventArgs e)
+ {
+ base.OnPointerExited(e);
+ if (_progressMode)
+ {
+ OnProgressPointerMoved(new Point(double.MaxValue / 4, 0));
+ return;
+ }
+ if (_press is null)
+ SetHover(-1);
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ var point = e.GetCurrentPoint(this);
+ var hit = HitTest(point.Position);
+
+ if (_progressMode)
+ {
+ if (point.Properties.IsLeftButtonPressed)
+ {
+ _press = (-1, point.Position, e);
+ e.Handled = true;
+ }
+ return;
+ }
+
+ if (point.Properties.IsRightButtonPressed)
+ {
+ if (hit.Kind is DonutHitKind.Segment or DonutHitKind.EditButton && (IsEditMode || AllowContextEdit))
+ {
+ SegmentContextRequested?.Invoke(this, hit.Index);
+ e.Handled = true;
+ }
+ return;
+ }
+
+ if (point.Properties.IsLeftButtonPressed)
+ {
+ _press = (hit.Kind == DonutHitKind.Segment ? hit.Index : -1, point.Position, e);
+ e.Handled = true;
+ }
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (_press is null)
+ return;
+ _press = null;
+
+ if (_progressMode)
+ {
+ OnProgressPointerReleased(e.GetPosition(this));
+ e.Handled = true;
+ return;
+ }
+
+ var hit = HitTest(e.GetPosition(this));
+ switch (hit.Kind)
+ {
+ case DonutHitKind.EditButton:
+ SegmentContextRequested?.Invoke(this, hit.Index);
+ break;
+ case DonutHitKind.Segment when !IsEditMode && Items![hit.Index].IsEnabled:
+ SegmentInvoked?.Invoke(this, hit.Index);
+ break;
+ case DonutHitKind.Center when !IsEditMode:
+ CenterInvoked?.Invoke(this, EventArgs.Empty);
+ break;
+ }
+ e.Handled = true;
+ }
+
+ private void SetHover(int index)
+ {
+ if (_hoverIndex == index)
+ return;
+ _hoverIndex = index;
+ ActiveIndexChanged?.Invoke(this, ActiveIndex);
+ StartAnimation();
+ }
+
+ // ───────────────────────── Animation ─────────────────────────
+
+ /// <summary>Critically-underdamped spring: gives the soft "boing" when a slice pops out.</summary>
+ private struct Spring
+ {
+ public double Value;
+ public double Velocity;
+
+ public bool Step(double target, double dt, double stiffness = 320, double damping = 20)
+ {
+ var force = stiffness * (target - Value) - damping * Velocity;
+ Velocity += force * dt;
+ Value += Velocity * dt;
+ var settled = Math.Abs(target - Value) < 0.001 && Math.Abs(Velocity) < 0.01;
+ if (settled)
+ {
+ Value = target;
+ Velocity = 0;
+ }
+ return !settled;
+ }
+ }
+
+ private void StartAnimation()
+ {
+ InvalidateVisual();
+ if (_animating)
+ return;
+ var top = TopLevel.GetTopLevel(this);
+ if (top is null)
+ return;
+ _animating = true;
+ _lastFrame = null;
+ top.RequestAnimationFrame(OnFrame);
+ }
+
+ private void OnFrame(TimeSpan time)
+ {
+ var dt = _lastFrame is { } last ? Math.Clamp((time - last).TotalSeconds, 0, 0.05) : 1 / 60.0;
+ _lastFrame = time;
+ var active = Advance(dt);
+
+ InvalidateVisual();
+ if (active && TopLevel.GetTopLevel(this) is { } top)
+ top.RequestAnimationFrame(OnFrame);
+ else
+ _animating = false;
+ }
+
+ /// <summary>
+ /// Advances every animation by <paramref name="dt"/> seconds. Returns true while more frames are needed.
+ /// Internal so tests can step time deterministically.
+ /// </summary>
+ internal bool Advance(double dt)
+ {
+ var active = false;
+
+ if (!Motion.Enabled)
+ {
+ for (var i = 0; i < _hover.Length; i++)
+ {
+ _hover[i].Value = i == ActiveIndex ? 1 : 0;
+ _hover[i].Velocity = 0;
+ }
+ Array.Fill(_open, _closing ? 0 : 1);
+ _centerPulse = default;
+ if (_closing)
+ FinishClose();
+ active |= StepProgress(dt); // hold timers still run without animation
+ }
+ else
+ {
+ for (var i = 0; i < _hover.Length; i++)
+ active |= _hover[i].Step(i == ActiveIndex ? 1 : 0, dt);
+ active |= _centerPulse.Step(0, dt, 260, 12);
+ active |= StepProgress(dt);
+
+ if (_openClock < double.MaxValue)
+ {
+ _openClock += dt;
+ var done = true;
+ for (var i = 0; i < _open.Length; i++)
+ {
+ var t = Math.Clamp((_openClock - i * (_closing ? 0.01 : OpenStagger)) / (_closing ? 0.16 : OpenDuration), 0, 1);
+ _open[i] = _closing ? 1 - EaseInCubic(t) : EaseOutBack(t);
+ done &= t >= 1;
+ }
+ if (done)
+ {
+ _openClock = double.MaxValue;
+ if (_closing)
+ FinishClose();
+ }
+ else
+ {
+ active = true;
+ }
+ }
+ }
+
+ return active;
+ }
+
+ private void FinishClose()
+ {
+ _closing = false;
+ var callback = _closeCallback;
+ _closeCallback = null;
+ callback?.Invoke();
+ }
+
+ private static double EaseOutBack(double t)
+ {
+ const double c1 = 1.55;
+ const double c3 = c1 + 1;
+ return 1 + c3 * Math.Pow(t - 1, 3) + c1 * Math.Pow(t - 1, 2);
+ }
+
+ private static double EaseInCubic(double t) => t * t * t;
+
+ // ───────────────────────── Rendering ─────────────────────────
+
+ public override void Render(DrawingContext context)
+ {
+ var center = Center;
+ var r2 = OuterRadius;
+ var r1 = InnerRadius;
+ var n = Count;
+ var typeface = new Typeface(GetValue(TextElement.FontFamilyProperty), FontStyle.Normal, FontWeight.SemiBold);
+ var typefaceRegular = new Typeface(GetValue(TextElement.FontFamilyProperty));
+
+ if (_progressMode)
+ {
+ RenderProgress(context, center, r1, r2, typeface, typefaceRegular);
+ return;
+ }
+
+ DrawSoftShadow(context, center, r2);
+
+ if (n == 0)
+ {
+ var ring = CreateRing(center, r1, r2);
+ context.DrawGeometry(WithOpacity(SliceBrush, SliceOpacity), BorderPen(), ring);
+ if (_dropTargetIndex >= 0)
+ context.DrawGeometry(WithOpacity(AccentBrush, 0.35), null, ring);
+ }
+
+ for (var i = 0; i < n; i++)
+ {
+ var item = Items![i];
+ var open = i < _open.Length ? _open[i] : 1;
+ if (open <= 0.001)
+ continue;
+
+ var hover = i < _hover.Length ? _hover[i].Value : 0;
+ var mid = DonutGeometry.MidAngle(i, n);
+ var offset = DonutGeometry.PointAt(new Point(0, 0), hover * PopOut, mid);
+
+ // Open animation: scale up from the centre with a small twist.
+ var scale = 0.55 + 0.45 * open;
+ var rotate = (1 - Math.Min(open, 1)) * -0.35;
+ var transform =
+ Matrix.CreateTranslation(-center.X, -center.Y) *
+ Matrix.CreateRotation(rotate) *
+ Matrix.CreateScale(scale * (1 + hover * 0.025), scale * (1 + hover * 0.025)) *
+ Matrix.CreateTranslation(center.X + offset.X, center.Y + offset.Y);
+
+ using (context.PushTransform(transform))
+ using (context.PushOpacity(Math.Clamp(open, 0, 1) * (i == _dimmedIndex ? 0.3 : 1)))
+ {
+ var wedge = CreateWedge(center, r1, r2, i, n);
+ context.DrawGeometry(WithOpacity(SliceBrush, SliceOpacity * (item.IsEnabled ? 1 : 0.55)), BorderPen(), wedge);
+
+ var emphasis = i == _dropTargetIndex ? 1.0 : hover;
+ if (emphasis > 0.01 && item.IsEnabled)
+ context.DrawGeometry(WithOpacity(AccentBrush, 0.22 + 0.6 * Math.Clamp(emphasis, 0, 1)), null, wedge);
+
+ var hot = (i == ActiveIndex || i == _dropTargetIndex) && item.IsEnabled;
+ DrawLabel(context, item, center, (r1 + r2) / 2, mid, DonutGeometry.Span(n) * (r1 + r2) / 2 - 10,
+ r2 - r1 - 16, typeface, typefaceRegular, hot);
+ }
+ }
+
+ DrawCenter(context, center, r1, typeface, typefaceRegular);
+
+ if (IsEditMode && _hoverIndex >= 0 && _hoverIndex < n && _dimmedIndex < 0)
+ DrawEditButton(context, EditButtonCenter(_hoverIndex));
+ }
+
+ private void DrawSoftShadow(DrawingContext context, Point center, double r2)
+ {
+ // A radial gradient ring fakes a soft drop shadow without blur effects (cheap on any GPU).
+ var shadowRadius = r2 + 14;
+ var brush = new RadialGradientBrush
+ {
+ GradientStops =
+ {
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), 0),
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), (r2 - 18) / shadowRadius),
+ new GradientStop(Color.FromArgb(46, 0, 0, 0), (r2 - 2) / shadowRadius),
+ new GradientStop(Color.FromArgb(0, 0, 0, 0), 1),
+ },
+ };
+ var opening = _open.Length == 0 ? 1 : Math.Clamp(_open.Average(), 0, 1);
+ using (context.PushOpacity(opening))
+ context.DrawEllipse(brush, null, new Point(center.X, center.Y + 4), shadowRadius, shadowRadius);
+ }
+
+ private void DrawCenter(DrawingContext context, Point center, double r1, Typeface bold, Typeface regular)
+ {
+ var pulse = 1 + _centerPulse.Value * 0.06;
+ var radius = (r1 - 6) * pulse;
+ var cancelHot = _externalCenterHot;
+ context.DrawEllipse(CenterBrush, BorderPen(), center, radius, radius);
+ if (cancelHot)
+ context.DrawEllipse(WithOpacity(DangerBrush, 0.18), null, center, radius, radius);
+
+ var maxWidth = radius * 1.6;
+ var title = MakeText(CenterTitle ?? "", bold, 14, Foreground, maxWidth, maxLines: 2);
+ var subtitle = MakeText(CenterSubtitle ?? "", regular, 11.5, cancelHot ? DangerBrush : SecondaryForeground, maxWidth, maxLines: 2);
+ var total = title.Height + (string.IsNullOrEmpty(CenterSubtitle) ? 0 : subtitle.Height + 2);
+ var y = center.Y - total / 2;
+ DrawCentered(context, title, center.X, y);
+ if (!string.IsNullOrEmpty(CenterSubtitle))
+ DrawCentered(context, subtitle, center.X, y + title.Height + 2);
+ }
+
+ private void DrawLabel(DrawingContext context, DonutItem item, Point center, double radius, double angle,
+ double maxWidth, double maxHeight, Typeface bold, Typeface regular, bool hot)
+ {
+ var foreground = hot ? OnAccentBrush : item.IsEnabled ? Foreground : SecondaryForeground;
+ var width = Math.Clamp(maxWidth, 30, 120);
+ var label = MakeText(item.Label, bold, 13, foreground, width, maxLines: 2);
+ var showCaption = !string.IsNullOrEmpty(item.Caption) &&
+ !string.Equals(item.Caption, item.Label, StringComparison.OrdinalIgnoreCase) &&
+ label.Height + 14 < maxHeight;
+ var caption = showCaption ? MakeText(item.Caption!, regular, 10.5, hot ? OnAccentBrush : SecondaryForeground, width) : null;
+
+ var total = label.Height + (caption?.Height ?? 0);
+ var anchor = DonutGeometry.PointAt(center, radius, angle);
+ var y = anchor.Y - total / 2;
+ DrawCentered(context, label, anchor.X, y);
+ if (caption is not null)
+ DrawCentered(context, caption, anchor.X, y + label.Height);
+ }
+
+ private Point EditButtonCenter(int index)
+ {
+ var mid = DonutGeometry.MidAngle(index, Count);
+ return DonutGeometry.PointAt(Center, OuterRadius - 14 + PopOut, mid);
+ }
+
+ private void DrawEditButton(DrawingContext context, Point at)
+ {
+ context.DrawEllipse(AccentBrush, new Pen(CenterBrush, 2), at, 12, 12);
+ var bounds = PencilIcon.Bounds;
+ var s = 13 / Math.Max(bounds.Width, bounds.Height);
+ var matrix = Matrix.CreateTranslation(-bounds.Center.X, -bounds.Center.Y) * Matrix.CreateScale(s, s) * Matrix.CreateTranslation(at.X, at.Y);
+ using (context.PushTransform(matrix))
+ context.DrawGeometry(OnAccentBrush, null, PencilIcon);
+ }
+
+ /// <summary>
+ /// Draws text horizontally centred on <paramref name="centerX"/>.
+ /// The text is laid out with <see cref="TextAlignment.Center"/> inside a box of <see cref="FormattedText.MaxTextWidth"/>,
+ /// so the box (not the measured <see cref="FormattedText.Width"/>) must be centred — otherwise short labels
+ /// drift right by (box − text) / 2.
+ /// </summary>
+ internal static void DrawCentered(DrawingContext context, FormattedText text, double centerX, double top) =>
+ context.DrawText(text, new Point(centerX - text.MaxTextWidth / 2, top));
+
+ private Pen? BorderPen() => SliceBorderBrush is null ? null : new Pen(SliceBorderBrush, 1);
+
+ private static FormattedText MakeText(string text, Typeface typeface, double size, IBrush? brush, double maxWidth, int maxLines = 1) =>
+ new(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeface, size, brush)
+ {
+ MaxTextWidth = Math.Max(10, maxWidth),
+ MaxLineCount = maxLines,
+ Trimming = TextTrimming.CharacterEllipsis,
+ TextAlignment = TextAlignment.Center,
+ };
+
+ private static IBrush? WithOpacity(IBrush? brush, double opacity) => brush switch
+ {
+ ISolidColorBrush solid => new SolidColorBrush(solid.Color, solid.Opacity * opacity),
+ _ => brush,
+ };
+
+ private static double Distance(Point a, Point b) => Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
+
+ /// <summary>Wedge-shaped slice with a constant-width gap to its neighbours.</summary>
+ private static StreamGeometry CreateWedge(Point c, double r1, double r2, int index, int count)
+ {
+ if (count == 1)
+ return CreateRing(c, r1, r2);
+
+ var span = DonutGeometry.Span(count);
+ var mid = DonutGeometry.MidAngle(index, count);
+ var outerHalf = span / 2 - GapPixels / 2 / r2;
+ var innerHalf = span / 2 - GapPixels / 2 / r1;
+
+ var geometry = new StreamGeometry();
+ using var ctx = geometry.Open();
+ ctx.BeginFigure(DonutGeometry.PointAt(c, r2, mid - outerHalf), true);
+ ctx.ArcTo(DonutGeometry.PointAt(c, r2, mid + outerHalf), new Size(r2, r2), 0, outerHalf * 2 > Math.PI, SweepDirection.Clockwise);
+ ctx.LineTo(DonutGeometry.PointAt(c, r1, mid + innerHalf));
+ ctx.ArcTo(DonutGeometry.PointAt(c, r1, mid - innerHalf), new Size(r1, r1), 0, innerHalf * 2 > Math.PI, SweepDirection.CounterClockwise);
+ ctx.EndFigure(true);
+ return geometry;
+ }
+
+ /// <summary>Full ring (used for a single slice and for the empty donut).</summary>
+ private static StreamGeometry CreateRing(Point c, double r1, double r2)
+ {
+ var geometry = new StreamGeometry();
+ using var ctx = geometry.Open();
+ ctx.SetFillRule(FillRule.EvenOdd);
+ foreach (var r in new[] { r2, r1 })
+ {
+ ctx.BeginFigure(new Point(c.X, c.Y - r), true);
+ ctx.ArcTo(new Point(c.X, c.Y + r), new Size(r, r), 0, false, SweepDirection.Clockwise);
+ ctx.ArcTo(new Point(c.X, c.Y - r), new Size(r, r), 0, false, SweepDirection.Clockwise);
+ ctx.EndFigure(true);
+ }
+ return geometry;
+ }
+}
diff --git a/src/Filee.App/Filee.App.csproj b/src/Filee.App/Filee.App.csproj
new file mode 100644
index 00000000..cde86697
--- /dev/null
+++ b/src/Filee.App/Filee.App.csproj
@@ -0,0 +1,60 @@
+<!--
+ Filee.App: the Avalonia desktop application (tray, donut toolbar, settings window).
+-->
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>WinExe</OutputType>
+ <AssemblyName>Filee</AssemblyName>
+ <RootNamespace>Filee.App</RootNamespace>
+ <ApplicationManifest>app.manifest</ApplicationManifest>
+ <ApplicationIcon>Assets\Icons\filee.ico</ApplicationIcon>
+ <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
+ <BuiltInComInteropSupport>true</BuiltInComInteropSupport>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />
+ <ProjectReference Include="..\Filee.Engines\Filee.Engines.csproj" />
+ <ProjectReference Include="..\Filee.Platform.Windows\Filee.Platform.Windows.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Avalonia" />
+ <PackageReference Include="Avalonia.Desktop" />
+ <PackageReference Include="Avalonia.Themes.Fluent" />
+ <PackageReference Include="AvaloniaUI.DiagnosticsSupport">
+ <IncludeAssets Condition="'$(Configuration)' != 'Debug'">None</IncludeAssets>
+ <PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets>
+ </PackageReference>
+ <PackageReference Include="CommunityToolkit.Mvvm" />
+ <PackageReference Include="Microsoft.Extensions.Logging" />
+ <PackageReference Include="SharpHook" />
+ <PackageReference Include="Velopack" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <AvaloniaResource Include="Assets\**" />
+ <!-- Shown on the About page. -->
+ <AvaloniaResource Include="..\..\THIRD-PARTY-NOTICES.md" Link="Assets\THIRD-PARTY-NOTICES.md" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <InternalsVisibleTo Include="Filee.App.Tests" />
+ </ItemGroup>
+
+ <!-- Native debug symbols from NuGet packages (SkiaSharp, HarfBuzz: ~100 MB) are useless to users. -->
+ <Target Name="FileeRemoveNativeSymbols" AfterTargets="Publish" Condition="'$(Configuration)' == 'Release'">
+ <ItemGroup>
+ <_FileeNativePdb Include="$(PublishDir)lib*.pdb" />
+ </ItemGroup>
+ <Delete Files="@(_FileeNativePdb)" />
+ </Target>
+
+ <!-- Repository URL for the updater / About page, taken from Directory.Build.props. -->
+ <ItemGroup>
+ <AssemblyAttribute Include="System.Reflection.AssemblyMetadataAttribute">
+ <_Parameter1>RepositoryUrl</_Parameter1>
+ <_Parameter2>$(FileeRepositoryUrl)</_Parameter2>
+ </AssemblyAttribute>
+ </ItemGroup>
+</Project>
diff --git a/src/Filee.App/Program.cs b/src/Filee.App/Program.cs
new file mode 100644
index 00000000..73d7c38b
--- /dev/null
+++ b/src/Filee.App/Program.cs
@@ -0,0 +1,64 @@
+// Entry point. Order matters:
+// 1. Velopack hooks (install/update/uninstall) must run before anything else.
+// 2. Single instance: a second launch (e.g. from the Explorer context menu) forwards its arguments
+// to the running instance and exits.
+// 3. Start Avalonia. The app lives in the tray, so it only exits via the tray "Quit" command.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+using Filee.App.Services;
+using Velopack;
+
+namespace Filee.App;
+
+internal static class Program
+{
+ /// <summary>Parsed command line of this process.</summary>
+ public static CommandLine Options { get; private set; } = CommandLine.Parse([]);
+
+ /// <summary>Owned by the first instance for its whole lifetime.</summary>
+ public static SingleInstance? Instance { get; private set; }
+
+ [STAThread]
+ public static int Main(string[] args)
+ {
+ var velopack = VelopackApp.Build();
+ if (OperatingSystem.IsWindows())
+ velopack = velopack.OnBeforeUninstallFastCallback(_ => UninstallCleanup.Run());
+ velopack.Run();
+
+ Options = CommandLine.Parse(args);
+ Instance = SingleInstance.Acquire();
+ if (!Instance.IsFirst)
+ {
+ Instance.ForwardToFirst(args);
+ Instance.Dispose();
+ return 0;
+ }
+
+ try
+ {
+ return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args, ShutdownMode.OnExplicitShutdown);
+ }
+ finally
+ {
+ Instance.Dispose();
+ }
+ }
+
+ /// <summary>Also used by the XAML previewer.</summary>
+ public static AppBuilder BuildAvaloniaApp() =>
+ AppBuilder.Configure<App>()
+ .UsePlatformDetect()
+ .ConfigureFonts(fonts => fonts.AddFontCollection(new FileeFontCollection()))
+#if DEBUG
+ .WithDeveloperTools()
+#endif
+ .LogToTrace();
+}
+
+/// <summary>Embedded Noto fonts: <c>fonts:Filee#Noto Sans</c>, <c>#Noto Sans KR</c>, <c>#Noto Sans SC</c>.</summary>
+internal sealed class FileeFontCollection() : Avalonia.Media.Fonts.EmbeddedFontCollection(
+ new Uri("fonts:Filee", UriKind.Absolute),
+ new Uri("avares://Filee/Assets/Fonts", UriKind.Absolute));
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
new file mode 100644
index 00000000..a9f22a35
--- /dev/null
+++ b/src/Filee.App/Services/AppHost.cs
@@ -0,0 +1,69 @@
+// Composition root: every long-lived service is created here. Views get services through AppHost.Get<T>().
+
+using Filee.App.Services.Triggers;
+using Filee.App.ViewModels;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+using Filee.Engines;
+using Filee.Engines.Infrastructure;
+using Filee.Platform.Windows;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.Services;
+
+public static class AppHost
+{
+ private static IServiceProvider? _services;
+
+ public static IServiceProvider Services => _services ?? throw new InvalidOperationException("AppHost not built.");
+
+ public static T Get<T>() where T : notnull => Services.GetRequiredService<T>();
+
+ public static IServiceProvider Build(string? dataDirectory = null)
+ {
+ var dataDir = dataDirectory ?? UserDataStore.DefaultDirectory;
+ var services = new ServiceCollection();
+
+ services.AddLogging(b => b
+ .AddProvider(new FileLoggerProvider(Path.Combine(dataDir, "logs")))
+ .SetMinimumLevel(LogLevel.Information));
+
+ services.AddSingleton(sp => new UserDataStore(dataDir, sp.GetRequiredService<ILogger<UserDataStore>>()));
+ services.AddSingleton<IPlatformServices>(_ =>
+ OperatingSystem.IsWindows() ? new WindowsPlatformServices() : new NullPlatformServices());
+
+ services.AddSingleton<LocalizationService>();
+ services.AddSingleton<ILocalizer>(sp => sp.GetRequiredService<LocalizationService>());
+ 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(sp => EngineRegistry.CreateAll(sp.GetRequiredService<EngineEnvironment>()));
+ services.AddSingleton(sp => new ConverterCatalog(sp.GetRequiredService<IReadOnlyList<IConverter>>()));
+ services.AddSingleton(sp => new JobQueue(
+ sp.GetRequiredService<ConverterCatalog>(),
+ EngineRegistry.FindPdfMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
+ sp.GetRequiredService<ILogger<JobQueue>>()));
+
+ services.AddSingleton<EngineDownloadService>();
+ services.AddSingleton<PresetAvailability>();
+ services.AddSingleton<RadialViewModel>();
+ services.AddSingleton<ConversionService>();
+ services.AddSingleton<TriggerService>();
+ services.AddSingleton<RadialController>();
+ services.AddSingleton<TrayService>();
+ services.AddSingleton<UpdateService>();
+ services.AddSingleton<WindowService>();
+ services.AddSingleton<MainWindowViewModel>();
+
+ _services = services.BuildServiceProvider();
+ return _services;
+ }
+}
diff --git a/src/Filee.App/Services/AppJsonContext.cs b/src/Filee.App/Services/AppJsonContext.cs
new file mode 100644
index 00000000..a4f7df24
--- /dev/null
+++ b/src/Filee.App/Services/AppJsonContext.cs
@@ -0,0 +1,10 @@
+// JSON source generation for types serialized by the app project itself.
+
+using System.Text.Json.Serialization;
+
+namespace Filee.App.Services;
+
+[JsonSourceGenerationOptions(ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip, AllowTrailingCommas = true)]
+[JsonSerializable(typeof(Dictionary<string, string>))]
+[JsonSerializable(typeof(string[]))]
+internal sealed partial class AppJsonContext : JsonSerializerContext;
diff --git a/src/Filee.App/Services/CommandLine.cs b/src/Filee.App/Services/CommandLine.cs
new file mode 100644
index 00000000..be1b9250
--- /dev/null
+++ b/src/Filee.App/Services/CommandLine.cs
@@ -0,0 +1,40 @@
+// Command line options:
+// Filee.exe open the main window
+// Filee.exe --background start in the tray only (used by "start with Windows")
+// Filee.exe --settings open the main window
+// Filee.exe --convert a b ... open the donut for these files (Explorer context menu / Send To)
+
+namespace Filee.App.Services;
+
+public sealed record CommandLine(bool Background, bool ShowSettings, IReadOnlyList<string> ConvertFiles)
+{
+ public static CommandLine Parse(IReadOnlyList<string> args)
+ {
+ var background = false;
+ var settings = false;
+ var files = new List<string>();
+ var collecting = false;
+
+ foreach (var arg in args)
+ {
+ switch (arg.ToLowerInvariant())
+ {
+ case "--background":
+ background = true;
+ break;
+ case "--settings":
+ settings = true;
+ break;
+ case "--convert":
+ collecting = true;
+ break;
+ default:
+ // Velopack passes its own --veloapp-* arguments; ignore anything unknown that isn't a file.
+ if (collecting && !arg.StartsWith("--", StringComparison.Ordinal) && (File.Exists(arg) || Directory.Exists(arg)))
+ files.Add(Path.GetFullPath(arg));
+ break;
+ }
+ }
+ return new CommandLine(background, settings, files);
+ }
+}
diff --git a/src/Filee.App/Services/ConversionService.cs b/src/Filee.App/Services/ConversionService.cs
new file mode 100644
index 00000000..30d89207
--- /dev/null
+++ b/src/Filee.App/Services/ConversionService.cs
@@ -0,0 +1,95 @@
+// UI-facing wrapper around JobQueue: starts jobs, keeps bindable lists for the toast window and records history.
+// Jobs started from the donut are first shown by its progress ring and only appear in the toast when the ring
+// hands them over (long job, failure, or a new drag).
+
+using System.Collections.ObjectModel;
+using Avalonia.Threading;
+using Filee.App.ViewModels;
+using Filee.Core.Conversion;
+using Filee.Core.History;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.App.Services;
+
+public sealed class ConversionService
+{
+ private static readonly TimeSpan KeepSuccess = TimeSpan.FromSeconds(5);
+ private static readonly TimeSpan KeepErrors = TimeSpan.FromSeconds(15);
+
+ private readonly JobQueue _queue;
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+ private readonly IPlatformServices _platform;
+ private readonly System.Collections.Concurrent.ConcurrentDictionary<string, JobViewModel> _byId = new();
+
+ public ConversionService(JobQueue queue, UserDataStore store, ILocalizer loc, IPlatformServices platform)
+ {
+ _queue = queue;
+ _store = store;
+ _loc = loc;
+ _platform = platform;
+ _queue.JobUpdated += OnJobUpdated;
+ _queue.JobFinished += OnJobFinished;
+ }
+
+ /// <summary>All jobs that are running or finished recently, newest first. UI thread only.</summary>
+ public ObservableCollection<JobViewModel> Jobs { get; } = [];
+
+ /// <summary>The subset shown in the toast window. UI thread only.</summary>
+ public ObservableCollection<JobViewModel> ToastJobs { get; } = [];
+
+ /// <summary>Starts converting files with a preset.</summary>
+ /// <param name="files">Source files.</param>
+ /// <param name="preset">Preset to apply.</param>
+ /// <param name="showInToast">False when another view (the donut's progress ring) displays the job first.</param>
+ /// <returns>The job's view model, or null when there was nothing to convert.</returns>
+ public JobViewModel? Start(IReadOnlyList<string> files, Preset preset, bool showInToast = true)
+ {
+ if (files.Count == 0)
+ return null;
+ var job = _queue.Enqueue(files, preset, _loc.DisplayName(preset));
+ var vm = new JobViewModel(job, _loc, _platform, Remove);
+ _byId[job.Id] = vm;
+ Jobs.Insert(0, vm);
+ if (showInToast)
+ ToastJobs.Insert(0, vm);
+ return vm;
+ }
+
+ /// <summary>Moves a job into the toast window (no-op if it is already there or gone).</summary>
+ public void ShowInToast(JobViewModel vm)
+ {
+ if (Jobs.Contains(vm) && !ToastJobs.Contains(vm))
+ ToastJobs.Insert(0, vm);
+ }
+
+ private void OnJobUpdated(object? sender, ConversionJob job)
+ {
+ // Called from worker threads, possibly many times per second: coalesce into one UI update.
+ if (_byId.TryGetValue(job.Id, out var vm) && vm.TryMarkPending())
+ Dispatcher.UIThread.Post(vm.Refresh, DispatcherPriority.Background);
+ }
+
+ private void OnJobFinished(object? sender, ConversionJob job)
+ {
+ _store.AddHistory(HistoryEntry.From(job));
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (!_byId.TryGetValue(job.Id, out var vm))
+ return;
+ vm.Refresh();
+ var keep = vm.HasErrors ? KeepErrors : KeepSuccess;
+ DispatcherTimer.RunOnce(() => Remove(vm), keep);
+ });
+ }
+
+ private void Remove(JobViewModel vm)
+ {
+ Jobs.Remove(vm);
+ ToastJobs.Remove(vm);
+ _byId.TryRemove(vm.Job.Id, out _);
+ }
+}
diff --git a/src/Filee.App/Services/EngineDownloadService.cs b/src/Filee.App/Services/EngineDownloadService.cs
new file mode 100644
index 00000000..bc430f57
--- /dev/null
+++ b/src/Filee.App/Services/EngineDownloadService.cs
@@ -0,0 +1,188 @@
+// Optional engine downloads for the UI: one observable state per package, one install at a time, and a catalog
+// refresh when an engine appears or disappears so donut slices and routes update immediately.
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Engines.Infrastructure;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.Services;
+
+public enum EnginePackageStatus
+{
+ NotInstalled,
+ Queued,
+ Downloading,
+ Unpacking,
+ Installed,
+ Failed,
+}
+
+/// <summary>Install state of one optional engine package, bound by the Engines page and the first-run setup.</summary>
+public sealed partial class EnginePackageState : ObservableObject
+{
+ private readonly ILocalizer _loc;
+
+ public EnginePackageState(EnginePackage package, ILocalizer loc)
+ {
+ Package = package;
+ _loc = loc;
+ }
+
+ public EnginePackage Package { get; }
+ public string Name => _loc[$"engines.package.{Package.Id}.name"];
+ public string Description => _loc[$"engines.package.{Package.Id}.description"];
+
+ public string Sizes => _loc.Format("engines.package.size",
+ FormatBytes(EngineDownloads.DownloadSize(Package)), FormatBytes(Package.InstalledSize));
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(StatusText), nameof(IsInstalled), nameof(IsBusy), nameof(CanInstall))]
+ private EnginePackageStatus _status;
+
+ /// <summary>0..100 while downloading or unpacking.</summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(StatusText))]
+ private double _progress;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(StatusText))]
+ private string? _error;
+
+ /// <summary>Ticked in the first-run setup.</summary>
+ [ObservableProperty]
+ private bool _selected;
+
+ public bool IsInstalled => Status == EnginePackageStatus.Installed;
+ public bool IsBusy => Status is EnginePackageStatus.Queued or EnginePackageStatus.Downloading or EnginePackageStatus.Unpacking;
+ public bool CanInstall => Status is EnginePackageStatus.NotInstalled or EnginePackageStatus.Failed;
+
+ public string StatusText => Status switch
+ {
+ EnginePackageStatus.Queued => _loc["engines.state.queued"],
+ EnginePackageStatus.Downloading => _loc.Format("engines.state.downloading", (int)Progress),
+ EnginePackageStatus.Unpacking => _loc["engines.state.unpacking"],
+ EnginePackageStatus.Installed => _loc["engines.state.installed"],
+ EnginePackageStatus.Failed => _loc.Format("engines.state.failed", Error ?? ""),
+ _ => _loc["engines.state.not_installed"],
+ };
+
+ internal CancellationTokenSource? Cancellation { get; set; }
+
+ /// <summary>Re-reads localized texts after a language change.</summary>
+ internal void Relocalize() => OnPropertyChanged(string.Empty);
+
+ /// <summary>"420 MB", "1.2 GB".</summary>
+ public static string FormatBytes(long bytes) => bytes >= 1_000_000_000
+ ? $"{bytes / 1_000_000_000.0:0.0} GB"
+ : $"{Math.Max(1, bytes / 1_000_000)} MB";
+}
+
+public sealed class EngineDownloadService
+{
+ private readonly EngineInstaller _installer;
+ private readonly ConverterCatalog _catalog;
+ private readonly ILogger<EngineDownloadService> _logger;
+ private readonly SemaphoreSlim _oneAtATime = new(1, 1);
+
+ public EngineDownloadService(ConverterCatalog catalog, ILocalizer loc, ILogger<EngineDownloadService> logger)
+ {
+ _catalog = catalog;
+ _logger = logger;
+ // Redirects are followed by the installer (mirrors may use plain HTTP; files are verified by SHA-256).
+ var http = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }) { Timeout = Timeout.InfiniteTimeSpan };
+ http.DefaultRequestHeaders.UserAgent.ParseAdd($"Filee/{typeof(EngineDownloadService).Assembly.GetName().Version}");
+ _installer = new EngineInstaller(http, logger: logger);
+ Packages = EngineDownloads.Packages.Select(p => new EnginePackageState(p, loc)).ToList();
+ if (loc is LocalizationService localization)
+ localization.LanguageChanged += (_, _) => Packages.ToList().ForEach(p => p.Relocalize());
+ RefreshStatus();
+ }
+
+ public IReadOnlyList<EnginePackageState> Packages { get; }
+
+ /// <summary>True while any package is downloading or waiting.</summary>
+ public bool IsBusy => Packages.Any(p => p.IsBusy);
+
+ /// <summary>Re-reads what is installed (e.g. after the user deleted a folder).</summary>
+ public void RefreshStatus()
+ {
+ foreach (var state in Packages.Where(p => !p.IsBusy))
+ state.Status = _installer.IsInstalled(state.Package) ? EnginePackageStatus.Installed : EnginePackageStatus.NotInstalled;
+ }
+
+ /// <summary>Downloads and installs a package; packages queue up and install one after another.</summary>
+ public async Task InstallAsync(EnginePackageState state)
+ {
+ if (state.IsBusy || state.IsInstalled)
+ return;
+ using var cancellation = new CancellationTokenSource();
+ state.Cancellation = cancellation;
+ state.Error = null;
+ state.Progress = 0;
+ state.Status = EnginePackageStatus.Queued;
+ try
+ {
+ await _oneAtATime.WaitAsync(cancellation.Token);
+ try
+ {
+ // Progress<T> reports on the UI thread it was created on.
+ var progress = new Progress<EngineInstallProgress>(p =>
+ {
+ if (!state.IsBusy)
+ return;
+ state.Status = p.Stage == EngineInstallStage.Downloading ? EnginePackageStatus.Downloading : EnginePackageStatus.Unpacking;
+ state.Progress = p.Fraction * 100;
+ });
+ await Task.Run(() => _installer.InstallAsync(state.Package, progress, cancellation.Token), cancellation.Token);
+ }
+ finally
+ {
+ _oneAtATime.Release();
+ }
+ state.Status = EnginePackageStatus.Installed;
+ _catalog.Refresh();
+ }
+ catch (OperationCanceledException)
+ {
+ state.Status = _installer.IsInstalled(state.Package) ? EnginePackageStatus.Installed : EnginePackageStatus.NotInstalled;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Installing engine package {Package} failed", state.Package.Id);
+ state.Error = ex is HttpRequestException ? ex.Message : ex.GetBaseException().Message;
+ state.Status = EnginePackageStatus.Failed;
+ }
+ finally
+ {
+ state.Cancellation = null;
+ }
+ }
+
+ public void Cancel(EnginePackageState state) => state.Cancellation?.Cancel();
+
+ /// <summary>Removes a package. Returns false when its files are in use (a conversion is running).</summary>
+ public bool Uninstall(EnginePackageState state)
+ {
+ if (state.IsBusy)
+ return false;
+ try
+ {
+ _installer.Uninstall(state.Package);
+ state.Status = EnginePackageStatus.NotInstalled;
+ _catalog.Refresh();
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ _logger.LogWarning(ex, "Removing engine package {Package} failed", state.Package.Id);
+ RefreshStatus();
+ return false;
+ }
+ }
+
+ /// <summary>The first not-installed package whose engines would make <paramref name="possible"/> true, if any.</summary>
+ public EnginePackageState? PackageEnabling(Func<RoutePlanner, bool> possible) =>
+ Packages.FirstOrDefault(p => !p.IsInstalled && possible(_catalog.CreatePlanner(p.Package.ConverterIds)));
+}
diff --git a/src/Filee.App/Services/FileLogger.cs b/src/Filee.App/Services/FileLogger.cs
new file mode 100644
index 00000000..4de17498
--- /dev/null
+++ b/src/Filee.App/Services/FileLogger.cs
@@ -0,0 +1,56 @@
+// Minimal file logger: %APPDATA%\Filee\logs\filee-yyyyMMdd.log, keeps the last 7 days.
+
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.Services;
+
+public sealed class FileLoggerProvider : ILoggerProvider
+{
+ private readonly string _directory;
+ private readonly object _lock = new();
+
+ public FileLoggerProvider(string directory)
+ {
+ _directory = directory;
+ Directory.CreateDirectory(directory);
+ foreach (var old in Directory.EnumerateFiles(directory, "filee-*.log")
+ .Where(f => File.GetLastWriteTime(f) < DateTime.Now.AddDays(-7)))
+ {
+ try { File.Delete(old); } catch (IOException) { }
+ }
+ }
+
+ public ILogger CreateLogger(string categoryName) => new FileLogger(this, categoryName);
+
+ public void Dispose() { }
+
+ private void Write(string line)
+ {
+ lock (_lock)
+ {
+ try
+ {
+ File.AppendAllText(Path.Combine(_directory, $"filee-{DateTime.Now:yyyyMMdd}.log"), line + Environment.NewLine);
+ }
+ catch (IOException) { }
+ }
+ }
+
+ private sealed class FileLogger(FileLoggerProvider provider, string category) : ILogger
+ {
+ public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information;
+
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
+ {
+ if (!IsEnabled(logLevel))
+ return;
+ var shortCategory = category[(category.LastIndexOf('.') + 1)..];
+ var line = $"{DateTime.Now:HH:mm:ss.fff} {logLevel.ToString()[..4].ToUpperInvariant()} {shortCategory}: {formatter(state, exception)}";
+ if (exception is not null)
+ line += Environment.NewLine + exception;
+ provider.Write(line);
+ }
+ }
+}
diff --git a/src/Filee.App/Services/GestureText.cs b/src/Filee.App/Services/GestureText.cs
new file mode 100644
index 00000000..9a069210
--- /dev/null
+++ b/src/Filee.App/Services/GestureText.cs
@@ -0,0 +1,26 @@
+// Human readable gesture text such as "Ctrl + Alt".
+
+using Filee.Core.Settings;
+
+namespace Filee.App.Services;
+
+public static class GestureText
+{
+ public static string Modifiers(ModifierKeys modifiers)
+ {
+ var parts = new List<string>();
+ if (modifiers.HasFlag(ModifierKeys.Ctrl)) parts.Add(OperatingSystem.IsMacOS() ? "⌃" : "Ctrl");
+ if (modifiers.HasFlag(ModifierKeys.Alt)) parts.Add(OperatingSystem.IsMacOS() ? "⌥ Option" : "Alt");
+ if (modifiers.HasFlag(ModifierKeys.Shift)) parts.Add("Shift");
+ if (modifiers.HasFlag(ModifierKeys.Meta)) parts.Add(OperatingSystem.IsMacOS() ? "⌘" : "Win");
+ return parts.Count == 0 ? "—" : string.Join(" + ", parts);
+ }
+
+ public static string Describe(TriggerGesture gesture)
+ {
+ var mods = Modifiers(gesture.Modifiers);
+ return gesture.Kind == TriggerKind.KeyChord
+ ? gesture.Modifiers == ModifierKeys.None ? gesture.Key ?? "—" : $"{mods} + {gesture.Key ?? "?"}"
+ : $"{mods} + {gesture.Button}";
+ }
+}
diff --git a/src/Filee.App/Services/LocalizationService.cs b/src/Filee.App/Services/LocalizationService.cs
new file mode 100644
index 00000000..cf6a9a2f
--- /dev/null
+++ b/src/Filee.App/Services/LocalizationService.cs
@@ -0,0 +1,111 @@
+// Loads Assets/i18n/<lang>.json and exposes the strings to XAML as dynamic resources.
+//
+// XAML: Text="{DynamicResource nav.home}" (updates live when the language changes)
+// Code: _loc["nav.home"] or _loc.Format("home.files", 3)
+
+using System.Globalization;
+using System.Text.Json;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Platform;
+using Filee.Core.Localization;
+
+namespace Filee.App.Services;
+
+/// <summary>JSON based localization with live language switching.</summary>
+public sealed class LocalizationService : ILocalizer
+{
+ /// <summary>Languages shipped with Filee: code → native name (shown in the language picker).</summary>
+ public static readonly IReadOnlyList<(string Code, string NativeName)> Languages =
+ [
+ ("en", "English"),
+ ("ko", "한국어"),
+ ("zh-CN", "简体中文"),
+ ];
+
+ private readonly ResourceDictionary _resources = new();
+ private readonly Dictionary<string, string> _english;
+ private Dictionary<string, string> _current;
+
+ public LocalizationService()
+ {
+ _english = LoadStrings("en");
+ _current = _english;
+ }
+
+ public string Language { get; private set; } = "en";
+
+ private bool _initialized;
+
+ /// <summary>True if <see cref="SetLanguage"/> would change anything.</summary>
+ public bool NeedsUpdate(string setting) => !_initialized || Resolve(setting) != Language;
+
+ public event EventHandler? LanguageChanged;
+
+ public string this[string key] =>
+ _current.TryGetValue(key, out var value) ? value
+ : _english.TryGetValue(key, out var fallback) ? fallback
+ : key;
+
+ public string Format(string key, params object[] args)
+ {
+ try
+ {
+ return string.Format(CultureInfo.CurrentCulture, this[key], args);
+ }
+ catch (FormatException)
+ {
+ return this[key];
+ }
+ }
+
+ /// <summary>Registers the string dictionary with the application so XAML can use DynamicResource.</summary>
+ public void Attach(Application app) => app.Resources.MergedDictionaries.Add(_resources);
+
+ /// <summary>
+ /// Switches the UI language. <paramref name="setting"/> is a language code or <c>"auto"</c>
+ /// (the OS UI language, falling back to English).
+ /// </summary>
+ public void SetLanguage(string setting)
+ {
+ var code = Resolve(setting);
+ _current = code == "en" ? _english : LoadStrings(code);
+ Language = code;
+
+ var culture = CultureInfo.GetCultureInfo(code);
+ CultureInfo.CurrentUICulture = culture;
+ CultureInfo.DefaultThreadCurrentUICulture = culture;
+
+ // Every key is published (English fallback for missing translations) so DynamicResource never breaks.
+ foreach (var key in _english.Keys.Concat(_current.Keys).Distinct())
+ _resources[key] = this[key];
+
+ _initialized = true;
+ LanguageChanged?.Invoke(this, EventArgs.Empty);
+ }
+
+ /// <summary>Maps "auto" / a culture name to one of the shipped languages.</summary>
+ public static string Resolve(string setting)
+ {
+ if (!string.Equals(setting, "auto", StringComparison.OrdinalIgnoreCase) &&
+ Languages.Any(l => l.Code.Equals(setting, StringComparison.OrdinalIgnoreCase)))
+ return Languages.First(l => l.Code.Equals(setting, StringComparison.OrdinalIgnoreCase)).Code;
+
+ var ui = CultureInfo.InstalledUICulture.Name;
+ if (ui.StartsWith("ko", StringComparison.OrdinalIgnoreCase))
+ return "ko";
+ if (ui.StartsWith("zh", StringComparison.OrdinalIgnoreCase))
+ return "zh-CN";
+ return "en";
+ }
+
+ /// <summary>Reads a translation file. Missing files yield an empty dictionary (English is used instead).</summary>
+ internal static Dictionary<string, string> LoadStrings(string code)
+ {
+ var uri = new Uri($"avares://Filee/Assets/i18n/{code}.json");
+ if (!AssetLoader.Exists(uri))
+ return [];
+ using var stream = AssetLoader.Open(uri);
+ return JsonSerializer.Deserialize(stream, AppJsonContext.Default.DictionaryStringString) ?? [];
+ }
+}
diff --git a/src/Filee.App/Services/Motion.cs b/src/Filee.App/Services/Motion.cs
new file mode 100644
index 00000000..428af755
--- /dev/null
+++ b/src/Filee.App/Services/Motion.cs
@@ -0,0 +1,40 @@
+// Global "reduce animations" switch. Styles react through the .reduced-motion class on windows;
+// custom-drawn controls (DonutMenu) read Motion.Enabled directly.
+
+using Avalonia.Controls;
+
+namespace Filee.App.Services;
+
+/// <summary>Whether animations are enabled.</summary>
+public static class Motion
+{
+ private static readonly List<WeakReference<Window>> Windows = [];
+
+ /// <summary>False when the user (or the OS) asked for reduced motion.</summary>
+ public static bool Enabled { get; private set; } = true;
+
+ public static event EventHandler? Changed;
+
+ public static void Set(bool enabled)
+ {
+ Enabled = enabled;
+ lock (Windows)
+ {
+ Windows.RemoveAll(w => !w.TryGetTarget(out _));
+ foreach (var weak in Windows)
+ if (weak.TryGetTarget(out var window))
+ Apply(window);
+ }
+ Changed?.Invoke(null, EventArgs.Empty);
+ }
+
+ /// <summary>Call once per window so its styles follow the setting.</summary>
+ public static void Track(Window window)
+ {
+ lock (Windows)
+ Windows.Add(new WeakReference<Window>(window));
+ Apply(window);
+ }
+
+ private static void Apply(Window window) => window.Classes.Set("reduced-motion", !Enabled);
+}
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
new file mode 100644
index 00000000..c581336b
--- /dev/null
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -0,0 +1,36 @@
+// Decides whether a preset can run for a set of files and why not — used to grey out donut slices.
+
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+
+namespace Filee.App.Services;
+
+public sealed class PresetAvailability(ConverterCatalog catalog, ILocalizer loc, EngineDownloadService downloads)
+{
+ /// <summary>
+ /// Returns <c>null</c> when at least one of <paramref name="formats"/> can be converted with the preset,
+ /// otherwise a localized reason — naming the optional engine to download when that would help.
+ /// </summary>
+ public string? Check(Preset preset, IReadOnlyList<FileFormat> formats)
+ {
+ if (formats.Count == 0)
+ return loc["error.unsupported_source"];
+
+ var merge = preset.Pdf.MergeIntoSingle && preset.TargetFormat == "pdf";
+ bool Possible(RoutePlanner planner) => formats.Any(f =>
+ {
+ var target = preset.TargetFormat == BuiltInData.SameAsSource ? f.Id : preset.TargetFormat;
+ if (merge && f.Id == "pdf")
+ return true;
+ return planner.CanConvert(f.Id, target);
+ });
+
+ if (Possible(catalog.CreatePlanner()))
+ return null;
+ return downloads.PackageEnabling(Possible) is { } package
+ ? loc.Format("engine.reason.needs_package", package.Name)
+ : loc["error.no_route"];
+ }
+}
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
new file mode 100644
index 00000000..135ca94d
--- /dev/null
+++ b/src/Filee.App/Services/RadialController.cs
@@ -0,0 +1,293 @@
+// Opens, fills and closes the live donut toolbar.
+//
+// Drag mode (modifier + drag in Explorer):
+// gesture detected → empty ring appears at the cursor (not activated) → DragEnter brings the file list →
+// slices pop out → drop on a slice converts / drop in the hole or release elsewhere closes.
+// Click mode (keyboard shortcut, context menu, drop zone):
+// files are known up front → donut appears activated → click a slice to convert, right-click to edit,
+// Esc / click outside closes.
+// After a drop / click the donut becomes a progress ring at the same spot (DonutMenu.Progress.cs):
+// finished quickly → ✓ pops up in the centre, then the ring fades out;
+// still running after HandOffAfter, failed, Esc, click elsewhere or a new gesture → the toast takes over.
+
+using System.ComponentModel;
+using Avalonia;
+using Avalonia.Threading;
+using Filee.App.Controls;
+using Filee.App.ViewModels;
+using Filee.App.Views;
+using Filee.Core.Conversion;
+using Filee.Core.Settings;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.Services;
+
+public sealed class RadialController(
+ RadialViewModel viewModel,
+ ConversionService conversions,
+ WindowService windows,
+ UserDataStore store,
+ ILogger<RadialController> log)
+{
+ /// <summary>How long the ring shows a running job before the toast window takes over.</summary>
+ private static readonly TimeSpan HandOffAfter = TimeSpan.FromSeconds(1.5);
+
+ private RadialWindow? _window;
+ private bool _visible;
+ private bool _dropped;
+ private bool _editing;
+ private JobViewModel? _progressJob; // job currently shown by the ring (null once finished / handed off)
+ private JobViewModel? _lastRingJob; // for "click the ✓ to open the folder"
+ private IDisposable? _handOffTimer;
+
+ public bool IsVisible => _visible;
+
+ /// <summary>Drag gesture started at the given physical screen point.</summary>
+ public void ShowForDrag(int x, int y)
+ {
+ ReleaseProgressToToast();
+ var window = EnsureWindow();
+ _dropped = false;
+ viewModel.ResetForDrag();
+ window.DonutControl.AllowContextEdit = false;
+ PlaceAndShow(window, x, y, activate: false);
+ window.DonutControl.PlayOpenAnimation();
+ }
+
+ /// <summary>Opens the donut for known files (click mode).</summary>
+ public void ShowForFiles(int x, int y, IReadOnlyList<string> files)
+ {
+ if (files.Count == 0)
+ return;
+ ReleaseProgressToToast();
+ var window = EnsureWindow();
+ _dropped = false;
+ viewModel.Load(files, clickMode: true);
+ window.DonutControl.AllowContextEdit = true;
+ PlaceAndShow(window, x, y, activate: true);
+ window.DonutControl.PlayOpenAnimation();
+ }
+
+ /// <summary>The mouse button of the drag gesture was released somewhere.</summary>
+ public void OnDragGestureEnded()
+ {
+ if (!_visible || viewModel.IsClickMode)
+ return;
+ // A drop on the donut arrives around the same time as the button release; give it a moment.
+ DispatcherTimer.RunOnce(() =>
+ {
+ if (_visible && !_dropped && !viewModel.IsClickMode)
+ Close(animate: true);
+ }, TimeSpan.FromMilliseconds(250));
+ }
+
+ public void Close(bool animate = true)
+ {
+ if (!_visible || _window is null)
+ return;
+ if (_window.DonutControl.IsInProgressMode)
+ {
+ // Esc / click elsewhere while the ring is showing: let the toast carry on (a finishing ✓ just fades).
+ if (_progressJob is not null)
+ HandOffToToast();
+ return;
+ }
+ _visible = false;
+ var window = _window;
+ if (animate)
+ window.DonutControl.PlayCloseAnimation(() =>
+ {
+ if (!_visible)
+ window.Hide();
+ });
+ else
+ window.Hide();
+ }
+
+ private RadialWindow EnsureWindow()
+ {
+ if (_window is not null)
+ return _window;
+
+ var window = new RadialWindow { DataContext = viewModel };
+ var donut = window.DonutControl;
+
+ window.FilesEntered += files =>
+ {
+ if (viewModel.IsClickMode || SameFiles(files, viewModel.Files))
+ return;
+ viewModel.Load(files, clickMode: false);
+ donut.PlayOpenAnimation();
+ };
+ window.Dropped += (hit, files) =>
+ {
+ _dropped = true;
+ if (hit.Kind == DonutHitKind.Segment)
+ Convert(hit.Index, files.Count > 0 ? files : viewModel.Files);
+ else
+ Close();
+ };
+ window.EscapePressed += () => Close();
+ window.Deactivated += (_, _) =>
+ {
+ if (viewModel.IsClickMode && !_editing)
+ Close();
+ };
+
+ donut.ActiveIndexChanged += (_, index) => viewModel.ShowHint(index, donut.IsCenterHot);
+ donut.SegmentInvoked += (_, index) => Convert(index, viewModel.Files);
+ donut.CenterInvoked += (_, _) => Close();
+ donut.SegmentContextRequested += async (_, index) => await EditPresetAsync(index);
+ donut.ProgressCancelRequested += (_, _) => _progressJob?.CancelCommand.Execute(null);
+ donut.ProgressClicked += (_, _) =>
+ {
+ if (_lastRingJob is { HasOutputs: true } job)
+ job.OpenFolderCommand.Execute(null);
+ };
+
+ _window = window;
+ return window;
+ }
+
+ private void Convert(int index, IReadOnlyList<string> files)
+ {
+ if (index < 0 || index >= viewModel.Presets.Count || !viewModel.Items[index].IsEnabled || files.Count == 0)
+ {
+ Close();
+ return;
+ }
+
+ var preset = viewModel.Presets[index];
+ log.LogInformation("Converting {Count} file(s) with preset {Preset}", files.Count, preset.Id);
+ var job = conversions.Start(files, preset, showInToast: false);
+ if (job is null || _window is null)
+ {
+ Close();
+ return;
+ }
+ ShowProgress(job);
+ }
+
+ // ───────── Progress ring ─────────
+
+ private void ShowProgress(JobViewModel job)
+ {
+ var donut = _window!.DonutControl;
+ _dropped = true;
+ _progressJob = job;
+ _lastRingJob = job;
+ donut.BeginProgress();
+ donut.SetProgress(job.Progress / 100);
+ job.PropertyChanged += OnProgressJobChanged;
+ _handOffTimer = DispatcherTimer.RunOnce(() =>
+ {
+ if (_progressJob == job && job.IsRunning)
+ HandOffToToast();
+ }, HandOffAfter);
+ }
+
+ private void OnProgressJobChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (sender is not JobViewModel job || job != _progressJob || _window is null)
+ return;
+ var donut = _window.DonutControl;
+ donut.SetProgress(job.Progress / 100);
+ if (job.IsRunning || e.PropertyName != nameof(JobViewModel.IsRunning))
+ return;
+
+ var outcome = job.Job.State switch
+ {
+ JobState.Completed => DonutProgressOutcome.Succeeded,
+ JobState.Cancelled => DonutProgressOutcome.Cancelled,
+ _ => DonutProgressOutcome.Failed,
+ };
+ if (outcome == DonutProgressOutcome.Failed)
+ conversions.ShowInToast(job); // the toast explains what went wrong
+ DetachProgress();
+ donut.CompleteProgress(outcome, HideWindow);
+ }
+
+ /// <summary>Hands the running job to the toast with a short "shrink away" of the ring.</summary>
+ private void HandOffToToast()
+ {
+ if (_progressJob is null || _window is null)
+ return;
+ conversions.ShowInToast(_progressJob);
+ DetachProgress();
+ _window.DonutControl.HandOffProgress(HideWindow);
+ }
+
+ /// <summary>A new gesture needs the window right now: move the job to the toast without animation.</summary>
+ private void ReleaseProgressToToast()
+ {
+ if (_progressJob is not null)
+ conversions.ShowInToast(_progressJob);
+ DetachProgress();
+ }
+
+ private void DetachProgress()
+ {
+ _handOffTimer?.Dispose();
+ _handOffTimer = null;
+ if (_progressJob is not null)
+ _progressJob.PropertyChanged -= OnProgressJobChanged;
+ _progressJob = null;
+ }
+
+ private void HideWindow()
+ {
+ _visible = false;
+ _window?.Hide();
+ }
+
+ private async Task EditPresetAsync(int index)
+ {
+ if (_window is null || index < 0 || index >= viewModel.Presets.Count)
+ return;
+ _editing = true;
+ try
+ {
+ if (await windows.EditPresetAsync(viewModel.Presets[index], _window))
+ {
+ store.SaveLibrary();
+ viewModel.Load(viewModel.Files, viewModel.IsClickMode);
+ }
+ }
+ finally
+ {
+ _editing = false;
+ }
+ if (_visible)
+ _window.Activate();
+ }
+
+ private void PlaceAndShow(RadialWindow window, int x, int y, bool activate)
+ {
+ var cursor = new PixelPoint(x, y);
+ var screen = window.Screens.ScreenFromPoint(cursor) ?? window.Screens.Primary;
+ var scaling = screen?.Scaling ?? 1;
+
+ // Window size follows the donut size (SizeToContent); compute it up front to centre on the cursor.
+ var side = 2 * (viewModel.OuterRadius + 7 + 14);
+ var sidePx = (int)Math.Ceiling(side * scaling);
+ var position = new PixelPoint(x - sidePx / 2, y - sidePx / 2);
+ if (screen is not null)
+ {
+ var area = screen.WorkingArea;
+ position = new PixelPoint(
+ Math.Clamp(position.X, area.X, Math.Max(area.X, area.Right - sidePx)),
+ Math.Clamp(position.Y, area.Y, Math.Max(area.Y, area.Bottom - sidePx)));
+ }
+
+ window.Position = position;
+ if (!window.IsVisible)
+ window.Show();
+ window.Position = position; // again, in case showing changed the DPI scale
+ _visible = true;
+ if (activate)
+ window.Activate();
+ }
+
+ private static bool SameFiles(IReadOnlyList<string> a, IReadOnlyList<string> b) =>
+ a.Count == b.Count && a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase);
+}
diff --git a/src/Filee.App/Services/SingleInstance.cs b/src/Filee.App/Services/SingleInstance.cs
new file mode 100644
index 00000000..46e287ea
--- /dev/null
+++ b/src/Filee.App/Services/SingleInstance.cs
@@ -0,0 +1,93 @@
+// Makes sure only one Filee runs per user session. Later launches send their command line to the first
+// instance through a named pipe (e.g. Explorer starts one process per selected file for the context menu).
+
+using System.IO.Pipes;
+using System.Text.Json;
+
+namespace Filee.App.Services;
+
+/// <summary>Named mutex + named pipe single-instance helper.</summary>
+public sealed class SingleInstance : IDisposable
+{
+ // string.GetHashCode() is randomized per process, so a stable hash is required for both processes to agree.
+ private static readonly string Name = "Filee-" + Convert.ToHexString(
+ System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(Environment.UserName)))[..12];
+ private readonly Mutex _mutex;
+ private readonly CancellationTokenSource _cts = new();
+
+ private SingleInstance(Mutex mutex, bool isFirst)
+ {
+ _mutex = mutex;
+ IsFirst = isFirst;
+ }
+
+ public bool IsFirst { get; }
+
+ /// <summary>Raised on a background thread with the arguments of a later launch.</summary>
+ public event Action<string[]>? ArgumentsReceived;
+
+ public static SingleInstance Acquire()
+ {
+ var mutex = new Mutex(initiallyOwned: true, @"Local\" + Name, out var createdNew);
+ return new SingleInstance(mutex, createdNew);
+ }
+
+ /// <summary>Starts listening for later launches (first instance only).</summary>
+ public void StartListening()
+ {
+ if (!IsFirst)
+ return;
+ _ = Task.Run(async () =>
+ {
+ while (!_cts.IsCancellationRequested)
+ {
+ try
+ {
+ await using var server = new NamedPipeServerStream(Name, PipeDirection.In, 1,
+ PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ await server.WaitForConnectionAsync(_cts.Token);
+ var args = await JsonSerializer.DeserializeAsync(server, AppJsonContext.Default.StringArray, _cts.Token);
+ if (args is not null)
+ ArgumentsReceived?.Invoke(args);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+ catch (Exception ex) when (ex is IOException or JsonException)
+ {
+ // A client disconnected half-way; keep serving.
+ }
+ }
+ });
+ }
+
+ /// <summary>Sends this process's arguments to the first instance.</summary>
+ public void ForwardToFirst(string[] args)
+ {
+ try
+ {
+ using var client = new NamedPipeClientStream(".", Name, PipeDirection.Out, PipeOptions.CurrentUserOnly);
+ client.Connect(3000);
+ JsonSerializer.Serialize(client, args, AppJsonContext.Default.StringArray);
+ }
+ catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
+ {
+ // The first instance is starting or shutting down; nothing sensible to do.
+ }
+ }
+
+ public void Dispose()
+ {
+ _cts.Cancel();
+ if (IsFirst)
+ {
+ try
+ {
+ _mutex.ReleaseMutex();
+ }
+ catch (ApplicationException) { }
+ }
+ _mutex.Dispose();
+ }
+}
diff --git a/src/Filee.App/Services/ThemeService.cs b/src/Filee.App/Services/ThemeService.cs
new file mode 100644
index 00000000..6f14882d
--- /dev/null
+++ b/src/Filee.App/Services/ThemeService.cs
@@ -0,0 +1,81 @@
+// Applies ThemeSettings (light/dark, accent colour, corner radius, font order, reduced motion) at runtime by
+// writing resources into Application.Resources. All styles reference these with DynamicResource.
+
+using Avalonia;
+using Avalonia.Media;
+using Avalonia.Styling;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+
+namespace Filee.App.Services;
+
+/// <summary>Runtime theming.</summary>
+public sealed class ThemeService(IPlatformServices platform)
+{
+ /// <summary>Accent swatches offered in the Theme page.</summary>
+ public static readonly IReadOnlyList<string> Swatches =
+ ["#7F77DD", "#1D9E75", "#D85A30", "#378ADD", "#D4537E", "#BA7517", "#639922", "#5F5E5A"];
+
+ /// <summary>Embedded Noto fonts (see build/fetch-fonts.ps1). Missing files fall back to system fonts.</summary>
+ private const string Latin = "fonts:Filee#Noto Sans";
+ private const string Korean = "fonts:Filee#Noto Sans KR";
+ private const string Chinese = "fonts:Filee#Noto Sans SC";
+ private const string SystemFallbacks = "Segoe UI, Malgun Gothic, Microsoft YaHei, PingFang SC, Apple SD Gothic Neo, sans-serif";
+
+ public void Apply(ThemeSettings theme, string language)
+ {
+ var app = Application.Current ?? throw new InvalidOperationException("No application.");
+ var res = app.Resources;
+
+ app.RequestedThemeVariant = theme.Mode switch
+ {
+ ThemeMode.Light => ThemeVariant.Light,
+ ThemeMode.Dark => ThemeVariant.Dark,
+ _ => ThemeVariant.Default,
+ };
+
+ // Accent colour + derived shades. Fluent controls read the System* keys.
+ var accent = Color.TryParse(theme.Accent, out var parsed) ? parsed : Color.Parse("#7F77DD");
+ res["AccentColor"] = accent;
+ res["AccentBrush"] = new SolidColorBrush(accent);
+ res["AccentSoftBrush"] = new SolidColorBrush(accent, 0.18);
+ res["AccentFaintBrush"] = new SolidColorBrush(accent, 0.09);
+ res["AccentStrongBrush"] = new SolidColorBrush(Shade(accent, -0.25));
+ res["OnAccentBrush"] = new SolidColorBrush(Luminance(accent) > 0.6 ? Color.Parse("#1F1E1D") : Colors.White);
+ res["SystemAccentColor"] = accent;
+ res["SystemAccentColorLight1"] = Shade(accent, 0.15);
+ res["SystemAccentColorLight2"] = Shade(accent, 0.30);
+ res["SystemAccentColorLight3"] = Shade(accent, 0.45);
+ res["SystemAccentColorDark1"] = Shade(accent, -0.15);
+ res["SystemAccentColorDark2"] = Shade(accent, -0.30);
+ res["SystemAccentColorDark3"] = Shade(accent, -0.45);
+
+ // "Softness": one radius drives every control.
+ var r = Math.Clamp(theme.CornerRadius, 0, 28);
+ res["SoftRadius"] = new CornerRadius(r);
+ res["SoftRadiusSmall"] = new CornerRadius(Math.Round(r * 0.55));
+ res["SoftRadiusLarge"] = new CornerRadius(Math.Round(r * 1.35));
+ res["ControlCornerRadius"] = new CornerRadius(Math.Round(r * 0.55));
+ res["OverlayCornerRadius"] = new CornerRadius(r);
+
+ // Han characters look different in Korean and Chinese fonts: put the UI language's font first.
+ var cjk = language.StartsWith("zh", StringComparison.OrdinalIgnoreCase)
+ ? $"{Chinese}, {Korean}"
+ : $"{Korean}, {Chinese}";
+ res["AppFontFamily"] = FontFamily.Parse($"{Latin}, {cjk}, {SystemFallbacks}");
+
+ Motion.Set(!(theme.ReduceMotion ?? platform.PrefersReducedMotion));
+ }
+
+ /// <summary>Lightens (amount &gt; 0) or darkens (amount &lt; 0) a colour.</summary>
+ public static Color Shade(Color c, double amount)
+ {
+ byte Mix(byte v) => amount >= 0
+ ? (byte)Math.Round(v + (255 - v) * amount)
+ : (byte)Math.Round(v * (1 + amount));
+ return Color.FromArgb(c.A, Mix(c.R), Mix(c.G), Mix(c.B));
+ }
+
+ /// <summary>Relative luminance 0..1 (sRGB approximation).</summary>
+ public static double Luminance(Color c) => (0.2126 * c.R + 0.7152 * c.G + 0.0722 * c.B) / 255.0;
+}
diff --git a/src/Filee.App/Services/TrayService.cs b/src/Filee.App/Services/TrayService.cs
new file mode 100644
index 00000000..50dd634f
--- /dev/null
+++ b/src/Filee.App/Services/TrayService.cs
@@ -0,0 +1,59 @@
+// System tray icon: open settings, pause gestures, quit.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Platform;
+using Filee.Core.Localization;
+using Filee.Core.Settings;
+
+namespace Filee.App.Services;
+
+public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowService windows)
+{
+ private TrayIcon? _tray;
+ private NativeMenuItem? _open, _pause, _quit;
+
+ public void Create(Application app)
+ {
+ using var iconStream = AssetLoader.Open(new Uri("avares://Filee/Assets/Icons/filee.ico"));
+ _open = new NativeMenuItem();
+ _open.Click += (_, _) => windows.ShowMain();
+ _pause = new NativeMenuItem();
+ _pause.Click += (_, _) =>
+ {
+ store.Settings.Paused = !store.Settings.Paused;
+ store.SaveSettings();
+ };
+ _quit = new NativeMenuItem();
+ _quit.Click += (_, _) => (app.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
+
+ _tray = new TrayIcon
+ {
+ Icon = new WindowIcon(iconStream),
+ Menu = new NativeMenu { Items = { _open, _pause, new NativeMenuItemSeparator(), _quit } },
+ IsVisible = true,
+ };
+ _tray.Clicked += (_, _) => windows.ShowMain();
+ TrayIcon.SetIcons(app, [_tray]);
+
+ Refresh();
+ loc.LanguageChanged += (_, _) => Refresh();
+ store.SettingsChanged += (_, _) => Refresh();
+ }
+
+ private void Refresh()
+ {
+ if (_tray is null)
+ return;
+ _open!.Header = loc["tray.open"];
+ _pause!.Header = store.Settings.Paused ? loc["tray.resume"] : loc["tray.pause"];
+ _quit!.Header = loc["tray.quit"];
+ var drag = store.Settings.Triggers.FirstOrDefault(t => t.Enabled && t.Kind == TriggerKind.Drag);
+ _tray.ToolTipText = store.Settings.Paused
+ ? loc["triggers.paused"]
+ : loc.Format("tray.tooltip", drag is null ? "—" : GestureText.Modifiers(drag.Modifiers));
+ }
+
+ public void Dispose() => _tray?.Dispose();
+}
diff --git a/src/Filee.App/Services/Triggers/GestureDetector.cs b/src/Filee.App/Services/Triggers/GestureDetector.cs
new file mode 100644
index 00000000..6b0f60de
--- /dev/null
+++ b/src/Filee.App/Services/Triggers/GestureDetector.cs
@@ -0,0 +1,189 @@
+// Pure state machine that turns low-level mouse/keyboard events into "open the donut" gestures.
+// It knows nothing about SharpHook or Avalonia so it can be unit tested (see Filee.App.Tests).
+//
+// Drag gesture: button down with the exact modifiers → (armed) → moved past threshold → DragStarted
+// → button up → DragEnded
+// Hold gesture: button down with modifiers → (armed) → HoldElapsed without moving → HoldTriggered
+// Key chord: key down with the exact modifiers → KeyChordTriggered at the last known cursor position
+
+using Filee.Core.Settings;
+
+namespace Filee.App.Services.Triggers;
+
+/// <summary>Detects configured <see cref="TriggerGesture"/>s in a stream of input events. Thread-safe.</summary>
+public sealed class GestureDetector
+{
+ private readonly object _lock = new();
+ private IReadOnlyList<TriggerGesture> _gestures = [];
+ private Armed? _armed;
+ private bool _dragActive;
+ private bool _lateRejected; // scope check failed for this drag; don't re-check on every move
+ private int _lastX, _lastY;
+
+ private sealed record Armed(TriggerGesture Gesture, TriggerMouseButton Button, int X, int Y, long Token);
+
+ /// <summary>
+ /// Decides whether a gesture may start at a screen point (scope / excluded apps / own windows).
+ /// Called on the hook thread; must be fast.
+ /// </summary>
+ public Func<TriggerGesture, int, int, bool> ScopeFilter { get; set; } = (_, _, _) => true;
+
+ /// <summary>Fallback drag threshold (physical pixels) when a gesture uses 0 = "system default".</summary>
+ public int SystemDragThreshold { get; set; } = 4;
+
+ /// <summary>When true nothing is detected (tray "Pause").</summary>
+ public bool Paused { get; set; }
+
+ public event Action<TriggerGesture, int, int>? DragStarted;
+ public event Action<int, int>? DragEnded;
+ public event Action<TriggerGesture, int, int>? HoldTriggered;
+ public event Action<TriggerGesture, int, int>? KeyChordTriggered;
+
+ /// <summary>Raised when a hold gesture is armed; the owner must call <see cref="HoldElapsed"/> after the delay.</summary>
+ public event Action<long, int>? HoldTimerRequested;
+
+ public void Configure(IEnumerable<TriggerGesture> gestures)
+ {
+ lock (_lock)
+ {
+ _gestures = gestures.Where(g => g.Enabled).Select(g => g.Clone()).ToList();
+ _armed = null;
+ }
+ }
+
+ public void MouseDown(TriggerMouseButton button, int x, int y, ModifierKeys modifiers)
+ {
+ TriggerGesture? holdGesture = null;
+ long token = 0;
+ lock (_lock)
+ {
+ _lastX = x;
+ _lastY = y;
+ _armed = null;
+ _lateRejected = false;
+ if (Paused)
+ return;
+
+ var gesture = _gestures.FirstOrDefault(g =>
+ g.Kind is TriggerKind.Drag or TriggerKind.Hold &&
+ g.Button == button &&
+ g.Modifiers == modifiers);
+ if (gesture is null || !ScopeFilter(gesture, x, y))
+ return;
+
+ token = Environment.TickCount64 ^ (x * 7919L) ^ y;
+ _armed = new Armed(gesture, button, x, y, token);
+ if (gesture.Kind == TriggerKind.Hold)
+ holdGesture = gesture;
+ }
+
+ if (holdGesture is not null)
+ HoldTimerRequested?.Invoke(token, holdGesture.HoldMilliseconds);
+ }
+
+ /// <summary>Pointer moved (physical pixels). <paramref name="heldButton"/> is the button currently held, or None.</summary>
+ public void MouseMove(int x, int y, ModifierKeys modifiers, TriggerMouseButton heldButton = TriggerMouseButton.None)
+ {
+ TriggerGesture? fire;
+ lock (_lock)
+ {
+ _lastX = x;
+ _lastY = y;
+ fire = _armed is null ? DetectLateModifier(x, y, modifiers, heldButton) : DetectDragPastThreshold(x, y);
+ if (fire is not null)
+ _dragActive = true;
+ }
+
+ if (fire is not null)
+ DragStarted?.Invoke(fire, x, y);
+ }
+
+ /// <summary>
+ /// An armed gesture moved: a drag gesture fires once the threshold is passed; a hold gesture is cancelled.
+ /// Caller holds the lock.
+ /// </summary>
+ private TriggerGesture? DetectDragPastThreshold(int x, int y)
+ {
+ var armed = _armed!;
+ var threshold = armed.Gesture.DragThreshold > 0 ? armed.Gesture.DragThreshold : SystemDragThreshold;
+ if (Math.Abs(x - armed.X) <= threshold && Math.Abs(y - armed.Y) <= threshold)
+ return null;
+
+ _armed = null;
+ return armed.Gesture.Kind == TriggerKind.Drag ? armed.Gesture : null;
+ }
+
+ /// <summary>
+ /// The modifier was pressed after the drag had already started (common in Explorer: start dragging,
+ /// then press Ctrl to copy). Treat it like a drag gesture that just passed the threshold. Caller holds the lock.
+ /// </summary>
+ private TriggerGesture? DetectLateModifier(int x, int y, ModifierKeys modifiers, TriggerMouseButton heldButton)
+ {
+ if (_dragActive || _lateRejected || Paused || heldButton == TriggerMouseButton.None || modifiers == ModifierKeys.None)
+ return null;
+
+ var late = _gestures.FirstOrDefault(g =>
+ g.Kind == TriggerKind.Drag && g.Button == heldButton && g.Modifiers == modifiers);
+ if (late is null)
+ return null;
+ if (ScopeFilter(late, x, y))
+ return late;
+ _lateRejected = true;
+ return null;
+ }
+
+ public void MouseUp(TriggerMouseButton button, int x, int y)
+ {
+ bool ended;
+ lock (_lock)
+ {
+ _lastX = x;
+ _lastY = y;
+ _armed = null;
+ ended = _dragActive;
+ _dragActive = false;
+ _lateRejected = false;
+ }
+ if (ended)
+ DragEnded?.Invoke(x, y);
+ }
+
+ /// <summary>Called when the hold timer for <paramref name="token"/> fires.</summary>
+ public void HoldElapsed(long token)
+ {
+ TriggerGesture? fire = null;
+ int x = 0, y = 0;
+ lock (_lock)
+ {
+ if (_armed is { } armed && armed.Token == token && armed.Gesture.Kind == TriggerKind.Hold)
+ {
+ fire = armed.Gesture;
+ (x, y) = (armed.X, armed.Y);
+ _armed = null;
+ }
+ }
+ if (fire is not null)
+ HoldTriggered?.Invoke(fire, x, y);
+ }
+
+ /// <summary>A key went down. <paramref name="key"/> is the key name without the "Vc" prefix, e.g. "Space".</summary>
+ public void KeyDown(string key, ModifierKeys modifiers)
+ {
+ TriggerGesture? fire;
+ int x, y;
+ lock (_lock)
+ {
+ if (Paused)
+ return;
+ fire = _gestures.FirstOrDefault(g =>
+ g.Kind == TriggerKind.KeyChord &&
+ string.Equals(g.Key, key, StringComparison.OrdinalIgnoreCase) &&
+ g.Modifiers == modifiers);
+ (x, y) = (_lastX, _lastY);
+ if (fire is not null && !ScopeFilter(fire, x, y))
+ fire = null;
+ }
+ if (fire is not null)
+ KeyChordTriggered?.Invoke(fire, x, y);
+ }
+}
diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.cs
new file mode 100644
index 00000000..da632dbc
--- /dev/null
+++ b/src/Filee.App/Services/Triggers/TriggerService.cs
@@ -0,0 +1,155 @@
+// Connects the global input hook (SharpHook / libuiohook) to the GestureDetector and forwards detected
+// gestures to the UI thread. Hook callbacks must return quickly: Windows silently removes a low-level hook
+// whose callback takes longer than ~1 s, so no UI work happens here.
+
+using System.Diagnostics;
+using Avalonia.Threading;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+using Microsoft.Extensions.Logging;
+using SharpHook;
+using SharpHook.Data;
+
+namespace Filee.App.Services.Triggers;
+
+/// <summary>Global gesture detection. Events are raised on the UI thread with physical screen coordinates.</summary>
+public sealed class TriggerService : IDisposable
+{
+ private readonly IPlatformServices _platform;
+ private readonly ILogger<TriggerService> _log;
+ private readonly GestureDetector _detector = new();
+ private readonly string _ownProcess = Process.GetCurrentProcess().ProcessName;
+ private EventLoopGlobalHook? _hook;
+ private HashSet<string> _excluded = new(StringComparer.OrdinalIgnoreCase);
+
+ public TriggerService(IPlatformServices platform, ILogger<TriggerService> log)
+ {
+ _platform = platform;
+ _log = log;
+ _detector.SystemDragThreshold = platform.SystemDragThreshold;
+ _detector.ScopeFilter = InScope;
+
+ _detector.DragStarted += (g, x, y) => Post(() => DragStarted?.Invoke(this, new GestureEventArgs(g, x, y)));
+ _detector.DragEnded += (x, y) => Post(() => DragEnded?.Invoke(this, new GestureEventArgs(null, x, y)));
+ _detector.HoldTriggered += (g, x, y) => Post(() => SelectionGesture?.Invoke(this, new GestureEventArgs(g, x, y)));
+ _detector.KeyChordTriggered += (g, x, y) => Post(() => SelectionGesture?.Invoke(this, new GestureEventArgs(g, x, y)));
+ _detector.HoldTimerRequested += (token, ms) =>
+ _ = Task.Delay(ms).ContinueWith(_ => _detector.HoldElapsed(token), TaskScheduler.Default);
+ }
+
+ /// <summary>A modifier+drag started (files may be dragged). Show the donut and wait for DragEnter.</summary>
+ public event EventHandler<GestureEventArgs>? DragStarted;
+
+ /// <summary>The mouse button of an active drag gesture was released.</summary>
+ public event EventHandler<GestureEventArgs>? DragEnded;
+
+ /// <summary>A hold or keyboard gesture: open the donut for the file manager's current selection.</summary>
+ public event EventHandler<GestureEventArgs>? SelectionGesture;
+
+ /// <summary>Last known cursor position (physical pixels).</summary>
+ public (int X, int Y) LastCursor { get; private set; }
+
+ public bool IsRunning => _hook?.IsRunning == true;
+
+ public void Apply(AppSettings settings)
+ {
+ _detector.Configure(settings.Triggers);
+ _detector.Paused = settings.Paused;
+ _excluded = new HashSet<string>(settings.ExcludedProcesses.Select(p => p.Trim().Replace(".exe", "", StringComparison.OrdinalIgnoreCase)),
+ StringComparer.OrdinalIgnoreCase);
+ }
+
+ public void Start()
+ {
+ if (_hook is not null)
+ return;
+ try
+ {
+ _hook = new EventLoopGlobalHook();
+ _hook.HookEnabled += (_, _) => _log.LogInformation("Global input hook started");
+ _hook.HookDisabled += (_, _) => _log.LogInformation("Global input hook stopped");
+ _hook.MousePressed += (_, e) => _detector.MouseDown(Map(e.Data.Button), e.Data.X, e.Data.Y, Map(e.RawEvent.Mask));
+ _hook.MouseReleased += (_, e) => _detector.MouseUp(Map(e.Data.Button), e.Data.X, e.Data.Y);
+ _hook.MouseDragged += (_, e) => OnMove(e);
+ _hook.MouseMoved += (_, e) => OnMove(e);
+ _hook.KeyPressed += (_, e) => _detector.KeyDown(KeyName(e.Data.KeyCode), Map(e.RawEvent.Mask));
+ _ = _hook.RunAsync().ContinueWith(t =>
+ {
+ // e.g. macOS without Accessibility permission. Drop zone and context menu keep working.
+ if (t.Exception is not null)
+ _log.LogError(t.Exception, "Global input hook failed; gestures are unavailable");
+ }, TaskScheduler.Default);
+ }
+ catch (Exception ex)
+ {
+ // e.g. macOS without Accessibility permission. The app keeps working via the drop zone / context menu.
+ _log.LogError(ex, "Could not start the global input hook");
+ _hook = null;
+ }
+ }
+
+ private void OnMove(MouseHookEventArgs e)
+ {
+ LastCursor = (e.Data.X, e.Data.Y);
+ _detector.MouseMove(e.Data.X, e.Data.Y, Map(e.RawEvent.Mask), HeldButton(e.RawEvent.Mask));
+ }
+
+ private bool InScope(TriggerGesture gesture, int x, int y)
+ {
+ var process = _platform.ProcessNameAt(x, y);
+ if (process is not null && (string.Equals(process, _ownProcess, StringComparison.OrdinalIgnoreCase) || _excluded.Contains(process)))
+ return false;
+ return gesture.Scope == TriggerScope.Anywhere || _platform.IsFileManagerAt(x, y);
+ }
+
+ private static void Post(Action action) => Dispatcher.UIThread.Post(action);
+
+ internal static TriggerMouseButton Map(MouseButton button) => button switch
+ {
+ MouseButton.Button1 => TriggerMouseButton.Left,
+ MouseButton.Button2 => TriggerMouseButton.Right,
+ MouseButton.Button3 => TriggerMouseButton.Middle,
+ MouseButton.Button4 => TriggerMouseButton.X1,
+ MouseButton.Button5 => TriggerMouseButton.X2,
+ _ => TriggerMouseButton.None,
+ };
+
+ internal static ModifierKeys Map(EventMask mask)
+ {
+ var result = ModifierKeys.None;
+ if (mask.HasCtrl()) result |= ModifierKeys.Ctrl;
+ if (mask.HasAlt()) result |= ModifierKeys.Alt;
+ if (mask.HasShift()) result |= ModifierKeys.Shift;
+ if (mask.HasMeta()) result |= ModifierKeys.Meta;
+ return result;
+ }
+
+ internal static TriggerMouseButton HeldButton(EventMask mask) =>
+ mask.HasFlag(EventMask.Button1) ? TriggerMouseButton.Left
+ : mask.HasFlag(EventMask.Button2) ? TriggerMouseButton.Right
+ : mask.HasFlag(EventMask.Button3) ? TriggerMouseButton.Middle
+ : mask.HasFlag(EventMask.Button4) ? TriggerMouseButton.X1
+ : mask.HasFlag(EventMask.Button5) ? TriggerMouseButton.X2
+ : TriggerMouseButton.None;
+
+ /// <summary>"VcSpace" → "Space".</summary>
+ internal static string KeyName(KeyCode code)
+ {
+ var name = code.ToString();
+ return name.StartsWith("Vc", StringComparison.Ordinal) ? name[2..] : name;
+ }
+
+ public void Dispose()
+ {
+ _hook?.Dispose();
+ _hook = null;
+ }
+}
+
+/// <summary>Gesture notification with physical screen coordinates.</summary>
+public sealed class GestureEventArgs(TriggerGesture? gesture, int x, int y) : EventArgs
+{
+ public TriggerGesture? Gesture { get; } = gesture;
+ public int X { get; } = x;
+ public int Y { get; } = y;
+}
diff --git a/src/Filee.App/Services/UninstallCleanup.cs b/src/Filee.App/Services/UninstallCleanup.cs
new file mode 100644
index 00000000..4cd3251c
--- /dev/null
+++ b/src/Filee.App/Services/UninstallCleanup.cs
@@ -0,0 +1,27 @@
+// Runs from the Velopack uninstall hook: removes registry entries Filee created for the current user.
+
+using Filee.Platform.Windows;
+
+namespace Filee.App.Services;
+
+internal static class UninstallCleanup
+{
+ public static void Run()
+ {
+ if (!OperatingSystem.IsWindows())
+ return;
+ try
+ {
+ var platform = new WindowsPlatformServices();
+ platform.SetContextMenu(false, "", "");
+ platform.SetStartWithSystem(false, "");
+ // Engines downloaded later live outside the app folder (see EngineEnvironment.DownloadRoot).
+ if (Directory.Exists(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot))
+ Directory.Delete(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot, recursive: true);
+ }
+ catch (Exception)
+ {
+ // Uninstall must never fail because of cleanup.
+ }
+ }
+}
diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.cs
new file mode 100644
index 00000000..a8d141de
--- /dev/null
+++ b/src/Filee.App/Services/UpdateService.cs
@@ -0,0 +1,68 @@
+// In-app updates from GitHub Releases via Velopack. Only works in installed builds (not when run from the IDE).
+
+using System.Reflection;
+using Microsoft.Extensions.Logging;
+using Velopack;
+using Velopack.Sources;
+
+namespace Filee.App.Services;
+
+public sealed class UpdateService(ILogger<UpdateService> log)
+{
+ private UpdateManager? _manager;
+ private UpdateInfo? _pending;
+
+ /// <summary>GitHub repository from Directory.Build.props (FileeRepositoryUrl).</summary>
+ public static string RepositoryUrl =>
+ typeof(UpdateService).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
+ .FirstOrDefault(a => a.Key == "RepositoryUrl")?.Value ?? "https://github.com/KnifeLemon/Filee";
+
+ public static string CurrentVersion =>
+ typeof(UpdateService).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion.Split('+')[0]
+ ?? typeof(UpdateService).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
+
+ /// <summary>False when running from source (no Velopack installation).</summary>
+ public bool IsInstalled => Manager?.IsInstalled == true;
+
+ private UpdateManager? Manager
+ {
+ get
+ {
+ try
+ {
+ return _manager ??= new UpdateManager(new GithubSource(RepositoryUrl, null, false));
+ }
+ catch (Exception ex)
+ {
+ log.LogWarning(ex, "Update manager unavailable");
+ return null;
+ }
+ }
+ }
+
+ /// <summary>Returns the new version string, or null if up to date / not installed / offline.</summary>
+ public async Task<string?> CheckAsync()
+ {
+ if (!IsInstalled)
+ return null;
+ try
+ {
+ _pending = await Manager!.CheckForUpdatesAsync();
+ return _pending?.TargetFullRelease.Version.ToString();
+ }
+ catch (Exception ex)
+ {
+ log.LogWarning(ex, "Update check failed");
+ return null;
+ }
+ }
+
+ /// <summary>Downloads the pending update and restarts into it.</summary>
+ public async Task ApplyAsync()
+ {
+ if (_pending is null || Manager is null)
+ return;
+ await Manager.DownloadUpdatesAsync(_pending);
+ Manager.ApplyUpdatesAndRestart(_pending);
+ }
+}
diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs
new file mode 100644
index 00000000..6fb0eec2
--- /dev/null
+++ b/src/Filee.App/Services/WindowService.cs
@@ -0,0 +1,129 @@
+// Opens windows and dialogs: the main (settings) window, the preset popup, confirmations and toasts.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.ApplicationLifetimes;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Filee.App.ViewModels;
+using Filee.App.Views;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Filee.App.Services;
+
+public sealed class WindowService(ILocalizer loc, IServiceProvider services)
+{
+ private MainWindow? _main;
+ private ToastWindow? _toast;
+ private EngineSetupWindow? _engineSetup;
+
+ public MainWindow? Main => _main;
+
+ /// <summary>Shows (or brings to front) the main window, optionally on a page.</summary>
+ public void ShowMain(string? page = null)
+ {
+ if (_main is null)
+ {
+ _main = new MainWindow { DataContext = services.GetRequiredService<MainWindowViewModel>() };
+ _main.Closed += (_, _) => _main = null;
+ }
+ if (page is not null && _main.DataContext is MainWindowViewModel vm)
+ vm.Navigate(page);
+
+ if (!_main.IsVisible)
+ _main.Show();
+ if (_main.WindowState == WindowState.Minimized)
+ _main.WindowState = WindowState.Normal;
+ _main.Activate();
+ }
+
+ /// <summary>Opens the optional-engine choice (first run); a second call brings the open window to front.</summary>
+ public void ShowEngineSetup()
+ {
+ if (_engineSetup is not null)
+ {
+ _engineSetup.Activate();
+ return;
+ }
+ _engineSetup = new EngineSetupWindow { DataContext = ActivatorUtilities.CreateInstance<EngineSetupViewModel>(services) };
+ _engineSetup.Closed += (_, _) => _engineSetup = null;
+ _engineSetup.Show();
+ }
+
+ /// <summary>Creates the toast window once; it shows and hides itself with the job list.</summary>
+ public void EnsureToast()
+ {
+ _toast ??= new ToastWindow { DataContext = services.GetRequiredService<ConversionService>() };
+ }
+
+ /// <summary>Opens the preset popup. Returns true when the user saved (the preset object was updated).</summary>
+ public async Task<bool> EditPresetAsync(Preset preset, Window? owner)
+ {
+ var dialog = new PresetEditorWindow
+ {
+ DataContext = new PresetEditorViewModel(preset, loc),
+ Topmost = owner?.Topmost ?? false,
+ };
+ owner ??= _main ?? MainWindowOrNull();
+ if (owner is null || !owner.IsVisible)
+ {
+ // No visible owner (e.g. the donut was opened from the tray): show as a normal window.
+ var closed = new TaskCompletionSource();
+ dialog.Closed += (_, _) => closed.TrySetResult();
+ dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+ dialog.Show();
+ await closed.Task;
+ return dialog.Saved;
+ }
+ return await dialog.ShowDialog<bool>(owner);
+ }
+
+ /// <summary>Simple yes/no confirmation.</summary>
+ public Task<bool> ConfirmAsync(Window owner, string message, bool destructive = false) =>
+ ShowMessageAsync(owner, message, destructive, withCancel: true);
+
+ /// <summary>A message with only an OK button.</summary>
+ public Task MessageAsync(Window owner, string message) => ShowMessageAsync(owner, message, destructive: false, withCancel: false);
+
+ private async Task<bool> ShowMessageAsync(Window owner, string message, bool destructive, bool withCancel)
+ {
+ var dialog = new Window
+ {
+ Title = loc["app.name"],
+ Width = 400,
+ SizeToContent = SizeToContent.Height,
+ CanResize = false,
+ WindowStartupLocation = WindowStartupLocation.CenterOwner,
+ ShowInTaskbar = false,
+ };
+ Motion.Track(dialog);
+ var yes = new Button { Content = destructive ? loc["common.delete"] : loc["common.ok"], IsDefault = true };
+ yes.Classes.Add("accent");
+ var no = new Button { Content = loc["common.cancel"], IsCancel = true };
+ yes.Click += (_, _) => dialog.Close(true);
+ no.Click += (_, _) => dialog.Close(false);
+ no.IsVisible = withCancel;
+ dialog.Content = new StackPanel
+ {
+ Margin = new Thickness(22),
+ Spacing = 18,
+ Children =
+ {
+ new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap },
+ new StackPanel
+ {
+ Orientation = Orientation.Horizontal,
+ HorizontalAlignment = HorizontalAlignment.Right,
+ Spacing = 8,
+ Children = { no, yes },
+ },
+ },
+ };
+ return await dialog.ShowDialog<bool>(owner);
+ }
+
+ private static Window? MainWindowOrNull() =>
+ (Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
+}
diff --git a/src/Filee.App/Styles/Icons.axaml b/src/Filee.App/Styles/Icons.axaml
new file mode 100644
index 00000000..c30c7f3b
--- /dev/null
+++ b/src/Filee.App/Styles/Icons.axaml
@@ -0,0 +1,29 @@
+<!--
+ Icon geometries (24×24) from Material Design Icons by Pictogrammers (Apache-2.0).
+ Use: <PathIcon Data="{StaticResource Icon.Home}" />
+-->
+<ResourceDictionary xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+ <StreamGeometry x:Key="Icon.Home">M10,20V14H14V20H19V12H22L12,3L2,12H5V20H10Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Settings">M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Keyboard">M19,10H17V8H19M19,13H17V11H19M16,10H14V8H16M16,13H14V11H16M16,17H8V15H16M7,10H5V8H7M7,13H5V11H7M8,11H10V13H8M8,8H10V10H8M11,11H13V13H11M11,8H13V10H11M20,5H4C2.89,5 2,5.89 2,7V17A2,2 0 0,0 4,19H20A2,2 0 0,0 22,17V7C22,5.89 21.1,5 20,5Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Donut">F1 M12,2A10,10 0 1,1 12,22A10,10 0 1,1 12,2Z M12,8A4,4 0 1,0 12,16A4,4 0 1,0 12,8Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Tune">M3,17V19H9V17H3M3,5V7H13V5H3M13,21V19H21V17H13V15H11V21H13M7,9V11H3V13H7V15H9V9H7M21,13V11H11V13H21M15,9H17V7H21V5H17V3H15V9Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Palette">M17.5,12A1.5,1.5 0 0,1 16,10.5A1.5,1.5 0 0,1 17.5,9A1.5,1.5 0 0,1 19,10.5A1.5,1.5 0 0,1 17.5,12M14.5,8A1.5,1.5 0 0,1 13,6.5A1.5,1.5 0 0,1 14.5,5A1.5,1.5 0 0,1 16,6.5A1.5,1.5 0 0,1 14.5,8M9.5,8A1.5,1.5 0 0,1 8,6.5A1.5,1.5 0 0,1 9.5,5A1.5,1.5 0 0,1 11,6.5A1.5,1.5 0 0,1 9.5,8M6.5,12A1.5,1.5 0 0,1 5,10.5A1.5,1.5 0 0,1 6.5,9A1.5,1.5 0 0,1 8,10.5A1.5,1.5 0 0,1 6.5,12M12,3A9,9 0 0,0 3,12A9,9 0 0,0 12,21A1.5,1.5 0 0,0 13.5,19.5C13.5,19.11 13.35,18.76 13.11,18.5C12.88,18.23 12.73,17.88 12.73,17.5A1.5,1.5 0 0,1 14.23,16H16A5,5 0 0,0 21,11C21,6.58 16.97,3 12,3Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Engine">M17,17H7V7H17M21,11V9H19V7C19,5.89 18.1,5 17,5H15V3H13V5H11V3H9V5H7C5.89,5 5,5.89 5,7V9H3V11H5V13H3V15H5V17A2,2 0 0,0 7,19H9V21H11V19H13V21H15V19H17A2,2 0 0,0 19,17V15H21V13H19V11M13,13H11V11H13M15,9H9V15H15V9Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Info">M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Folder">M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Plus">M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Delete">M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Copy">M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Close">M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.ArrowUp">M7,15L12,10L17,15H7Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.ArrowDown">M7,10L12,15L17,10H7Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Upload">M9,16V10H5L12,3L19,10H15V16H9M5,20V18H19V20H5Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Check">M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Alert">M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Pencil">M3,17.25V21h3.75L17.81,9.94l-3.75-3.75L3,17.25z M20.71,7.04c0.39-0.39,0.39-1.02,0-1.41l-2.34-2.34c-0.39-0.39-1.02-0.39-1.41,0l-1.83,1.83l3.75,3.75L20.71,7.04z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Link">M10.59,13.41C11,13.8 11,14.44 10.59,14.83C10.2,15.22 9.56,15.22 9.17,14.83C7.22,12.88 7.22,9.71 9.17,7.76V7.76L12.71,4.22C14.66,2.27 17.83,2.27 19.78,4.22C21.73,6.17 21.73,9.34 19.78,11.29L18.29,12.78C18.3,11.96 18.17,11.14 17.89,10.36L18.36,9.88C19.54,8.71 19.54,6.81 18.36,5.64C17.19,4.46 15.29,4.46 14.12,5.64L10.59,9.17C9.41,10.34 9.41,12.24 10.59,13.41M13.41,9.17C13.8,8.78 14.44,8.78 14.83,9.17C16.78,11.12 16.78,14.29 14.83,16.24V16.24L11.29,19.78C9.34,21.73 6.17,21.73 4.22,19.78C2.27,17.83 2.27,14.66 4.22,12.71L5.71,11.22C5.7,12.04 5.83,12.86 6.11,13.65L5.64,14.12C4.46,15.29 4.46,17.19 5.64,18.36C6.81,19.54 8.71,19.54 9.88,18.36L13.41,14.83C14.59,13.66 14.59,11.76 13.41,10.59C13,10.2 13,9.56 13.41,9.17Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Refresh">M17.65,6.35C16.2,4.9 14.21,4 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20C15.73,20 18.84,17.45 19.73,14H17.65C16.83,16.33 14.61,18 12,18A6,6 0 0,1 6,12A6,6 0 0,1 12,6C13.66,6 15.14,6.69 16.22,7.78L13,11H20V4L17.65,6.35Z</StreamGeometry>
+ <StreamGeometry x:Key="Icon.Record">M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,7A5,5 0 0,1 17,12A5,5 0 0,1 12,17A5,5 0 0,1 7,12A5,5 0 0,1 12,7Z</StreamGeometry>
+</ResourceDictionary>
diff --git a/src/Filee.App/Styles/Soft.axaml b/src/Filee.App/Styles/Soft.axaml
new file mode 100644
index 00000000..207672cb
--- /dev/null
+++ b/src/Filee.App/Styles/Soft.axaml
@@ -0,0 +1,246 @@
+<!--
+ Filee "soft" look: rounded corners, gentle surfaces, springy press feedback.
+ Colours that depend on light/dark live in ThemeDictionaries below; the accent colour, corner radii and
+ the UI font are written at runtime by ThemeService (so users can customise them).
+-->
+<Styles xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:c="using:Filee.App.Controls">
+
+ <Styles.Resources>
+ <ResourceDictionary>
+ <ResourceDictionary.ThemeDictionaries>
+ <ResourceDictionary x:Key="Light">
+ <SolidColorBrush x:Key="PageBrush" Color="#F6F5F1" />
+ <SolidColorBrush x:Key="SurfaceBrush" Color="#FFFFFF" />
+ <SolidColorBrush x:Key="SurfaceAltBrush" Color="#EFEDE6" />
+ <SolidColorBrush x:Key="SubtleBorderBrush" Color="#16000000" />
+ <SolidColorBrush x:Key="TextPrimaryBrush" Color="#1F1E1D" />
+ <SolidColorBrush x:Key="TextSecondaryBrush" Color="#6B6A66" />
+ <SolidColorBrush x:Key="DangerBrush" Color="#C73A39" />
+ <SolidColorBrush x:Key="SuccessBrush" Color="#0F7A5A" />
+ <SolidColorBrush x:Key="WarningBrush" Color="#9A5B0C" />
+ <BoxShadows x:Key="CardShadow">0 1 3 0 #12000000, 0 6 18 0 #0D000000</BoxShadows>
+ </ResourceDictionary>
+ <ResourceDictionary x:Key="Dark">
+ <SolidColorBrush x:Key="PageBrush" Color="#1B1B19" />
+ <SolidColorBrush x:Key="SurfaceBrush" Color="#262624" />
+ <SolidColorBrush x:Key="SurfaceAltBrush" Color="#31312E" />
+ <SolidColorBrush x:Key="SubtleBorderBrush" Color="#1CFFFFFF" />
+ <SolidColorBrush x:Key="TextPrimaryBrush" Color="#F1EFE8" />
+ <SolidColorBrush x:Key="TextSecondaryBrush" Color="#AEACA4" />
+ <SolidColorBrush x:Key="DangerBrush" Color="#F09595" />
+ <SolidColorBrush x:Key="SuccessBrush" Color="#5DCAA5" />
+ <SolidColorBrush x:Key="WarningBrush" Color="#EF9F27" />
+ <BoxShadows x:Key="CardShadow">0 1 3 0 #40000000, 0 8 24 0 #33000000</BoxShadows>
+ </ResourceDictionary>
+ </ResourceDictionary.ThemeDictionaries>
+
+ <!-- Defaults; ThemeService overwrites these at startup. -->
+ <SolidColorBrush x:Key="AccentBrush" Color="#7F77DD" />
+ <SolidColorBrush x:Key="AccentSoftBrush" Color="#2E7F77DD" />
+ <SolidColorBrush x:Key="AccentFaintBrush" Color="#177F77DD" />
+ <SolidColorBrush x:Key="AccentStrongBrush" Color="#5F59A6" />
+ <SolidColorBrush x:Key="OnAccentBrush" Color="#FFFFFF" />
+ <CornerRadius x:Key="SoftRadius">16</CornerRadius>
+ <CornerRadius x:Key="SoftRadiusSmall">9</CornerRadius>
+ <CornerRadius x:Key="SoftRadiusLarge">22</CornerRadius>
+ <FontFamily x:Key="AppFontFamily">Segoe UI, Malgun Gothic, Microsoft YaHei, sans-serif</FontFamily>
+
+ <!-- Springy easing used by press/hover transitions ("말랑말랑"). -->
+ <BackEaseOut x:Key="SoftEase" />
+ </ResourceDictionary>
+ </Styles.Resources>
+
+ <!-- ───────── Windows & typography ───────── -->
+ <Style Selector="Window">
+ <Setter Property="Background" Value="{DynamicResource PageBrush}" />
+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
+ <Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}" />
+ <Setter Property="FontSize" Value="14" />
+ </Style>
+
+ <Style Selector="TextBlock.h1">
+ <Setter Property="FontSize" Value="24" />
+ <Setter Property="FontWeight" Value="SemiBold" />
+ </Style>
+ <Style Selector="TextBlock.h2">
+ <Setter Property="FontSize" Value="16" />
+ <Setter Property="FontWeight" Value="SemiBold" />
+ </Style>
+ <Style Selector="TextBlock.muted">
+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />
+ </Style>
+ <Style Selector="TextBlock.caption">
+ <Setter Property="FontSize" Value="12" />
+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />
+ </Style>
+ <Style Selector="TextBlock.label">
+ <Setter Property="FontSize" Value="12.5" />
+ <Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}" />
+ <Setter Property="Margin" Value="0,0,0,4" />
+ </Style>
+ <Style Selector="TextBlock.danger">
+ <Setter Property="Foreground" Value="{DynamicResource DangerBrush}" />
+ </Style>
+
+ <!-- ───────── Cards ───────── -->
+ <Style Selector="Border.card">
+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />
+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />
+ <Setter Property="BorderThickness" Value="1" />
+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadius}" />
+ <Setter Property="Padding" Value="18,16" />
+ <Setter Property="BoxShadow" Value="{DynamicResource CardShadow}" />
+ </Style>
+
+ <Style Selector="Border.chip">
+ <Setter Property="Background" Value="{DynamicResource SurfaceBrush}" />
+ <Setter Property="BorderBrush" Value="{DynamicResource SubtleBorderBrush}" />
+ <Setter Property="BorderThickness" Value="1" />
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="Padding" Value="10,5" />
+ <Setter Property="Margin" Value="3" />
+ <Setter Property="Cursor" Value="SizeAll" />
+ <Setter Property="RenderTransform" Value="none" />
+ <Setter Property="Transitions">
+ <Transitions>
+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.25" Easing="{StaticResource SoftEase}" />
+ <BrushTransition Property="Background" Duration="0:0:0.15" />
+ </Transitions>
+ </Setter>
+ </Style>
+ <Style Selector="Border.chip:pointerover">
+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />
+ <Setter Property="RenderTransform" Value="scale(1.05)" />
+ </Style>
+
+ <!-- Badge for engine status etc. -->
+ <Style Selector="Border.badge">
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="Padding" Value="8,2" />
+ <Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />
+ </Style>
+ <Style Selector="Border.badge.ok">
+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />
+ </Style>
+
+ <!-- ───────── Buttons: soft corners and a springy press ───────── -->
+ <Style Selector="Button, ToggleButton, RepeatButton">
+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />
+ <Setter Property="Padding" Value="14,7" />
+ <Setter Property="Transitions">
+ <Transitions>
+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.22" Easing="{StaticResource SoftEase}" />
+ </Transitions>
+ </Setter>
+ </Style>
+ <Style Selector="Button:pressed, ToggleButton:pressed">
+ <Setter Property="RenderTransform" Value="scale(0.95)" />
+ </Style>
+ <Style Selector="Button.ghost">
+ <Setter Property="Background" Value="Transparent" />
+ <Setter Property="BorderThickness" Value="0" />
+ </Style>
+ <Style Selector="Button.icon">
+ <Setter Property="Padding" Value="8" />
+ <Setter Property="Background" Value="Transparent" />
+ <Setter Property="BorderThickness" Value="0" />
+ </Style>
+
+ <Style Selector="ProgressBar.soft">
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="MinHeight" Value="6" />
+ <Setter Property="Height" Value="6" />
+ </Style>
+
+ <Style Selector="TextBox, ComboBox, NumericUpDown">
+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />
+ </Style>
+
+ <!-- ───────── Navigation list ───────── -->
+ <Style Selector="ListBox.nav">
+ <Setter Property="Background" Value="Transparent" />
+ <Setter Property="Padding" Value="0" />
+ </Style>
+ <Style Selector="ListBox.nav ListBoxItem">
+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />
+ <Setter Property="Padding" Value="12,9" />
+ <Setter Property="Margin" Value="0,1" />
+ <Setter Property="RenderTransform" Value="none" />
+ <Setter Property="Transitions">
+ <Transitions>
+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.25" Easing="{StaticResource SoftEase}" />
+ </Transitions>
+ </Setter>
+ </Style>
+ <Style Selector="ListBox.nav ListBoxItem:pointerover">
+ <Setter Property="RenderTransform" Value="translateX(3px)" />
+ </Style>
+ <Style Selector="ListBox.nav ListBoxItem:selected /template/ ContentPresenter#PART_ContentPresenter">
+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />
+ <Setter Property="Foreground" Value="{DynamicResource AccentStrongBrush}" />
+ </Style>
+ <Style Selector="ListBox.nav ListBoxItem:selected:pointerover /template/ ContentPresenter#PART_ContentPresenter">
+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />
+ </Style>
+
+ <!-- Generic rounded list items (profiles, presets) -->
+ <Style Selector="ListBox.soft">
+ <Setter Property="Background" Value="Transparent" />
+ </Style>
+ <Style Selector="ListBox.soft ListBoxItem">
+ <Setter Property="CornerRadius" Value="{DynamicResource SoftRadiusSmall}" />
+ <Setter Property="Padding" Value="10,7" />
+ <Setter Property="Margin" Value="0,1" />
+ </Style>
+ <Style Selector="ListBox.soft ListBoxItem:selected /template/ ContentPresenter#PART_ContentPresenter">
+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />
+ </Style>
+
+ <!-- ───────── Donut control colours ───────── -->
+ <Style Selector="c|DonutMenu">
+ <Setter Property="SliceBrush" Value="{DynamicResource SurfaceBrush}" />
+ <Setter Property="SliceBorderBrush" Value="{DynamicResource SubtleBorderBrush}" />
+ <Setter Property="CenterBrush" Value="{DynamicResource SurfaceBrush}" />
+ <Setter Property="AccentBrush" Value="{DynamicResource AccentBrush}" />
+ <Setter Property="OnAccentBrush" Value="{DynamicResource OnAccentBrush}" />
+ <Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
+ <Setter Property="SecondaryForeground" Value="{DynamicResource TextSecondaryBrush}" />
+ <Setter Property="DangerBrush" Value="{DynamicResource DangerBrush}" />
+ <Setter Property="SuccessBrush" Value="{DynamicResource SuccessBrush}" />
+ </Style>
+
+ <!-- ───────── Page content fade-in (keyframes can't animate RenderTransform, so Margin slides) ───────── -->
+ <Style Selector="ContentControl.page > :is(Control)">
+ <Style.Animations>
+ <Animation Duration="0:0:0.28" Easing="CubicEaseOut" FillMode="Forward">
+ <KeyFrame Cue="0%">
+ <Setter Property="Opacity" Value="0" />
+ <Setter Property="Margin" Value="0,10,0,-10" />
+ </KeyFrame>
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ <Setter Property="Margin" Value="0" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+
+ <!-- ───────── Reduced motion: remove every transition and animation above ───────── -->
+ <Style Selector="Window.reduced-motion :is(Button), Window.reduced-motion :is(ToggleButton), Window.reduced-motion Border.chip, Window.reduced-motion ListBoxItem">
+ <Setter Property="Transitions" Value="{x:Null}" />
+ </Style>
+ <Style Selector="Window.reduced-motion Button:pressed, Window.reduced-motion ToggleButton:pressed, Window.reduced-motion Border.chip:pointerover, Window.reduced-motion ListBox.nav ListBoxItem:pointerover">
+ <Setter Property="RenderTransform" Value="none" />
+ </Style>
+ <Style Selector="Window.reduced-motion ContentControl.page > :is(Control)">
+ <Style.Animations>
+ <Animation Duration="0:0:0.001" FillMode="Forward">
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+</Styles>
diff --git a/src/Filee.App/ViewLocator.cs b/src/Filee.App/ViewLocator.cs
new file mode 100644
index 00000000..2e21e24d
--- /dev/null
+++ b/src/Filee.App/ViewLocator.cs
@@ -0,0 +1,26 @@
+// Resolves a view for a view model by naming convention:
+// Filee.App.ViewModels.Pages.HomePageViewModel → Filee.App.Views.Pages.HomePage
+
+using Avalonia.Controls;
+using Avalonia.Controls.Templates;
+using CommunityToolkit.Mvvm.ComponentModel;
+
+namespace Filee.App;
+
+public sealed class ViewLocator : IDataTemplate
+{
+ public Control? Build(object? data)
+ {
+ if (data is null)
+ return null;
+ var name = data.GetType().FullName!
+ .Replace(".ViewModels.", ".Views.", StringComparison.Ordinal)
+ .Replace("ViewModel", "", StringComparison.Ordinal);
+ var type = Type.GetType(name);
+ return type is null
+ ? new TextBlock { Text = "View not found: " + name }
+ : (Control)Activator.CreateInstance(type)!;
+ }
+
+ public bool Match(object? data) => data is ObservableObject && data.GetType().Name.EndsWith("PageViewModel", StringComparison.Ordinal);
+}
diff --git a/src/Filee.App/ViewModels/EngineSetupViewModel.cs b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
new file mode 100644
index 00000000..51704fb8
--- /dev/null
+++ b/src/Filee.App/ViewModels/EngineSetupViewModel.cs
@@ -0,0 +1,80 @@
+// First-run engine choice: the installer only contains the small engines, so right after installing Filee asks
+// which large ones to download (like optional components in a classic setup wizard).
+
+using System.ComponentModel;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Localization;
+
+namespace Filee.App.ViewModels;
+
+public sealed partial class EngineSetupViewModel : ObservableObject
+{
+ private readonly EngineDownloadService _downloads;
+ private readonly ILocalizer _loc;
+
+ public EngineSetupViewModel(EngineDownloadService downloads, ILocalizer loc)
+ {
+ _downloads = downloads;
+ _loc = loc;
+ foreach (var package in Packages)
+ {
+ package.Selected = !package.IsInstalled;
+ package.PropertyChanged += OnPackageChanged;
+ }
+ }
+
+ public IReadOnlyList<EnginePackageState> Packages => _downloads.Packages;
+
+ /// <summary>Installation was started from this window (checkboxes lock, progress shows).</summary>
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(CanChoose), nameof(CloseText))]
+ [NotifyCanExecuteChangedFor(nameof(InstallCommand))]
+ private bool _started;
+
+ public bool CanChoose => !Started;
+
+ public string SelectionText
+ {
+ get
+ {
+ var selected = Packages.Where(p => p.Selected && p.CanInstall).ToList();
+ return selected.Count == 0
+ ? _loc["setup.nothing_selected"]
+ : _loc.Format("setup.selection", EnginePackageState.FormatBytes(selected.Sum(p => Filee.Engines.Infrastructure.EngineDownloads.DownloadSize(p.Package))));
+ }
+ }
+
+ /// <summary>"Later" before starting, "Continue in the background" while downloading, then "Done".</summary>
+ public string CloseText => !Started ? _loc["setup.later"] : _downloads.IsBusy ? _loc["setup.background"] : _loc["setup.done"];
+
+ /// <summary>Raised when the window should close.</summary>
+ public event EventHandler? CloseRequested;
+
+ private bool CanInstall() => !Started && Packages.Any(p => p.Selected && p.CanInstall);
+
+ [RelayCommand(CanExecute = nameof(CanInstall))]
+ private void Install()
+ {
+ Started = true;
+ // The service installs one package at a time; the others wait in its queue.
+ foreach (var package in Packages.Where(p => p.Selected && p.CanInstall))
+ _ = _downloads.InstallAsync(package);
+ }
+
+ [RelayCommand]
+ private void Close()
+ {
+ foreach (var package in Packages)
+ package.PropertyChanged -= OnPackageChanged;
+ CloseRequested?.Invoke(this, EventArgs.Empty);
+ }
+
+ private void OnPackageChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ OnPropertyChanged(nameof(SelectionText));
+ OnPropertyChanged(nameof(CloseText));
+ InstallCommand.NotifyCanExecuteChanged();
+ }
+}
diff --git a/src/Filee.App/ViewModels/JobViewModel.cs b/src/Filee.App/ViewModels/JobViewModel.cs
new file mode 100644
index 00000000..0e5867f9
--- /dev/null
+++ b/src/Filee.App/ViewModels/JobViewModel.cs
@@ -0,0 +1,80 @@
+// One running / finished conversion as shown in the toast window.
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+
+namespace Filee.App.ViewModels;
+
+public sealed partial class JobViewModel : ObservableObject
+{
+ private readonly ILocalizer _loc;
+ private readonly IPlatformServices _platform;
+ private readonly Action<JobViewModel> _dismiss;
+ private int _refreshPending;
+
+ public JobViewModel(ConversionJob job, ILocalizer loc, IPlatformServices platform, Action<JobViewModel> dismiss)
+ {
+ Job = job;
+ _loc = loc;
+ _platform = platform;
+ _dismiss = dismiss;
+ var what = job.Sources.Count == 1 ? Path.GetFileName(job.Sources[0]) : loc.Format("home.files", job.Sources.Count);
+ Title = loc.Format("toast.converting", what, job.PresetDisplayName);
+ Refresh();
+ }
+
+ public ConversionJob Job { get; }
+
+ public string Title { get; }
+
+ [ObservableProperty] private double _progress;
+ [ObservableProperty] private string _status = "";
+ [ObservableProperty] private bool _isRunning = true;
+ [ObservableProperty] private bool _hasErrors;
+ [ObservableProperty] private bool _hasOutputs;
+ [ObservableProperty] private string? _errorDetails;
+
+ /// <summary>Marks a refresh as pending; returns false if one is already queued (coalesces UI updates).</summary>
+ internal bool TryMarkPending() => Interlocked.Exchange(ref _refreshPending, 1) == 0;
+
+ /// <summary>Copies job state into bindable properties. UI thread only.</summary>
+ public void Refresh()
+ {
+ Interlocked.Exchange(ref _refreshPending, 0);
+ Progress = Job.Progress * 100;
+ IsRunning = Job.State is JobState.Queued or JobState.Running;
+ HasOutputs = Job.Outputs.Any();
+
+ var failed = Job.Files.Where(f => f.State == FileState.Failed).ToList();
+ HasErrors = failed.Count > 0;
+ ErrorDetails = failed.Count == 0 ? null : string.Join(Environment.NewLine,
+ failed.Select(f => $"{Path.GetFileName(f.SourcePath)} — {_loc[f.ErrorKey ?? "error.conversion_failed"]}{(f.ErrorDetail is null ? "" : $" ({f.ErrorDetail})")}"));
+
+ Status = Job.State switch
+ {
+ JobState.Completed when Job.Files.All(f => f.State == FileState.Skipped) => _loc["toast.skipped"],
+ JobState.Completed => _loc["toast.done"],
+ JobState.CompletedWithErrors => _loc.Format("toast.done_errors", failed.Count, Job.Files.Count),
+ JobState.Failed => _loc["toast.failed"],
+ JobState.Cancelled => _loc["toast.cancelled"],
+ _ => $"{Progress:0}%",
+ };
+ }
+
+ [RelayCommand]
+ private void OpenFolder()
+ {
+ var first = Job.Outputs.FirstOrDefault();
+ if (first is not null)
+ _platform.RevealInFileManager(first);
+ }
+
+ [RelayCommand]
+ private void Cancel() => Job.Cancel();
+
+ [RelayCommand]
+ private void Dismiss() => _dismiss(this);
+}
diff --git a/src/Filee.App/ViewModels/MainWindowViewModel.cs b/src/Filee.App/ViewModels/MainWindowViewModel.cs
new file mode 100644
index 00000000..4e38ea87
--- /dev/null
+++ b/src/Filee.App/ViewModels/MainWindowViewModel.cs
@@ -0,0 +1,76 @@
+// Main (settings) window: left navigation + current page.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.App.ViewModels.Pages;
+using Filee.Core.Localization;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Filee.App.ViewModels;
+
+/// <summary>Navigation entry. <see cref="Title"/> follows the UI language.</summary>
+public sealed partial class NavItem(string key, string titleKey, string iconKey, Type pageType) : ObservableObject
+{
+ public string Key { get; } = key;
+ public string TitleKey { get; } = titleKey;
+ public Geometry? Icon { get; } = Application.Current?.FindResource(iconKey) as Geometry;
+ public Type PageType { get; } = pageType;
+
+ [ObservableProperty] private string _title = "";
+
+ public void Refresh(ILocalizer loc) => Title = loc[TitleKey];
+}
+
+public sealed partial class MainWindowViewModel : ObservableObject
+{
+ private readonly IServiceProvider _services;
+
+ public MainWindowViewModel(IServiceProvider services, ILocalizer loc)
+ {
+ _services = services;
+ Items =
+ [
+ new("home", "nav.home", "Icon.Home", typeof(HomePageViewModel)),
+ new("general", "nav.general", "Icon.Settings", typeof(GeneralPageViewModel)),
+ new("triggers", "nav.triggers", "Icon.Keyboard", typeof(TriggersPageViewModel)),
+ new("toolbar", "nav.toolbar", "Icon.Donut", typeof(ToolbarPageViewModel)),
+ new("presets", "nav.presets", "Icon.Tune", typeof(PresetsPageViewModel)),
+ new("theme", "nav.theme", "Icon.Palette", typeof(ThemePageViewModel)),
+ new("engines", "nav.engines", "Icon.Engine", typeof(EnginesPageViewModel)),
+ new("about", "nav.about", "Icon.Info", typeof(AboutPageViewModel)),
+ ];
+ foreach (var item in Items)
+ item.Refresh(loc);
+ loc.LanguageChanged += (_, _) =>
+ {
+ foreach (var item in Items)
+ item.Refresh(loc);
+ CurrentPage = CreatePage(SelectedItem); // rebuild so code-generated labels update too
+ };
+ _selectedItem = Items[0];
+ _currentPage = CreatePage(Items[0]);
+ }
+
+ public IReadOnlyList<NavItem> Items { get; }
+
+ [ObservableProperty] private NavItem _selectedItem;
+ [ObservableProperty] private ObservableObject _currentPage;
+
+ public void Navigate(string key)
+ {
+ var item = Items.FirstOrDefault(i => i.Key == key);
+ if (item is not null)
+ SelectedItem = item;
+ }
+
+ // Pages are recreated on every visit so they always reflect the latest settings.
+ partial void OnSelectedItemChanged(NavItem value) => CurrentPage = CreatePage(value);
+
+ // Old pages may hold event subscriptions on long-lived services.
+ partial void OnCurrentPageChanged(ObservableObject? oldValue, ObservableObject newValue) => (oldValue as IDisposable)?.Dispose();
+
+ private ObservableObject CreatePage(NavItem item) =>
+ (ObservableObject)ActivatorUtilities.CreateInstance(_services, item.PageType);
+}
diff --git a/src/Filee.App/ViewModels/Pages/AboutPageViewModel.cs b/src/Filee.App/ViewModels/Pages/AboutPageViewModel.cs
new file mode 100644
index 00000000..eb55e147
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/AboutPageViewModel.cs
@@ -0,0 +1,25 @@
+// About: version, license, third-party notices.
+
+using Avalonia.Platform;
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.App.Services;
+using Filee.Core.Localization;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class AboutPageViewModel(ILocalizer loc) : ObservableObject
+{
+ public string Version { get; } = loc.Format("about.version", UpdateService.CurrentVersion);
+ public string RepositoryUrl { get; } = UpdateService.RepositoryUrl;
+
+ public string Notices { get; } = ReadNotices();
+
+ private static string ReadNotices()
+ {
+ var uri = new Uri("avares://Filee/Assets/THIRD-PARTY-NOTICES.md");
+ if (!AssetLoader.Exists(uri))
+ return "";
+ using var reader = new StreamReader(AssetLoader.Open(uri));
+ return reader.ReadToEnd();
+ }
+}
diff --git a/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs b/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs
new file mode 100644
index 00000000..6d0430e7
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/EnginesPageViewModel.cs
@@ -0,0 +1,121 @@
+// Conversion engines: optional downloads, availability, priority order and custom executable paths.
+
+using System.Collections.ObjectModel;
+using Avalonia.Threading;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Conversion;
+using Filee.Core.Localization;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class EngineItemViewModel : ObservableObject
+{
+ 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 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 sealed partial class EnginesPageViewModel : ObservableObject, IDisposable
+{
+ private readonly UserDataStore _store;
+ private readonly ConverterCatalog _catalog;
+ private readonly ILocalizer _loc;
+ private readonly EngineDownloadService _downloads;
+
+ public EnginesPageViewModel(UserDataStore store, ConverterCatalog catalog, ILocalizer loc, EngineDownloadService downloads)
+ {
+ _store = store;
+ _catalog = catalog;
+ _loc = loc;
+ _downloads = downloads;
+ _catalog.Changed += OnCatalogChanged;
+ Reload();
+ }
+
+ /// <summary>Optional engines that are downloaded on demand.</summary>
+ public IReadOnlyList<EnginePackageState> Packages => _downloads.Packages;
+
+ public ObservableCollection<EngineItemViewModel> Engines { get; } = [];
+
+ [RelayCommand]
+ private Task Install(EnginePackageState package) => _downloads.InstallAsync(package);
+
+ [RelayCommand]
+ private void Cancel(EnginePackageState package) => _downloads.Cancel(package);
+
+ /// <summary>Removes a package (after the view asked for confirmation). False when its files are in use.</summary>
+ public bool Remove(EnginePackageState package) => _downloads.Uninstall(package);
+
+ // Installing or removing an engine changes the list below (status, supported conversions).
+ private void OnCatalogChanged(object? sender, EventArgs e) => Dispatcher.UIThread.Post(Reload);
+
+ public void Dispose() => _catalog.Changed -= OnCatalogChanged;
+
+ private void Reload()
+ {
+ Engines.Clear();
+ foreach (var converter in _catalog.Ordered)
+ Engines.Add(new EngineItemViewModel(converter, _catalog.StatusOf(converter),
+ _store.Settings.EnginePaths.GetValueOrDefault(converter.Id), _loc, OnPathChanged));
+ }
+
+ [RelayCommand]
+ private void MoveUp(EngineItemViewModel item) => Move(item, -1);
+
+ [RelayCommand]
+ private void MoveDown(EngineItemViewModel item) => Move(item, +1);
+
+ [RelayCommand]
+ private void Recheck()
+ {
+ _downloads.RefreshStatus();
+ _catalog.Refresh();
+ }
+
+ private void Move(EngineItemViewModel item, int delta)
+ {
+ var index = Engines.IndexOf(item);
+ var target = index + delta;
+ if (index < 0 || target < 0 || target >= Engines.Count)
+ return;
+ Engines.Move(index, target);
+ _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/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
new file mode 100644
index 00000000..572c6c2c
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs
@@ -0,0 +1,97 @@
+// General settings: language, start-up, Explorer integration, updates, preset library import/export.
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class GeneralPageViewModel : ObservableObject
+{
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+ private readonly IPlatformServices _platform;
+ private readonly UpdateService _updates;
+
+ public GeneralPageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices platform, UpdateService updates)
+ {
+ _store = store;
+ _loc = loc;
+ _platform = platform;
+ _updates = updates;
+
+ Languages =
+ [
+ new Choice<string>("auto", loc["general.language_auto"]),
+ .. LocalizationService.Languages.Select(l => new Choice<string>(l.Code, l.NativeName)),
+ ];
+ _language = Languages.FirstOrDefault(l => l.Value == store.Settings.Language) ?? Languages[0];
+ _startWithSystem = store.Settings.StartWithSystem;
+ _contextMenu = store.Settings.ContextMenuEnabled;
+ _checkForUpdates = store.Settings.CheckForUpdates;
+ _updateStatus = updates.IsInstalled ? null : loc["general.update_dev"];
+ }
+
+ public IReadOnlyList<Choice<string>> Languages { get; }
+ public string DataFolder => _store.Directory;
+ public bool IsWindows => OperatingSystem.IsWindows();
+
+ [ObservableProperty] private Choice<string> _language;
+ [ObservableProperty] private bool _startWithSystem;
+ [ObservableProperty] private bool _contextMenu;
+ [ObservableProperty] private bool _checkForUpdates;
+ [ObservableProperty] private string? _updateStatus;
+ [ObservableProperty] private bool _updateAvailable;
+ [ObservableProperty] private string? _libraryMessage;
+
+ partial void OnLanguageChanged(Choice<string> value) => Save(s => s.Language = value.Value);
+ partial void OnStartWithSystemChanged(bool value) => Save(s => s.StartWithSystem = value);
+ partial void OnContextMenuChanged(bool value) => Save(s => s.ContextMenuEnabled = value);
+ partial void OnCheckForUpdatesChanged(bool value) => Save(s => s.CheckForUpdates = value);
+
+ private void Save(Action<AppSettings> change)
+ {
+ change(_store.Settings);
+ _store.SaveSettings();
+ }
+
+ [RelayCommand]
+ private void OpenDataFolder() => _platform.RevealInFileManager(_store.Directory);
+
+ [RelayCommand]
+ private async Task CheckNow()
+ {
+ if (!_updates.IsInstalled)
+ return;
+ var version = await _updates.CheckAsync();
+ UpdateAvailable = version is not null;
+ UpdateStatus = version is null ? _loc["general.update_none"] : _loc.Format("general.update_available", version);
+ }
+
+ [RelayCommand]
+ private Task InstallUpdate() => _updates.ApplyAsync();
+
+ public void Export(string path)
+ {
+ _store.Export(path);
+ LibraryMessage = Path.GetFileName(path);
+ }
+
+ public void Import(string path)
+ {
+ try
+ {
+ var count = _store.Import(path);
+ LibraryMessage = _loc.Format("general.imported", count);
+ }
+ catch (Exception ex) when (ex is IOException or System.Text.Json.JsonException or InvalidDataException)
+ {
+ LibraryMessage = ex.Message;
+ }
+ }
+
+ public void ResetLibrary() => _store.ResetLibrary();
+}
diff --git a/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
new file mode 100644
index 00000000..f596ae00
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/HomePageViewModel.cs
@@ -0,0 +1,83 @@
+// Home: drop zone (handled in the view) and recent conversions.
+
+using System.Collections.ObjectModel;
+using Avalonia.Threading;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Conversion;
+using Filee.Core.History;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class HistoryItemViewModel(HistoryEntry entry, ILocalizer loc, IPlatformServices platform) : ObservableObject
+{
+ public string Title { get; } = entry.PresetName;
+
+ public string Subtitle { get; } = entry.Sources.Count == 1
+ ? Path.GetFileName(entry.Sources[0])
+ : loc.Format("home.files", entry.Sources.Count);
+
+ public string Time { get; } = entry.FinishedAt.Date == DateTime.Today
+ ? entry.FinishedAt.ToString("t")
+ : entry.FinishedAt.ToString("d");
+
+ public bool Succeeded { get; } = entry.State == JobState.Completed;
+ public bool HasErrors { get; } = entry.Errors.Count > 0 || entry.State == JobState.Failed;
+ public string? Errors { get; } = entry.Errors.Count == 0 ? null : string.Join(Environment.NewLine, entry.Errors);
+ public bool HasOutputs { get; } = entry.Outputs.Any(File.Exists);
+
+ [RelayCommand]
+ private void OpenFolder()
+ {
+ var output = entry.Outputs.FirstOrDefault(File.Exists);
+ if (output is not null)
+ platform.RevealInFileManager(output);
+ }
+}
+
+public sealed partial class HomePageViewModel : ObservableObject, IDisposable
+{
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+ private readonly IPlatformServices _platform;
+
+ public HomePageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices platform)
+ {
+ _store = store;
+ _loc = loc;
+ _platform = platform;
+ var drag = store.Settings.Triggers.FirstOrDefault(t => t.Enabled && t.Kind == TriggerKind.Drag);
+ DropHint = loc.Format("home.drop_hint", drag is null ? "—" : GestureText.Modifiers(drag.Modifiers));
+ store.HistoryChanged += OnHistoryChanged;
+ Reload();
+ }
+
+ private void OnHistoryChanged(object? sender, EventArgs e) => Dispatcher.UIThread.Post(Reload);
+
+ public void Dispose() => _store.HistoryChanged -= OnHistoryChanged;
+
+ public string DropHint { get; }
+
+ public ObservableCollection<HistoryItemViewModel> History { get; } = [];
+
+ [ObservableProperty] private bool _isEmpty;
+
+ private void Reload()
+ {
+ History.Clear();
+ foreach (var entry in _store.History.Take(40))
+ History.Add(new HistoryItemViewModel(entry, _loc, _platform));
+ IsEmpty = History.Count == 0;
+ }
+
+ [RelayCommand]
+ private void ClearHistory()
+ {
+ _store.ClearHistory();
+ Reload();
+ }
+}
diff --git a/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs
new file mode 100644
index 00000000..53e668c6
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs
@@ -0,0 +1,112 @@
+// Preset list + the shared PresetEditorView on the right.
+
+using System.Collections.ObjectModel;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class PresetListItem(Preset preset, ILocalizer loc) : ObservableObject
+{
+ public Preset Preset { get; } = preset;
+
+ [ObservableProperty] private string _name = loc.DisplayName(preset);
+ [ObservableProperty] private string _target = TargetLabel(preset, loc);
+
+ public void Refresh(ILocalizer l)
+ {
+ Name = l.DisplayName(Preset);
+ Target = TargetLabel(Preset, l);
+ }
+
+ private static string TargetLabel(Preset p, ILocalizer l) =>
+ p.TargetFormat == BuiltInData.SameAsSource ? l["presets.same_as_source"]
+ : "→ " + (FormatRegistry.FindById(p.TargetFormat)?.DisplayName ?? p.TargetFormat);
+}
+
+public sealed partial class PresetsPageViewModel : ObservableObject
+{
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+ private readonly WindowService _windows;
+
+ public PresetsPageViewModel(UserDataStore store, ILocalizer loc, WindowService windows)
+ {
+ _store = store;
+ _loc = loc;
+ _windows = windows;
+ foreach (var preset in store.Presets)
+ Presets.Add(new PresetListItem(preset, loc));
+ SelectedPreset = Presets.FirstOrDefault();
+ }
+
+ public ObservableCollection<PresetListItem> Presets { get; } = [];
+
+ [ObservableProperty] private PresetListItem? _selectedPreset;
+ [ObservableProperty] private PresetEditorViewModel? _editor;
+ [ObservableProperty] private string? _savedMessage;
+
+ partial void OnSelectedPresetChanged(PresetListItem? value)
+ {
+ Editor = value is null ? null : new PresetEditorViewModel(value.Preset, _loc);
+ SavedMessage = null;
+ }
+
+ [RelayCommand]
+ private void Save()
+ {
+ if (Editor is null || SelectedPreset is null || !Editor.Apply())
+ return;
+ _store.SaveLibrary();
+ SelectedPreset.Refresh(_loc);
+ SavedMessage = "✓";
+ }
+
+ [RelayCommand]
+ private void Revert() => OnSelectedPresetChanged(SelectedPreset);
+
+ [RelayCommand]
+ private void Add() => AddPreset(new Preset { Name = _loc["toolbar.new_preset"], TargetFormat = "png" });
+
+ [RelayCommand]
+ private void Duplicate()
+ {
+ if (SelectedPreset is null)
+ return;
+ var copy = SelectedPreset.Preset.Clone();
+ copy.Id = Preset.NewId();
+ copy.Name = _loc.DisplayName(SelectedPreset.Preset) + " 2";
+ copy.NameKey = null;
+ AddPreset(copy);
+ }
+
+ [RelayCommand]
+ private async Task Delete()
+ {
+ if (SelectedPreset is null || _windows.Main is null)
+ return;
+ var message = _loc.Format("presets.delete_confirm", SelectedPreset.Name);
+ if (!await _windows.ConfirmAsync(_windows.Main, message, destructive: true))
+ return;
+
+ var index = Presets.IndexOf(SelectedPreset);
+ _store.Presets.Remove(SelectedPreset.Preset);
+ _store.SaveLibrary(); // also removes it from every profile
+ Presets.Remove(SelectedPreset);
+ SelectedPreset = Presets.Count == 0 ? null : Presets[Math.Clamp(index, 0, Presets.Count - 1)];
+ }
+
+ private void AddPreset(Preset preset)
+ {
+ _store.Presets.Add(preset);
+ _store.SaveLibrary();
+ var item = new PresetListItem(preset, _loc);
+ Presets.Add(item);
+ SelectedPreset = item;
+ }
+}
diff --git a/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs b/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs
new file mode 100644
index 00000000..c93ecbd4
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/ThemePageViewModel.cs
@@ -0,0 +1,82 @@
+// Theme: light/dark, accent colour, softness (corner radius), reduce animations. Changes apply live.
+
+using Avalonia.Media;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Controls;
+using Filee.App.Services;
+using Filee.Core.Localization;
+using Filee.Core.Platform;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class ThemePageViewModel : ObservableObject
+{
+ private readonly UserDataStore _store;
+ private readonly bool _loading;
+
+ public ThemePageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices platform)
+ {
+ _store = store;
+ _loading = true;
+ var theme = store.Settings.Theme;
+ Modes = Enum.GetValues<ThemeMode>().Select(m => new Choice<ThemeMode>(m, loc[$"theme.mode.{m}"])).ToList();
+ Mode = Modes.First(m => m.Value == theme.Mode);
+ Accent = Color.TryParse(theme.Accent, out var c) ? c : Colors.MediumPurple;
+ AccentHex = $"#{Accent.R:X2}{Accent.G:X2}{Accent.B:X2}";
+ CornerRadius = theme.CornerRadius;
+ ReduceMotion = theme.ReduceMotion ?? platform.PrefersReducedMotion;
+ PreviewItems =
+ [
+ new DonutItem { Id = "a", Label = "PNG" },
+ new DonutItem { Id = "b", Label = "PDF" },
+ new DonutItem { Id = "c", Label = "WEBP" },
+ new DonutItem { Id = "d", Label = "HWPX" },
+ new DonutItem { Id = "e", Label = "JPG 70%", Caption = "JPG" },
+ new DonutItem { Id = "f", Label = "TIFF" },
+ ];
+ _loading = false;
+ }
+
+ public IReadOnlyList<Choice<ThemeMode>> Modes { get; }
+ public IReadOnlyList<Color> Swatches { get; } = ThemeService.Swatches.Select(Color.Parse).ToList();
+ public IReadOnlyList<DonutItem> PreviewItems { get; }
+
+ [ObservableProperty] private Choice<ThemeMode> _mode = null!;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(AccentBrush))] private Color _accent;
+ [ObservableProperty] private string _accentHex = "";
+
+ public IBrush AccentBrush => new SolidColorBrush(Accent);
+ [ObservableProperty] private double _cornerRadius;
+ [ObservableProperty] private bool _reduceMotion;
+
+ partial void OnModeChanged(Choice<ThemeMode> value) => Save(t => t.Mode = value.Value);
+ partial void OnAccentChanged(Color value)
+ {
+ var hex = $"#{value.R:X2}{value.G:X2}{value.B:X2}";
+ if (!string.Equals(AccentHex, hex, StringComparison.OrdinalIgnoreCase))
+ AccentHex = hex;
+ Save(t => t.Accent = hex);
+ }
+
+ // Custom colour typed as #RRGGBB; ignored until it parses.
+ partial void OnAccentHexChanged(string value)
+ {
+ if (Color.TryParse(value.Trim(), out var color) && color != Accent)
+ Accent = Color.FromRgb(color.R, color.G, color.B);
+ }
+ partial void OnCornerRadiusChanged(double value) => Save(t => t.CornerRadius = Math.Round(value));
+ partial void OnReduceMotionChanged(bool value) => Save(t => t.ReduceMotion = value);
+
+ [RelayCommand]
+ private void PickSwatch(Color color) => Accent = color;
+
+ private void Save(Action<ThemeSettings> change)
+ {
+ if (_loading)
+ return;
+ change(_store.Settings.Theme);
+ _store.SaveSettings(); // App re-applies the theme on SettingsChanged
+ }
+}
diff --git a/src/Filee.App/ViewModels/Pages/ToolbarConverters.cs b/src/Filee.App/ViewModels/Pages/ToolbarConverters.cs
new file mode 100644
index 00000000..2a11252b
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/ToolbarConverters.cs
@@ -0,0 +1,9 @@
+using Avalonia.Data.Converters;
+
+namespace Filee.App.ViewModels.Pages;
+
+/// <summary>Converters used by the donut editor (slider percent → 0..1 fraction).</summary>
+public static class ToolbarConverters
+{
+ public static readonly IValueConverter Percent = new FuncValueConverter<double, double>(v => v / 100.0);
+}
diff --git a/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs
new file mode 100644
index 00000000..ea47b1f9
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/ToolbarPageViewModel.cs
@@ -0,0 +1,250 @@
+// Donut toolbar editor: 1) choose a profile 2) arrange its presets on a live donut by drag & drop.
+// The drag gestures themselves live in the view (ToolbarPage.axaml.cs); this class only mutates the model.
+
+using System.Collections.ObjectModel;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Controls;
+using Filee.App.Services;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class ProfileItemViewModel(ToolbarProfile profile, ILocalizer loc) : ObservableObject
+{
+ public ToolbarProfile Profile { get; } = profile;
+
+ [ObservableProperty] private string _name = loc.DisplayName(profile);
+
+ public string Count => $"{Profile.PresetIds.Count}";
+
+ public void Refresh(ILocalizer l)
+ {
+ Name = l.DisplayName(Profile);
+ OnPropertyChanged(nameof(Count));
+ }
+}
+
+/// <summary>A preset chip in the "available presets" palette.</summary>
+public sealed record PaletteChip(string PresetId, string Label, string? Caption);
+
+public sealed partial class ToolbarPageViewModel : ObservableObject
+{
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+ private readonly WindowService _windows;
+ private bool _loading;
+
+ public ToolbarPageViewModel(UserDataStore store, ILocalizer loc, WindowService windows)
+ {
+ _store = store;
+ _loc = loc;
+ _windows = windows;
+ foreach (var profile in store.Profiles)
+ Profiles.Add(new ProfileItemViewModel(profile, loc));
+
+ _loading = true;
+ OuterRadius = store.Settings.Donut.OuterRadius;
+ HoleRatio = store.Settings.Donut.HoleRatio * 100;
+ SliceOpacity = store.Settings.Donut.Opacity * 100;
+ _loading = false;
+
+ SelectedProfile = Profiles.FirstOrDefault();
+ }
+
+ public ObservableCollection<ProfileItemViewModel> Profiles { get; } = [];
+ public ObservableCollection<PaletteChip> Palette { get; } = [];
+
+ [ObservableProperty] private ProfileItemViewModel? _selectedProfile;
+ [ObservableProperty] private IReadOnlyList<DonutItem> _donutItems = [];
+ [ObservableProperty] private string _centerTitle = "";
+ [ObservableProperty] private string _centerSubtitle = "";
+ [ObservableProperty] private string _profileName = "";
+ [ObservableProperty] private string _extensions = "";
+ [ObservableProperty] private bool _isFallback;
+ [ObservableProperty] private string? _message;
+ [ObservableProperty] private double _outerRadius;
+ [ObservableProperty] private double _holeRatio;
+ [ObservableProperty] private double _sliceOpacity;
+
+ private ToolbarProfile? Profile => SelectedProfile?.Profile;
+
+ partial void OnSelectedProfileChanged(ProfileItemViewModel? value)
+ {
+ _loading = true;
+ ProfileName = value is null ? "" : _loc.DisplayName(value.Profile);
+ Extensions = value is null ? "" : string.Join(", ", value.Profile.Extensions);
+ IsFallback = value?.Profile.IsFallback == true;
+ _loading = false;
+ Message = null;
+ Rebuild();
+ }
+
+ partial void OnProfileNameChanged(string value)
+ {
+ if (_loading || Profile is null || string.IsNullOrWhiteSpace(value) || value == _loc.DisplayName(Profile))
+ return;
+ Profile.Name = value.Trim();
+ SelectedProfile!.Refresh(_loc);
+ CenterTitle = value.Trim();
+ _store.SaveLibrary();
+ }
+
+ partial void OnExtensionsChanged(string value)
+ {
+ if (_loading || Profile is null || Profile.IsFallback)
+ return;
+ Profile.Extensions = value
+ .Split([',', ' ', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(e => e.TrimStart('.').ToLowerInvariant())
+ .Distinct()
+ .ToList();
+ _store.SaveLibrary();
+ }
+
+ partial void OnOuterRadiusChanged(double value) => SaveAppearance();
+ partial void OnHoleRatioChanged(double value) => SaveAppearance();
+ partial void OnSliceOpacityChanged(double value) => SaveAppearance();
+
+ private void SaveAppearance()
+ {
+ if (_loading)
+ return;
+ _store.Settings.Donut.OuterRadius = Math.Round(OuterRadius);
+ _store.Settings.Donut.HoleRatio = Math.Round(HoleRatio) / 100;
+ _store.Settings.Donut.Opacity = Math.Round(SliceOpacity) / 100;
+ _store.SaveSettings();
+ }
+
+ // ───────── Editing operations called by the view's drag & drop ─────────
+
+ public int SliceCount => Profile?.PresetIds.Count ?? 0;
+
+ /// <summary>Adds a palette preset at <paramref name="index"/> (clamped). Returns false when the donut is full.</summary>
+ public bool Insert(string presetId, int index)
+ {
+ if (Profile is null || Profile.PresetIds.Contains(presetId))
+ return false;
+ if (Profile.PresetIds.Count >= ToolbarProfile.MaxSlices)
+ {
+ Message = _loc.Format("toolbar.max_reached", ToolbarProfile.MaxSlices);
+ return false;
+ }
+ Profile.PresetIds.Insert(Math.Clamp(index, 0, Profile.PresetIds.Count), presetId);
+ Commit();
+ return true;
+ }
+
+ public void RemoveAt(int index)
+ {
+ if (Profile is null || index < 0 || index >= Profile.PresetIds.Count)
+ return;
+ Profile.PresetIds.RemoveAt(index);
+ Commit();
+ }
+
+ /// <summary>Moves a slice onto another slice's position.</summary>
+ public void Move(int from, int to)
+ {
+ if (Profile is null || from == to || from < 0 || from >= Profile.PresetIds.Count)
+ return;
+ var id = Profile.PresetIds[from];
+ Profile.PresetIds.RemoveAt(from);
+ Profile.PresetIds.Insert(Math.Clamp(to, 0, Profile.PresetIds.Count), id);
+ Commit();
+ }
+
+ /// <summary>Opens the preset popup for the slice at <paramref name="index"/>.</summary>
+ public async Task EditAsync(int index)
+ {
+ if (Profile is null || index < 0 || index >= Profile.PresetIds.Count)
+ return;
+ var preset = _store.FindPreset(Profile.PresetIds[index]);
+ if (preset is not null && await _windows.EditPresetAsync(preset, _windows.Main))
+ Commit();
+ }
+
+ /// <summary>Opens the preset popup for a palette chip.</summary>
+ public async Task EditChipAsync(string presetId)
+ {
+ var preset = _store.FindPreset(presetId);
+ if (preset is not null && await _windows.EditPresetAsync(preset, _windows.Main))
+ Commit();
+ }
+
+ [RelayCommand]
+ private async Task NewPreset()
+ {
+ var preset = new Preset { Name = _loc["toolbar.new_preset"], TargetFormat = "png" };
+ if (!await _windows.EditPresetAsync(preset, _windows.Main))
+ return;
+ _store.Presets.Add(preset);
+ if (Profile is not null && Profile.PresetIds.Count < ToolbarProfile.MaxSlices)
+ Profile.PresetIds.Add(preset.Id);
+ Commit();
+ }
+
+ [RelayCommand]
+ private void AddProfile()
+ {
+ var profile = new ToolbarProfile { Name = _loc["toolbar.profile_new"], PresetIds = ["to-pdf", "to-png"] };
+ _store.Profiles.Insert(Math.Max(0, _store.Profiles.Count - 1), profile); // keep the fallback last
+ _store.SaveLibrary();
+ var item = new ProfileItemViewModel(profile, _loc);
+ Profiles.Insert(Math.Max(0, Profiles.Count - 1), item);
+ SelectedProfile = item;
+ }
+
+ [RelayCommand]
+ private async Task DeleteProfile()
+ {
+ if (Profile is null || Profile.IsFallback || _windows.Main is null)
+ return;
+ if (!await _windows.ConfirmAsync(_windows.Main, _loc["toolbar.delete_profile"] + "?", destructive: true))
+ return;
+ _store.Profiles.Remove(Profile);
+ _store.SaveLibrary();
+ Profiles.Remove(SelectedProfile!);
+ SelectedProfile = Profiles.FirstOrDefault();
+ }
+
+ private void Commit()
+ {
+ _store.SaveLibrary();
+ SelectedProfile?.Refresh(_loc);
+ Rebuild();
+ }
+
+ /// <summary>Rebuilds the donut slices and the palette from the model.</summary>
+ private void Rebuild()
+ {
+ var profile = Profile;
+ var used = profile?.PresetIds ?? [];
+ DonutItems = used
+ .Select(_store.FindPreset)
+ .OfType<Preset>()
+ .Select(p => new DonutItem { Id = p.Id, Label = _loc.DisplayName(p), Caption = Caption(p) })
+ .ToList();
+
+ Palette.Clear();
+ foreach (var preset in _store.Presets.Where(p => !used.Contains(p.Id)))
+ {
+ var label = _loc.DisplayName(preset);
+ var caption = Caption(preset);
+ // "GIF GIF" says nothing twice: only show the format when the name doesn't already.
+ if (caption is not null && label.Contains(caption, StringComparison.OrdinalIgnoreCase))
+ caption = null;
+ Palette.Add(new PaletteChip(preset.Id, label, caption));
+ }
+
+ CenterTitle = profile is null ? "" : _loc.DisplayName(profile);
+ CenterSubtitle = $"{used.Count} / {ToolbarProfile.MaxSlices}";
+ }
+
+ private string? Caption(Preset p) =>
+ p.TargetFormat == BuiltInData.SameAsSource ? _loc["donut.same_format"] : FormatRegistry.FindById(p.TargetFormat)?.DisplayName;
+}
diff --git a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs
new file mode 100644
index 00000000..0e312436
--- /dev/null
+++ b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs
@@ -0,0 +1,215 @@
+// Shortcut / gesture settings. Every gesture is fully configurable: kind, modifiers, mouse button,
+// extra key (recorded), drag distance, hold time and where it is active.
+
+using System.Collections.ObjectModel;
+using Avalonia.Input;
+using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using Filee.App.Services;
+using Filee.Core.Localization;
+using Filee.Core.Settings;
+using ModifierKeys = Filee.Core.Settings.ModifierKeys;
+
+namespace Filee.App.ViewModels.Pages;
+
+public sealed partial class TriggerGestureViewModel : ObservableObject
+{
+ private readonly TriggerGesture _gesture;
+ private readonly Action _save;
+ private bool _loading = true;
+
+ public TriggerGestureViewModel(TriggerGesture gesture, ILocalizer loc, Action save)
+ {
+ _gesture = gesture;
+ _save = save;
+ Kinds = Enum.GetValues<TriggerKind>().Select(k => new Choice<TriggerKind>(k, loc[$"triggers.kind.{k}"])).ToList();
+ Buttons = Enum.GetValues<TriggerMouseButton>().Where(b => b != TriggerMouseButton.None)
+ .Select(b => new Choice<TriggerMouseButton>(b, loc[$"triggers.button.{b}"])).ToList();
+ Scopes = Enum.GetValues<TriggerScope>().Select(s => new Choice<TriggerScope>(s, loc[$"triggers.scope.{s}"])).ToList();
+ RecordLabel = loc["triggers.record"];
+ RecordingLabel = loc["triggers.recording"];
+ SystemLabel = loc["triggers.threshold_system"];
+
+ Enabled = gesture.Enabled;
+ Kind = Kinds.First(k => k.Value == gesture.Kind);
+ Ctrl = gesture.Modifiers.HasFlag(ModifierKeys.Ctrl);
+ Alt = gesture.Modifiers.HasFlag(ModifierKeys.Alt);
+ Shift = gesture.Modifiers.HasFlag(ModifierKeys.Shift);
+ Meta = gesture.Modifiers.HasFlag(ModifierKeys.Meta);
+ Button = Buttons.FirstOrDefault(b => b.Value == gesture.Button) ?? Buttons[0];
+ Key = gesture.Key;
+ DragThreshold = gesture.DragThreshold;
+ HoldMilliseconds = gesture.HoldMilliseconds;
+ Scope = Scopes.First(s => s.Value == gesture.Scope);
+ _loading = false;
+ }
+
+ public TriggerGesture Gesture => _gesture;
+ public IReadOnlyList<Choice<TriggerKind>> Kinds { get; }
+ public IReadOnlyList<Choice<TriggerMouseButton>> Buttons { get; }
+ public IReadOnlyList<Choice<TriggerScope>> Scopes { get; }
+ public string RecordLabel { get; }
+ public string RecordingLabel { get; }
+ public string SystemLabel { get; }
+ public string MetaLabel => OperatingSystem.IsMacOS() ? "⌘ Cmd" : "Win";
+
+ [ObservableProperty] private bool _enabled;
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(UsesMouse), nameof(UsesKey), nameof(UsesThreshold), nameof(UsesHold))]
+ private Choice<TriggerKind> _kind = null!;
+
+ [ObservableProperty] private bool _ctrl;
+ [ObservableProperty] private bool _alt;
+ [ObservableProperty] private bool _shift;
+ [ObservableProperty] private bool _meta;
+ [ObservableProperty] private Choice<TriggerMouseButton> _button = null!;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(KeyText))] private string? _key;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ThresholdText))] private int _dragThreshold;
+ [ObservableProperty] private int _holdMilliseconds;
+ [ObservableProperty] private Choice<TriggerScope> _scope = null!;
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(KeyText))] private bool _isRecording;
+
+ public bool UsesMouse => Kind.Value != TriggerKind.KeyChord;
+ public bool UsesKey => Kind.Value == TriggerKind.KeyChord;
+ public bool UsesThreshold => Kind.Value == TriggerKind.Drag;
+ public bool UsesHold => Kind.Value == TriggerKind.Hold;
+ public string KeyText => IsRecording ? RecordingLabel : string.IsNullOrEmpty(Key) ? "—" : Key;
+ public string ThresholdText => DragThreshold == 0 ? SystemLabel : $"{DragThreshold}px";
+ public string Summary => GestureText.Describe(_gesture);
+
+ protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
+ {
+ base.OnPropertyChanged(e);
+ if (_loading || e.PropertyName is nameof(IsRecording) or nameof(KeyText) or nameof(ThresholdText) or nameof(Summary)
+ or nameof(UsesMouse) or nameof(UsesKey) or nameof(UsesThreshold) or nameof(UsesHold))
+ return;
+
+ _gesture.Enabled = Enabled;
+ _gesture.Kind = Kind.Value;
+ _gesture.Modifiers = (Ctrl ? ModifierKeys.Ctrl : 0) | (Alt ? ModifierKeys.Alt : 0) |
+ (Shift ? ModifierKeys.Shift : 0) | (Meta ? ModifierKeys.Meta : 0);
+ _gesture.Button = Kind.Value == TriggerKind.KeyChord ? TriggerMouseButton.None : Button.Value;
+ _gesture.Key = Key;
+ _gesture.DragThreshold = Math.Clamp(DragThreshold, 0, 200);
+ _gesture.HoldMilliseconds = Math.Clamp(HoldMilliseconds, 150, 3000);
+ _gesture.Scope = Scope.Value;
+ OnPropertyChanged(nameof(Summary));
+ _save();
+ }
+
+ [RelayCommand]
+ private void ToggleRecording() => IsRecording = !IsRecording;
+
+ [RelayCommand]
+ private void ClearKey() => Key = null;
+
+ /// <summary>Called by the view while recording. Returns true when the key was accepted.</summary>
+ public bool Record(Key key, KeyModifiers modifiers)
+ {
+ if (!IsRecording || key is Avalonia.Input.Key.LeftCtrl or Avalonia.Input.Key.RightCtrl or Avalonia.Input.Key.LeftAlt
+ or Avalonia.Input.Key.RightAlt or Avalonia.Input.Key.LeftShift or Avalonia.Input.Key.RightShift
+ or Avalonia.Input.Key.LWin or Avalonia.Input.Key.RWin)
+ return false;
+
+ var name = KeyNames.ToHookName(key);
+ if (name is null)
+ return false;
+
+ _loading = true;
+ Ctrl = modifiers.HasFlag(KeyModifiers.Control);
+ Alt = modifiers.HasFlag(KeyModifiers.Alt);
+ Shift = modifiers.HasFlag(KeyModifiers.Shift);
+ Meta = modifiers.HasFlag(KeyModifiers.Meta);
+ _loading = false;
+ IsRecording = false;
+ Key = name; // triggers save
+ return true;
+ }
+}
+
+public sealed partial class TriggersPageViewModel : ObservableObject
+{
+ private readonly UserDataStore _store;
+ private readonly ILocalizer _loc;
+
+ public TriggersPageViewModel(UserDataStore store, ILocalizer loc)
+ {
+ _store = store;
+ _loc = loc;
+ foreach (var gesture in store.Settings.Triggers)
+ Gestures.Add(new TriggerGestureViewModel(gesture, loc, Save));
+ _excluded = string.Join(", ", store.Settings.ExcludedProcesses);
+ }
+
+ public ObservableCollection<TriggerGestureViewModel> Gestures { get; } = [];
+
+ [ObservableProperty] private string _excluded;
+
+ partial void OnExcludedChanged(string value)
+ {
+ _store.Settings.ExcludedProcesses = value
+ .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .ToList();
+ Save();
+ }
+
+ [RelayCommand]
+ private void Add()
+ {
+ var gesture = new TriggerGesture { Modifiers = ModifierKeys.Alt, Button = TriggerMouseButton.Left };
+ _store.Settings.Triggers.Add(gesture);
+ Gestures.Add(new TriggerGestureViewModel(gesture, _loc, Save));
+ Save();
+ }
+
+ [RelayCommand]
+ private void Remove(TriggerGestureViewModel item)
+ {
+ _store.Settings.Triggers.Remove(item.Gesture);
+ Gestures.Remove(item);
+ Save();
+ }
+
+ private void Save() => _store.SaveSettings();
+}
+
+/// <summary>Maps Avalonia keys to SharpHook key names (KeyCode without "Vc").</summary>
+public static class KeyNames
+{
+ public static string? ToHookName(Key key) => key switch
+ {
+ >= Key.A and <= Key.Z => key.ToString(),
+ >= Key.D0 and <= Key.D9 => ((int)(key - Key.D0)).ToString(),
+ >= Key.NumPad0 and <= Key.NumPad9 => "NumPad" + (int)(key - Key.NumPad0),
+ >= Key.F1 and <= Key.F24 => key.ToString(),
+ Key.Space => "Space",
+ Key.Enter => "Enter",
+ Key.Tab => "Tab",
+ Key.Escape => "Escape",
+ Key.Back => "Backspace",
+ Key.Insert => "Insert",
+ Key.Delete => "Delete",
+ Key.Home => "Home",
+ Key.End => "End",
+ Key.PageUp => "PageUp",
+ Key.PageDown => "PageDown",
+ Key.Left => "Left",
+ Key.Right => "Right",
+ Key.Up => "Up",
+ Key.Down => "Down",
+ Key.OemTilde => "BackQuote",
+ Key.OemMinus => "Minus",
+ Key.OemPlus => "Equals",
+ Key.OemOpenBrackets => "OpenBracket",
+ Key.OemCloseBrackets => "CloseBracket",
+ Key.OemPipe => "Backslash",
+ Key.OemSemicolon => "Semicolon",
+ Key.OemQuotes => "Quote",
+ Key.OemComma => "Comma",
+ Key.OemPeriod => "Period",
+ Key.OemQuestion => "Slash",
+ Key.PrintScreen => "PrintScreen",
+ Key.Pause => "Pause",
+ _ => null,
+ };
+}
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
new file mode 100644
index 00000000..20e9faa3
--- /dev/null
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -0,0 +1,188 @@
+// Editable view of one Preset. Shared by the Presets page and the preset popup (right-click / ✎ on the donut),
+// so both always show exactly the same editor.
+//
+// Works on a clone; Apply() copies the edits back into the original preset (Cancel = just drop the VM).
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+
+namespace Filee.App.ViewModels;
+
+/// <summary>A value with a localized label for combo boxes.</summary>
+public sealed record Choice<T>(T Value, string Label)
+{
+ public override string ToString() => Label;
+}
+
+public sealed partial class PresetEditorViewModel : ObservableObject
+{
+ private static readonly HashSet<string> LossyTargets = ["jpg", "webp", "avif"];
+ private readonly Preset _original;
+ private readonly Preset _edit;
+ private readonly ILocalizer _loc;
+
+ public PresetEditorViewModel(Preset preset, ILocalizer loc)
+ {
+ _original = preset;
+ _edit = preset.Clone();
+ _loc = loc;
+
+ Targets =
+ [
+ new Choice<string>(BuiltInData.SameAsSource, loc["presets.same_as_source"]),
+ .. FormatRegistry.Known
+ .Where(f => f.Id != "heic") // read-only format
+ .Select(f => new Choice<string>(f.Id, f.DisplayName)),
+ ];
+ ResizeModes = Enum.GetValues<ResizeMode>().Select(v => new Choice<ResizeMode>(v, loc[$"presets.resize.{v}"])).ToList();
+ PageSizes = Enum.GetValues<PdfPageSize>().Select(v => new Choice<PdfPageSize>(v, loc[$"presets.page_size.{v}"])).ToList();
+ Locations = Enum.GetValues<OutputLocation>().Select(v => new Choice<OutputLocation>(v, loc[$"presets.location.{v}"])).ToList();
+ Conflicts = Enum.GetValues<ConflictPolicy>().Select(v => new Choice<ConflictPolicy>(v, loc[$"presets.conflict.{v}"])).ToList();
+ TiffCompressions = Enum.GetValues<TiffCompression>().Select(v => new Choice<TiffCompression>(v, v.ToString().ToUpperInvariant())).ToList();
+
+ _name = string.IsNullOrWhiteSpace(_edit.Name) ? loc.DisplayName(_edit) : _edit.Name;
+ _target = Targets.FirstOrDefault(t => t.Value == _edit.TargetFormat) ?? Targets[1];
+ _resize = ResizeModes.First(r => r.Value == _edit.Image.Resize);
+ _pageSize = PageSizes.First(p => p.Value == _edit.Pdf.PageSize);
+ _location = Locations.First(l => l.Value == _edit.Output.Location);
+ _conflict = Conflicts.First(c => c.Value == _edit.Output.Conflict);
+ _tiffCompression = TiffCompressions.First(t => t.Value == _edit.Image.TiffCompression);
+ _quality = _edit.Image.Quality;
+ _resizePercent = _edit.Image.ResizePercent;
+ _longEdge = _edit.Image.LongEdge;
+ _setDpi = _edit.Image.Dpi.HasValue;
+ _dpi = _edit.Image.Dpi ?? 300;
+ _keepMetadata = _edit.Image.KeepMetadata;
+ _grayscale = _edit.Image.Grayscale;
+ _background = _edit.Image.Background;
+ _webpLossless = _edit.Image.WebpLossless;
+ _icoSizes = string.Join(", ", _edit.Image.IcoSizes);
+ _merge = _edit.Pdf.MergeIntoSingle;
+ _marginMm = _edit.Pdf.MarginMm;
+ _renderDpi = _edit.Pdf.RenderDpi;
+ _pageRange = _edit.Pdf.PageRange;
+ _splitPages = _edit.Pdf.SplitPages;
+ _pdfA = _edit.Document.PdfA;
+ _subfolderName = _edit.Output.SubfolderName;
+ _customFolder = _edit.Output.CustomFolder;
+ _pattern = _edit.Output.FileNamePattern;
+ }
+
+ public string PresetId => _original.Id;
+
+ public IReadOnlyList<Choice<string>> Targets { get; }
+ public IReadOnlyList<Choice<ResizeMode>> ResizeModes { get; }
+ public IReadOnlyList<Choice<PdfPageSize>> PageSizes { get; }
+ public IReadOnlyList<Choice<OutputLocation>> Locations { get; }
+ public IReadOnlyList<Choice<ConflictPolicy>> Conflicts { get; }
+ public IReadOnlyList<Choice<TiffCompression>> TiffCompressions { get; }
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(NameError), nameof(IsValid))]
+ private string _name;
+
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(ShowImage), nameof(ShowQuality), nameof(ShowTiff), nameof(ShowWebp), nameof(ShowIco),
+ nameof(ShowPdfBuild), nameof(ShowDocument), nameof(ShowPdfSplit))]
+ private Choice<string> _target;
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowPercent), nameof(ShowLongEdge))]
+ private Choice<ResizeMode> _resize;
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowMargin))]
+ private Choice<PdfPageSize> _pageSize;
+
+ [ObservableProperty, NotifyPropertyChangedFor(nameof(ShowSubfolder), nameof(ShowCustomFolder))]
+ private Choice<OutputLocation> _location;
+
+ [ObservableProperty] private Choice<ConflictPolicy> _conflict;
+ [ObservableProperty] private Choice<TiffCompression> _tiffCompression;
+ [ObservableProperty] private int _quality;
+ [ObservableProperty] private int _resizePercent;
+ [ObservableProperty] private int _longEdge;
+ [ObservableProperty] private bool _setDpi;
+ [ObservableProperty] private int _dpi;
+ [ObservableProperty] private bool _keepMetadata;
+ [ObservableProperty] private bool _grayscale;
+ [ObservableProperty] private string _background;
+ [ObservableProperty] private bool _webpLossless;
+ [ObservableProperty] private string _icoSizes;
+ [ObservableProperty] private bool _merge;
+ [ObservableProperty] private double _marginMm;
+ [ObservableProperty] private int _renderDpi;
+ [ObservableProperty] private string _pageRange;
+ [ObservableProperty] private bool _splitPages;
+ [ObservableProperty] private bool _pdfA;
+ [ObservableProperty] private string _subfolderName;
+ [ObservableProperty] private string _customFolder;
+ [ObservableProperty] private string _pattern;
+
+ private string TargetId => Target.Value;
+ private bool TargetIsImage => TargetId == BuiltInData.SameAsSource || FormatRegistry.FindById(TargetId)?.Category == FormatCategory.Image;
+
+ public bool ShowImage => TargetIsImage;
+ public bool ShowQuality => TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId);
+ public bool ShowTiff => TargetId is "tiff" or BuiltInData.SameAsSource;
+ public bool ShowWebp => TargetId is "webp" or BuiltInData.SameAsSource;
+ public bool ShowIco => TargetId == "ico";
+ public bool ShowPdfBuild => TargetId == "pdf";
+ public bool ShowPdfSplit => TargetId == "pdf";
+ public bool ShowDocument => TargetId == "pdf";
+ public bool ShowPercent => Resize.Value == ResizeMode.Percent;
+ public bool ShowLongEdge => Resize.Value == ResizeMode.LongEdge;
+ public bool ShowMargin => PageSize.Value != PdfPageSize.FitImage;
+ public bool ShowSubfolder => Location.Value == OutputLocation.Subfolder;
+ public bool ShowCustomFolder => Location.Value == OutputLocation.CustomFolder;
+
+ public string? NameError => string.IsNullOrWhiteSpace(Name) ? _loc["presets.name_required"] : null;
+ public bool IsValid => NameError is null;
+
+ /// <summary>Writes the edits into the original preset. Returns false if the input is invalid.</summary>
+ public bool Apply()
+ {
+ if (!IsValid)
+ return false;
+
+ // Keep a built-in preset's translatable name unless the user actually renamed it.
+ if (_original.NameKey is null || Name.Trim() != _loc.DisplayName(_original))
+ _original.Name = Name.Trim();
+
+ _original.TargetFormat = TargetId;
+ var image = _original.Image;
+ image.Quality = Math.Clamp(Quality, 1, 100);
+ image.Resize = Resize.Value;
+ image.ResizePercent = Math.Clamp(ResizePercent, 1, 1000);
+ image.LongEdge = Math.Clamp(LongEdge, 16, 20000);
+ image.Dpi = SetDpi ? Math.Clamp(Dpi, 36, 2400) : null;
+ image.KeepMetadata = KeepMetadata;
+ image.Grayscale = Grayscale;
+ image.Background = string.IsNullOrWhiteSpace(Background) ? "#FFFFFF" : Background.Trim();
+ image.TiffCompression = TiffCompression.Value;
+ image.WebpLossless = WebpLossless;
+ image.IcoSizes = IcoSizes.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(s => int.TryParse(s, out var v) ? v : 0)
+ .Where(v => v is > 0 and <= 256)
+ .Distinct()
+ .ToList();
+ if (image.IcoSizes.Count == 0)
+ image.IcoSizes = [256, 48, 32, 16];
+
+ var pdf = _original.Pdf;
+ pdf.MergeIntoSingle = Merge;
+ pdf.PageSize = PageSize.Value;
+ pdf.MarginMm = Math.Clamp(MarginMm, 0, 100);
+ pdf.RenderDpi = Math.Clamp(RenderDpi, 36, 1200);
+ pdf.PageRange = PageRange.Trim();
+ pdf.SplitPages = SplitPages;
+ _original.Document.PdfA = PdfA;
+
+ var output = _original.Output;
+ output.Location = Location.Value;
+ output.SubfolderName = string.IsNullOrWhiteSpace(SubfolderName) ? "converted" : SubfolderName.Trim();
+ output.CustomFolder = CustomFolder.Trim();
+ output.FileNamePattern = string.IsNullOrWhiteSpace(Pattern) ? "{name}" : Pattern.Trim();
+ output.Conflict = Conflict.Value;
+ return true;
+ }
+}
diff --git a/src/Filee.App/ViewModels/RadialViewModel.cs b/src/Filee.App/ViewModels/RadialViewModel.cs
new file mode 100644
index 00000000..d47587e3
--- /dev/null
+++ b/src/Filee.App/ViewModels/RadialViewModel.cs
@@ -0,0 +1,100 @@
+// State of the live donut toolbar: which files are being converted and which presets are offered.
+
+using CommunityToolkit.Mvvm.ComponentModel;
+using Filee.App.Controls;
+using Filee.App.Services;
+using Filee.Core.Formats;
+using Filee.Core.Localization;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.App.ViewModels;
+
+public sealed partial class RadialViewModel(UserDataStore store, ILocalizer loc, PresetAvailability availability) : ObservableObject
+{
+ [ObservableProperty] private IReadOnlyList<DonutItem> _items = [];
+ [ObservableProperty] private string _centerTitle = "";
+ [ObservableProperty] private string? _centerSubtitle;
+ [ObservableProperty] private double _outerRadius = 150;
+ [ObservableProperty] private double _holeRatio = 0.42;
+ [ObservableProperty] private double _sliceOpacity = 0.96;
+
+ /// <summary>Files the donut will convert (empty while waiting for a drag to enter).</summary>
+ public IReadOnlyList<string> Files { get; private set; } = [];
+
+ /// <summary>Presets in slice order.</summary>
+ public IReadOnlyList<Preset> Presets { get; private set; } = [];
+
+ /// <summary>True when opened with known files (keyboard, context menu, drop zone): slices are clicked.</summary>
+ public bool IsClickMode { get; private set; }
+
+ public bool HasFiles => Files.Count > 0;
+
+ /// <summary>Drag mode before any file entered: an empty ring saying "Bring files here".</summary>
+ public void ResetForDrag()
+ {
+ IsClickMode = false;
+ Files = [];
+ Presets = [];
+ ApplyAppearance();
+ Items = [];
+ CenterTitle = loc["donut.center_drag"];
+ CenterSubtitle = null;
+ }
+
+ /// <summary>Fills the donut for the given files.</summary>
+ public void Load(IReadOnlyList<string> files, bool clickMode)
+ {
+ IsClickMode = clickMode;
+ Files = files;
+ ApplyAppearance();
+
+ var profile = ProfileSelector.Select(store.Profiles, files);
+ var formats = ProfileSelector.DetectFormats(files);
+ Presets = (profile?.PresetIds ?? [])
+ .Select(store.FindPreset)
+ .OfType<Preset>()
+ .ToList();
+
+ Items = Presets.Select(p =>
+ {
+ var reason = availability.Check(p, formats);
+ return new DonutItem
+ {
+ Id = p.Id,
+ Label = loc.DisplayName(p),
+ Caption = p.TargetFormat == BuiltInData.SameAsSource
+ ? string.Join("/", formats.Select(f => f.DisplayName).Take(2))
+ : FormatRegistry.FindById(p.TargetFormat)?.DisplayName,
+ IsEnabled = reason is null,
+ DisabledReason = reason,
+ };
+ }).ToList();
+
+ CenterTitle = formats.Count == 1
+ ? loc.Format("donut.files_same", files.Count, formats[0].DisplayName)
+ : loc.Format("donut.files_mixed", files.Count);
+ CenterSubtitle = clickMode ? loc["donut.close_hint"] : null;
+ }
+
+ /// <summary>Updates the centre hint for the emphasised slice.</summary>
+ public void ShowHint(int index, bool centerHot)
+ {
+ if (centerHot)
+ CenterSubtitle = loc["donut.cancel"];
+ else if (index >= 0 && index < Items.Count)
+ CenterSubtitle = Items[index].IsEnabled
+ ? loc.Format(IsClickMode ? "donut.click_to" : "donut.drop_to", Items[index].Label)
+ : Items[index].DisabledReason;
+ else
+ CenterSubtitle = IsClickMode ? loc["donut.close_hint"] : null;
+ }
+
+ private void ApplyAppearance()
+ {
+ OuterRadius = Math.Clamp(store.Settings.Donut.OuterRadius, 100, 240);
+ HoleRatio = store.Settings.Donut.HoleRatio;
+ SliceOpacity = store.Settings.Donut.Opacity;
+ }
+}
diff --git a/src/Filee.App/Views/EngineSetupWindow.axaml b/src/Filee.App/Views/EngineSetupWindow.axaml
new file mode 100644
index 00000000..8952898f
--- /dev/null
+++ b/src/Filee.App/Views/EngineSetupWindow.axaml
@@ -0,0 +1,60 @@
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ xmlns:svc="using:Filee.App.Services"
+ x:Class="Filee.App.Views.EngineSetupWindow"
+ x:DataType="vm:EngineSetupViewModel"
+ Title="{DynamicResource setup.title}"
+ Width="560" SizeToContent="Height" CanResize="False"
+ WindowStartupLocation="CenterScreen"
+ Background="{DynamicResource SurfaceBrush}">
+ <StackPanel Margin="26,24" Spacing="16">
+ <StackPanel Spacing="6">
+ <TextBlock Classes="h1" Text="{DynamicResource setup.title}" />
+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource setup.description}" />
+ </StackPanel>
+
+ <ItemsControl ItemsSource="{Binding Packages}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="10" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="svc:EnginePackageState">
+ <Border Classes="card" Padding="14,12">
+ <DockPanel>
+ <!-- Already installed packages cannot be ticked; ticking is locked once installation started. -->
+ <CheckBox DockPanel.Dock="Left" VerticalAlignment="Top" Margin="0,0,10,0"
+ IsChecked="{Binding Selected}" IsEnabled="{Binding CanInstall}"
+ IsVisible="{Binding !IsInstalled}" />
+ <PathIcon DockPanel.Dock="Left" VerticalAlignment="Top" Margin="2,3,14,0" Width="14" Height="14"
+ Data="{StaticResource Icon.Check}" Foreground="{DynamicResource SuccessBrush}" IsVisible="{Binding IsInstalled}" />
+ <StackPanel Spacing="4">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Name}" />
+ <Border Classes="badge">
+ <TextBlock Classes="caption" Text="{Binding StatusText}" />
+ </Border>
+ </StackPanel>
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Description}" />
+ <TextBlock Classes="caption" Text="{Binding Sizes}" />
+ <ProgressBar Classes="soft" Maximum="100" Value="{Binding Progress}" IsVisible="{Binding IsBusy}" Margin="0,4,0,0" />
+ </StackPanel>
+ </DockPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource setup.note}" />
+
+ <DockPanel>
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="8">
+ <Button Content="{Binding CloseText}" Command="{Binding CloseCommand}" />
+ <Button Classes="accent" Content="{DynamicResource setup.install}" Command="{Binding InstallCommand}" IsVisible="{Binding CanChoose}" />
+ </StackPanel>
+ <TextBlock Classes="muted" VerticalAlignment="Center" Text="{Binding SelectionText}" IsVisible="{Binding CanChoose}" />
+ </DockPanel>
+ </StackPanel>
+</Window>
diff --git a/src/Filee.App/Views/EngineSetupWindow.axaml.cs b/src/Filee.App/Views/EngineSetupWindow.axaml.cs
new file mode 100644
index 00000000..23f5e020
--- /dev/null
+++ b/src/Filee.App/Views/EngineSetupWindow.axaml.cs
@@ -0,0 +1,19 @@
+using Avalonia.Controls;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+
+namespace Filee.App.Views;
+
+public partial class EngineSetupWindow : Window
+{
+ public EngineSetupWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+ DataContextChanged += (_, _) =>
+ {
+ if (DataContext is EngineSetupViewModel vm)
+ vm.CloseRequested += (_, _) => Close();
+ };
+ }
+}
diff --git a/src/Filee.App/Views/MainWindow.axaml b/src/Filee.App/Views/MainWindow.axaml
new file mode 100644
index 00000000..91932eec
--- /dev/null
+++ b/src/Filee.App/Views/MainWindow.axaml
@@ -0,0 +1,40 @@
+<!-- Main window = settings: navigation on the left, current page on the right. Closing hides to the tray. -->
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ x:Class="Filee.App.Views.MainWindow"
+ x:DataType="vm:MainWindowViewModel"
+ Title="Filee"
+ Icon="avares://Filee/Assets/Icons/filee.ico"
+ Width="1080" Height="760" MinWidth="820" MinHeight="560"
+ WindowStartupLocation="CenterScreen">
+ <Grid ColumnDefinitions="230,*">
+ <!-- Navigation -->
+ <Border Background="{DynamicResource SurfaceBrush}" BorderBrush="{DynamicResource SubtleBorderBrush}" BorderThickness="0,0,1,0">
+ <DockPanel Margin="14,18">
+ <StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Spacing="10" Margin="8,0,0,20">
+ <Image Source="avares://Filee/Assets/Icons/filee.png" Width="30" Height="30" />
+ <StackPanel VerticalAlignment="Center">
+ <TextBlock Text="Filee" FontSize="18" FontWeight="Bold" />
+ <TextBlock Classes="caption" Text="{DynamicResource app.tagline}" />
+ </StackPanel>
+ </StackPanel>
+ <ListBox Classes="nav" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
+ <ListBox.ItemTemplate>
+ <DataTemplate x:DataType="vm:NavItem">
+ <StackPanel Orientation="Horizontal" Spacing="12">
+ <PathIcon Width="17" Height="17" Data="{Binding Icon}" />
+ <TextBlock Text="{Binding Title}" VerticalAlignment="Center" />
+ </StackPanel>
+ </DataTemplate>
+ </ListBox.ItemTemplate>
+ </ListBox>
+ </DockPanel>
+ </Border>
+
+ <!-- Page -->
+ <ScrollViewer Grid.Column="1" x:Name="PageScroller">
+ <ContentControl Classes="page" Content="{Binding CurrentPage}" Margin="32,26,32,32" MaxWidth="980" HorizontalAlignment="Stretch" />
+ </ScrollViewer>
+ </Grid>
+</Window>
diff --git a/src/Filee.App/Views/MainWindow.axaml.cs b/src/Filee.App/Views/MainWindow.axaml.cs
new file mode 100644
index 00000000..82110467
--- /dev/null
+++ b/src/Filee.App/Views/MainWindow.axaml.cs
@@ -0,0 +1,24 @@
+using Avalonia.Controls;
+using Filee.App.Services;
+
+namespace Filee.App.Views;
+
+public partial class MainWindow : Window
+{
+ public MainWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+ }
+
+ /// <summary>Closing the window keeps Filee running in the tray (Quit is in the tray menu).</summary>
+ protected override void OnClosing(WindowClosingEventArgs e)
+ {
+ base.OnClosing(e);
+ if (e.CloseReason is WindowCloseReason.WindowClosing)
+ {
+ e.Cancel = true;
+ Hide();
+ }
+ }
+}
diff --git a/src/Filee.App/Views/Pages/AboutPage.axaml b/src/Filee.App/Views/Pages/AboutPage.axaml
new file mode 100644
index 00000000..a268fd0f
--- /dev/null
+++ b/src/Filee.App/Views/Pages/AboutPage.axaml
@@ -0,0 +1,31 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ x:Class="Filee.App.Views.Pages.AboutPage"
+ x:DataType="vm:AboutPageViewModel">
+ <StackPanel Spacing="18">
+ <TextBlock Classes="h1" Text="{DynamicResource about.title}" />
+ <Border Classes="card">
+ <StackPanel Orientation="Horizontal" Spacing="18">
+ <Image Source="avares://Filee/Assets/Icons/filee.png" Width="72" Height="72" />
+ <StackPanel VerticalAlignment="Center" Spacing="4">
+ <TextBlock Text="Filee" FontSize="24" FontWeight="Bold" />
+ <TextBlock Classes="muted" Text="{Binding Version}" />
+ <TextBlock Classes="muted" Text="{DynamicResource about.license}" />
+ <Button Classes="ghost" Padding="0" Click="OnOpenRepository" Margin="0,4,0,0">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Link}" Foreground="{DynamicResource AccentBrush}" />
+ <TextBlock Text="{Binding RepositoryUrl}" Foreground="{DynamicResource AccentBrush}" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ </StackPanel>
+ </Border>
+ <Border Classes="card">
+ <StackPanel Spacing="8">
+ <TextBlock Classes="h2" Text="{DynamicResource about.notices}" />
+ <SelectableTextBlock Text="{Binding Notices}" TextWrapping="Wrap" FontSize="12.5" Foreground="{DynamicResource TextSecondaryBrush}" />
+ </StackPanel>
+ </Border>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/AboutPage.axaml.cs b/src/Filee.App/Views/Pages/AboutPage.axaml.cs
new file mode 100644
index 00000000..4413b5d7
--- /dev/null
+++ b/src/Filee.App/Views/Pages/AboutPage.axaml.cs
@@ -0,0 +1,16 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Filee.App.ViewModels.Pages;
+
+namespace Filee.App.Views.Pages;
+
+public partial class AboutPage : UserControl
+{
+ public AboutPage() => InitializeComponent();
+
+ private async void OnOpenRepository(object? sender, RoutedEventArgs e)
+ {
+ if (DataContext is AboutPageViewModel vm && TopLevel.GetTopLevel(this) is { } top)
+ await top.Launcher.LaunchUriAsync(new Uri(vm.RepositoryUrl));
+ }
+}
diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml b/src/Filee.App/Views/Pages/EnginesPage.axaml
new file mode 100644
index 00000000..446ead46
--- /dev/null
+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml
@@ -0,0 +1,109 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ xmlns:svc="using:Filee.App.Services"
+ x:Class="Filee.App.Views.Pages.EnginesPage"
+ x:DataType="vm:EnginesPageViewModel">
+ <StackPanel Spacing="18">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Command="{Binding RecheckCommand}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Refresh}" />
+ <TextBlock Text="{DynamicResource engines.recheck}" />
+ </StackPanel>
+ </Button>
+ <StackPanel>
+ <TextBlock Classes="h1" Text="{DynamicResource engines.title}" />
+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource engines.description}" />
+ </StackPanel>
+ </DockPanel>
+
+ <!-- Optional engines: downloaded on demand because they are large. -->
+ <StackPanel Spacing="10">
+ <StackPanel Spacing="2">
+ <TextBlock Classes="h2" Text="{DynamicResource engines.optional_title}" />
+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource engines.optional_description}" />
+ </StackPanel>
+ <ItemsControl ItemsSource="{Binding Packages}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="10" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="svc:EnginePackageState">
+ <Border Classes="card" Padding="16,12">
+ <DockPanel>
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="6" VerticalAlignment="Center" Margin="12,0,0,0">
+ <Button Classes="accent" Content="{DynamicResource engines.install}" IsVisible="{Binding CanInstall}"
+ Command="{Binding $parent[ItemsControl].((vm:EnginesPageViewModel)DataContext).InstallCommand}" CommandParameter="{Binding}" />
+ <Button Content="{DynamicResource engines.cancel}" IsVisible="{Binding IsBusy}"
+ Command="{Binding $parent[ItemsControl].((vm:EnginesPageViewModel)DataContext).CancelCommand}" CommandParameter="{Binding}" />
+ <Button Content="{DynamicResource engines.remove}" IsVisible="{Binding IsInstalled}" Click="OnRemove" />
+ </StackPanel>
+ <StackPanel Spacing="4">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Name}" />
+ <Border Classes="badge">
+ <TextBlock Classes="caption" Text="{Binding StatusText}" />
+ </Border>
+ </StackPanel>
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Description}" />
+ <TextBlock Classes="caption" Text="{Binding Sizes}" />
+ <ProgressBar Classes="soft" Maximum="100" Value="{Binding Progress}" IsVisible="{Binding IsBusy}" Margin="0,4,0,0" />
+ </StackPanel>
+ </DockPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ <TextBlock Classes="h2" Margin="0,8,0,0" Text="{DynamicResource engines.all_title}" />
+ </StackPanel>
+
+ <ItemsControl ItemsSource="{Binding Engines}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="10" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:EngineItemViewModel">
+ <Border Classes="card" Padding="16,12">
+ <StackPanel Spacing="10">
+ <DockPanel>
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="4">
+ <Button Classes="icon" ToolTip.Tip="{DynamicResource engines.move_up}"
+ Command="{Binding $parent[ItemsControl].((vm:EnginesPageViewModel)DataContext).MoveUpCommand}" CommandParameter="{Binding}">
+ <PathIcon Width="14" Height="14" Data="{StaticResource Icon.ArrowUp}" />
+ </Button>
+ <Button Classes="icon" ToolTip.Tip="{DynamicResource engines.move_down}"
+ Command="{Binding $parent[ItemsControl].((vm:EnginesPageViewModel)DataContext).MoveDownCommand}" CommandParameter="{Binding}">
+ <PathIcon Width="14" Height="14" Data="{StaticResource Icon.ArrowDown}" />
+ </Button>
+ </StackPanel>
+ <Border DockPanel.Dock="Left" Width="10" Height="10" CornerRadius="999" Margin="2,0,12,0" VerticalAlignment="Center"
+ Background="{DynamicResource SuccessBrush}" IsVisible="{Binding IsAvailable}" />
+ <Border DockPanel.Dock="Left" Width="10" Height="10" CornerRadius="999" Margin="2,0,12,0" VerticalAlignment="Center"
+ Background="{DynamicResource TextSecondaryBrush}" IsVisible="{Binding !IsAvailable}" />
+ <StackPanel>
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Name}" />
+ <Border Classes="badge">
+ <TextBlock Classes="caption" Text="{Binding StatusText}" />
+ </Border>
+ <TextBlock Classes="caption" VerticalAlignment="Center" Text="{Binding Conversions}" />
+ </StackPanel>
+ <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>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml.cs b/src/Filee.App/Views/Pages/EnginesPage.axaml.cs
new file mode 100644
index 00000000..ef6d8921
--- /dev/null
+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml.cs
@@ -0,0 +1,34 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Avalonia.Platform.Storage;
+using Filee.App.Services;
+using Filee.App.ViewModels.Pages;
+using Filee.Core.Localization;
+
+namespace Filee.App.Views.Pages;
+
+public partial class EnginesPage : UserControl
+{
+ public EnginesPage() => InitializeComponent();
+
+ private async void OnRemove(object? sender, RoutedEventArgs e)
+ {
+ if (sender is not Button { DataContext: EnginePackageState package } || DataContext is not EnginesPageViewModel vm ||
+ TopLevel.GetTopLevel(this) is not Window window)
+ return;
+ var loc = AppHost.Get<ILocalizer>();
+ if (!await AppHost.Get<WindowService>().ConfirmAsync(window, loc.Format("engines.remove_confirm", package.Name), destructive: true))
+ return;
+ 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.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axaml
new file mode 100644
index 00000000..4cd68c44
--- /dev/null
+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml
@@ -0,0 +1,53 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ x:Class="Filee.App.Views.Pages.GeneralPage"
+ x:DataType="vm:GeneralPageViewModel">
+ <StackPanel Spacing="18">
+ <TextBlock Classes="h1" Text="{DynamicResource general.title}" />
+
+ <Border Classes="card">
+ <StackPanel Spacing="14">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource general.language}" />
+ <ComboBox ItemsSource="{Binding Languages}" SelectedItem="{Binding Language}" MinWidth="240" />
+ </StackPanel>
+ <ToggleSwitch Content="{DynamicResource general.start_with_system}" IsChecked="{Binding StartWithSystem}" />
+ <ToggleSwitch Content="{DynamicResource general.context_menu}" IsChecked="{Binding ContextMenu}" IsVisible="{Binding IsWindows}" />
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="12">
+ <ToggleSwitch Content="{DynamicResource general.check_updates}" IsChecked="{Binding CheckForUpdates}" />
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <Button Content="{DynamicResource general.check_now}" Command="{Binding CheckNowCommand}" />
+ <Button Classes="accent" Content="{DynamicResource general.update_install}" Command="{Binding InstallUpdateCommand}" IsVisible="{Binding UpdateAvailable}" />
+ <TextBlock Classes="muted" VerticalAlignment="Center" Text="{Binding UpdateStatus}" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="12">
+ <TextBlock Classes="h2" Text="{DynamicResource general.library}" />
+ <WrapPanel>
+ <Button Content="{DynamicResource general.export}" Click="OnExport" Margin="0,0,8,8" />
+ <Button Content="{DynamicResource general.import}" Click="OnImport" Margin="0,0,8,8" />
+ <Button Content="{DynamicResource general.reset_library}" Click="OnReset" Margin="0,0,8,8" />
+ </WrapPanel>
+ <TextBlock Classes="muted" Text="{Binding LibraryMessage}" />
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Content="{DynamicResource general.open_data_folder}" Command="{Binding OpenDataFolderCommand}" />
+ <StackPanel VerticalAlignment="Center">
+ <TextBlock Classes="label" Text="{DynamicResource general.data_folder}" />
+ <TextBlock Text="{Binding DataFolder}" TextTrimming="CharacterEllipsis" />
+ </StackPanel>
+ </DockPanel>
+ </Border>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml.cs b/src/Filee.App/Views/Pages/GeneralPage.axaml.cs
new file mode 100644
index 00000000..69a0cf7e
--- /dev/null
+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml.cs
@@ -0,0 +1,49 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Avalonia.Platform.Storage;
+using Filee.App.Services;
+using Filee.App.ViewModels.Pages;
+using Filee.Core.Localization;
+
+namespace Filee.App.Views.Pages;
+
+public partial class GeneralPage : UserControl
+{
+ private static readonly FilePickerFileType JsonType = new("Filee presets") { Patterns = ["*.json"] };
+
+ public GeneralPage() => InitializeComponent();
+
+ private GeneralPageViewModel? Vm => DataContext as GeneralPageViewModel;
+
+ private async void OnExport(object? sender, RoutedEventArgs e)
+ {
+ if (Vm is null || TopLevel.GetTopLevel(this) is not { } top)
+ return;
+ var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
+ {
+ SuggestedFileName = "filee-presets.json",
+ DefaultExtension = "json",
+ FileTypeChoices = [JsonType],
+ });
+ if (file?.TryGetLocalPath() is { } path)
+ Vm.Export(path);
+ }
+
+ private async void OnImport(object? sender, RoutedEventArgs e)
+ {
+ if (Vm is null || TopLevel.GetTopLevel(this) is not { } top)
+ return;
+ var files = await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { FileTypeFilter = [JsonType] });
+ if (files.FirstOrDefault()?.TryGetLocalPath() is { } path)
+ Vm.Import(path);
+ }
+
+ private async void OnReset(object? sender, RoutedEventArgs e)
+ {
+ if (Vm is null || TopLevel.GetTopLevel(this) is not Window owner)
+ return;
+ var loc = AppHost.Get<ILocalizer>();
+ if (await AppHost.Get<WindowService>().ConfirmAsync(owner, loc["general.reset_confirm"]))
+ Vm.ResetLibrary();
+ }
+}
diff --git a/src/Filee.App/Views/Pages/HomePage.axaml b/src/Filee.App/Views/Pages/HomePage.axaml
new file mode 100644
index 00000000..c80c4e82
--- /dev/null
+++ b/src/Filee.App/Views/Pages/HomePage.axaml
@@ -0,0 +1,84 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ x:Class="Filee.App.Views.Pages.HomePage"
+ x:DataType="vm:HomePageViewModel">
+ <UserControl.Styles>
+ <Style Selector="Border#DropZone">
+ <Setter Property="Transitions">
+ <Transitions>
+ <BrushTransition Property="Background" Duration="0:0:0.2" />
+ <TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.3" Easing="BackEaseOut" />
+ </Transitions>
+ </Setter>
+ </Style>
+ <Style Selector="Border#DropZone.over">
+ <Setter Property="Background" Value="{DynamicResource AccentSoftBrush}" />
+ <Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}" />
+ <Setter Property="RenderTransform" Value="scale(1.015)" />
+ </Style>
+ </UserControl.Styles>
+
+ <StackPanel Spacing="22">
+ <TextBlock Classes="h1" Text="{DynamicResource home.title}" />
+
+ <!-- Drop zone: files dropped here open the donut toolbar at the cursor. -->
+ <Border x:Name="DropZone" DragDrop.AllowDrop="True" MinHeight="220"
+ Background="{DynamicResource AccentFaintBrush}" BorderBrush="{DynamicResource AccentSoftBrush}"
+ BorderThickness="2" CornerRadius="{DynamicResource SoftRadiusLarge}" Padding="24">
+ <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Spacing="10">
+ <Border Width="64" Height="64" CornerRadius="999" Background="{DynamicResource AccentSoftBrush}" HorizontalAlignment="Center">
+ <PathIcon Width="28" Height="28" Data="{StaticResource Icon.Upload}" Foreground="{DynamicResource AccentStrongBrush}" />
+ </Border>
+ <TextBlock Classes="h2" HorizontalAlignment="Center" Text="{DynamicResource home.drop_title}" />
+ <TextBlock Classes="muted" HorizontalAlignment="Center" TextAlignment="Center" TextWrapping="Wrap" MaxWidth="460"
+ Text="{Binding DropHint}" />
+ </StackPanel>
+ </Border>
+
+ <!-- Recent conversions -->
+ <StackPanel Spacing="10">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Classes="ghost" Content="{DynamicResource home.clear_history}" Command="{Binding ClearHistoryCommand}" />
+ <TextBlock Classes="h2" VerticalAlignment="Center" Text="{DynamicResource home.recent}" />
+ </DockPanel>
+ <TextBlock Classes="muted" Text="{DynamicResource home.recent_empty}" IsVisible="{Binding IsEmpty}" />
+ <ItemsControl ItemsSource="{Binding History}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="8" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:HistoryItemViewModel">
+ <Border Classes="card" Padding="14,10">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Command="{Binding OpenFolderCommand}" IsVisible="{Binding HasOutputs}" Padding="10,5">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Folder}" />
+ <TextBlock Text="{DynamicResource home.open_folder}" />
+ </StackPanel>
+ </Button>
+ <Border DockPanel.Dock="Left" Width="32" Height="32" CornerRadius="999" Margin="0,0,12,0"
+ Background="{DynamicResource AccentSoftBrush}">
+ <Panel>
+ <PathIcon Width="15" Height="15" Data="{StaticResource Icon.Check}" Foreground="{DynamicResource AccentStrongBrush}" IsVisible="{Binding !HasErrors}" />
+ <PathIcon Width="15" Height="15" Data="{StaticResource Icon.Alert}" Foreground="{DynamicResource DangerBrush}" IsVisible="{Binding HasErrors}" />
+ </Panel>
+ </Border>
+ <StackPanel VerticalAlignment="Center" ToolTip.Tip="{Binding Errors}">
+ <TextBlock FontWeight="SemiBold" Text="{Binding Title}" />
+ <StackPanel Orientation="Horizontal" Spacing="8">
+ <TextBlock Classes="caption" Text="{Binding Subtitle}" TextTrimming="CharacterEllipsis" MaxWidth="420" />
+ <TextBlock Classes="caption" Text="·" />
+ <TextBlock Classes="caption" Text="{Binding Time}" />
+ </StackPanel>
+ </StackPanel>
+ </DockPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </StackPanel>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/HomePage.axaml.cs b/src/Filee.App/Views/Pages/HomePage.axaml.cs
new file mode 100644
index 00000000..4c9c161b
--- /dev/null
+++ b/src/Filee.App/Views/Pages/HomePage.axaml.cs
@@ -0,0 +1,42 @@
+// Drop zone: files dropped on the Home page open the donut (click mode) at the drop position.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Platform.Storage;
+using Filee.App.Services;
+
+namespace Filee.App.Views.Pages;
+
+public partial class HomePage : UserControl
+{
+ public HomePage()
+ {
+ InitializeComponent();
+ DragDrop.AddDragEnterHandler(DropZone, (_, e) =>
+ {
+ DropZone.Classes.Add("over");
+ e.DragEffects = e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None;
+ });
+ DragDrop.AddDragOverHandler(DropZone, (_, e) =>
+ e.DragEffects = e.DataTransfer.Contains(DataFormat.File) ? DragDropEffects.Copy : DragDropEffects.None);
+ DragDrop.AddDragLeaveHandler(DropZone, (_, _) => DropZone.Classes.Remove("over"));
+ DragDrop.AddDropHandler(DropZone, OnDrop);
+ }
+
+ private void OnDrop(object? sender, DragEventArgs e)
+ {
+ DropZone.Classes.Remove("over");
+ var files = (e.DataTransfer.TryGetFiles() ?? [])
+ .Select(f => f.TryGetLocalPath())
+ .OfType<string>()
+ .Where(File.Exists)
+ .ToList();
+ if (files.Count == 0)
+ return;
+
+ e.DragEffects = DragDropEffects.Copy;
+ var screenPoint = this.PointToScreen(e.GetPosition(this));
+ AppHost.Get<RadialController>().ShowForFiles(screenPoint.X, screenPoint.Y, files);
+ }
+}
diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml b/src/Filee.App/Views/Pages/PresetsPage.axaml
new file mode 100644
index 00000000..472fbc1b
--- /dev/null
+++ b/src/Filee.App/Views/Pages/PresetsPage.axaml
@@ -0,0 +1,50 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ xmlns:views="using:Filee.App.Views"
+ x:Class="Filee.App.Views.Pages.PresetsPage"
+ x:DataType="vm:PresetsPageViewModel">
+ <Grid RowDefinitions="Auto,*" ColumnDefinitions="260,20,*">
+ <TextBlock Grid.ColumnSpan="3" Classes="h1" Text="{DynamicResource presets.title}" Margin="0,0,0,18" />
+
+ <!-- List -->
+ <StackPanel Grid.Row="1" Spacing="8">
+ <WrapPanel>
+ <Button Classes="accent" Command="{Binding AddCommand}" Margin="0,0,6,6">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
+ <TextBlock Text="{DynamicResource presets.add}" />
+ </StackPanel>
+ </Button>
+ <Button Command="{Binding DuplicateCommand}" Margin="0,0,6,6" ToolTip.Tip="{DynamicResource presets.duplicate}">
+ <PathIcon Width="14" Height="14" Data="{StaticResource Icon.Copy}" />
+ </Button>
+ <Button Command="{Binding DeleteCommand}" Margin="0,0,6,6" ToolTip.Tip="{DynamicResource presets.delete}">
+ <PathIcon Width="14" Height="14" Data="{StaticResource Icon.Delete}" />
+ </Button>
+ </WrapPanel>
+ <ListBox Classes="soft" ItemsSource="{Binding Presets}" SelectedItem="{Binding SelectedPreset}">
+ <ListBox.ItemTemplate>
+ <DataTemplate x:DataType="vm:PresetListItem">
+ <StackPanel>
+ <TextBlock Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" />
+ <TextBlock Classes="caption" Text="{Binding Target}" />
+ </StackPanel>
+ </DataTemplate>
+ </ListBox.ItemTemplate>
+ </ListBox>
+ </StackPanel>
+
+ <!-- Editor (same control as the donut's preset popup) -->
+ <StackPanel Grid.Row="1" Grid.Column="2" Spacing="12">
+ <TextBlock Classes="muted" Text="{DynamicResource presets.select}" IsVisible="{Binding Editor, Converter={x:Static ObjectConverters.IsNull}}" />
+ <views:PresetEditorView DataContext="{Binding Editor}" IsVisible="{Binding $parent[UserControl].((vm:PresetsPageViewModel)DataContext).Editor, Converter={x:Static ObjectConverters.IsNotNull}}" />
+ <StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Right"
+ IsVisible="{Binding Editor, Converter={x:Static ObjectConverters.IsNotNull}}">
+ <TextBlock Text="{Binding SavedMessage}" VerticalAlignment="Center" Foreground="{DynamicResource SuccessBrush}" FontWeight="Bold" />
+ <Button Content="{DynamicResource presets.revert}" Command="{Binding RevertCommand}" />
+ <Button Classes="accent" Content="{DynamicResource presets.save}" Command="{Binding SaveCommand}" />
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml.cs b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs
new file mode 100644
index 00000000..82fddc4f
--- /dev/null
+++ b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs
@@ -0,0 +1,8 @@
+using Avalonia.Controls;
+
+namespace Filee.App.Views.Pages;
+
+public partial class PresetsPage : UserControl
+{
+ public PresetsPage() => InitializeComponent();
+}
diff --git a/src/Filee.App/Views/Pages/ThemePage.axaml b/src/Filee.App/Views/Pages/ThemePage.axaml
new file mode 100644
index 00000000..6d96b46b
--- /dev/null
+++ b/src/Filee.App/Views/Pages/ThemePage.axaml
@@ -0,0 +1,79 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ xmlns:c="using:Filee.App.Controls"
+ x:Class="Filee.App.Views.Pages.ThemePage"
+ x:DataType="vm:ThemePageViewModel">
+ <Grid ColumnDefinitions="*,20,340" RowDefinitions="Auto,*">
+ <TextBlock Grid.ColumnSpan="3" Classes="h1" Text="{DynamicResource theme.title}" Margin="0,0,0,18" />
+
+ <StackPanel Grid.Row="1" Spacing="16">
+ <Border Classes="card">
+ <StackPanel Spacing="8">
+ <TextBlock Classes="label" Text="{DynamicResource theme.mode}" />
+ <ComboBox ItemsSource="{Binding Modes}" SelectedItem="{Binding Mode}" MinWidth="220" />
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="label" Text="{DynamicResource theme.accent}" />
+ <ItemsControl ItemsSource="{Binding Swatches}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <WrapPanel />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="Color">
+ <Button Width="34" Height="34" Margin="0,0,8,8" CornerRadius="999" Padding="0"
+ Command="{Binding $parent[ItemsControl].((vm:ThemePageViewModel)DataContext).PickSwatchCommand}"
+ CommandParameter="{Binding}">
+ <Button.Background>
+ <SolidColorBrush Color="{Binding}" />
+ </Button.Background>
+ </Button>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <Border Width="34" Height="34" CornerRadius="999" Background="{Binding AccentBrush}" />
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource theme.custom_color}" Margin="0" />
+ <TextBox Text="{Binding AccentHex}" Width="120" PlaceholderText="#7F77DD" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="8">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" FontWeight="SemiBold" Text="{Binding CornerRadius, StringFormat={}{0:0}}" />
+ <TextBlock Classes="label" Text="{DynamicResource theme.corner_radius}" />
+ </DockPanel>
+ <Slider Minimum="0" Maximum="28" Value="{Binding CornerRadius}" TickFrequency="1" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="4">
+ <CheckBox Content="{DynamicResource theme.reduce_motion}" IsChecked="{Binding ReduceMotion}" FontWeight="SemiBold" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource theme.reduce_motion_hint}" Margin="28,0,0,0" />
+ </StackPanel>
+ </Border>
+ </StackPanel>
+
+ <!-- Live preview -->
+ <Border Grid.Row="1" Grid.Column="2" Classes="card" VerticalAlignment="Top">
+ <StackPanel Spacing="14">
+ <TextBlock Classes="label" Text="{DynamicResource theme.preview}" />
+ <c:DonutMenu x:Name="PreviewDonut" Items="{Binding PreviewItems}" OuterRadius="120" CenterTitle="JPG × 3" HorizontalAlignment="Center" />
+ <StackPanel Orientation="Horizontal" Spacing="8" HorizontalAlignment="Center">
+ <Button Classes="accent" Content="{DynamicResource common.save}" />
+ <Button Content="{DynamicResource common.cancel}" />
+ </StackPanel>
+ <Slider Value="60" Maximum="100" />
+ <ToggleSwitch IsChecked="True" HorizontalAlignment="Center" />
+ </StackPanel>
+ </Border>
+ </Grid>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/ThemePage.axaml.cs b/src/Filee.App/Views/Pages/ThemePage.axaml.cs
new file mode 100644
index 00000000..9d64f60d
--- /dev/null
+++ b/src/Filee.App/Views/Pages/ThemePage.axaml.cs
@@ -0,0 +1,16 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+
+namespace Filee.App.Views.Pages;
+
+public partial class ThemePage : UserControl
+{
+ public ThemePage() => InitializeComponent();
+
+ /// <summary>Plays the donut's open animation so the "reduce animations" setting can be felt right away.</summary>
+ protected override void OnLoaded(RoutedEventArgs e)
+ {
+ base.OnLoaded(e);
+ PreviewDonut.PlayOpenAnimation();
+ }
+}
diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml b/src/Filee.App/Views/Pages/ToolbarPage.axaml
new file mode 100644
index 00000000..5d02d7d8
--- /dev/null
+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml
@@ -0,0 +1,150 @@
+<!--
+ Donut toolbar editor.
+ 1. Pick a profile on the left. 2. Arrange its presets on the live donut:
+ chip → donut = add · slice → palette = remove · slice → slice = reorder · right-click / ✎ = edit.
+ Drag & drop is implemented in ToolbarPage.axaml.cs.
+-->
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ xmlns:c="using:Filee.App.Controls"
+ x:Class="Filee.App.Views.Pages.ToolbarPage"
+ x:DataType="vm:ToolbarPageViewModel">
+ <UserControl.Styles>
+ <Style Selector="Border#PaletteBox.over">
+ <Setter Property="BorderBrush" Value="{DynamicResource DangerBrush}" />
+ <Setter Property="Background" Value="{DynamicResource AccentFaintBrush}" />
+ </Style>
+ <Style Selector="Border#Ghost">
+ <Setter Property="Background" Value="{DynamicResource AccentBrush}" />
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="Padding" Value="12,6" />
+ <Setter Property="BoxShadow" Value="0 6 18 0 #33000000" />
+ </Style>
+ </UserControl.Styles>
+
+ <Grid x:Name="Root" RowDefinitions="Auto,*">
+ <StackPanel Spacing="4" Margin="0,0,0,18">
+ <TextBlock Classes="h1" Text="{DynamicResource toolbar.title}" />
+ </StackPanel>
+
+ <Grid Grid.Row="1" ColumnDefinitions="200,20,*,20,230">
+ <!-- 1. Profiles -->
+ <StackPanel Spacing="8">
+ <TextBlock Classes="label" Text="{DynamicResource toolbar.step_profile}" />
+ <ListBox Classes="soft" ItemsSource="{Binding Profiles}" SelectedItem="{Binding SelectedProfile}">
+ <ListBox.ItemTemplate>
+ <DataTemplate x:DataType="vm:ProfileItemViewModel">
+ <DockPanel>
+ <Border DockPanel.Dock="Right" Classes="badge">
+ <TextBlock Classes="caption" Text="{Binding Count}" />
+ </Border>
+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
+ </DockPanel>
+ </DataTemplate>
+ </ListBox.ItemTemplate>
+ </ListBox>
+ <Button HorizontalAlignment="Stretch" Command="{Binding AddProfileCommand}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
+ <TextBlock Text="{DynamicResource toolbar.add_profile}" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+
+ <!-- 2. Donut -->
+ <StackPanel Grid.Column="2" Spacing="12">
+ <TextBlock Classes="label" Text="{DynamicResource toolbar.step_arrange}" />
+ <Border Classes="card" Padding="8">
+ <c:DonutMenu x:Name="Donut" IsEditMode="True" HorizontalAlignment="Center"
+ Items="{Binding DonutItems}"
+ CenterTitle="{Binding CenterTitle}"
+ CenterSubtitle="{Binding CenterSubtitle}"
+ OuterRadius="{Binding OuterRadius}"
+ HoleRatio="{Binding HoleRatio, Converter={x:Static vm:ToolbarConverters.Percent}}"
+ SliceOpacity="{Binding SliceOpacity, Converter={x:Static vm:ToolbarConverters.Percent}}" />
+ </Border>
+ <TextBlock Classes="caption danger" Text="{Binding Message}" HorizontalAlignment="Center" />
+
+ <Border Classes="card">
+ <StackPanel Spacing="10">
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource toolbar.name}" />
+ <TextBox Text="{Binding ProfileName}" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource toolbar.extensions}" />
+ <TextBox Text="{Binding Extensions}" PlaceholderText="{DynamicResource toolbar.extensions_hint}" IsEnabled="{Binding !IsFallback}" />
+ </StackPanel>
+ </Grid>
+ <TextBlock Classes="caption" Text="{DynamicResource toolbar.fallback_note}" IsVisible="{Binding IsFallback}" TextWrapping="Wrap" />
+ <Button HorizontalAlignment="Right" Content="{DynamicResource toolbar.delete_profile}" Command="{Binding DeleteProfileCommand}" IsVisible="{Binding !IsFallback}" />
+ </StackPanel>
+ </Border>
+
+ <Border Classes="card">
+ <StackPanel Spacing="6">
+ <TextBlock Classes="h2" Text="{DynamicResource toolbar.appearance}" />
+ <Grid ColumnDefinitions="90,*">
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource toolbar.size}" />
+ <Slider Grid.Column="1" Minimum="110" Maximum="220" Value="{Binding OuterRadius}" />
+ </Grid>
+ <Grid ColumnDefinitions="90,*">
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource toolbar.hole}" />
+ <Slider Grid.Column="1" Minimum="25" Maximum="65" Value="{Binding HoleRatio}" />
+ </Grid>
+ <Grid ColumnDefinitions="90,*">
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource toolbar.opacity}" />
+ <Slider Grid.Column="1" Minimum="50" Maximum="100" Value="{Binding SliceOpacity}" />
+ </Grid>
+ </StackPanel>
+ </Border>
+ </StackPanel>
+
+ <!-- Palette -->
+ <StackPanel Grid.Column="4" Spacing="8">
+ <TextBlock Classes="label" Text="{DynamicResource toolbar.available}" />
+ <Border x:Name="PaletteBox" MinHeight="180" Padding="6" CornerRadius="{DynamicResource SoftRadius}"
+ BorderThickness="2" BorderBrush="{DynamicResource SubtleBorderBrush}" Background="Transparent">
+ <ItemsControl ItemsSource="{Binding Palette}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <WrapPanel />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:PaletteChip">
+ <Border Classes="chip" PointerPressed="OnChipPressed" DoubleTapped="OnChipDoubleTapped">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <TextBlock Text="{Binding Label}" FontWeight="SemiBold" />
+ <TextBlock Classes="caption" Text="{Binding Caption}" VerticalAlignment="Center" />
+ </StackPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+ </Border>
+ <Button HorizontalAlignment="Stretch" Command="{Binding NewPresetCommand}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Plus}" />
+ <TextBlock Text="{DynamicResource toolbar.new_preset}" />
+ </StackPanel>
+ </Button>
+ <StackPanel Spacing="4" Margin="2,6,0,0">
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_add}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_remove}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_reorder}" />
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource toolbar.hint_edit}" />
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+
+ <!-- Drag ghost layer -->
+ <Canvas x:Name="DragLayer" Grid.RowSpan="2" IsHitTestVisible="False">
+ <Border x:Name="Ghost" IsVisible="False">
+ <TextBlock x:Name="GhostText" Foreground="{DynamicResource OnAccentBrush}" FontWeight="SemiBold" />
+ </Border>
+ </Canvas>
+ </Grid>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs b/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs
new file mode 100644
index 00000000..e7f5b45e
--- /dev/null
+++ b/src/Filee.App/Views/Pages/ToolbarPage.axaml.cs
@@ -0,0 +1,162 @@
+// Drag & drop for the donut editor.
+//
+// Sources: a palette chip (add) or a donut slice (reorder / remove).
+// Targets: a donut slice (insert at / move to that position), the empty ring or the hole (append),
+// or the palette box (remove a slice).
+// A floating "ghost" chip follows the pointer; the donut highlights the slice that would receive the drop.
+
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Interactivity;
+using Filee.App.Controls;
+using Filee.App.ViewModels.Pages;
+
+namespace Filee.App.Views.Pages;
+
+public partial class ToolbarPage : UserControl
+{
+ private const double DragThreshold = 5;
+
+ private enum Source { Chip, Slice }
+
+ private sealed record DragState(Source Source, string? PresetId, int SliceIndex, string Label, Point Start)
+ {
+ public bool Active { get; set; }
+ }
+
+ private DragState? _drag;
+
+ public ToolbarPage()
+ {
+ InitializeComponent();
+
+ // See every pointer event on the page, even while a chip / the donut has pointer capture.
+ Root.AddHandler(PointerMovedEvent, OnRootPointerMoved, RoutingStrategies.Tunnel, handledEventsToo: true);
+ Root.AddHandler(PointerReleasedEvent, OnRootPointerReleased, RoutingStrategies.Tunnel, handledEventsToo: true);
+ Root.AddHandler(PointerCaptureLostEvent, (_, _) => EndDrag(), RoutingStrategies.Tunnel, handledEventsToo: true);
+
+ Donut.SegmentDragStarted += (_, e) =>
+ {
+ if (Vm is null || e.Index >= Vm.DonutItems.Count)
+ return;
+ var p = e.Args.GetPosition(Root);
+ _drag = new DragState(Source.Slice, null, e.Index, Vm.DonutItems[e.Index].Label, p) { Active = true };
+ Donut.SetDimmedIndex(e.Index);
+ ShowGhost(_drag.Label, p);
+ };
+ Donut.SegmentContextRequested += async (_, index) =>
+ {
+ if (Vm is not null)
+ await Vm.EditAsync(index);
+ };
+ }
+
+ private ToolbarPageViewModel? Vm => DataContext as ToolbarPageViewModel;
+
+ private void OnChipPressed(object? sender, PointerPressedEventArgs e)
+ {
+ if (sender is not Border { DataContext: PaletteChip chip } border)
+ return;
+ var point = e.GetCurrentPoint(border);
+ if (point.Properties.IsRightButtonPressed)
+ {
+ _ = Vm?.EditChipAsync(chip.PresetId);
+ e.Handled = true;
+ return;
+ }
+ if (!point.Properties.IsLeftButtonPressed)
+ return;
+
+ _drag = new DragState(Source.Chip, chip.PresetId, -1, chip.Label, e.GetPosition(Root));
+ e.Pointer.Capture(border);
+ e.Handled = true;
+ }
+
+ /// <summary>Double-clicking a chip appends it to the donut.</summary>
+ private void OnChipDoubleTapped(object? sender, TappedEventArgs e)
+ {
+ if (sender is Border { DataContext: PaletteChip chip } && Vm is { } vm)
+ vm.Insert(chip.PresetId, vm.SliceCount);
+ }
+
+ private void OnRootPointerMoved(object? sender, PointerEventArgs e)
+ {
+ if (_drag is null)
+ return;
+ var p = e.GetPosition(Root);
+ if (!_drag.Active)
+ {
+ if (Math.Abs(p.X - _drag.Start.X) < DragThreshold && Math.Abs(p.Y - _drag.Start.Y) < DragThreshold)
+ return;
+ _drag.Active = true;
+ }
+
+ ShowGhost(_drag.Label, p);
+ var (sliceTarget, overPalette) = FindTarget(e);
+ Donut.SetDropTarget(sliceTarget);
+ PaletteBox.Classes.Set("over", overPalette && _drag.Source == Source.Slice);
+ }
+
+ private void OnRootPointerReleased(object? sender, PointerReleasedEventArgs e)
+ {
+ var drag = _drag;
+ if (drag is null)
+ return;
+
+ if (drag.Active && Vm is { } vm)
+ {
+ var (sliceTarget, overPalette) = FindTarget(e);
+ switch (drag.Source)
+ {
+ case Source.Chip when sliceTarget >= 0:
+ vm.Insert(drag.PresetId!, sliceTarget);
+ break;
+ case Source.Slice when overPalette:
+ vm.RemoveAt(drag.SliceIndex);
+ break;
+ case Source.Slice when sliceTarget >= 0 && sliceTarget < vm.SliceCount:
+ vm.Move(drag.SliceIndex, sliceTarget);
+ break;
+ }
+ }
+ e.Pointer.Capture(null);
+ EndDrag();
+ }
+
+ /// <summary>
+ /// Where would a drop land? Returns the slice index (or SliceCount = append; -1 = not on the donut)
+ /// and whether the pointer is over the palette.
+ /// </summary>
+ private (int SliceTarget, bool OverPalette) FindTarget(PointerEventArgs e)
+ {
+ var overPalette = new Rect(PaletteBox.Bounds.Size).Contains(e.GetPosition(PaletteBox));
+ var hit = Donut.HitTest(e.GetPosition(Donut));
+ var count = Vm?.SliceCount ?? 0;
+ var target = hit.Kind switch
+ {
+ DonutHitKind.Segment or DonutHitKind.EditButton => hit.Index,
+ DonutHitKind.EmptyRing => 0,
+ DonutHitKind.Center when _drag?.Source == Source.Chip => count, // drop in the hole = append
+ _ => -1,
+ };
+ return (target, overPalette);
+ }
+
+ private void ShowGhost(string label, Point at)
+ {
+ GhostText.Text = label;
+ Ghost.IsVisible = true;
+ Canvas.SetLeft(Ghost, at.X + 12);
+ Canvas.SetTop(Ghost, at.Y + 12);
+ }
+
+ private void EndDrag()
+ {
+ _drag = null;
+ Ghost.IsVisible = false;
+ Donut.SetDropTarget(-1);
+ Donut.SetDimmedIndex(-1);
+ PaletteBox.Classes.Set("over", false);
+ }
+}
diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml b/src/Filee.App/Views/Pages/TriggersPage.axaml
new file mode 100644
index 00000000..feb93161
--- /dev/null
+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml
@@ -0,0 +1,115 @@
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels.Pages"
+ x:Class="Filee.App.Views.Pages.TriggersPage"
+ x:DataType="vm:TriggersPageViewModel">
+ <StackPanel Spacing="18">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Classes="accent" Command="{Binding AddCommand}">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Plus}" />
+ <TextBlock Text="{DynamicResource triggers.add}" />
+ </StackPanel>
+ </Button>
+ <StackPanel>
+ <TextBlock Classes="h1" Text="{DynamicResource triggers.title}" />
+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{DynamicResource triggers.description}" />
+ </StackPanel>
+ </DockPanel>
+
+ <ItemsControl ItemsSource="{Binding Gestures}">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="12" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:TriggerGestureViewModel">
+ <Border Classes="card">
+ <StackPanel Spacing="14">
+ <!-- Header: on/off, summary, remove -->
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Classes="icon"
+ Command="{Binding $parent[ItemsControl].((vm:TriggersPageViewModel)DataContext).RemoveCommand}"
+ CommandParameter="{Binding}" ToolTip.Tip="{DynamicResource triggers.remove}">
+ <PathIcon Width="15" Height="15" Data="{StaticResource Icon.Delete}" />
+ </Button>
+ <ToggleSwitch DockPanel.Dock="Left" IsChecked="{Binding Enabled}" OnContent="" OffContent="" Margin="0,0,8,0" />
+ <Border Classes="badge ok" VerticalAlignment="Center" HorizontalAlignment="Left">
+ <TextBlock Text="{Binding Summary}" FontWeight="SemiBold" Foreground="{DynamicResource AccentStrongBrush}" />
+ </Border>
+ </DockPanel>
+
+ <Grid ColumnDefinitions="*,16,*" RowDefinitions="Auto,14,Auto">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource triggers.kind}" />
+ <ComboBox ItemsSource="{Binding Kinds}" SelectedItem="{Binding Kind}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource triggers.scope}" />
+ <ComboBox ItemsSource="{Binding Scopes}" SelectedItem="{Binding Scope}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+
+ <StackPanel Grid.Row="2">
+ <TextBlock Classes="label" Text="{DynamicResource triggers.modifiers}" />
+ <WrapPanel>
+ <ToggleButton Content="Ctrl" IsChecked="{Binding Ctrl}" Margin="0,0,6,6" />
+ <ToggleButton Content="Alt" IsChecked="{Binding Alt}" Margin="0,0,6,6" />
+ <ToggleButton Content="Shift" IsChecked="{Binding Shift}" Margin="0,0,6,6" />
+ <ToggleButton Content="{Binding MetaLabel}" IsChecked="{Binding Meta}" Margin="0,0,6,6" />
+ </WrapPanel>
+ </StackPanel>
+
+ <StackPanel Grid.Row="2" Grid.Column="2" Spacing="10">
+ <StackPanel IsVisible="{Binding UsesMouse}">
+ <TextBlock Classes="label" Text="{DynamicResource triggers.button}" />
+ <ComboBox ItemsSource="{Binding Buttons}" SelectedItem="{Binding Button}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel IsVisible="{Binding UsesKey}">
+ <TextBlock Classes="label" Text="{DynamicResource triggers.key}" />
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <Border Classes="badge" MinWidth="120" Padding="12,6">
+ <TextBlock Text="{Binding KeyText}" FontWeight="SemiBold" />
+ </Border>
+ <ToggleButton IsChecked="{Binding IsRecording}" KeyDown="OnRecorderKeyDown">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Record}" Foreground="{DynamicResource DangerBrush}" />
+ <TextBlock Text="{Binding RecordLabel}" />
+ </StackPanel>
+ </ToggleButton>
+ <Button Classes="ghost" Content="{DynamicResource triggers.clear}" Command="{Binding ClearKeyCommand}" />
+ </StackPanel>
+ </StackPanel>
+ </StackPanel>
+ </Grid>
+
+ <StackPanel IsVisible="{Binding UsesThreshold}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding ThresholdText}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource triggers.threshold}" />
+ </DockPanel>
+ <Slider Minimum="0" Maximum="80" Value="{Binding DragThreshold}" TickFrequency="1" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ <StackPanel IsVisible="{Binding UsesHold}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" FontWeight="SemiBold">
+ <Run Text="{Binding HoldMilliseconds}" /><Run Text=" ms" />
+ </TextBlock>
+ <TextBlock Classes="label" Text="{DynamicResource triggers.hold_ms}" />
+ </DockPanel>
+ <Slider Minimum="150" Maximum="2000" Value="{Binding HoldMilliseconds}" TickFrequency="50" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+
+ <Border Classes="card">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource triggers.excluded}" />
+ <TextBox Text="{Binding Excluded}" PlaceholderText="{DynamicResource triggers.excluded_hint}" />
+ </StackPanel>
+ </Border>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml.cs b/src/Filee.App/Views/Pages/TriggersPage.axaml.cs
new file mode 100644
index 00000000..71b94a85
--- /dev/null
+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml.cs
@@ -0,0 +1,18 @@
+using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
+using Avalonia.Input;
+using Filee.App.ViewModels.Pages;
+
+namespace Filee.App.Views.Pages;
+
+public partial class TriggersPage : UserControl
+{
+ public TriggersPage() => InitializeComponent();
+
+ /// <summary>While "Record" is on, the next key combination pressed on the button becomes the shortcut.</summary>
+ private void OnRecorderKeyDown(object? sender, KeyEventArgs e)
+ {
+ if (sender is ToggleButton { DataContext: TriggerGestureViewModel vm } && vm.IsRecording)
+ e.Handled = vm.Record(e.Key, e.KeyModifiers);
+ }
+}
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
new file mode 100644
index 00000000..700fcdfd
--- /dev/null
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -0,0 +1,135 @@
+<!-- Preset editor form. Used on the Presets page and inside PresetEditorWindow (donut right-click / ✎). -->
+<UserControl xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ x:Class="Filee.App.Views.PresetEditorView"
+ x:DataType="vm:PresetEditorViewModel">
+ <StackPanel Spacing="14">
+ <!-- Name + target -->
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.name}" />
+ <TextBox Text="{Binding Name}" />
+ <TextBlock Classes="caption danger" Text="{Binding NameError}" IsVisible="{Binding NameError, Converter={x:Static ObjectConverters.IsNotNull}}" Margin="2,4,0,0" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.target}" />
+ <ComboBox ItemsSource="{Binding Targets}" SelectedItem="{Binding Target}" HorizontalAlignment="Stretch" MaxDropDownHeight="360" />
+ </StackPanel>
+ </Grid>
+
+ <!-- Image options -->
+ <Border Classes="card" IsVisible="{Binding ShowImage}" Padding="14">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.image}" />
+ <StackPanel IsVisible="{Binding ShowQuality}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding Quality}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.quality}" />
+ </DockPanel>
+ <Slider Minimum="1" Maximum="100" Value="{Binding Quality}" TickFrequency="1" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.resize}" />
+ <ComboBox ItemsSource="{Binding ResizeModes}" SelectedItem="{Binding Resize}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowPercent}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.percent}" />
+ <NumericUpDown Value="{Binding ResizePercent}" Minimum="1" Maximum="1000" Increment="5" FormatString="0" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowLongEdge}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.long_edge}" />
+ <NumericUpDown Value="{Binding LongEdge}" Minimum="16" Maximum="20000" Increment="100" FormatString="0" />
+ </StackPanel>
+ </Grid>
+ <Grid ColumnDefinitions="Auto,12,*">
+ <CheckBox Content="{DynamicResource presets.dpi}" IsChecked="{Binding SetDpi}" />
+ <NumericUpDown Grid.Column="2" Value="{Binding Dpi}" Minimum="36" Maximum="2400" Increment="50" FormatString="0" IsEnabled="{Binding SetDpi}" />
+ </Grid>
+ <WrapPanel>
+ <CheckBox Content="{DynamicResource presets.keep_metadata}" IsChecked="{Binding KeepMetadata}" Margin="0,0,18,0" />
+ <CheckBox Content="{DynamicResource presets.grayscale}" IsChecked="{Binding Grayscale}" Margin="0,0,18,0" />
+ <CheckBox Content="{DynamicResource presets.webp_lossless}" IsChecked="{Binding WebpLossless}" IsVisible="{Binding ShowWebp}" />
+ </WrapPanel>
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.background}" />
+ <TextBox Text="{Binding Background}" PlaceholderText="#FFFFFF" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowTiff}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.tiff_compression}" />
+ <ComboBox ItemsSource="{Binding TiffCompressions}" SelectedItem="{Binding TiffCompression}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowIco}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.ico_sizes}" />
+ <TextBox Text="{Binding IcoSizes}" PlaceholderText="256, 64, 48, 32, 16" />
+ </StackPanel>
+ </Grid>
+ </StackPanel>
+ </Border>
+
+ <!-- PDF options (render settings also apply when a PDF is converted to images) -->
+ <Border Classes="card" Padding="14">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.pdf}" />
+ <CheckBox Content="{DynamicResource presets.merge}" IsChecked="{Binding Merge}" IsVisible="{Binding ShowPdfBuild}" />
+ <CheckBox Content="{DynamicResource presets.split}" IsChecked="{Binding SplitPages}" IsVisible="{Binding ShowPdfSplit}" />
+ <Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowPdfBuild}">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.page_size}" />
+ <ComboBox ItemsSource="{Binding PageSizes}" SelectedItem="{Binding PageSize}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2" IsVisible="{Binding ShowMargin}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.margin}" />
+ <NumericUpDown Value="{Binding MarginMm}" Minimum="0" Maximum="100" Increment="1" FormatString="0" />
+ </StackPanel>
+ </Grid>
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.render_dpi}" />
+ <NumericUpDown Value="{Binding RenderDpi}" Minimum="36" Maximum="1200" Increment="25" FormatString="0" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.page_range}" />
+ <TextBox Text="{Binding PageRange}" PlaceholderText="{DynamicResource presets.page_range_hint}" />
+ </StackPanel>
+ </Grid>
+ <CheckBox Content="{DynamicResource presets.pdfa}" IsChecked="{Binding PdfA}" IsVisible="{Binding ShowDocument}" />
+ </StackPanel>
+ </Border>
+
+ <!-- Output -->
+ <Border Classes="card" Padding="14">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.output}" />
+ <Grid ColumnDefinitions="*,12,*">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.location}" />
+ <ComboBox ItemsSource="{Binding Locations}" SelectedItem="{Binding Location}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Grid.Column="2">
+ <TextBlock Classes="label" Text="{DynamicResource presets.conflict}" />
+ <ComboBox ItemsSource="{Binding Conflicts}" SelectedItem="{Binding Conflict}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ </Grid>
+ <StackPanel IsVisible="{Binding ShowSubfolder}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.subfolder}" />
+ <TextBox Text="{Binding SubfolderName}" PlaceholderText="converted" />
+ </StackPanel>
+ <StackPanel IsVisible="{Binding ShowCustomFolder}">
+ <TextBlock Classes="label" Text="{DynamicResource presets.custom_folder}" />
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Margin="8,0,0,0" Content="{DynamicResource presets.browse}" Click="OnBrowseFolder" />
+ <TextBox Text="{Binding CustomFolder}" />
+ </DockPanel>
+ </StackPanel>
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.pattern}" />
+ <TextBox Text="{Binding Pattern}" PlaceholderText="{}{name}" />
+ <TextBlock Classes="caption" Text="{DynamicResource presets.pattern_hint}" Margin="2,4,0,0" />
+ </StackPanel>
+ </StackPanel>
+ </Border>
+ </StackPanel>
+</UserControl>
diff --git a/src/Filee.App/Views/PresetEditorView.axaml.cs b/src/Filee.App/Views/PresetEditorView.axaml.cs
new file mode 100644
index 00000000..2e0282eb
--- /dev/null
+++ b/src/Filee.App/Views/PresetEditorView.axaml.cs
@@ -0,0 +1,21 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Avalonia.Platform.Storage;
+using Filee.App.ViewModels;
+
+namespace Filee.App.Views;
+
+public partial class PresetEditorView : UserControl
+{
+ public PresetEditorView() => InitializeComponent();
+
+ private async void OnBrowseFolder(object? sender, RoutedEventArgs e)
+ {
+ if (DataContext is not PresetEditorViewModel vm || TopLevel.GetTopLevel(this) is not { } top)
+ return;
+ var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { AllowMultiple = false });
+ var path = folders.FirstOrDefault()?.TryGetLocalPath();
+ if (path is not null)
+ vm.CustomFolder = path;
+ }
+}
diff --git a/src/Filee.App/Views/PresetEditorWindow.axaml b/src/Filee.App/Views/PresetEditorWindow.axaml
new file mode 100644
index 00000000..660dbb49
--- /dev/null
+++ b/src/Filee.App/Views/PresetEditorWindow.axaml
@@ -0,0 +1,33 @@
+<!-- The preset popup opened by right-click / ✎ on a donut slice. Same editor as the Presets page. -->
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ xmlns:views="using:Filee.App.Views"
+ x:Class="Filee.App.Views.PresetEditorWindow"
+ x:DataType="vm:PresetEditorViewModel"
+ Title="{DynamicResource presets.editor_title}"
+ Icon="avares://Filee/Assets/Icons/filee.ico"
+ Width="560" Height="680" MinWidth="440" MinHeight="400"
+ WindowStartupLocation="CenterOwner"
+ ShowInTaskbar="False">
+ <DockPanel>
+ <Border DockPanel.Dock="Bottom" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{DynamicResource SubtleBorderBrush}"
+ Background="{DynamicResource SurfaceBrush}">
+ <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8">
+ <Button Content="{DynamicResource common.cancel}" Click="OnCancel" IsCancel="True" />
+ <Button Classes="accent" Content="{DynamicResource common.save}" Click="OnSave" IsDefault="True" IsEnabled="{Binding IsValid}" />
+ </StackPanel>
+ </Border>
+ <ScrollViewer Padding="20,16">
+ <StackPanel Spacing="12">
+ <StackPanel Orientation="Horizontal" Spacing="10">
+ <Border Width="34" Height="34" CornerRadius="999" Background="{DynamicResource AccentSoftBrush}">
+ <PathIcon Width="16" Height="16" Data="{StaticResource Icon.Pencil}" Foreground="{DynamicResource AccentStrongBrush}" />
+ </Border>
+ <TextBlock Classes="h2" VerticalAlignment="Center" Text="{DynamicResource presets.editor_title}" />
+ </StackPanel>
+ <views:PresetEditorView />
+ </StackPanel>
+ </ScrollViewer>
+ </DockPanel>
+</Window>
diff --git a/src/Filee.App/Views/PresetEditorWindow.axaml.cs b/src/Filee.App/Views/PresetEditorWindow.axaml.cs
new file mode 100644
index 00000000..cc0d0b38
--- /dev/null
+++ b/src/Filee.App/Views/PresetEditorWindow.axaml.cs
@@ -0,0 +1,29 @@
+using Avalonia.Controls;
+using Avalonia.Interactivity;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+
+namespace Filee.App.Views;
+
+/// <summary>Modal preset editor. Returns true from ShowDialog when the user saved.</summary>
+public partial class PresetEditorWindow : Window
+{
+ public PresetEditorWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+ }
+
+ /// <summary>True after the user saved (also available when the window was not shown as a dialog).</summary>
+ public bool Saved { get; private set; }
+
+ private void OnSave(object? sender, RoutedEventArgs e)
+ {
+ if (DataContext is not PresetEditorViewModel vm || !vm.Apply())
+ return;
+ Saved = true;
+ Close(true);
+ }
+
+ private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
+}
diff --git a/src/Filee.App/Views/RadialWindow.axaml b/src/Filee.App/Views/RadialWindow.axaml
new file mode 100644
index 00000000..5b1d9d7c
--- /dev/null
+++ b/src/Filee.App/Views/RadialWindow.axaml
@@ -0,0 +1,30 @@
+<!--
+ Borderless, transparent, always-on-top window that hosts the live donut toolbar at the cursor.
+ It is created once and reused (shown/hidden) so it appears instantly.
+ ShowActivated=False: during a file drag it must not steal focus from Explorer, or the drag would break.
+-->
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:c="using:Filee.App.Controls"
+ xmlns:vm="using:Filee.App.ViewModels"
+ x:Class="Filee.App.Views.RadialWindow"
+ x:DataType="vm:RadialViewModel"
+ Title="Filee"
+ WindowDecorations="None"
+ Background="Transparent"
+ TransparencyLevelHint="Transparent"
+ Topmost="True"
+ ShowInTaskbar="False"
+ ShowActivated="False"
+ CanResize="False"
+ SizeToContent="WidthAndHeight">
+ <Panel x:Name="Root" Background="Transparent" DragDrop.AllowDrop="True">
+ <c:DonutMenu x:Name="Donut"
+ Items="{Binding Items}"
+ CenterTitle="{Binding CenterTitle}"
+ CenterSubtitle="{Binding CenterSubtitle}"
+ OuterRadius="{Binding OuterRadius}"
+ HoleRatio="{Binding HoleRatio}"
+ SliceOpacity="{Binding SliceOpacity}" />
+ </Panel>
+</Window>
diff --git a/src/Filee.App/Views/RadialWindow.axaml.cs b/src/Filee.App/Views/RadialWindow.axaml.cs
new file mode 100644
index 00000000..f9f4ed8f
--- /dev/null
+++ b/src/Filee.App/Views/RadialWindow.axaml.cs
@@ -0,0 +1,91 @@
+// Thin view for the live donut: forwards drag & drop and pointer events to RadialController.
+
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Platform.Storage;
+using Filee.App.Controls;
+using Filee.App.Services;
+
+namespace Filee.App.Views;
+
+public partial class RadialWindow : Window
+{
+ public RadialWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+
+ DragDrop.AddDragEnterHandler(Root, OnDragEnter);
+ DragDrop.AddDragOverHandler(Root, OnDragOver);
+ DragDrop.AddDragLeaveHandler(Root, OnDragLeave);
+ DragDrop.AddDropHandler(Root, OnDrop);
+ }
+
+ public DonutMenu DonutControl => Donut;
+
+ /// <summary>Files entered the window during a drag.</summary>
+ public event Action<IReadOnlyList<string>>? FilesEntered;
+
+ /// <summary>A drop landed on the donut: (hit, files).</summary>
+ public event Action<DonutHit, IReadOnlyList<string>>? Dropped;
+
+ public event Action? DragLeft;
+
+ private void OnDragEnter(object? sender, DragEventArgs e)
+ {
+ var files = LocalFiles(e);
+ if (files.Count == 0)
+ {
+ e.DragEffects = DragDropEffects.None;
+ return;
+ }
+ FilesEntered?.Invoke(files);
+ OnDragOver(sender, e);
+ }
+
+ private void OnDragOver(object? sender, DragEventArgs e)
+ {
+ var hit = Donut.HitTest(e.GetPosition(Donut));
+ var files = e.DataTransfer.Contains(DataFormat.File);
+ Donut.SetExternalHighlight(hit.Kind == DonutHitKind.Segment ? hit.Index : -1, hit.Kind == DonutHitKind.Center);
+
+ // Always COPY. Reporting MOVE would make Explorer delete the source files after the drop.
+ e.DragEffects = files && hit.Kind == DonutHitKind.Segment ? DragDropEffects.Copy : DragDropEffects.None;
+ e.Handled = true;
+ }
+
+ private void OnDragLeave(object? sender, DragEventArgs e)
+ {
+ Donut.SetExternalHighlight(-1);
+ DragLeft?.Invoke();
+ }
+
+ private void OnDrop(object? sender, DragEventArgs e)
+ {
+ var hit = Donut.HitTest(e.GetPosition(Donut));
+ Donut.SetExternalHighlight(-1);
+ e.DragEffects = hit.Kind == DonutHitKind.Segment ? DragDropEffects.Copy : DragDropEffects.None;
+ Dropped?.Invoke(hit, LocalFiles(e));
+ e.Handled = true;
+ }
+
+ protected override void OnKeyDown(KeyEventArgs e)
+ {
+ base.OnKeyDown(e);
+ if (e.Key == Key.Escape)
+ {
+ EscapePressed?.Invoke();
+ e.Handled = true;
+ }
+ }
+
+ public event Action? EscapePressed;
+
+ /// <summary>Local file paths in the drag data (folders and virtual items are ignored).</summary>
+ private static IReadOnlyList<string> LocalFiles(DragEventArgs e) =>
+ (e.DataTransfer.TryGetFiles() ?? [])
+ .Select(item => item.TryGetLocalPath())
+ .OfType<string>()
+ .Where(File.Exists)
+ .ToList();
+}
diff --git a/src/Filee.App/Views/ToastWindow.axaml b/src/Filee.App/Views/ToastWindow.axaml
new file mode 100644
index 00000000..e140b8f2
--- /dev/null
+++ b/src/Filee.App/Views/ToastWindow.axaml
@@ -0,0 +1,85 @@
+<!-- Progress cards in the bottom-right corner. Shows itself while ToastJobs is non-empty, hides when empty. -->
+<Window xmlns="https://github.com/avaloniaui"
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+ xmlns:vm="using:Filee.App.ViewModels"
+ xmlns:s="using:Filee.App.Services"
+ x:Class="Filee.App.Views.ToastWindow"
+ x:DataType="s:ConversionService"
+ Title="Filee"
+ Width="360"
+ SizeToContent="Height"
+ WindowDecorations="None"
+ Background="Transparent"
+ TransparencyLevelHint="Transparent"
+ Topmost="True"
+ ShowInTaskbar="False"
+ ShowActivated="False"
+ CanResize="False">
+ <Window.Styles>
+ <Style Selector="ItemsControl#Jobs ContentPresenter">
+ <Style.Animations>
+ <Animation Duration="0:0:0.35" Easing="BackEaseOut" FillMode="Forward">
+ <KeyFrame Cue="0%">
+ <Setter Property="Opacity" Value="0" />
+ <Setter Property="Margin" Value="40,0,-40,0" />
+ </KeyFrame>
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ <Setter Property="Margin" Value="0" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+ <Style Selector="Window.reduced-motion ItemsControl#Jobs ContentPresenter">
+ <Style.Animations>
+ <Animation Duration="0:0:0.001" FillMode="Forward">
+ <KeyFrame Cue="100%">
+ <Setter Property="Opacity" Value="1" />
+ </KeyFrame>
+ </Animation>
+ </Style.Animations>
+ </Style>
+ <Style Selector="ProgressBar">
+ <Setter Property="CornerRadius" Value="999" />
+ <Setter Property="MinHeight" Value="6" />
+ <Setter Property="Height" Value="6" />
+ </Style>
+ </Window.Styles>
+
+ <ItemsControl x:Name="Jobs" ItemsSource="{Binding ToastJobs}" Margin="12">
+ <ItemsControl.ItemsPanel>
+ <ItemsPanelTemplate>
+ <StackPanel Spacing="8" />
+ </ItemsPanelTemplate>
+ </ItemsControl.ItemsPanel>
+ <ItemsControl.ItemTemplate>
+ <DataTemplate x:DataType="vm:JobViewModel">
+ <Border Classes="card" Padding="14,12">
+ <StackPanel Spacing="8">
+ <DockPanel>
+ <Button DockPanel.Dock="Right" Classes="icon" Command="{Binding DismissCommand}" Padding="4" VerticalAlignment="Top">
+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" />
+ </Button>
+ <TextBlock Text="{Binding Title}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
+ </DockPanel>
+ <ProgressBar Value="{Binding Progress}" Maximum="100" IsVisible="{Binding IsRunning}" />
+ <DockPanel>
+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Spacing="6">
+ <Button Content="{DynamicResource toast.cancel}" Command="{Binding CancelCommand}" IsVisible="{Binding IsRunning}" Padding="10,4" />
+ <Button Classes="accent" Command="{Binding OpenFolderCommand}" IsVisible="{Binding HasOutputs}" Padding="10,4">
+ <StackPanel Orientation="Horizontal" Spacing="6">
+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Folder}" />
+ <TextBlock Text="{DynamicResource toast.open_folder}" />
+ </StackPanel>
+ </Button>
+ </StackPanel>
+ <TextBlock Classes="caption" Text="{Binding Status}" VerticalAlignment="Center" />
+ </DockPanel>
+ <TextBlock Classes="caption danger" Text="{Binding ErrorDetails}" TextWrapping="Wrap" MaxLines="4"
+ IsVisible="{Binding HasErrors}" />
+ </StackPanel>
+ </Border>
+ </DataTemplate>
+ </ItemsControl.ItemTemplate>
+ </ItemsControl>
+</Window>
diff --git a/src/Filee.App/Views/ToastWindow.axaml.cs b/src/Filee.App/Views/ToastWindow.axaml.cs
new file mode 100644
index 00000000..00c7cb0d
--- /dev/null
+++ b/src/Filee.App/Views/ToastWindow.axaml.cs
@@ -0,0 +1,51 @@
+using System.Collections.Specialized;
+using Avalonia;
+using Avalonia.Controls;
+using Filee.App.Services;
+
+namespace Filee.App.Views;
+
+/// <summary>Bottom-right progress stack. Visible exactly while ConversionService.ToastJobs is non-empty.</summary>
+public partial class ToastWindow : Window
+{
+ private const int ScreenMargin = 12;
+
+ public ToastWindow()
+ {
+ InitializeComponent();
+ Motion.Track(this);
+ SizeChanged += (_, _) => PlaceBottomRight();
+ }
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ if (DataContext is ConversionService service)
+ service.ToastJobs.CollectionChanged += (_, args) => OnJobsChanged(service, args);
+ }
+
+ private void OnJobsChanged(ConversionService service, NotifyCollectionChangedEventArgs e)
+ {
+ if (service.ToastJobs.Count > 0 && !IsVisible)
+ {
+ Show();
+ PlaceBottomRight();
+ }
+ else if (service.ToastJobs.Count == 0 && IsVisible)
+ {
+ Hide();
+ }
+ }
+
+ private void PlaceBottomRight()
+ {
+ var screen = Screens.Primary;
+ if (screen is null)
+ return;
+ var area = screen.WorkingArea;
+ var scaling = screen.Scaling;
+ var width = (int)Math.Ceiling(Bounds.Width * scaling);
+ var height = (int)Math.Ceiling(Bounds.Height * scaling);
+ Position = new PixelPoint(area.Right - width - ScreenMargin, area.Bottom - height - ScreenMargin);
+ }
+}
diff --git a/src/Filee.App/app.manifest b/src/Filee.App/app.manifest
new file mode 100644
index 00000000..bb7cdaad
--- /dev/null
+++ b/src/Filee.App/app.manifest
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
+ <!-- Windows only. Required for transparent windows and per-monitor DPI. -->
+ <assemblyIdentity version="1.0.0.0" name="Filee.Desktop"/>
+
+ <!--
+ Filee must NOT run elevated: Windows (UIPI) blocks drag and drop from Explorer
+ into elevated windows, which would break the donut toolbar.
+ -->
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
+ <security>
+ <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
+ <requestedExecutionLevel level="asInvoker" uiAccess="false" />
+ </requestedPrivileges>
+ </security>
+ </trustInfo>
+
+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+ <application>
+ <!-- Windows 10 / 11 -->
+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
+ </application>
+ </compatibility>
+
+ <application xmlns="urn:schemas-microsoft-com:asm.v3">
+ <windowsSettings>
+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
+ </windowsSettings>
+ </application>
+</assembly>
diff --git a/src/Filee.Core/Conversion/ConversionJob.cs b/src/Filee.Core/Conversion/ConversionJob.cs
new file mode 100644
index 00000000..7ef352c3
--- /dev/null
+++ b/src/Filee.Core/Conversion/ConversionJob.cs
@@ -0,0 +1,73 @@
+// State of one "drop" — a batch of files converted with one preset.
+
+using Filee.Core.Presets;
+
+namespace Filee.Core.Conversion;
+
+public enum JobState
+{
+ Queued,
+ Running,
+ Completed,
+ CompletedWithErrors,
+ Failed,
+ Cancelled,
+}
+
+public enum FileState
+{
+ Pending,
+ Running,
+ Done,
+ Skipped,
+ Failed,
+ Cancelled,
+}
+
+/// <summary>Result for one source file of a job.</summary>
+public sealed class FileResult
+{
+ public required string SourcePath { get; init; }
+ public FileState State { get; set; } = FileState.Pending;
+ public double Progress { get; set; }
+ public List<string> Outputs { get; } = [];
+
+ /// <summary>Localization key of the error (e.g. <c>error.no_route</c>), if any.</summary>
+ public string? ErrorKey { get; set; }
+
+ /// <summary>Raw error detail for logs / tooltips.</summary>
+ public string? ErrorDetail { get; set; }
+}
+
+/// <summary>A batch of files converted with one preset.</summary>
+public sealed class ConversionJob
+{
+ private readonly CancellationTokenSource _cts = new();
+
+ public ConversionJob(IReadOnlyList<string> sources, Preset preset, string presetDisplayName)
+ {
+ Sources = sources;
+ Preset = preset.Clone(); // later edits of the preset must not affect a running job
+ PresetDisplayName = presetDisplayName;
+ Files = sources.Select(s => new FileResult { SourcePath = s }).ToList();
+ }
+
+ public string Id { get; } = Guid.NewGuid().ToString("N")[..10];
+ public DateTime CreatedAt { get; } = DateTime.Now;
+ public IReadOnlyList<string> Sources { get; }
+ public Preset Preset { get; }
+ public string PresetDisplayName { get; }
+ public IReadOnlyList<FileResult> Files { get; }
+ public JobState State { get; internal set; } = JobState.Queued;
+
+ /// <summary>Overall progress 0..1.</summary>
+ public double Progress => Files.Count == 0 ? 1 : Files.Average(f => f.Progress);
+
+ /// <summary>Every file written by the job.</summary>
+ public IEnumerable<string> Outputs => Files.SelectMany(f => f.Outputs);
+
+ public CancellationToken CancellationToken => _cts.Token;
+
+ /// <summary>Requests cancellation. Running engines stop as soon as they can.</summary>
+ public void Cancel() => _cts.Cancel();
+}
diff --git a/src/Filee.Core/Conversion/ConverterCatalog.cs b/src/Filee.Core/Conversion/ConverterCatalog.cs
new file mode 100644
index 00000000..584765fc
--- /dev/null
+++ b/src/Filee.Core/Conversion/ConverterCatalog.cs
@@ -0,0 +1,82 @@
+// Holds every registered converter, caches their availability and builds route planners.
+
+namespace Filee.Core.Conversion;
+
+/// <summary>Registry of all converters plus the user's engine priority.</summary>
+public sealed class ConverterCatalog
+{
+ private readonly IReadOnlyList<IConverter> _all;
+ private Dictionary<string, EngineStatus>? _statusCache;
+ private IReadOnlyList<string> _priority = [];
+
+ public ConverterCatalog(IEnumerable<IConverter> converters) => _all = converters.ToList();
+
+ /// <summary>Every registered converter, available or not.</summary>
+ public IReadOnlyList<IConverter> All => _all;
+
+ /// <summary>Raised after <see cref="Refresh"/> or a priority change.</summary>
+ public event EventHandler? Changed;
+
+ /// <summary>
+ /// Engine ids in preferred order. Engines earlier in the list win ties.
+ /// Engines not listed keep their registration order after the listed ones.
+ /// </summary>
+ public IReadOnlyList<string> Priority
+ {
+ get => _priority;
+ set
+ {
+ _priority = value;
+ Changed?.Invoke(this, EventArgs.Empty);
+ }
+ }
+
+ /// <summary>Converters ordered by priority (for display in settings).</summary>
+ public IReadOnlyList<IConverter> Ordered =>
+ _all.OrderBy(c => PriorityIndex(c)).ThenBy(c => _all.ToList().IndexOf(c)).ToList();
+
+ /// <summary>Cached availability of a converter.</summary>
+ public EngineStatus StatusOf(IConverter converter)
+ {
+ _statusCache ??= _all.ToDictionary(c => c.Id, SafeStatus);
+ return _statusCache[converter.Id];
+ }
+
+ /// <summary>Re-checks every engine (e.g. after the user changed an engine path).</summary>
+ public void Refresh()
+ {
+ _statusCache = null;
+ Changed?.Invoke(this, EventArgs.Empty);
+ }
+
+ /// <summary>Creates a planner over the currently available converters.</summary>
+ public RoutePlanner CreatePlanner() =>
+ new(_all.Where(c => StatusOf(c).IsAvailable), c => Math.Min(PriorityIndex(c), 9));
+
+ /// <summary>
+ /// Creates a planner that also treats the engines in <paramref name="assumeInstalled"/> as available, to tell
+ /// which conversions an optional engine download would enable.
+ /// </summary>
+ public RoutePlanner CreatePlanner(IReadOnlyCollection<string> assumeInstalled) =>
+ new(_all.Where(c => StatusOf(c).IsAvailable || assumeInstalled.Contains(c.Id)), c => Math.Min(PriorityIndex(c), 9));
+
+ private int PriorityIndex(IConverter c)
+ {
+ for (var i = 0; i < _priority.Count; i++)
+ if (string.Equals(_priority[i], c.Id, StringComparison.OrdinalIgnoreCase))
+ return i;
+ return _priority.Count;
+ }
+
+ private static EngineStatus SafeStatus(IConverter c)
+ {
+ try
+ {
+ return c.GetStatus();
+ }
+ catch (Exception ex)
+ {
+ return EngineStatus.Unavailable("engine.reason.error", ex.Message);
+ }
+ }
+}
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
new file mode 100644
index 00000000..4562895c
--- /dev/null
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -0,0 +1,88 @@
+// The contract every conversion engine implements. Adding a new engine = one class implementing IConverter.
+// See docs/ADDING-A-CONVERTER.md.
+
+using Filee.Core.Presets;
+
+namespace Filee.Core.Conversion;
+
+/// <summary>
+/// One direct conversion a converter can perform, e.g. <c>docx → pdf</c>.
+/// </summary>
+/// <param name="From">Source format id.</param>
+/// <param name="To">Target format id. May equal <paramref name="From"/> (e.g. re-encode a JPG at lower quality).</param>
+/// <param name="Cost">
+/// Relative cost used by <see cref="RoutePlanner"/>. Use 10 for a normal direct conversion,
+/// higher for lossy or slow paths. Multi-step routes add up their costs.
+/// </param>
+public readonly record struct ConversionEdge(string From, string To, int Cost = 10);
+
+/// <summary>Whether an engine can currently be used.</summary>
+/// <param name="IsAvailable">True if conversions can run.</param>
+/// <param name="ReasonKey">Localization key explaining why the engine is unavailable (e.g. <c>engine.reason.not_installed</c>).</param>
+/// <param name="Detail">Extra, non-localized detail such as a path or version.</param>
+public sealed record EngineStatus(bool IsAvailable, string? ReasonKey = null, string? Detail = null)
+{
+ public static EngineStatus Available(string? detail = null) => new(true, null, detail);
+ public static EngineStatus Unavailable(string reasonKey, string? detail = null) => new(false, reasonKey, detail);
+}
+
+/// <summary>Hands out output paths to a converter.</summary>
+public interface IOutputAllocator
+{
+ /// <summary>
+ /// Returns the path the converter should write the next output file to.
+ /// </summary>
+ /// <param name="extension">Extension of the file being written, without dot.</param>
+ /// <param name="suffix">Optional name suffix such as <c>"_p2"</c> when one input produces several files.</param>
+ /// <returns>A path, or <c>null</c> if this output must be skipped (existing file + "skip" policy).</returns>
+ string? Allocate(string extension, string? suffix = null);
+}
+
+/// <summary>Everything a converter needs to perform one step.</summary>
+/// <param name="InputPath">File to read.</param>
+/// <param name="From">Format id of <paramref name="InputPath"/>.</param>
+/// <param name="To">Format id to produce.</param>
+/// <param name="Preset">Options chosen by the user.</param>
+/// <param name="Output">Where to write results.</param>
+/// <param name="WorkDirectory">Private scratch directory for this job; deleted afterwards.</param>
+public sealed record ConversionStep(
+ string InputPath,
+ string From,
+ string To,
+ Preset Preset,
+ IOutputAllocator Output,
+ string WorkDirectory);
+
+/// <summary>
+/// A conversion engine (ImageMagick, LibreOffice, rhwp, ...).
+/// </summary>
+/// <remarks>
+/// Implementations must be thread-safe up to <see cref="MaxParallelism"/> concurrent calls,
+/// must honour the cancellation token, and must never modify the input file.
+/// </remarks>
+public interface IConverter
+{
+ /// <summary>Stable id used in settings (engine priority, custom paths). Lower-case, no spaces.</summary>
+ string Id { get; }
+
+ /// <summary>Human readable engine name (not localized, e.g. "LibreOffice").</summary>
+ string DisplayName { get; }
+
+ /// <summary>Direct conversions this engine supports.</summary>
+ IReadOnlyList<ConversionEdge> Edges { get; }
+
+ /// <summary>How many conversions may run at the same time. 0 means "one per CPU core".</summary>
+ int MaxParallelism { get; }
+
+ /// <summary>Checks if the engine is installed / usable. Should be cheap; results may be cached.</summary>
+ EngineStatus GetStatus();
+
+ /// <summary>Performs one conversion step and returns the files that were written.</summary>
+ Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken);
+}
+
+/// <summary>Merges several PDF files into one. Implemented by the PDF engine.</summary>
+public interface IPdfMerger
+{
+ Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken);
+}
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
new file mode 100644
index 00000000..ea8e61fb
--- /dev/null
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -0,0 +1,308 @@
+// Runs conversion jobs in the background: plans routes, limits engine concurrency,
+// allocates output paths and reports progress. UI code only enqueues and listens to events.
+
+using System.Collections.Concurrent;
+using System.Threading.Channels;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Filee.Core.Conversion;
+
+/// <summary>Background queue that executes <see cref="ConversionJob"/>s one after another.</summary>
+public sealed class JobQueue : IAsyncDisposable
+{
+ private readonly ConverterCatalog _catalog;
+ private readonly IPdfMerger? _pdfMerger;
+ private readonly ILogger _log;
+ private readonly Channel<ConversionJob> _channel = Channel.CreateUnbounded<ConversionJob>();
+ private readonly ConcurrentDictionary<string, SemaphoreSlim> _engineGates = new();
+ private readonly HashSet<string> _reservedOutputs = new(StringComparer.OrdinalIgnoreCase);
+ private readonly Task _worker;
+
+ public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger<JobQueue>? log = null)
+ {
+ _catalog = catalog;
+ _pdfMerger = pdfMerger;
+ _log = log ?? (ILogger)NullLogger.Instance;
+ _worker = Task.Run(WorkLoopAsync);
+ }
+
+ /// <summary>Raised (on a background thread) whenever a job's state or progress changes.</summary>
+ public event EventHandler<ConversionJob>? JobUpdated;
+
+ /// <summary>Raised (on a background thread) once when a job reaches a final state.</summary>
+ public event EventHandler<ConversionJob>? JobFinished;
+
+ /// <summary>Adds a job to the queue and returns it immediately.</summary>
+ public ConversionJob Enqueue(IReadOnlyList<string> sources, Preset preset, string presetDisplayName)
+ {
+ var job = new ConversionJob(sources, preset, presetDisplayName);
+ _channel.Writer.TryWrite(job);
+ JobUpdated?.Invoke(this, job);
+ return job;
+ }
+
+ /// <summary>Runs a job to completion on the calling task. Used by tests and by <see cref="Enqueue"/>'s worker.</summary>
+ public async Task RunAsync(ConversionJob job)
+ {
+ job.State = JobState.Running;
+ Notify(job);
+
+ var workDir = Path.Combine(Path.GetTempPath(), "Filee", job.Id);
+ Directory.CreateDirectory(workDir);
+ try
+ {
+ var planner = _catalog.CreatePlanner();
+ var merge = job.Preset.Pdf.MergeIntoSingle
+ && job.Preset.TargetFormat == "pdf"
+ && job.Files.Count > 1
+ && _pdfMerger is not null;
+
+ if (merge)
+ await RunMergedAsync(job, planner, workDir);
+ else
+ await Parallel.ForEachAsync(
+ job.Files.Select((f, i) => (File: f, Index: i + 1)),
+ new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = CancellationToken.None },
+ async (item, _) => await RunFileAsync(job, item.File, item.Index, planner, workDir, finalOutput: true));
+
+ job.State = job.CancellationToken.IsCancellationRequested ? JobState.Cancelled
+ : job.Files.All(f => f.State is FileState.Done or FileState.Skipped) ? JobState.Completed
+ : job.Files.Any(f => f.State == FileState.Done) ? JobState.CompletedWithErrors
+ : JobState.Failed;
+ }
+ catch (Exception ex)
+ {
+ _log.LogError(ex, "Job {Job} failed", job.Id);
+ job.State = JobState.Failed;
+ }
+ finally
+ {
+ lock (_reservedOutputs)
+ foreach (var output in job.Outputs)
+ _reservedOutputs.Remove(output);
+ TryDelete(workDir);
+ }
+
+ Notify(job);
+ JobFinished?.Invoke(this, job);
+ }
+
+ /// <summary>Converts every file to PDF in the work directory, then merges them into one output.</summary>
+ private async Task RunMergedAsync(ConversionJob job, RoutePlanner planner, string workDir)
+ {
+ var parts = new string?[job.Files.Count];
+ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count),
+ new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
+ async (i, _) =>
+ {
+ var file = job.Files[i];
+ if (FormatRegistry.Detect(file.SourcePath)?.Id == "pdf")
+ {
+ parts[i] = file.SourcePath; // already a PDF, merge as-is
+ return;
+ }
+ var produced = await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false);
+ parts[i] = produced.FirstOrDefault();
+ });
+
+ var inputs = parts.OfType<string>().ToList();
+ if (inputs.Count == 0 || job.CancellationToken.IsCancellationRequested)
+ return;
+
+ var first = job.Files[0];
+ var allocator = CreateFinalAllocator(job, first.SourcePath, 1);
+ var output = allocator.Allocate("pdf");
+ if (output is null)
+ {
+ foreach (var f in job.Files) f.State = FileState.Skipped;
+ return;
+ }
+
+ await _pdfMerger!.MergeAsync(inputs, output, job.CancellationToken);
+ first.Outputs.Add(output);
+ foreach (var f in job.Files.Where(f => f.State != FileState.Failed))
+ {
+ f.State = FileState.Done;
+ f.Progress = 1;
+ }
+ Notify(job);
+ }
+
+ /// <summary>
+ /// Converts one source file along its planned route.
+ /// With <paramref name="finalOutput"/> false, results stay in the work directory (used for merging).
+ /// </summary>
+ private async Task<IReadOnlyList<string>> RunFileAsync(
+ ConversionJob job, FileResult file, int index, RoutePlanner planner, string workDir, bool finalOutput)
+ {
+ var ct = job.CancellationToken;
+ var source = FormatRegistry.Detect(file.SourcePath);
+ if (source is null)
+ return Fail(file, "error.unsupported_source", Path.GetExtension(file.SourcePath));
+
+ var target = !finalOutput ? "pdf"
+ : job.Preset.TargetFormat == BuiltInData.SameAsSource ? source.Id
+ : job.Preset.TargetFormat;
+
+ var route = planner.Plan(source.Id, target);
+ if (route is null)
+ return Fail(file, "error.no_route", $"{source.Id} → {target}");
+
+ file.State = FileState.Running;
+ Notify(job);
+
+ try
+ {
+ IReadOnlyList<string> inputs = [file.SourcePath];
+ for (var s = 0; s < route.Steps.Count; s++)
+ {
+ var step = route.Steps[s];
+ var isLast = s == route.Steps.Count - 1;
+ IOutputAllocator allocator = isLast && finalOutput
+ ? CreateFinalAllocator(job, file.SourcePath, index)
+ : new TempAllocator(workDir, Path.GetFileNameWithoutExtension(file.SourcePath));
+
+ var outputs = new List<string>();
+ foreach (var input in inputs)
+ {
+ ct.ThrowIfCancellationRequested();
+ var stepIndex = s;
+ var progress = new Progress<double>(p =>
+ {
+ file.Progress = (stepIndex + Math.Clamp(p, 0, 1)) / route.Steps.Count;
+ Notify(job);
+ });
+
+ var gate = GateFor(step.Converter);
+ await gate.WaitAsync(ct);
+ try
+ {
+ var stepInfo = new ConversionStep(input, step.From, step.To, job.Preset, allocator, workDir);
+ outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));
+ }
+ finally
+ {
+ gate.Release();
+ }
+ }
+ inputs = outputs;
+ }
+
+ if (finalOutput)
+ file.Outputs.AddRange(inputs);
+ file.State = inputs.Count == 0 && finalOutput ? FileState.Skipped : FileState.Done;
+ file.Progress = 1;
+ Notify(job);
+ return inputs;
+ }
+ catch (OperationCanceledException)
+ {
+ file.State = FileState.Cancelled;
+ Notify(job);
+ return [];
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Converting {File} failed", file.SourcePath);
+ return Fail(file, "error.conversion_failed", ex.Message);
+ }
+
+ IReadOnlyList<string> Fail(FileResult f, string key, string? detail)
+ {
+ f.State = FileState.Failed;
+ f.ErrorKey = key;
+ f.ErrorDetail = detail;
+ f.Progress = 1;
+ Notify(job);
+ return [];
+ }
+ }
+
+ private SemaphoreSlim GateFor(IConverter converter) =>
+ _engineGates.GetOrAdd(converter.Id, _ =>
+ {
+ var max = converter.MaxParallelism <= 0 ? Environment.ProcessorCount : converter.MaxParallelism;
+ return new SemaphoreSlim(max, max);
+ });
+
+ private FinalAllocator CreateFinalAllocator(ConversionJob job, string sourcePath, int index) =>
+ new(this, job.Preset.Output, new OutputPathResolver.Tokens(sourcePath, job.PresetDisplayName, index, job.CreatedAt));
+
+ private void Notify(ConversionJob job)
+ {
+ try
+ {
+ JobUpdated?.Invoke(this, job);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "JobUpdated handler threw");
+ }
+ }
+
+ private async Task WorkLoopAsync()
+ {
+ await foreach (var job in _channel.Reader.ReadAllAsync())
+ {
+ if (job.CancellationToken.IsCancellationRequested)
+ {
+ job.State = JobState.Cancelled;
+ Notify(job);
+ JobFinished?.Invoke(this, job);
+ continue;
+ }
+ await RunAsync(job);
+ }
+ }
+
+ private static void TryDelete(string dir)
+ {
+ try
+ {
+ if (Directory.Exists(dir))
+ Directory.Delete(dir, recursive: true);
+ }
+ catch (IOException) { /* a viewer may still hold a temp file; the OS cleans temp eventually */ }
+ catch (UnauthorizedAccessException) { }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ _channel.Writer.TryComplete();
+ await _worker;
+ }
+
+ /// <summary>Allocates final output paths according to the preset's <see cref="OutputRule"/>.</summary>
+ private sealed class FinalAllocator(JobQueue queue, OutputRule rule, OutputPathResolver.Tokens tokens) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null)
+ {
+ // Reserve under a lock so two parallel files never pick the same name.
+ lock (queue._reservedOutputs)
+ {
+ var path = OutputPathResolver.Resolve(rule, tokens, extension,
+ p => File.Exists(p) || queue._reservedOutputs.Contains(p), suffix);
+ if (path is null)
+ return null;
+
+ queue._reservedOutputs.Add(path);
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ return path;
+ }
+ }
+ }
+
+ /// <summary>Allocates unique paths inside the job's work directory for intermediate files.</summary>
+ private sealed class TempAllocator(string workDir, string baseName) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null)
+ {
+ var dir = Path.Combine(workDir, Guid.NewGuid().ToString("N")[..8]);
+ Directory.CreateDirectory(dir);
+ return Path.Combine(dir, $"{baseName}{suffix}.{extension.TrimStart('.')}");
+ }
+ }
+}
diff --git a/src/Filee.Core/Conversion/PageRange.cs b/src/Filee.Core/Conversion/PageRange.cs
new file mode 100644
index 00000000..3952731a
--- /dev/null
+++ b/src/Filee.Core/Conversion/PageRange.cs
@@ -0,0 +1,50 @@
+// Parses user page selections such as "1-3, 5, 8-" into zero-based page indices.
+
+namespace Filee.Core.Conversion;
+
+/// <summary>Page range parsing.</summary>
+public static class PageRange
+{
+ /// <summary>
+ /// Parses a 1-based page range expression. Empty or whitespace means every page.
+ /// Supported forms: <c>"3"</c>, <c>"2-5"</c>, <c>"7-"</c> (to the end), <c>"-4"</c> (from the start), comma separated.
+ /// Invalid parts are ignored; out-of-range pages are clamped away.
+ /// </summary>
+ /// <returns>Sorted, distinct zero-based page indices.</returns>
+ public static IReadOnlyList<int> Parse(string? expression, int pageCount)
+ {
+ if (pageCount <= 0)
+ return [];
+ if (string.IsNullOrWhiteSpace(expression))
+ return Enumerable.Range(0, pageCount).ToList();
+
+ var pages = new SortedSet<int>();
+ foreach (var raw in expression.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
+ {
+ var dash = raw.IndexOf('-');
+ int start, end;
+ if (dash < 0)
+ {
+ if (!int.TryParse(raw, out start))
+ continue;
+ end = start;
+ }
+ else
+ {
+ var left = raw[..dash].Trim();
+ var right = raw[(dash + 1)..].Trim();
+ start = left.Length == 0 ? 1 : int.TryParse(left, out var l) ? l : -1;
+ end = right.Length == 0 ? pageCount : int.TryParse(right, out var r) ? r : -1;
+ if (start < 0 || end < 0)
+ continue;
+ }
+
+ if (start > end)
+ (start, end) = (end, start);
+ for (var p = Math.Max(1, start); p <= Math.Min(pageCount, end); p++)
+ pages.Add(p - 1);
+ }
+
+ return pages.Count == 0 ? Enumerable.Range(0, pageCount).ToList() : pages.ToList();
+ }
+}
diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.cs
new file mode 100644
index 00000000..0b923e31
--- /dev/null
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -0,0 +1,100 @@
+// Finds the cheapest chain of converters from a source format to a target format.
+//
+// Why a graph search: engines only know direct conversions (edges). Many useful conversions need
+// two hops, e.g. HWPX → PDF (rhwp) → PNG (PDFium). Treating formats as nodes and converter edges as
+// weighted arcs lets new engines automatically unlock new routes without touching any other code.
+
+namespace Filee.Core.Conversion;
+
+/// <summary>One hop of a route.</summary>
+public sealed record RouteStep(IConverter Converter, string From, string To);
+
+/// <summary>A planned conversion from one format to another.</summary>
+public sealed record Route(IReadOnlyList<RouteStep> Steps, int Cost);
+
+/// <summary>Plans conversion routes over the available converters.</summary>
+public sealed class RoutePlanner
+{
+ /// <summary>Maximum number of hops. Longer chains are almost always lossy and slow.</summary>
+ public const int MaxSteps = 3;
+
+ private readonly IReadOnlyList<IConverter> _converters;
+ private readonly Func<IConverter, int> _priorityPenalty;
+
+ /// <param name="converters">Converters that are currently available.</param>
+ /// <param name="priorityPenalty">
+ /// Extra cost per step for a converter, derived from the user's engine priority order.
+ /// Keep it small (0..9) so priority breaks ties between engines without making routes longer.
+ /// </param>
+ public RoutePlanner(IEnumerable<IConverter> converters, Func<IConverter, int>? priorityPenalty = null)
+ {
+ _converters = converters.ToList();
+ _priorityPenalty = priorityPenalty ?? (_ => 0);
+ }
+
+ /// <summary>Returns the cheapest route, or <c>null</c> if the conversion is impossible.</summary>
+ public Route? Plan(string from, string to)
+ {
+ from = from.ToLowerInvariant();
+ to = to.ToLowerInvariant();
+
+ // Same-format "conversions" (re-encode, split, compress) must use an explicit self edge.
+ if (from == to)
+ {
+ var best = AllEdges()
+ .Where(e => e.Edge.From == from && e.Edge.To == to)
+ .OrderBy(e => e.Cost)
+ .FirstOrDefault();
+ return best.Converter is null
+ ? null
+ : new Route([new RouteStep(best.Converter, from, to)], best.Cost);
+ }
+
+ // Dijkstra over formats. The graph is tiny (dozens of nodes), so a simple list-based
+ // priority queue is fine and easy to read.
+ var edges = AllEdges().Where(e => e.Edge.From != e.Edge.To).ToList();
+ var dist = new Dictionary<string, int> { [from] = 0 };
+ var prev = new Dictionary<string, (string Node, RouteStep Step)>();
+ var hops = new Dictionary<string, int> { [from] = 0 };
+ var queue = new PriorityQueue<string, int>();
+ queue.Enqueue(from, 0);
+
+ while (queue.TryDequeue(out var node, out var cost))
+ {
+ if (cost > dist[node])
+ continue; // stale queue entry
+ if (node == to)
+ break;
+ if (hops[node] >= MaxSteps)
+ continue;
+
+ foreach (var (converter, edge, edgeCost) in edges.Where(e => e.Edge.From == node))
+ {
+ var next = cost + edgeCost;
+ if (dist.TryGetValue(edge.To, out var known) && known <= next)
+ continue;
+
+ dist[edge.To] = next;
+ hops[edge.To] = hops[node] + 1;
+ prev[edge.To] = (node, new RouteStep(converter, edge.From, edge.To));
+ queue.Enqueue(edge.To, next);
+ }
+ }
+
+ if (!prev.ContainsKey(to))
+ return null;
+
+ var steps = new List<RouteStep>();
+ for (var node = to; node != from; node = prev[node].Node)
+ steps.Add(prev[node].Step);
+ steps.Reverse();
+ return new Route(steps, dist[to]);
+ }
+
+ /// <summary>True if <paramref name="from"/> can be converted to <paramref name="to"/>.</summary>
+ public bool CanConvert(string from, string to) => Plan(from, to) is not null;
+
+ private IEnumerable<(IConverter Converter, ConversionEdge Edge, int Cost)> AllEdges() =>
+ _converters.SelectMany(c => c.Edges.Select(e =>
+ (c, e with { From = e.From.ToLowerInvariant(), To = e.To.ToLowerInvariant() }, e.Cost + _priorityPenalty(c))));
+}
diff --git a/src/Filee.Core/Filee.Core.csproj b/src/Filee.Core/Filee.Core.csproj
new file mode 100644
index 00000000..c4e5998a
--- /dev/null
+++ b/src/Filee.Core/Filee.Core.csproj
@@ -0,0 +1,18 @@
+<!--
+ Filee.Core: platform- and UI-independent domain model.
+ Formats, presets, toolbar profiles, settings and the conversion pipeline live here.
+ This project must not reference Avalonia or any OS-specific API.
+-->
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <RootNamespace>Filee.Core</RootNamespace>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <InternalsVisibleTo Include="Filee.Core.Tests" />
+ </ItemGroup>
+</Project>
diff --git a/src/Filee.Core/Formats/FileFormat.cs b/src/Filee.Core/Formats/FileFormat.cs
new file mode 100644
index 00000000..1396ed51
--- /dev/null
+++ b/src/Filee.Core/Formats/FileFormat.cs
@@ -0,0 +1,28 @@
+// Describes a file format Filee understands (e.g. "png", "hwpx") and groups formats into categories.
+
+namespace Filee.Core.Formats;
+
+/// <summary>Broad family a format belongs to. Toolbar profiles and the UI group formats by this.</summary>
+public enum FormatCategory
+{
+ Image,
+ Pdf,
+ Document,
+ Spreadsheet,
+ Presentation,
+ Hwp,
+ Text,
+}
+
+/// <summary>
+/// A file format known to Filee.
+/// </summary>
+/// <param name="Id">Stable lower-case identifier used in presets and converter edges (e.g. <c>"jpg"</c>).</param>
+/// <param name="DisplayName">Short label shown in the UI (e.g. <c>"JPG"</c>).</param>
+/// <param name="Category">Format family.</param>
+/// <param name="Extensions">File extensions without the dot; the first one is used for output files.</param>
+public sealed record FileFormat(string Id, string DisplayName, FormatCategory Category, IReadOnlyList<string> Extensions)
+{
+ /// <summary>Extension (without dot) used when writing a file of this format.</summary>
+ public string PrimaryExtension => Extensions[0];
+}
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
new file mode 100644
index 00000000..0e83e153
--- /dev/null
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -0,0 +1,73 @@
+// Central list of supported formats and extension lookup.
+// To add a new format: add one line to Known and give at least one converter an edge for it.
+
+namespace Filee.Core.Formats;
+
+/// <summary>Lookup table of every format Filee knows about.</summary>
+public static class FormatRegistry
+{
+ /// <summary>All known formats. Order is the order shown in format pickers.</summary>
+ public static IReadOnlyList<FileFormat> Known { get; } =
+ [
+ // Raster images
+ new("png", "PNG", FormatCategory.Image, ["png"]),
+ new("jpg", "JPG", FormatCategory.Image, ["jpg", "jpeg", "jpe", "jfif"]),
+ new("webp", "WEBP", FormatCategory.Image, ["webp"]),
+ new("tiff", "TIFF", FormatCategory.Image, ["tiff", "tif"]),
+ new("bmp", "BMP", FormatCategory.Image, ["bmp", "dib"]),
+ new("gif", "GIF", FormatCategory.Image, ["gif"]),
+ new("ico", "ICO", FormatCategory.Image, ["ico"]),
+ new("avif", "AVIF", FormatCategory.Image, ["avif"]),
+ new("heic", "HEIC", FormatCategory.Image, ["heic", "heif"]),
+
+ // PDF
+ new("pdf", "PDF", FormatCategory.Pdf, ["pdf"]),
+
+ // Word processing
+ new("docx", "DOCX", FormatCategory.Document, ["docx"]),
+ new("doc", "DOC", FormatCategory.Document, ["doc"]),
+ new("odt", "ODT", FormatCategory.Document, ["odt"]),
+ new("rtf", "RTF", FormatCategory.Document, ["rtf"]),
+
+ // Korean word processor (Hancom)
+ new("hwpx", "HWPX", FormatCategory.Hwp, ["hwpx"]),
+ new("hwp", "HWP", FormatCategory.Hwp, ["hwp"]),
+
+ // Spreadsheets
+ new("xlsx", "XLSX", FormatCategory.Spreadsheet, ["xlsx"]),
+ new("xls", "XLS", FormatCategory.Spreadsheet, ["xls"]),
+ new("ods", "ODS", FormatCategory.Spreadsheet, ["ods"]),
+ new("csv", "CSV", FormatCategory.Spreadsheet, ["csv"]),
+
+ // Presentations
+ new("pptx", "PPTX", FormatCategory.Presentation, ["pptx"]),
+ new("ppt", "PPT", FormatCategory.Presentation, ["ppt"]),
+ new("odp", "ODP", FormatCategory.Presentation, ["odp"]),
+
+ // Plain text / markup
+ new("txt", "TXT", FormatCategory.Text, ["txt"]),
+ new("md", "Markdown", FormatCategory.Text, ["md", "markdown"]),
+ new("html", "HTML", FormatCategory.Text, ["html", "htm"]),
+ ];
+
+ private static readonly Dictionary<string, FileFormat> ById =
+ Known.ToDictionary(f => f.Id, StringComparer.OrdinalIgnoreCase);
+
+ private static readonly Dictionary<string, FileFormat> ByExtension =
+ Known.SelectMany(f => f.Extensions.Select(e => (e, f)))
+ .ToDictionary(x => x.e, x => x.f, StringComparer.OrdinalIgnoreCase);
+
+ /// <summary>Returns the format with the given id, or <c>null</c>.</summary>
+ public static FileFormat? FindById(string id) => ById.GetValueOrDefault(id);
+
+ /// <summary>Returns the format with the given id or throws if it is unknown.</summary>
+ public static FileFormat Get(string id) =>
+ FindById(id) ?? throw new KeyNotFoundException($"Unknown format id '{id}'.");
+
+ /// <summary>Returns the format for an extension (with or without the leading dot), or <c>null</c>.</summary>
+ public static FileFormat? FindByExtension(string extension) =>
+ ByExtension.GetValueOrDefault(extension.TrimStart('.'));
+
+ /// <summary>Detects the format of a file from its extension, or <c>null</c> if it is not supported.</summary>
+ public static FileFormat? Detect(string path) => FindByExtension(Path.GetExtension(path));
+}
diff --git a/src/Filee.Core/History/HistoryEntry.cs b/src/Filee.Core/History/HistoryEntry.cs
new file mode 100644
index 00000000..63e71894
--- /dev/null
+++ b/src/Filee.Core/History/HistoryEntry.cs
@@ -0,0 +1,35 @@
+// A finished conversion job as shown on the Home page ("Recent conversions").
+
+using Filee.Core.Conversion;
+
+namespace Filee.Core.History;
+
+/// <summary>Persisted summary of a finished job.</summary>
+public sealed class HistoryEntry
+{
+ public string JobId { get; set; } = "";
+ public DateTime FinishedAt { get; set; }
+ public string PresetId { get; set; } = "";
+ public string PresetName { get; set; } = "";
+ public JobState State { get; set; }
+ public List<string> Sources { get; set; } = [];
+ public List<string> Outputs { get; set; } = [];
+
+ /// <summary>"source: error" lines for failed files.</summary>
+ public List<string> Errors { get; set; } = [];
+
+ public static HistoryEntry From(ConversionJob job) => new()
+ {
+ JobId = job.Id,
+ FinishedAt = DateTime.Now,
+ PresetId = job.Preset.Id,
+ PresetName = job.PresetDisplayName,
+ State = job.State,
+ Sources = [.. job.Sources],
+ Outputs = [.. job.Outputs],
+ Errors = job.Files
+ .Where(f => f.State == FileState.Failed)
+ .Select(f => $"{Path.GetFileName(f.SourcePath)}: {f.ErrorKey} {f.ErrorDetail}".Trim())
+ .ToList(),
+ };
+}
diff --git a/src/Filee.Core/Localization/ILocalizer.cs b/src/Filee.Core/Localization/ILocalizer.cs
new file mode 100644
index 00000000..4bbca446
--- /dev/null
+++ b/src/Filee.Core/Localization/ILocalizer.cs
@@ -0,0 +1,37 @@
+// Localization contract. The Avalonia implementation lives in Filee.App (LocalizationService).
+// Translations are JSON files in src/Filee.App/Assets/i18n. See docs/ADDING-A-LANGUAGE.md.
+
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+
+namespace Filee.Core.Localization;
+
+/// <summary>Looks up translated UI strings by key.</summary>
+public interface ILocalizer
+{
+ /// <summary>Current language code, e.g. <c>"ko"</c>.</summary>
+ string Language { get; }
+
+ /// <summary>Returns the translation for <paramref name="key"/>, falling back to English, then to the key itself.</summary>
+ string this[string key] { get; }
+
+ /// <summary>Translation with <see cref="string.Format(string, object[])"/> style arguments.</summary>
+ string Format(string key, params object[] args);
+
+ /// <summary>Raised after the language changed.</summary>
+ event EventHandler? LanguageChanged;
+}
+
+/// <summary>Helpers that resolve user-facing names of presets and profiles.</summary>
+public static class LocalizerExtensions
+{
+ public static string DisplayName(this ILocalizer loc, Preset preset) =>
+ !string.IsNullOrWhiteSpace(preset.Name) ? preset.Name
+ : preset.NameKey is not null ? loc[preset.NameKey]
+ : preset.TargetFormat.ToUpperInvariant();
+
+ public static string DisplayName(this ILocalizer loc, ToolbarProfile profile) =>
+ !string.IsNullOrWhiteSpace(profile.Name) ? profile.Name
+ : profile.NameKey is not null ? loc[profile.NameKey]
+ : profile.Id;
+}
diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.cs
new file mode 100644
index 00000000..e29485a2
--- /dev/null
+++ b/src/Filee.Core/Platform/IPlatformServices.cs
@@ -0,0 +1,53 @@
+// OS integration points. Windows implementation: Filee.Platform.Windows. macOS: planned.
+// Code that needs the OS goes through this interface so the rest of the app stays portable.
+
+namespace Filee.Core.Platform;
+
+/// <summary>Operating-system specific services.</summary>
+public interface IPlatformServices
+{
+ /// <summary>True if the window under the given screen point (physical pixels) belongs to the file manager or desktop.</summary>
+ bool IsFileManagerAt(int x, int y);
+
+ /// <summary>Process name (without extension) owning the window under the point, or <c>null</c>.</summary>
+ string? ProcessNameAt(int x, int y);
+
+ /// <summary>Files currently selected in the foreground file manager window (empty if none).</summary>
+ IReadOnlyList<string> GetFileManagerSelection();
+
+ /// <summary>System drag threshold in physical pixels.</summary>
+ int SystemDragThreshold { get; }
+
+ /// <summary>True if the user asked the OS to reduce animations.</summary>
+ bool PrefersReducedMotion { get; }
+
+ /// <summary>Adds or removes "start with the system".</summary>
+ void SetStartWithSystem(bool enabled, string executablePath);
+
+ /// <summary>Adds or removes the file manager context-menu entry ("Convert with Filee") and Send To shortcut.</summary>
+ void SetContextMenu(bool enabled, string executablePath, string label);
+
+ /// <summary>Opens a folder in the file manager and selects the file, if given.</summary>
+ void RevealInFileManager(string path);
+}
+
+/// <summary>Fallback used on platforms without an implementation yet. Everything is a no-op.</summary>
+public sealed class NullPlatformServices : IPlatformServices
+{
+ public bool IsFileManagerAt(int x, int y) => true;
+ public string? ProcessNameAt(int x, int y) => null;
+ public IReadOnlyList<string> GetFileManagerSelection() => [];
+ public int SystemDragThreshold => 4;
+ public bool PrefersReducedMotion => false;
+ public void SetStartWithSystem(bool enabled, string executablePath) { }
+ public void SetContextMenu(bool enabled, string executablePath, string label) { }
+
+ public void RevealInFileManager(string path)
+ {
+ var target = Directory.Exists(path) ? path : Path.GetDirectoryName(path);
+ if (target is null)
+ return;
+ var opener = OperatingSystem.IsMacOS() ? "open" : "xdg-open";
+ System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(opener, $"\"{target}\"") { UseShellExecute = false });
+ }
+}
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
new file mode 100644
index 00000000..8760d66f
--- /dev/null
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -0,0 +1,97 @@
+// Factory defaults: presets and toolbar profiles created on first run or "Reset to defaults".
+
+using Filee.Core.Profiles;
+
+namespace Filee.Core.Presets;
+
+/// <summary>Built-in presets and profiles.</summary>
+public static class BuiltInData
+{
+ /// <summary>Special target format meaning "same format as the source file" (e.g. resize only).</summary>
+ public const string SameAsSource = "*";
+
+ /// <summary>Creates the default preset list.</summary>
+ public static List<Preset> CreatePresets() =>
+ [
+ new() { Id = "to-png", Name = "PNG", TargetFormat = "png" },
+ new() { Id = "to-jpg", Name = "JPG", TargetFormat = "jpg", Image = { Quality = 90 } },
+ new()
+ {
+ Id = "jpg-70", Name = "JPG 70%", TargetFormat = "jpg",
+ Image = { Quality = 70 }, Output = { FileNamePattern = "{name}_70" },
+ },
+ new() { Id = "to-webp", Name = "WEBP", TargetFormat = "webp", Image = { Quality = 85 } },
+ new() { Id = "to-tiff", Name = "TIFF", TargetFormat = "tiff" },
+ new() { Id = "to-bmp", Name = "BMP", TargetFormat = "bmp" },
+ new() { Id = "to-ico", Name = "ICO", TargetFormat = "ico" },
+ new() { Id = "to-gif", Name = "GIF", TargetFormat = "gif" },
+ new() { Id = "to-avif", Name = "AVIF", TargetFormat = "avif", Image = { Quality = 60 } },
+ new()
+ {
+ Id = "half-size", NameKey = "preset.half_size", TargetFormat = SameAsSource,
+ Image = { Resize = ResizeMode.Percent, ResizePercent = 50 }, Output = { FileNamePattern = "{name}_50" },
+ },
+ new()
+ {
+ Id = "grayscale", NameKey = "preset.grayscale", TargetFormat = SameAsSource,
+ Image = { Grayscale = true }, Output = { FileNamePattern = "{name}_gray" },
+ },
+ new()
+ {
+ Id = "tiff-300", Name = "TIFF 300dpi", TargetFormat = "tiff",
+ Image = { Dpi = 300 }, Pdf = { RenderDpi = 300 }, Output = { FileNamePattern = "{name}_300dpi" },
+ },
+ new() { Id = "to-pdf", Name = "PDF", TargetFormat = "pdf" },
+ new()
+ {
+ Id = "merge-pdf", NameKey = "preset.merge_pdf", TargetFormat = "pdf",
+ Pdf = { MergeIntoSingle = true }, Output = { FileNamePattern = "{name}_merged" },
+ },
+ new()
+ {
+ Id = "pdf-split", NameKey = "preset.split_pdf", TargetFormat = "pdf",
+ Pdf = { SplitPages = true }, Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}" },
+ },
+ new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
+ new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
+ new() { Id = "to-odt", Name = "ODT", TargetFormat = "odt" },
+ new() { Id = "to-rtf", Name = "RTF", TargetFormat = "rtf" },
+ new() { Id = "to-txt", Name = "TXT", TargetFormat = "txt" },
+ new() { Id = "to-md", Name = "Markdown", TargetFormat = "md" },
+ new() { Id = "to-html", Name = "HTML", TargetFormat = "html" },
+ ];
+
+ /// <summary>Creates the default toolbar profiles.</summary>
+ public static List<ToolbarProfile> CreateProfiles() =>
+ [
+ new()
+ {
+ Id = "images", NameKey = "profile.images",
+ Extensions = ["png", "jpg", "jpeg", "jpe", "jfif", "webp", "tiff", "tif", "bmp", "dib", "gif", "ico", "avif", "heic", "heif"],
+ PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "to-tiff", "to-bmp", "to-ico", "half-size"],
+ },
+ new()
+ {
+ Id = "pdf", NameKey = "profile.pdf",
+ Extensions = ["pdf"],
+ PresetIds = ["to-png", "to-jpg", "to-docx", "to-hwpx", "to-txt", "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"],
+ },
+ new()
+ {
+ Id = "hwp", NameKey = "profile.hwp",
+ Extensions = ["hwp", "hwpx"],
+ PresetIds = ["to-pdf", "to-docx", "to-hwpx", "to-png", "to-txt", "to-md", "merge-pdf"],
+ },
+ new()
+ {
+ Id = "mixed", NameKey = "profile.mixed", IsFallback = true,
+ PresetIds = ["to-pdf", "merge-pdf", "to-png", "to-txt"],
+ },
+ ];
+}
diff --git a/src/Filee.Core/Presets/OutputPathResolver.cs b/src/Filee.Core/Presets/OutputPathResolver.cs
new file mode 100644
index 00000000..39ca7e98
--- /dev/null
+++ b/src/Filee.Core/Presets/OutputPathResolver.cs
@@ -0,0 +1,89 @@
+// Turns an OutputRule + source file into the concrete output path. Pure logic, unit tested.
+
+using System.Text;
+
+namespace Filee.Core.Presets;
+
+/// <summary>Resolves output file paths from <see cref="OutputRule"/>s.</summary>
+public static class OutputPathResolver
+{
+ /// <summary>Values available to file name pattern tokens.</summary>
+ public readonly record struct Tokens(string SourcePath, string PresetName, int Index, DateTime Now);
+
+ /// <summary>
+ /// Computes the output path for one output file.
+ /// </summary>
+ /// <param name="rule">Placement rule of the preset.</param>
+ /// <param name="tokens">Token values for the file name pattern.</param>
+ /// <param name="targetExtension">Extension of the output, without dot.</param>
+ /// <param name="exists">Returns true if a path is already taken (on disk or reserved by this batch).</param>
+ /// <param name="suffix">Optional suffix appended to the name, e.g. <c>"_p3"</c> for page 3.</param>
+ /// <returns>The path to write, or <c>null</c> when the rule says to skip an existing file.</returns>
+ public static string? Resolve(OutputRule rule, Tokens tokens, string targetExtension,
+ Func<string, bool> exists, string? suffix = null)
+ {
+ var sourceDir = Path.GetDirectoryName(Path.GetFullPath(tokens.SourcePath)) ?? "";
+ var dir = rule.Location switch
+ {
+ OutputLocation.Subfolder => Path.Combine(sourceDir, Sanitize(ExpandPattern(rule.SubfolderName, tokens), "converted")),
+ OutputLocation.CustomFolder when !string.IsNullOrWhiteSpace(rule.CustomFolder) => rule.CustomFolder,
+ _ => sourceDir,
+ };
+
+ var sourceName = Path.GetFileNameWithoutExtension(tokens.SourcePath);
+ var name = Sanitize(ExpandPattern(rule.FileNamePattern, tokens), sourceName) + suffix;
+ var ext = targetExtension.TrimStart('.');
+ var candidate = Path.Combine(dir, $"{name}.{ext}");
+
+ // The source file is never overwritten, whatever the policy says.
+ var isSource = PathsEqual(candidate, tokens.SourcePath);
+ if (!isSource && !exists(candidate))
+ return candidate;
+
+ if (!isSource && rule.Conflict == ConflictPolicy.Overwrite)
+ return candidate;
+ if (!isSource && rule.Conflict == ConflictPolicy.Skip)
+ return null;
+
+ for (var n = 2; ; n++)
+ {
+ candidate = Path.Combine(dir, $"{name} ({n}).{ext}");
+ if (!exists(candidate) && !PathsEqual(candidate, tokens.SourcePath))
+ return candidate;
+ }
+ }
+
+ /// <summary>Replaces <c>{token}</c> placeholders in a file name pattern.</summary>
+ public static string ExpandPattern(string pattern, Tokens tokens)
+ {
+ if (string.IsNullOrWhiteSpace(pattern))
+ pattern = "{name}";
+
+ var ext = Path.GetExtension(tokens.SourcePath).TrimStart('.');
+ return pattern
+ .Replace("{name}", Path.GetFileNameWithoutExtension(tokens.SourcePath), StringComparison.OrdinalIgnoreCase)
+ .Replace("{ext}", ext, StringComparison.OrdinalIgnoreCase)
+ .Replace("{preset}", tokens.PresetName, StringComparison.OrdinalIgnoreCase)
+ .Replace("{date}", tokens.Now.ToString("yyyyMMdd"), StringComparison.OrdinalIgnoreCase)
+ .Replace("{time}", tokens.Now.ToString("HHmmss"), StringComparison.OrdinalIgnoreCase)
+ .Replace("{index}", tokens.Index.ToString(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// <summary>Removes characters that are invalid in file names on any supported OS.</summary>
+ public static string Sanitize(string name, string fallback)
+ {
+ var invalid = Path.GetInvalidFileNameChars().Concat(['<', '>', ':', '"', '/', '\\', '|', '?', '*']).ToHashSet();
+ var sb = new StringBuilder(name.Length);
+ foreach (var c in name)
+ sb.Append(invalid.Contains(c) || char.IsControl(c) ? '_' : c);
+
+ var result = sb.ToString().Trim().TrimEnd('.');
+ return result.Length == 0 ? fallback : result;
+ }
+
+ private static bool PathsEqual(string a, string b) =>
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b),
+ OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()
+ ? StringComparison.OrdinalIgnoreCase
+ : StringComparison.Ordinal);
+}
diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs
new file mode 100644
index 00000000..e9bdf579
--- /dev/null
+++ b/src/Filee.Core/Presets/OutputRule.cs
@@ -0,0 +1,46 @@
+// Output location / file naming / conflict handling for a preset.
+
+namespace Filee.Core.Presets;
+
+/// <summary>Where converted files go.</summary>
+public enum OutputLocation
+{
+ /// <summary>Next to the source file.</summary>
+ SameFolder,
+ /// <summary>In a sub folder (see <see cref="OutputRule.SubfolderName"/>) next to the source file.</summary>
+ Subfolder,
+ /// <summary>In a fixed folder (see <see cref="OutputRule.CustomFolder"/>).</summary>
+ CustomFolder,
+}
+
+/// <summary>What to do when the output file already exists.</summary>
+public enum ConflictPolicy
+{
+ /// <summary>Append " (2)", " (3)" ... to the file name.</summary>
+ Rename,
+ /// <summary>Replace the existing file (never the source file itself).</summary>
+ Overwrite,
+ /// <summary>Leave the existing file alone and skip this conversion.</summary>
+ Skip,
+}
+
+/// <summary>Output placement and naming rules.</summary>
+public sealed class OutputRule
+{
+ public OutputLocation Location { get; set; } = OutputLocation.SameFolder;
+
+ public string SubfolderName { get; set; } = "converted";
+
+ public string CustomFolder { get; set; } = "";
+
+ /// <summary>
+ /// File name pattern without extension. Tokens:
+ /// <c>{name}</c> source name, <c>{ext}</c> source extension, <c>{preset}</c> preset name,
+ /// <c>{date}</c> yyyyMMdd, <c>{time}</c> HHmmss, <c>{index}</c> 1-based position in the batch.
+ /// </summary>
+ public string FileNamePattern { get; set; } = "{name}";
+
+ public ConflictPolicy Conflict { get; set; } = ConflictPolicy.Rename;
+
+ public OutputRule Clone() => (OutputRule)MemberwiseClone();
+}
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
new file mode 100644
index 00000000..2b031622
--- /dev/null
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -0,0 +1,155 @@
+// A preset is one slice of the donut toolbar: "convert to <TargetFormat> with these options".
+
+namespace Filee.Core.Presets;
+
+/// <summary>
+/// A named conversion recipe. The donut toolbar shows presets; dropping files on one runs it.
+/// </summary>
+/// <remarks>
+/// Presets are plain mutable objects so they serialize to JSON directly and the editor can bind to them.
+/// Use <see cref="Clone"/> before editing so that "Cancel" can discard changes.
+/// </remarks>
+public sealed class Preset
+{
+ /// <summary>Stable identifier referenced by toolbar profiles. Never shown to users.</summary>
+ public string Id { get; set; } = NewId();
+
+ /// <summary>User-defined name. When empty, <see cref="NameKey"/> is localized and shown instead.</summary>
+ public string Name { get; set; } = "";
+
+ /// <summary>Localization key for built-in presets (e.g. <c>preset.merge_pdf</c>). Ignored when <see cref="Name"/> is set.</summary>
+ public string? NameKey { get; set; }
+
+ /// <summary>Id of the output format (see <see cref="Formats.FormatRegistry"/>).</summary>
+ public string TargetFormat { get; set; } = "png";
+
+ /// <summary>Options used when the output is a raster image.</summary>
+ public ImageOptions Image { get; set; } = new();
+
+ /// <summary>Options used when the input or output is a PDF.</summary>
+ public PdfOptions Pdf { get; set; } = new();
+
+ /// <summary>Options used for office / HWP documents.</summary>
+ public DocumentOptions Document { get; set; } = new();
+
+ /// <summary>Where and how output files are written.</summary>
+ public OutputRule Output { get; set; } = new();
+
+ /// <summary>Creates a new random preset id.</summary>
+ public static string NewId() => Guid.NewGuid().ToString("N")[..12];
+
+ /// <summary>Deep copy, used by editors so changes can be cancelled.</summary>
+ public Preset Clone() => new()
+ {
+ Id = Id,
+ Name = Name,
+ NameKey = NameKey,
+ TargetFormat = TargetFormat,
+ Image = Image.Clone(),
+ Pdf = Pdf.Clone(),
+ Document = Document.Clone(),
+ Output = Output.Clone(),
+ };
+}
+
+/// <summary>How an image is resized before it is encoded.</summary>
+public enum ResizeMode
+{
+ /// <summary>Keep the original pixel size.</summary>
+ None,
+ /// <summary>Scale by <see cref="ImageOptions.ResizePercent"/>.</summary>
+ Percent,
+ /// <summary>Scale so the longer edge equals <see cref="ImageOptions.LongEdge"/> (never upscales).</summary>
+ LongEdge,
+}
+
+/// <summary>TIFF compression schemes.</summary>
+public enum TiffCompression
+{
+ None,
+ Lzw,
+ Zip,
+}
+
+/// <summary>Raster image encoding options.</summary>
+public sealed class ImageOptions
+{
+ /// <summary>Lossy quality 1-100 (JPG, WEBP, AVIF).</summary>
+ public int Quality { get; set; } = 90;
+
+ public ResizeMode Resize { get; set; } = ResizeMode.None;
+
+ /// <summary>Scale in percent when <see cref="Resize"/> is <see cref="ResizeMode.Percent"/>.</summary>
+ public int ResizePercent { get; set; } = 50;
+
+ /// <summary>Target long-edge length in pixels when <see cref="Resize"/> is <see cref="ResizeMode.LongEdge"/>.</summary>
+ public int LongEdge { get; set; } = 1920;
+
+ /// <summary>Output DPI written into the file. <c>null</c> keeps the source value.</summary>
+ public int? Dpi { get; set; }
+
+ /// <summary>Keep EXIF / XMP / ICC metadata.</summary>
+ public bool KeepMetadata { get; set; } = true;
+
+ /// <summary>Convert to grayscale.</summary>
+ public bool Grayscale { get; set; }
+
+ /// <summary>Fill colour for transparent pixels when the target has no alpha channel (e.g. JPG).</summary>
+ public string Background { get; set; } = "#FFFFFF";
+
+ public TiffCompression TiffCompression { get; set; } = TiffCompression.Lzw;
+
+ /// <summary>Use lossless WEBP encoding.</summary>
+ public bool WebpLossless { get; set; }
+
+ /// <summary>Icon sizes embedded in an ICO file.</summary>
+ public List<int> IcoSizes { get; set; } = [256, 128, 64, 48, 32, 16];
+
+ public ImageOptions Clone()
+ {
+ var copy = (ImageOptions)MemberwiseClone();
+ copy.IcoSizes = [.. IcoSizes];
+ return copy;
+ }
+}
+
+/// <summary>Page size used when images are placed into a PDF.</summary>
+public enum PdfPageSize
+{
+ /// <summary>Each page has the size of its image.</summary>
+ FitImage,
+ A4,
+ Letter,
+}
+
+/// <summary>PDF related options.</summary>
+public sealed class PdfOptions
+{
+ /// <summary>Combine all dropped files into one PDF instead of one PDF per file.</summary>
+ public bool MergeIntoSingle { get; set; }
+
+ public PdfPageSize PageSize { get; set; } = PdfPageSize.FitImage;
+
+ /// <summary>Page margin in millimetres (ignored for <see cref="PdfPageSize.FitImage"/>).</summary>
+ public double MarginMm { get; set; }
+
+ /// <summary>Resolution used when PDF pages are rendered to images.</summary>
+ public int RenderDpi { get; set; } = 150;
+
+ /// <summary>Pages to process, e.g. <c>"1-3,5"</c>. Empty means all pages.</summary>
+ public string PageRange { get; set; } = "";
+
+ /// <summary>For PDF → PDF: write every page as its own file.</summary>
+ public bool SplitPages { get; set; }
+
+ public PdfOptions Clone() => (PdfOptions)MemberwiseClone();
+}
+
+/// <summary>Options for office and HWP documents.</summary>
+public sealed class DocumentOptions
+{
+ /// <summary>Export PDF/A (archival) when producing PDF from documents.</summary>
+ public bool PdfA { get; set; }
+
+ public DocumentOptions Clone() => (DocumentOptions)MemberwiseClone();
+}
diff --git a/src/Filee.Core/Profiles/ToolbarProfile.cs b/src/Filee.Core/Profiles/ToolbarProfile.cs
new file mode 100644
index 00000000..c2a27e15
--- /dev/null
+++ b/src/Filee.Core/Profiles/ToolbarProfile.cs
@@ -0,0 +1,76 @@
+// A toolbar profile decides which presets the donut shows for a given set of source files.
+
+using Filee.Core.Formats;
+
+namespace Filee.Core.Profiles;
+
+/// <summary>
+/// A donut toolbar layout for one family of source files (e.g. "Images" for jpg/png/...).
+/// </summary>
+public sealed class ToolbarProfile
+{
+ /// <summary>Maximum number of slices on one donut ring.</summary>
+ public const int MaxSlices = 12;
+
+ public string Id { get; set; } = Guid.NewGuid().ToString("N")[..12];
+
+ /// <summary>User-defined name. When empty, <see cref="NameKey"/> is localized instead.</summary>
+ public string Name { get; set; } = "";
+
+ public string? NameKey { get; set; }
+
+ /// <summary>Source extensions (without dot) this profile is used for.</summary>
+ public List<string> Extensions { get; set; } = [];
+
+ /// <summary>
+ /// Used when dropped files match no other profile, or when they span several profiles.
+ /// Exactly one profile should be the fallback.
+ /// </summary>
+ public bool IsFallback { get; set; }
+
+ /// <summary>Preset ids in donut order, clockwise starting at 12 o'clock.</summary>
+ public List<string> PresetIds { get; set; } = [];
+
+ /// <summary>Returns true if the extension (with or without dot) belongs to this profile.</summary>
+ public bool Matches(string extension) =>
+ Extensions.Contains(extension.TrimStart('.'), StringComparer.OrdinalIgnoreCase);
+
+ public ToolbarProfile Clone() => new()
+ {
+ Id = Id,
+ Name = Name,
+ NameKey = NameKey,
+ Extensions = [.. Extensions],
+ IsFallback = IsFallback,
+ PresetIds = [.. PresetIds],
+ };
+}
+
+/// <summary>Chooses the profile for a set of dropped files.</summary>
+public static class ProfileSelector
+{
+ /// <summary>
+ /// Picks the profile matching every file's extension. If the files match different profiles
+ /// (or none), the fallback profile is returned.
+ /// </summary>
+ public static ToolbarProfile? Select(IReadOnlyList<ToolbarProfile> profiles, IEnumerable<string> filePaths)
+ {
+ var extensions = filePaths
+ .Select(p => Path.GetExtension(p).TrimStart('.'))
+ .Distinct(StringComparer.OrdinalIgnoreCase)
+ .ToList();
+
+ if (extensions.Count > 0)
+ {
+ var match = profiles.FirstOrDefault(p => !p.IsFallback && extensions.All(p.Matches));
+ if (match is not null)
+ return match;
+ }
+
+ return profiles.FirstOrDefault(p => p.IsFallback) ?? profiles.FirstOrDefault();
+ }
+
+ /// <summary>Formats of the given files that Filee recognises.</summary>
+ public static IReadOnlyList<FileFormat> DetectFormats(IEnumerable<string> filePaths) =>
+ filePaths.Select(FormatRegistry.Detect).OfType<FileFormat>().Distinct().ToList();
+}
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
new file mode 100644
index 00000000..e6e023e0
--- /dev/null
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -0,0 +1,85 @@
+// Root settings object persisted to settings.json.
+
+namespace Filee.Core.Settings;
+
+public enum ThemeMode
+{
+ System,
+ Light,
+ Dark,
+}
+
+/// <summary>Look and feel.</summary>
+public sealed class ThemeSettings
+{
+ public ThemeMode Mode { get; set; } = ThemeMode.System;
+
+ /// <summary>Accent colour as <c>#RRGGBB</c>.</summary>
+ public string Accent { get; set; } = "#7F77DD";
+
+ /// <summary>Base corner radius in pixels. Larger = "softer" UI.</summary>
+ public double CornerRadius { get; set; } = 16;
+
+ /// <summary>
+ /// Disables animations (for low-end PCs or motion sensitivity).
+ /// <c>null</c> follows the operating system setting.
+ /// </summary>
+ public bool? ReduceMotion { get; set; }
+
+ public ThemeSettings Clone() => (ThemeSettings)MemberwiseClone();
+}
+
+/// <summary>Geometry and appearance of the donut toolbar.</summary>
+public sealed class DonutSettings
+{
+ /// <summary>Outer radius in logical pixels.</summary>
+ public double OuterRadius { get; set; } = 150;
+
+ /// <summary>Inner (hole) radius as a fraction of the outer radius (0.2 - 0.7).</summary>
+ public double HoleRatio { get; set; } = 0.42;
+
+ /// <summary>Background opacity of the slices (0.5 - 1).</summary>
+ public double Opacity { get; set; } = 0.96;
+
+ public DonutSettings Clone() => (DonutSettings)MemberwiseClone();
+}
+
+/// <summary>All user settings except presets and profiles (which have their own files).</summary>
+public sealed class AppSettings
+{
+ /// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
+ public const int CurrentSchemaVersion = 3;
+
+ public int SchemaVersion { get; set; } = CurrentSchemaVersion;
+
+ /// <summary><c>"auto"</c>, <c>"en"</c>, <c>"ko"</c> or <c>"zh-CN"</c>.</summary>
+ public string Language { get; set; } = "auto";
+
+ public bool StartWithSystem { get; set; } = true;
+
+ /// <summary>Show the Explorer "Convert with Filee" context menu entry.</summary>
+ public bool ContextMenuEnabled { get; set; } = true;
+
+ public bool CheckForUpdates { get; set; } = true;
+
+ /// <summary>Temporarily disable all trigger gestures (tray "Pause").</summary>
+ public bool Paused { get; set; }
+
+ public ThemeSettings Theme { get; set; } = new();
+
+ public DonutSettings Donut { get; set; } = new();
+
+ public List<TriggerGesture> Triggers { get; set; } = TriggerGesture.Defaults();
+
+ /// <summary>Process names (without .exe) in which gestures never trigger.</summary>
+ 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", "hwpx-writer", "word", "pandoc", "libreoffice"];
+
+ /// <summary>User-provided executable paths per engine id, overriding auto-detection.</summary>
+ public Dictionary<string, string> EnginePaths { get; set; } = [];
+
+ /// <summary>Set once the first-run welcome has been shown.</summary>
+ public bool FirstRunCompleted { get; set; }
+}
diff --git a/src/Filee.Core/Settings/FileeJsonContext.cs b/src/Filee.Core/Settings/FileeJsonContext.cs
new file mode 100644
index 00000000..5258396b
--- /dev/null
+++ b/src/Filee.Core/Settings/FileeJsonContext.cs
@@ -0,0 +1,30 @@
+// System.Text.Json source generation for everything Filee persists. Reflection-free and trim-safe.
+
+using System.Text.Json.Serialization;
+using Filee.Core.History;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+
+namespace Filee.Core.Settings;
+
+[JsonSourceGenerationOptions(
+ WriteIndented = true,
+ PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
+ UseStringEnumConverter = true,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
+ AllowTrailingCommas = true)]
+[JsonSerializable(typeof(AppSettings))]
+[JsonSerializable(typeof(List<Preset>))]
+[JsonSerializable(typeof(List<ToolbarProfile>))]
+[JsonSerializable(typeof(PresetBundle))]
+[JsonSerializable(typeof(List<HistoryEntry>))]
+internal sealed partial class FileeJsonContext : JsonSerializerContext;
+
+/// <summary>File format used to import / export presets and profiles.</summary>
+public sealed class PresetBundle
+{
+ public int SchemaVersion { get; set; } = 1;
+ public List<Preset> Presets { get; set; } = [];
+ public List<ToolbarProfile> Profiles { get; set; } = [];
+}
diff --git a/src/Filee.Core/Settings/TriggerGesture.cs b/src/Filee.Core/Settings/TriggerGesture.cs
new file mode 100644
index 00000000..b6bcab5c
--- /dev/null
+++ b/src/Filee.Core/Settings/TriggerGesture.cs
@@ -0,0 +1,85 @@
+// Describes what the user has to press to open the donut toolbar. Deliberately flexible:
+// any modifier combination, any mouse button, optional extra key, drag / hold / key-only.
+
+namespace Filee.Core.Settings;
+
+/// <summary>Modifier keys. Left/right variants are treated the same.</summary>
+[Flags]
+public enum ModifierKeys
+{
+ None = 0,
+ Ctrl = 1,
+ Alt = 2,
+ Shift = 4,
+ /// <summary>Windows key on Windows, Command on macOS.</summary>
+ Meta = 8,
+}
+
+/// <summary>Mouse buttons a gesture can use.</summary>
+public enum TriggerMouseButton
+{
+ None,
+ Left,
+ Right,
+ Middle,
+ X1,
+ X2,
+}
+
+/// <summary>What physical action completes the gesture.</summary>
+public enum TriggerKind
+{
+ /// <summary>Hold the modifiers and drag with the mouse button past the threshold. Used for file drags.</summary>
+ Drag,
+ /// <summary>Hold the modifiers and keep the mouse button pressed without moving for <see cref="TriggerGesture.HoldMilliseconds"/>.</summary>
+ Hold,
+ /// <summary>Press the modifiers + <see cref="TriggerGesture.Key"/> (no mouse). Uses the file manager selection.</summary>
+ KeyChord,
+}
+
+/// <summary>Where the gesture is active.</summary>
+public enum TriggerScope
+{
+ /// <summary>Only when the cursor is over the system file manager (Explorer / Finder) or the desktop.</summary>
+ FileManager,
+ /// <summary>Everywhere, except excluded applications.</summary>
+ Anywhere,
+}
+
+/// <summary>A user-configurable gesture that opens the donut toolbar.</summary>
+public sealed class TriggerGesture
+{
+ public string Id { get; set; } = Guid.NewGuid().ToString("N")[..8];
+ public bool Enabled { get; set; } = true;
+ public TriggerKind Kind { get; set; } = TriggerKind.Drag;
+ public ModifierKeys Modifiers { get; set; } = ModifierKeys.Ctrl;
+ public TriggerMouseButton Button { get; set; } = TriggerMouseButton.Left;
+
+ /// <summary>
+ /// Extra non-modifier key (SharpHook <c>KeyCode</c> name without the "Vc" prefix, e.g. <c>"Space"</c>).
+ /// Required for <see cref="TriggerKind.KeyChord"/>, optional otherwise.
+ /// </summary>
+ public string? Key { get; set; }
+
+ /// <summary>Distance in logical pixels the mouse must travel before a drag counts. 0 = system default.</summary>
+ public int DragThreshold { get; set; }
+
+ /// <summary>Press duration for <see cref="TriggerKind.Hold"/>.</summary>
+ public int HoldMilliseconds { get; set; } = 450;
+
+ public TriggerScope Scope { get; set; } = TriggerScope.FileManager;
+
+ public TriggerGesture Clone() => (TriggerGesture)MemberwiseClone();
+
+ /// <summary>Default gestures for the current OS.</summary>
+ public static List<TriggerGesture> Defaults()
+ {
+ // On macOS Ctrl+click means right-click, and Option already means "copy" in Finder.
+ var dragModifier = OperatingSystem.IsMacOS() ? ModifierKeys.Alt : ModifierKeys.Ctrl;
+ return
+ [
+ new() { Kind = TriggerKind.Drag, Modifiers = dragModifier, Button = TriggerMouseButton.Left },
+ new() { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Button = TriggerMouseButton.None, Key = "Space" },
+ ];
+ }
+}
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
new file mode 100644
index 00000000..c7723e3f
--- /dev/null
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -0,0 +1,234 @@
+// Loads and saves settings.json, presets.json, profiles.json and history.json.
+// Writes are atomic (temp file + replace) so a crash never leaves a half-written file.
+
+using System.Text.Json;
+using System.Text.Json.Serialization.Metadata;
+using Filee.Core.History;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Filee.Core.Settings;
+
+/// <summary>
+/// In-memory copy of all user data plus persistence. The app keeps exactly one instance.
+/// </summary>
+public sealed class UserDataStore
+{
+ private const int MaxHistory = 200;
+ private readonly ILogger _log;
+ private readonly object _saveLock = new();
+
+ public UserDataStore(string directory, ILogger<UserDataStore>? log = null)
+ {
+ Directory = directory;
+ _log = log ?? (ILogger)NullLogger.Instance;
+ }
+
+ /// <summary>Default data directory: %APPDATA%\Filee on Windows, ~/Library/Application Support/Filee on macOS.</summary>
+ public static string DefaultDirectory =>
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Filee");
+
+ public string Directory { get; }
+
+ public AppSettings Settings { get; private set; } = new();
+ public List<Preset> Presets { get; private set; } = BuiltInData.CreatePresets();
+ public List<ToolbarProfile> Profiles { get; private set; } = BuiltInData.CreateProfiles();
+ public List<HistoryEntry> History { get; private set; } = [];
+
+ /// <summary>Raised after settings were saved.</summary>
+ public event EventHandler? SettingsChanged;
+
+ /// <summary>Raised after presets or profiles were saved.</summary>
+ public event EventHandler? LibraryChanged;
+
+ /// <summary>Raised after a history entry was added.</summary>
+ public event EventHandler? HistoryChanged;
+
+ private string SettingsPath => Path.Combine(Directory, "settings.json");
+ private string PresetsPath => Path.Combine(Directory, "presets.json");
+ private string ProfilesPath => Path.Combine(Directory, "profiles.json");
+ private string HistoryPath => Path.Combine(Directory, "history.json");
+
+ /// <summary>Loads everything from disk, falling back to defaults for missing or corrupt files.</summary>
+ public void Load()
+ {
+ System.IO.Directory.CreateDirectory(Directory);
+ Settings = Read(SettingsPath, FileeJsonContext.Default.AppSettings) ?? new AppSettings();
+ Presets = Read(PresetsPath, FileeJsonContext.Default.ListPreset) ?? BuiltInData.CreatePresets();
+ Profiles = Read(ProfilesPath, FileeJsonContext.Default.ListToolbarProfile) ?? BuiltInData.CreateProfiles();
+ History = Read(HistoryPath, FileeJsonContext.Default.ListHistoryEntry) ?? [];
+
+ SettingsMigrations.Apply(Settings);
+ EnsureConsistency();
+ }
+
+ public void SaveSettings()
+ {
+ Write(SettingsPath, Settings, FileeJsonContext.Default.AppSettings);
+ SettingsChanged?.Invoke(this, EventArgs.Empty);
+ }
+
+ public void SaveLibrary()
+ {
+ EnsureConsistency();
+ Write(PresetsPath, Presets, FileeJsonContext.Default.ListPreset);
+ Write(ProfilesPath, Profiles, FileeJsonContext.Default.ListToolbarProfile);
+ LibraryChanged?.Invoke(this, EventArgs.Empty);
+ }
+
+ public void AddHistory(HistoryEntry entry)
+ {
+ lock (_saveLock)
+ {
+ History.Insert(0, entry);
+ if (History.Count > MaxHistory)
+ History.RemoveRange(MaxHistory, History.Count - MaxHistory);
+ }
+ Write(HistoryPath, History, FileeJsonContext.Default.ListHistoryEntry);
+ HistoryChanged?.Invoke(this, EventArgs.Empty);
+ }
+
+ public void ClearHistory()
+ {
+ lock (_saveLock)
+ History.Clear();
+ Write(HistoryPath, History, FileeJsonContext.Default.ListHistoryEntry);
+ HistoryChanged?.Invoke(this, EventArgs.Empty);
+ }
+
+ /// <summary>Replaces presets and profiles with factory defaults.</summary>
+ public void ResetLibrary()
+ {
+ Presets = BuiltInData.CreatePresets();
+ Profiles = BuiltInData.CreateProfiles();
+ SaveLibrary();
+ }
+
+ public Preset? FindPreset(string id) => Presets.FirstOrDefault(p => p.Id == id);
+
+ /// <summary>Exports presets and profiles to a shareable JSON file.</summary>
+ public void Export(string path) =>
+ Write(path, new PresetBundle { Presets = Presets, Profiles = Profiles }, FileeJsonContext.Default.PresetBundle);
+
+ /// <summary>
+ /// Imports presets and profiles from a bundle. Items with an existing id are replaced, new ones added.
+ /// </summary>
+ /// <returns>Number of imported presets + profiles.</returns>
+ public int Import(string path)
+ {
+ using var stream = File.OpenRead(path);
+ var bundle = JsonSerializer.Deserialize(stream, FileeJsonContext.Default.PresetBundle)
+ ?? throw new InvalidDataException("Empty preset bundle.");
+
+ foreach (var preset in bundle.Presets)
+ {
+ Presets.RemoveAll(p => p.Id == preset.Id);
+ Presets.Add(preset);
+ }
+ foreach (var profile in bundle.Profiles)
+ {
+ Profiles.RemoveAll(p => p.Id == profile.Id);
+ profile.IsFallback = false; // keep our own fallback
+ Profiles.Add(profile);
+ }
+ SaveLibrary();
+ return bundle.Presets.Count + bundle.Profiles.Count;
+ }
+
+ /// <summary>Removes dangling preset references and guarantees exactly one fallback profile.</summary>
+ private void EnsureConsistency()
+ {
+ var ids = Presets.Select(p => p.Id).ToHashSet();
+ foreach (var profile in Profiles)
+ {
+ profile.PresetIds = profile.PresetIds.Where(ids.Contains).Distinct().Take(ToolbarProfile.MaxSlices).ToList();
+ }
+
+ var fallbacks = Profiles.Where(p => p.IsFallback).ToList();
+ if (fallbacks.Count == 0)
+ {
+ var mixed = BuiltInData.CreateProfiles().First(p => p.IsFallback);
+ mixed.PresetIds = mixed.PresetIds.Where(ids.Contains).ToList();
+ Profiles.Add(mixed);
+ }
+ foreach (var extra in fallbacks.Skip(1))
+ extra.IsFallback = false;
+ }
+
+ private T? Read<T>(string path, JsonTypeInfo<T> type) where T : class
+ {
+ if (!File.Exists(path))
+ return null;
+ try
+ {
+ using var stream = File.OpenRead(path);
+ return JsonSerializer.Deserialize(stream, type);
+ }
+ catch (Exception ex) when (ex is JsonException or IOException or NotSupportedException)
+ {
+ // Keep the broken file for inspection and continue with defaults.
+ _log.LogWarning(ex, "Could not read {Path}; using defaults", path);
+ try
+ {
+ File.Copy(path, path + ".broken", overwrite: true);
+ }
+ catch (IOException) { }
+ return null;
+ }
+ }
+
+ private void Write<T>(string path, T value, JsonTypeInfo<T> type)
+ {
+ lock (_saveLock)
+ {
+ System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ var temp = path + ".tmp";
+ using (var stream = File.Create(temp))
+ JsonSerializer.Serialize(stream, value, type);
+ File.Move(temp, path, overwrite: true);
+ }
+ }
+}
+
+/// <summary>Upgrades settings written by older versions. Add one step per schema bump.</summary>
+internal static class SettingsMigrations
+{
+ public static void Apply(AppSettings settings)
+ {
+ // v2: engines "pandoc-hwpx" (HWPX without Hancom Office, placed before "hancom" so HWPX saving needs
+ // no approval dialog) and "pandoc" (Markdown) were added.
+ if (settings.SchemaVersion < 2)
+ {
+ InsertBefore(settings.EnginePriority, "pandoc-hwpx", "hancom");
+ InsertBefore(settings.EnginePriority, "pandoc", "libreoffice");
+ }
+
+ // v3: the Hancom Office engine was removed (rhwp converts HWP <-> HWPX without the approval dialog of 한글)
+ // and "pandoc-hwpx" became "hwpx-writer" (DOCX is read without Pandoc).
+ if (settings.SchemaVersion < 3)
+ {
+ settings.EnginePriority.Remove("hancom");
+ var index = settings.EnginePriority.IndexOf("pandoc-hwpx");
+ if (index >= 0)
+ settings.EnginePriority[index] = "hwpx-writer";
+ }
+
+ if (settings.Triggers.Count == 0)
+ settings.Triggers = TriggerGesture.Defaults();
+
+ settings.SchemaVersion = AppSettings.CurrentSchemaVersion;
+ }
+
+ private static void InsertBefore(List<string> list, string id, string before)
+ {
+ if (list.Contains(id))
+ return;
+ var index = list.IndexOf(before);
+ if (index < 0)
+ list.Add(id);
+ else
+ list.Insert(index, id);
+ }
+}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
new file mode 100644
index 00000000..113517fd
--- /dev/null
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -0,0 +1,36 @@
+// THE place where conversion engines are registered. Adding an engine = one line in CreateAll.
+
+using Filee.Core.Conversion;
+using Filee.Engines.Hwp;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Magick;
+using Filee.Engines.Office;
+using Filee.Engines.Pdf;
+
+namespace Filee.Engines;
+
+/// <summary>Creates every built-in converter.</summary>
+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.
+ /// </summary>
+ public static IReadOnlyList<IConverter> CreateAll(EngineEnvironment env) =>
+ [
+ new MagickImageConverter(),
+ new PdfSharpConverter(),
+ new PdfiumConverter(),
+ new RhwpConverter(env),
+ new UnhwpConverter(),
+ new HwpxConverter(env),
+ new WordComConverter(),
+ new PandocConverter(env),
+ new LibreOfficeConverter(env),
+ ];
+
+ /// <summary>Finds the PDF merger among the converters.</summary>
+ public static IPdfMerger? FindPdfMerger(IEnumerable<IConverter> converters) =>
+ converters.OfType<IPdfMerger>().FirstOrDefault();
+}
diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj
new file mode 100644
index 00000000..6052b884
--- /dev/null
+++ b/src/Filee.Engines/Filee.Engines.csproj
@@ -0,0 +1,33 @@
+<!--
+ Filee.Engines: IConverter implementations (one file per engine) and helpers to find external tools.
+ Register new engines in EngineRegistry.cs.
+-->
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <RootNamespace>Filee.Engines</RootNamespace>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Magick.NET-Q8-AnyCPU" />
+ <PackageReference Include="PDFsharp" />
+ <PackageReference Include="PDFtoImage" />
+ <PackageReference Include="Unhwp" />
+ <PackageReference Include="Markdig" />
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <InternalsVisibleTo Include="Filee.Engines.Tests" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <!-- Reference HWPX (styles, page setup) from pypandoc-hwpx (MIT), see Hwp/Hwpx/HwpxWriter.cs. -->
+ <EmbeddedResource Include="Hwp\Hwpx\blank.hwpx" LogicalName="Filee.Engines.Hwpx.blank.hwpx" />
+ <!-- Pinned downloads of optional engines, also read by build/fetch-engines.ps1. -->
+ <EmbeddedResource Include="Infrastructure\engines.json" LogicalName="Filee.Engines.engines.json" />
+ </ItemGroup>
+</Project>
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
new file mode 100644
index 00000000..1bf67d03
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs
@@ -0,0 +1,521 @@
+// DOCX graphic objects: DrawingML pictures, text boxes (wps), groups and drawing canvases, plus legacy VML
+// (w:pict / w:object) used by older documents and as the fallback of mc:AlternateContent.
+
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal sealed partial class DocxReader
+{
+ private static readonly XNamespace Wpc = "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas";
+ private static readonly XNamespace W10 = "urn:schemas-microsoft-com:office:word";
+
+ /// <summary>Default DrawingML text box insets: 0.1" left/right, 0.05" top/bottom.</summary>
+ private static readonly HInsets DefaultTextBoxPadding = new(720, 720, 360, 360);
+
+ private readonly Dictionary<string, string> _themeColors = [];
+
+ private IEnumerable<HInline> Drawing(XElement drawing)
+ {
+ foreach (var container in drawing.Elements())
+ {
+ var anchored = container.Name == Wp + "anchor";
+ if (!anchored && container.Name != Wp + "inline")
+ continue;
+ var extent = container.Element(Wp + "extent");
+ var width = HwpxUnits.FromEmu(Long(extent, "cx") ?? 0);
+ var height = HwpxUnits.FromEmu(Long(extent, "cy") ?? 0);
+ var anchor = anchored ? Anchor(container) : null;
+ var data = container.Element(A + "graphic")?.Element(A + "graphicData");
+ foreach (var inline in GraphicObjects(data?.Elements() ?? [], width, height, anchor, (0, 0, 1, 1)))
+ yield return inline;
+ }
+ }
+
+ /// <summary>
+ /// Pictures and text boxes of a graphic frame. Members of groups and canvases become separate objects placed at
+ /// their position inside the group (<paramref name="groupTransform"/>: offset and scale of the child coordinates).
+ /// </summary>
+ private IEnumerable<HInline> GraphicObjects(IEnumerable<XElement> objects, int width, int height, HAnchor? anchor,
+ (double X, double Y, double ScaleX, double ScaleY) groupTransform)
+ {
+ foreach (var obj in objects)
+ {
+ if (obj.Name == Pic + "pic")
+ {
+ if (Picture(obj, width, height, anchor) is { } picture)
+ yield return picture;
+ }
+ else if (obj.Name == Wps + "wsp")
+ {
+ if (Shape(obj, width, height, anchor) is { } shape)
+ yield return shape;
+ }
+ else if (obj.Name == Wpg + "wgp" || obj.Name == Wpg + "grpSp" || obj.Name == Wpc + "wpc")
+ {
+ foreach (var inline in Group(obj, width, height, anchor, groupTransform))
+ yield return inline;
+ }
+ }
+ }
+
+ private IEnumerable<HInline> Group(XElement group, int width, int height, HAnchor? anchor,
+ (double X, double Y, double ScaleX, double ScaleY) parent)
+ {
+ var xfrm = group.Element(Wpg + "grpSpPr")?.Element(A + "xfrm") ?? group.Element(A + "grpSpPr")?.Element(A + "xfrm");
+ var chOff = xfrm?.Element(A + "chOff");
+ var chExt = xfrm?.Element(A + "chExt");
+ // Child coordinates → HWPUNIT relative to the group's top-left corner.
+ var scaleX = (Long(chExt, "cx") ?? 0) > 0 ? width / (double)Long(chExt, "cx")! : 1 / 127.0;
+ var scaleY = (Long(chExt, "cy") ?? 0) > 0 ? height / (double)Long(chExt, "cy")! : 1 / 127.0;
+ var originX = Long(chOff, "x") ?? 0;
+ var originY = Long(chOff, "y") ?? 0;
+
+ foreach (var child in group.Elements())
+ {
+ var childXfrm = child.Descendants(A + "xfrm").FirstOrDefault();
+ var off = childXfrm?.Element(A + "off");
+ var childExt = childXfrm?.Element(A + "ext");
+ var x = (int)(((Long(off, "x") ?? 0) - originX) * scaleX);
+ var y = (int)(((Long(off, "y") ?? 0) - originY) * scaleY);
+ var childWidth = (int)((Long(childExt, "cx") ?? 0) * scaleX);
+ var childHeight = (int)((Long(childExt, "cy") ?? 0) * scaleY);
+
+ // An inline group becomes objects floating over the paragraph at the same place.
+ var childAnchor = anchor is null
+ ? new HAnchor("COLUMN", "LEFT", x, "PARA", "TOP", y, "IN_FRONT_OF_TEXT", true)
+ : anchor with
+ {
+ HorizontalOffset = anchor.HorizontalOffset + AlignedOffset(anchor.HorizontalAlign, x, childWidth, width),
+ VerticalOffset = anchor.VerticalOffset + AlignedOffset(anchor.VerticalAlign, y, childHeight, height),
+ AllowOverlap = true,
+ };
+ foreach (var inline in GraphicObjects([child], childWidth, childHeight, childAnchor, parent))
+ yield return inline;
+ }
+ }
+
+ /// <summary>
+ /// Offset of a group member when the group is aligned (centered, right-aligned ...) rather than placed at an
+ /// offset: the member keeps its distance from the group's center or far edge.
+ /// </summary>
+ private static int AlignedOffset(string align, int position, int size, int groupSize) => align switch
+ {
+ "CENTER" => position + size / 2 - groupSize / 2,
+ "RIGHT" or "BOTTOM" => position + size - groupSize,
+ _ => position,
+ };
+
+ private HImage? Picture(XElement pic, int width, int height, HAnchor? anchor)
+ {
+ var blip = pic.Descendants(A + "blip").FirstOrDefault();
+ var path = ExtractImage(Attr(blip, "embed", R));
+ return path is null ? null : new HImage(path) { Width = width > 0 ? width : null, Height = height > 0 ? height : null, Anchor = anchor };
+ }
+
+ /// <summary>A text box, or a rectangle / ellipse / line without text. Other geometries are skipped.</summary>
+ private HInline? Shape(XElement wsp, int width, int height, HAnchor? anchor)
+ {
+ var spPr = wsp.Element(Wps + "spPr");
+ var style = wsp.Element(Wps + "style");
+ var (fill, gradient) = FillOf(spPr, style);
+ var geometry = Attr(spPr?.Element(A + "prstGeom"), "prst");
+ if (wsp.Element(Wps + "txbx")?.Element(W + "txbxContent") is { } content)
+ {
+ if (geometry is "rect" or "roundRect" or "flowChartProcess" or "flowChartAlternateProcess")
+ return TextBox(wsp, content, width, height, anchor, fill ?? gradient?.Colors[0]);
+ // Text on a free-form or decorative shape: keep the text, drop the outline 한글 cannot draw.
+ if (string.IsNullOrWhiteSpace(content.Value))
+ return null;
+ var box = TextBox(wsp, content, width, height, anchor, fill: null);
+ box.Line = HBorder.None;
+ return box;
+ }
+
+ HShapeKind? kind = geometry switch
+ {
+ "rect" or "roundRect" or "snip1Rect" or "snip2SameRect" or "round1Rect" or "round2SameRect"
+ or "flowChartProcess" or "flowChartAlternateProcess" or "frame" => HShapeKind.Rectangle,
+ "ellipse" or "flowChartConnector" => HShapeKind.Ellipse,
+ "line" or "straightConnector1" => HShapeKind.Line,
+ _ => null, // free-form and other preset shapes have no 한글 equivalent
+ };
+ if (kind is null)
+ return null;
+ var xfrm = spPr?.Element(A + "xfrm");
+ return new HShape(kind.Value)
+ {
+ Width = width,
+ Height = height,
+ Anchor = anchor,
+ Fill = kind == HShapeKind.Line ? null : fill,
+ Gradient = kind == HShapeKind.Line ? null : gradient,
+ Line = Line(spPr?.Element(A + "ln"), style),
+ CornerRatio = geometry is "roundRect" or "round1Rect" or "round2SameRect" or "flowChartAlternateProcess" ? 20 : 0,
+ FlipHorizontal = Attr(xfrm, "flipH") is "1" or "true",
+ FlipVertical = Attr(xfrm, "flipV") is "1" or "true",
+ };
+ }
+
+ private HTextBox TextBox(XElement wsp, XElement content, int width, int height, HAnchor? anchor, string? fill)
+ {
+ var spPr = wsp.Element(Wps + "spPr");
+ var bodyPr = wsp.Element(Wps + "bodyPr");
+ var box = new TextBoxBuilder(width, height, anchor)
+ {
+ Fill = fill,
+ Line = Line(spPr?.Element(A + "ln"), wsp.Element(Wps + "style")),
+ Padding = new HInsets(
+ Inset(bodyPr, "lIns", DefaultTextBoxPadding.Left), Inset(bodyPr, "rIns", DefaultTextBoxPadding.Right),
+ Inset(bodyPr, "tIns", DefaultTextBoxPadding.Top), Inset(bodyPr, "bIns", DefaultTextBoxPadding.Bottom)),
+ VerticalAlign = Attr(bodyPr, "anchor") switch
+ {
+ "ctr" => HVerticalAlign.Center,
+ "b" => HVerticalAlign.Bottom,
+ _ => HVerticalAlign.Top,
+ },
+ }.Build();
+ ReadTextBoxContent(content, box.Blocks);
+ return box;
+ }
+
+ /// <summary>Text box paragraphs; Word's document grid does not apply inside text boxes.</summary>
+ private void ReadTextBoxContent(XElement content, List<HBlock> output)
+ {
+ _textBoxDepth++;
+ try
+ {
+ ReadBlocks(content.Elements(), output);
+ }
+ finally
+ {
+ _textBoxDepth--;
+ }
+ }
+
+ /// <summary>Collects text box settings before the HTextBox (whose Blocks list is read-only) is created.</summary>
+ private sealed class TextBoxBuilder(int width, int height, HAnchor? anchor)
+ {
+ public string? Fill { get; init; }
+ public HBorder Line { get; init; } = HBorder.Thin;
+ public HInsets Padding { get; init; } = DefaultTextBoxPadding;
+ public HVerticalAlign VerticalAlign { get; init; }
+
+ public HTextBox Build() => new()
+ {
+ Width = Math.Max(width, 1000),
+ Height = Math.Max(height, 600),
+ Anchor = anchor,
+ Fill = Fill,
+ Line = Line,
+ Padding = Padding,
+ VerticalAlign = VerticalAlign,
+ };
+ }
+
+ private static int Inset(XElement? bodyPr, string name, int fallback) =>
+ Long(bodyPr, name) is { } emu ? HwpxUnits.FromEmu(emu) : fallback;
+
+ /// <summary>Solid colour or linear gradient of a shape; without its own fill the shape style decides.</summary>
+ private (string? Solid, HGradient? Gradient) FillOf(XElement? spPr, XElement? style)
+ {
+ if (spPr?.Element(A + "noFill") is not null)
+ return (null, null);
+ if (spPr?.Element(A + "solidFill") is { } solid)
+ return (Color(solid), null);
+ if (spPr?.Element(A + "gradFill") is { } gradient)
+ {
+ var colors = gradient.Element(A + "gsLst")?.Elements(A + "gs")
+ .OrderBy(gs => Long(gs, "pos") ?? 0)
+ .Select(Color)
+ .OfType<string>()
+ .ToList() ?? [];
+ var angle = (int)((Long(gradient.Element(A + "lin"), "ang") ?? 0) / 60000);
+ return colors.Count >= 2 ? (null, new HGradient(colors, angle)) : (colors.FirstOrDefault(), null);
+ }
+ var fillRef = style?.Element(A + "fillRef");
+ return fillRef is not null && Attr(fillRef, "idx") is not (null or "0") ? (Color(fillRef), null) : (null, null);
+ }
+
+ private HBorder Line(XElement? ln, XElement? style)
+ {
+ if (ln is null)
+ {
+ // No explicit outline: the shape style decides (lnRef idx 0 = no line).
+ var lnRef = style?.Element(A + "lnRef");
+ return lnRef is not null && Attr(lnRef, "idx") is not (null or "0")
+ ? HBorder.Thin with { Color = Color(lnRef) ?? "#000000" }
+ : HBorder.None;
+ }
+ if (ln.Element(A + "noFill") is not null)
+ return HBorder.None;
+ var widthMm = Long(ln, "w") is { } emu ? emu / 36000.0 : 0.12;
+ var dash = Attr(ln.Element(A + "prstDash"), "val");
+ var borderStyle = dash switch
+ {
+ null or "solid" => HBorderStyle.Solid,
+ "dot" or "sysDot" => HBorderStyle.Dot,
+ "dashDot" or "sysDashDot" or "lgDashDot" => HBorderStyle.DashDot,
+ _ => HBorderStyle.Dash,
+ };
+ return new HBorder(borderStyle, widthMm, Color(ln.Element(A + "solidFill")) ?? "#000000");
+ }
+
+ /// <summary>Colour of a fill element: srgbClr, sysClr or a theme colour (luminance modifiers are ignored).</summary>
+ private string? Color(XElement? fill)
+ {
+ if (fill is null)
+ return null;
+ if (fill.Element(A + "srgbClr") is { } rgb)
+ return "#" + (Val(rgb) ?? "000000").ToUpperInvariant();
+ if (fill.Element(A + "sysClr") is { } sys)
+ return "#" + (Attr(sys, "lastClr") ?? "000000").ToUpperInvariant();
+ if (fill.Element(A + "schemeClr") is { } scheme)
+ {
+ var name = Val(scheme) switch
+ {
+ "bg1" => "lt1",
+ "tx1" => "dk1",
+ "bg2" => "lt2",
+ "tx2" => "dk2",
+ var other => other ?? "dk1",
+ };
+ return _themeColors.GetValueOrDefault(name, name.StartsWith("lt", StringComparison.Ordinal) ? "#FFFFFF" : "#000000");
+ }
+ return null;
+ }
+
+ private void LoadThemeColors(Part? theme)
+ {
+ foreach (var color in theme?.Xml.Descendants(A + "clrScheme").FirstOrDefault()?.Elements() ?? [])
+ {
+ var value = Val(color.Element(A + "srgbClr")) ?? Attr(color.Element(A + "sysClr"), "lastClr");
+ if (value is { Length: 6 })
+ _themeColors[color.Name.LocalName] = "#" + value.ToUpperInvariant();
+ }
+ }
+
+ /// <summary>Position of a floating DrawingML object (wp:anchor).</summary>
+ private static HAnchor Anchor(XElement anchor)
+ {
+ var horizontal = anchor.Element(Wp + "positionH");
+ var vertical = anchor.Element(Wp + "positionV");
+ var wrap = anchor.Elements().FirstOrDefault(e => e.Name.Namespace == Wp && e.Name.LocalName.StartsWith("wrap", StringComparison.Ordinal))?.Name.LocalName;
+ var behind = Attr(anchor, "behindDoc") is "1" or "true";
+ return new HAnchor(
+ HorizontalRelativeTo: Attr(horizontal, "relativeFrom") switch
+ {
+ "page" or "leftMargin" or "rightMargin" or "insideMargin" or "outsideMargin" => "PAPER",
+ "margin" => "PAGE",
+ "character" => "PARA",
+ _ => "COLUMN",
+ },
+ HorizontalAlign: horizontal?.Element(Wp + "align")?.Value switch
+ {
+ "center" => "CENTER",
+ "right" => "RIGHT",
+ "inside" => "INSIDE",
+ "outside" => "OUTSIDE",
+ _ => "LEFT",
+ },
+ HorizontalOffset: OffsetOf(horizontal),
+ VerticalRelativeTo: Attr(vertical, "relativeFrom") switch
+ {
+ "page" or "topMargin" or "bottomMargin" or "insideMargin" or "outsideMargin" => "PAPER",
+ "margin" => "PAGE",
+ _ => "PARA",
+ },
+ VerticalAlign: vertical?.Element(Wp + "align")?.Value switch
+ {
+ "center" => "CENTER",
+ "bottom" => "BOTTOM",
+ "inside" => "INSIDE",
+ "outside" => "OUTSIDE",
+ _ => "TOP",
+ },
+ VerticalOffset: OffsetOf(vertical),
+ Wrap: wrap switch
+ {
+ "wrapSquare" or "wrapTight" or "wrapThrough" => "SQUARE",
+ "wrapTopAndBottom" => "TOP_AND_BOTTOM",
+ _ => behind ? "BEHIND_TEXT" : "IN_FRONT_OF_TEXT",
+ },
+ AllowOverlap: Attr(anchor, "allowOverlap") is not ("0" or "false"));
+ }
+
+ private static int OffsetOf(XElement? position) =>
+ long.TryParse(position?.Element(Wp + "posOffset")?.Value, out var emu) ? HwpxUnits.FromEmu(emu) : 0;
+
+ private string? ExtractImage(string? relationshipId)
+ {
+ if (relationshipId is null || !_part.Relationships.TryGetValue(relationshipId, out var rel) || rel.External)
+ return null;
+ if (_media.TryGetValue(rel.Target, out var existing))
+ return existing;
+ if (_zip.GetEntry(rel.Target) is not { } entry)
+ return null;
+ Directory.CreateDirectory(_mediaFolder);
+ var path = Path.Combine(_mediaFolder, $"docx-media-{_media.Count + 1}{Path.GetExtension(rel.Target)}");
+ using (var source = entry.Open())
+ using (var target = File.Create(path))
+ source.CopyTo(target);
+ _media[rel.Target] = path;
+ return path;
+ }
+
+ // ───────────────────────── VML (legacy) ─────────────────────────
+
+ private IEnumerable<HInline> Vml(XElement container)
+ {
+ foreach (var shape in container.Elements())
+ {
+ if (shape.Name.Namespace != V)
+ continue;
+ if (shape.Name.LocalName == "group")
+ {
+ foreach (var inline in Vml(shape))
+ yield return inline;
+ continue;
+ }
+ if (shape.Name.LocalName is "shapetype")
+ continue;
+
+ var style = VmlStyle((string?)shape.Attribute("style"));
+ var width = HwpxUnits.ParseLength(style.GetValueOrDefault("width")) ?? 0;
+ var height = HwpxUnits.ParseLength(style.GetValueOrDefault("height")) ?? 0;
+ var anchor = style.GetValueOrDefault("position") == "absolute" ? VmlAnchor(shape, style) : null;
+
+ if (shape.Element(V + "imagedata") is { } imageData && ExtractImage(Attr(imageData, "id", R)) is { } path)
+ {
+ yield return new HImage(path) { Width = width > 0 ? width : null, Height = height > 0 ? height : null, Anchor = anchor };
+ }
+ else if (shape.Element(V + "textbox")?.Element(W + "txbxContent") is { } content)
+ {
+ var box = new TextBoxBuilder(width, height, anchor)
+ {
+ Fill = VmlFill(shape),
+ Line = VmlLine(shape),
+ }.Build();
+ ReadTextBoxContent(content, box.Blocks);
+ yield return box;
+ }
+ else if (shape.Name.LocalName is "rect" or "roundrect" or "oval" or "line")
+ {
+ var kind = shape.Name.LocalName switch
+ {
+ "oval" => HShapeKind.Ellipse,
+ "line" => HShapeKind.Line,
+ _ => HShapeKind.Rectangle,
+ };
+ if (kind == HShapeKind.Line)
+ {
+ // v:line has from="x,y" to="x,y" instead of a size.
+ var from = VmlPoint((string?)shape.Attribute("from"));
+ var to = VmlPoint((string?)shape.Attribute("to"));
+ width = Math.Abs(to.X - from.X);
+ height = Math.Abs(to.Y - from.Y);
+ var lineAnchor = anchor ?? VmlAnchor(shape, style);
+ anchor = lineAnchor with
+ {
+ HorizontalOffset = lineAnchor.HorizontalOffset + Math.Min(from.X, to.X),
+ VerticalOffset = lineAnchor.VerticalOffset + Math.Min(from.Y, to.Y),
+ };
+ }
+ yield return new HShape(kind)
+ {
+ Width = width,
+ Height = height,
+ Anchor = anchor,
+ Fill = kind == HShapeKind.Line ? null : VmlFill(shape),
+ Line = VmlLine(shape),
+ CornerRatio = shape.Name.LocalName == "roundrect" ? 20 : 0,
+ };
+ }
+ }
+ }
+
+ private static string? VmlFill(XElement shape) =>
+ (string?)shape.Attribute("filled") is "f" or "false" ? null : VmlColor((string?)shape.Attribute("fillcolor")) ?? "#FFFFFF";
+
+ private static HBorder VmlLine(XElement shape) =>
+ (string?)shape.Attribute("stroked") is "f" or "false"
+ ? HBorder.None
+ : HBorder.Thin with
+ {
+ Color = VmlColor((string?)shape.Attribute("strokecolor")) ?? "#000000",
+ WidthMm = HwpxUnits.ParseLength((string?)shape.Attribute("strokeweight")) is { } weight ? weight / HwpxUnits.PerMm : 0.12,
+ };
+
+ /// <summary>"x,y" of a VML line end; bare numbers are points.</summary>
+ private static (int X, int Y) VmlPoint(string? point)
+ {
+ var parts = (point ?? "0,0").Split(',');
+ int Coordinate(int index)
+ {
+ var text = parts.ElementAtOrDefault(index)?.Trim() ?? "0";
+ if (text.Length == 0)
+ text = "0";
+ return HwpxUnits.ParseLength(char.IsDigit(text[^1]) ? text + "pt" : text) ?? 0;
+ }
+ return (Coordinate(0), Coordinate(1));
+ }
+
+ private static Dictionary<string, string> VmlStyle(string? style) =>
+ (style ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
+ .Select(p => p.Split(':', 2))
+ .Where(p => p.Length == 2)
+ .GroupBy(p => p[0].Trim().ToLowerInvariant())
+ .ToDictionary(g => g.Key, g => g.Last()[1].Trim());
+
+ private static HAnchor VmlAnchor(XElement shape, Dictionary<string, string> style)
+ {
+ var wrap = (string?)shape.Element(W10 + "wrap")?.Attribute("type");
+ return new HAnchor(
+ HorizontalRelativeTo: style.GetValueOrDefault("mso-position-horizontal-relative") switch
+ {
+ "page" => "PAPER",
+ "margin" => "PAGE",
+ "char" => "PARA",
+ _ => "COLUMN",
+ },
+ HorizontalAlign: style.GetValueOrDefault("mso-position-horizontal") switch
+ {
+ "center" => "CENTER",
+ "right" => "RIGHT",
+ _ => "LEFT",
+ },
+ HorizontalOffset: HwpxUnits.ParseLength(style.GetValueOrDefault("margin-left")) ?? 0,
+ VerticalRelativeTo: style.GetValueOrDefault("mso-position-vertical-relative") switch
+ {
+ "page" => "PAPER",
+ "margin" => "PAGE",
+ _ => "PARA",
+ },
+ VerticalAlign: style.GetValueOrDefault("mso-position-vertical") switch
+ {
+ "center" => "CENTER",
+ "bottom" => "BOTTOM",
+ _ => "TOP",
+ },
+ VerticalOffset: HwpxUnits.ParseLength(style.GetValueOrDefault("margin-top")) ?? 0,
+ Wrap: wrap switch
+ {
+ "square" or "tight" or "through" => "SQUARE",
+ "topAndBottom" => "TOP_AND_BOTTOM",
+ _ => style.TryGetValue("z-index", out var z) && z.StartsWith('-') ? "BEHIND_TEXT" : "IN_FRONT_OF_TEXT",
+ },
+ AllowOverlap: true);
+ }
+
+ /// <summary>VML colours: "#RRGGBB", "#RGB" or "#RRGGBB [index]".</summary>
+ private static string? VmlColor(string? value)
+ {
+ var color = value?.Split(' ')[0].Trim();
+ if (color is null || !color.StartsWith('#'))
+ return null;
+ if (color.Length == 4)
+ color = $"#{color[1]}{color[1]}{color[2]}{color[2]}{color[3]}{color[3]}";
+ return color.Length == 7 && int.TryParse(color.AsSpan(1), NumberStyles.HexNumber, null, out _) ? color.ToUpperInvariant() : null;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
new file mode 100644
index 00000000..ec312a8f
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs
@@ -0,0 +1,543 @@
+// DOCX formatting: styles (with basedOn inheritance), document defaults, theme fonts and list numbering,
+// resolved to the same property bags as direct formatting so each paragraph and run gets one merged format.
+
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal sealed partial class DocxReader
+{
+ /// <summary>
+ /// 한글 line spacing is a percentage of the font size, Word's "multiple" of the font's natural line height
+ /// (about 1.3 em for the fonts Korean documents use). Word "single" therefore corresponds to about 130%.
+ /// </summary>
+ private const double WordLineToHwpPercent = 130;
+
+ // ───────────────────────── Property bags ─────────────────────────
+
+ /// <summary>Paragraph properties; later layers (style → numbering → direct) override earlier ones.</summary>
+ private sealed class ParaProps
+ {
+ public string? Jc;
+ public int? Left, Right, FirstLine, Hanging, Before, After, Line;
+ public string? LineRule;
+ public bool? KeepNext, KeepLines, PageBreakBefore, WidowControl, SnapToGrid;
+ public int? OutlineLevel;
+ public string? NumId;
+ public int? Ilvl;
+ public List<(int Position, string Kind, string Leader)> Tabs = [];
+
+ public ParaProps Clone()
+ {
+ var copy = (ParaProps)MemberwiseClone();
+ copy.Tabs = [.. Tabs];
+ return copy;
+ }
+
+ public void Apply(XElement? pPr)
+ {
+ if (pPr is null)
+ return;
+ if (pPr.Element(W + "jc") is { } jc)
+ Jc = Val(jc);
+ if (pPr.Element(W + "ind") is { } ind)
+ {
+ Left = Twips(ind, "left") ?? Twips(ind, "start") ?? Left;
+ Right = Twips(ind, "right") ?? Twips(ind, "end") ?? Right;
+ if (Twips(ind, "hanging") is { } hanging)
+ (Hanging, FirstLine) = (hanging, null);
+ if (Twips(ind, "firstLine") is { } firstLine)
+ (FirstLine, Hanging) = (firstLine, null);
+ }
+ if (pPr.Element(W + "spacing") is { } spacing)
+ {
+ Before = Bool(spacing, "beforeAutospacing") == true ? 280 : Twips(spacing, "before") ?? Before;
+ After = Bool(spacing, "afterAutospacing") == true ? 280 : Twips(spacing, "after") ?? After;
+ if (Twips(spacing, "line") is { } line)
+ (Line, LineRule) = (line, Attr(spacing, "lineRule") ?? "auto");
+ }
+ KeepNext = Toggle(pPr, "keepNext") ?? KeepNext;
+ KeepLines = Toggle(pPr, "keepLines") ?? KeepLines;
+ PageBreakBefore = Toggle(pPr, "pageBreakBefore") ?? PageBreakBefore;
+ WidowControl = Toggle(pPr, "widowControl") ?? WidowControl;
+ SnapToGrid = Toggle(pPr, "snapToGrid") ?? SnapToGrid;
+ if (pPr.Element(W + "outlineLvl") is { } outline && int.TryParse(Val(outline), out var level))
+ OutlineLevel = level;
+ if (pPr.Element(W + "numPr") is { } numPr)
+ {
+ if (numPr.Element(W + "numId") is { } numId)
+ NumId = Val(numId);
+ if (numPr.Element(W + "ilvl") is { } ilvl && int.TryParse(Val(ilvl), out var ilvlValue))
+ Ilvl = ilvlValue;
+ }
+ if (pPr.Element(W + "tabs") is { } tabs)
+ {
+ foreach (var tab in tabs.Elements(W + "tab"))
+ {
+ var position = Twips(tab, "pos") ?? 0;
+ Tabs.RemoveAll(t => t.Position == position);
+ if (Val(tab) is { } kind and not "clear")
+ Tabs.Add((position, kind, Attr(tab, "leader") ?? "none"));
+ }
+ Tabs.Sort((a, b) => a.Position.CompareTo(b.Position));
+ }
+ }
+ }
+
+ /// <summary>Run (character) properties.</summary>
+ private sealed class RunProps
+ {
+ public bool? Bold, Italic, Underline, Strike, Hidden;
+ public string? VertAlign, Color, Highlight, Shade, Ascii, EastAsia, AsciiTheme, EastAsiaTheme;
+ public int? Size, Spacing;
+
+ public RunProps Clone() => (RunProps)MemberwiseClone();
+
+ public void Apply(XElement? rPr)
+ {
+ if (rPr is null)
+ return;
+ Bold = Toggle(rPr, "b") ?? Bold;
+ Italic = Toggle(rPr, "i") ?? Italic;
+ Strike = Toggle(rPr, "strike") ?? Toggle(rPr, "dstrike") ?? Strike;
+ Hidden = Toggle(rPr, "vanish") ?? Hidden;
+ if (rPr.Element(W + "u") is { } u)
+ Underline = Val(u) is not ("none" or null);
+ if (rPr.Element(W + "vertAlign") is { } vertAlign)
+ VertAlign = Val(vertAlign);
+ if (rPr.Element(W + "color") is { } color)
+ Color = Val(color) is { Length: 6 } hex ? "#" + hex.ToUpperInvariant() : null;
+ if (rPr.Element(W + "highlight") is { } highlight)
+ Highlight = HighlightColor(Val(highlight));
+ if (rPr.Element(W + "shd") is { } shd)
+ Shade = ShadingColor(shd);
+ if (rPr.Element(W + "sz") is { } sz && int.TryParse(Val(sz), out var halfPoints))
+ Size = halfPoints;
+ if (rPr.Element(W + "spacing") is { } spacing && int.TryParse(Val(spacing), out var twips))
+ Spacing = twips;
+ if (rPr.Element(W + "rFonts") is { } fonts)
+ {
+ // A theme reference wins over an explicit name in Word, so a later explicit name clears it.
+ if ((Attr(fonts, "ascii") ?? Attr(fonts, "hAnsi")) is { } ascii)
+ (Ascii, AsciiTheme) = (ascii, null);
+ if ((Attr(fonts, "asciiTheme") ?? Attr(fonts, "hAnsiTheme")) is { } asciiTheme)
+ AsciiTheme = asciiTheme;
+ if (Attr(fonts, "eastAsia") is { } eastAsia)
+ (EastAsia, EastAsiaTheme) = (eastAsia, null);
+ if (Attr(fonts, "eastAsiaTheme") is { } eastAsiaTheme)
+ EastAsiaTheme = eastAsiaTheme;
+ }
+ }
+ }
+
+ private sealed class Style
+ {
+ public required string Id;
+ public required string Type;
+ public string? Name, BasedOn;
+ public XElement? PPr, RPr, TblPr, TcPr;
+ public List<XElement> TableConditions = [];
+ }
+
+ private sealed class NumberingLevel
+ {
+ public int Start = 1;
+ public string Format = "decimal";
+ public string Text = "%1.";
+ public XElement? PPr, RPr;
+ }
+
+ // ───────────────────────── Loading ─────────────────────────
+
+ private readonly Dictionary<string, Style> _styles = [];
+ private readonly Dictionary<string, (ParaProps Para, RunProps Run)> _resolvedStyles = [];
+ private readonly Dictionary<string, NumberingLevel[]> _numberingLevels = [];
+ private readonly Dictionary<string, HNumbering> _numberings = [];
+ private readonly ParaProps _defaultPara = new();
+ private readonly RunProps _defaultRun = new();
+ private string? _defaultParagraphStyle;
+ private string? _defaultTableStyle;
+ private (string? Latin, string? EastAsian) _minorFont, _majorFont;
+
+ private void LoadStyles(Part? part)
+ {
+ var root = part?.Xml.Root;
+ if (root is null)
+ return;
+ var defaults = root.Element(W + "docDefaults");
+ _defaultPara.Apply(defaults?.Element(W + "pPrDefault")?.Element(W + "pPr"));
+ _defaultRun.Apply(defaults?.Element(W + "rPrDefault")?.Element(W + "rPr"));
+
+ foreach (var element in root.Elements(W + "style"))
+ {
+ var style = new Style
+ {
+ Id = Attr(element, "styleId") ?? "",
+ Type = Attr(element, "type") ?? "paragraph",
+ Name = Val(element.Element(W + "name")),
+ BasedOn = Val(element.Element(W + "basedOn")),
+ PPr = element.Element(W + "pPr"),
+ RPr = element.Element(W + "rPr"),
+ TblPr = element.Element(W + "tblPr"),
+ TcPr = element.Element(W + "tcPr"),
+ TableConditions = [.. element.Elements(W + "tblStylePr")],
+ };
+ _styles[style.Id] = style;
+ if (Bool(element, "default") == true)
+ {
+ if (style.Type == "paragraph")
+ _defaultParagraphStyle = style.Id;
+ else if (style.Type == "table")
+ _defaultTableStyle = style.Id;
+ }
+ }
+ }
+
+ private void LoadTheme(Part? part)
+ {
+ var fonts = part?.Xml.Descendants(A + "fontScheme").FirstOrDefault();
+ (string?, string?) Read(string name)
+ {
+ var font = fonts?.Element(A + name);
+ var latin = Attr(font?.Element(A + "latin"), "typeface");
+ var eastAsian = Attr(font?.Element(A + "ea"), "typeface");
+ if (string.IsNullOrEmpty(eastAsian))
+ eastAsian = Attr(font?.Elements(A + "font").FirstOrDefault(f => Attr(f, "script") == "Hang"), "typeface");
+ return (NullIfEmpty(latin), NullIfEmpty(eastAsian));
+ }
+ _minorFont = Read("minorFont");
+ _majorFont = Read("majorFont");
+ }
+
+ private void LoadNumbering(Part? part)
+ {
+ var root = part?.Xml.Root;
+ if (root is null)
+ return;
+ var abstracts = root.Elements(W + "abstractNum")
+ .ToDictionary(a => Attr(a, "abstractNumId") ?? "", a => a);
+ foreach (var num in root.Elements(W + "num"))
+ {
+ var numId = Attr(num, "numId") ?? "";
+ if (!abstracts.TryGetValue(Val(num.Element(W + "abstractNumId")) ?? "", out var abstractNum))
+ continue;
+ var levels = new NumberingLevel[9];
+ for (var i = 0; i < levels.Length; i++)
+ levels[i] = new NumberingLevel { Text = $"%{i + 1}." };
+ foreach (var lvl in abstractNum.Elements(W + "lvl"))
+ ApplyLevel(levels, lvl);
+ foreach (var over in num.Elements(W + "lvlOverride"))
+ {
+ if (!int.TryParse(Attr(over, "ilvl"), out var index) || index is < 0 or > 8)
+ continue;
+ if (over.Element(W + "lvl") is { } lvl)
+ ApplyLevel(levels, lvl);
+ if (int.TryParse(Val(over.Element(W + "startOverride")), out var start))
+ levels[index].Start = start;
+ }
+ _numberingLevels[numId] = levels;
+ }
+
+ static void ApplyLevel(NumberingLevel[] levels, XElement lvl)
+ {
+ if (!int.TryParse(Attr(lvl, "ilvl"), out var index) || index is < 0 or > 8)
+ return;
+ var level = levels[index];
+ if (int.TryParse(Val(lvl.Element(W + "start")), out var start))
+ level.Start = start;
+ level.Format = Val(lvl.Element(W + "numFmt")) ?? level.Format;
+ level.Text = Val(lvl.Element(W + "lvlText")) ?? level.Text;
+ level.PPr = lvl.Element(W + "pPr") ?? level.PPr;
+ level.RPr = lvl.Element(W + "rPr") ?? level.RPr;
+ }
+ }
+
+ // ───────────────────────── Resolution ─────────────────────────
+
+ /// <summary>Merged properties of a paragraph or character style including everything it is based on.</summary>
+ private (ParaProps Para, RunProps Run) ResolveStyle(string? styleId)
+ {
+ if (styleId is null || !_styles.TryGetValue(styleId, out var style))
+ return (_defaultPara.Clone(), _defaultRun.Clone());
+ if (_resolvedStyles.TryGetValue(styleId, out var cached))
+ return (cached.Para.Clone(), cached.Run.Clone());
+
+ // Guard against basedOn cycles in damaged files.
+ _resolvedStyles[styleId] = (_defaultPara.Clone(), _defaultRun.Clone());
+ var (para, run) = style.BasedOn is { } parent && parent != styleId ? ResolveStyle(parent) : (_defaultPara.Clone(), _defaultRun.Clone());
+ para.Apply(style.PPr);
+ run.Apply(style.RPr);
+ _resolvedStyles[styleId] = (para.Clone(), run.Clone());
+ return (para, run);
+ }
+
+ /// <summary>Properties of a paragraph: defaults → style chain → list level → direct formatting.</summary>
+ private (ParaProps Para, RunProps Mark) ParagraphProperties(XElement? pPr)
+ {
+ var styleId = Val(pPr?.Element(W + "pStyle")) ?? _defaultParagraphStyle;
+ var (para, run) = ResolveStyle(styleId);
+
+ var direct = new ParaProps();
+ direct.Apply(pPr);
+ var numId = direct.NumId ?? para.NumId;
+ var ilvl = direct.Ilvl ?? para.Ilvl ?? 0;
+ if (numId is not null && _numberingLevels.TryGetValue(numId, out var levels))
+ para.Apply(levels[Math.Clamp(ilvl, 0, 8)].PPr);
+ para.Apply(pPr);
+ para.NumId = numId;
+ para.Ilvl = ilvl;
+
+ run.Apply(pPr?.Element(W + "rPr"));
+ return (para, run);
+ }
+
+ /// <summary>Properties of a run inside a paragraph whose style gave <paramref name="paragraphRun"/>.</summary>
+ private RunProps RunProperties(XElement? rPr, RunProps paragraphRun)
+ {
+ var run = paragraphRun.Clone();
+ if (Val(rPr?.Element(W + "rStyle")) is { } characterStyle && _styles.TryGetValue(characterStyle, out var style))
+ {
+ // Character styles only carry run properties; apply their chain on top of the paragraph's.
+ var chain = new List<Style>();
+ for (var current = style; current is not null && chain.Count < 20; current = current.BasedOn is { } b ? _styles.GetValueOrDefault(b) : null)
+ chain.Add(current);
+ for (var i = chain.Count - 1; i >= 0; i--)
+ run.Apply(chain[i].RPr);
+ }
+ run.Apply(rPr);
+ return run;
+ }
+
+ /// <summary>Heading level 1..9 from the outline level (Word's heading styles set it), else 0.</summary>
+ private int HeadingLevel(ParaProps para, XElement? pPr)
+ {
+ if (para.OutlineLevel is >= 0 and <= 8 and var level)
+ return level + 1;
+ var name = _styles.GetValueOrDefault(Val(pPr?.Element(W + "pStyle")) ?? "")?.Name ?? "";
+ return name.StartsWith("heading ", StringComparison.OrdinalIgnoreCase) &&
+ int.TryParse(name.AsSpan(8), out var byName) && byName is >= 1 and <= 9 ? byName : 0;
+ }
+
+ private HParaFormat ParaFormat(ParaProps p)
+ {
+ var firstLine = p.Hanging is { } hanging ? -hanging : p.FirstLine ?? 0;
+ HLineSpacing? lineSpacing = p.Line is not { } line ? null : p.LineRule switch
+ {
+ "exact" => new HLineSpacing(HLineSpacingKind.Fixed, HwpxUnits.FromTwips(line)),
+ "atLeast" => new HLineSpacing(HLineSpacingKind.AtLeast, HwpxUnits.FromTwips(line)),
+ _ => new HLineSpacing(HLineSpacingKind.Percent, (int)Math.Round(line / 240.0 * WordLineToHwpPercent)),
+ };
+ return new HParaFormat(
+ Align: p.Jc switch
+ {
+ "center" => HAlign.Center,
+ "right" or "end" => HAlign.Right,
+ "both" or "lowKashida" or "mediumKashida" or "highKashida" or "thaiDistribute" => HAlign.Justify,
+ "distribute" => HAlign.Distribute,
+ _ => HAlign.Left,
+ },
+ Left: HwpxUnits.FromTwips(p.Left ?? 0),
+ Right: HwpxUnits.FromTwips(p.Right ?? 0),
+ FirstLine: HwpxUnits.FromTwips(firstLine),
+ Before: HwpxUnits.FromTwips(p.Before ?? 0),
+ After: HwpxUnits.FromTwips(p.After ?? 0),
+ LineSpacing: lineSpacing ?? new HLineSpacing(HLineSpacingKind.Percent, (int)WordLineToHwpPercent),
+ KeepWithNext: p.KeepNext ?? false,
+ KeepLines: p.KeepLines ?? false,
+ WidowOrphan: p.WidowControl ?? true,
+ Tabs: p.Tabs.Count == 0 ? null : p.Tabs
+ .Where(t => t.Kind is not ("bar" or "num"))
+ .Select(t => new HTabStop(HwpxUnits.FromTwips(t.Position), t.Kind switch
+ {
+ "right" or "end" => HTabKind.Right,
+ "center" => HTabKind.Center,
+ "decimal" => HTabKind.Decimal,
+ _ => HTabKind.Left,
+ }, t.Leader switch
+ {
+ "dot" or "middleDot" => "DOT",
+ "hyphen" => "DASH",
+ "underscore" or "heavy" => "SOLID",
+ _ => "NONE",
+ }))
+ .ToList());
+ }
+
+ private HCharFormat CharFormat(RunProps r)
+ {
+ var (latin, eastAsian) = Fonts(r);
+ var size = r.Size ?? 20;
+ return new HCharFormat(
+ Bold: r.Bold ?? false,
+ Italic: r.Italic ?? false,
+ Underline: r.Underline ?? false,
+ Strike: r.Strike ?? false,
+ Superscript: r.VertAlign == "superscript",
+ Subscript: r.VertAlign == "subscript",
+ Size: size * 50,
+ Font: latin,
+ EastAsianFont: eastAsian,
+ Color: r.Color ?? "#000000",
+ Shade: r.Highlight ?? r.Shade,
+ // Word letter spacing is absolute (twips); 한글's is a percentage of the font size.
+ Spacing: r.Spacing is { } twips and not 0 ? Math.Clamp((int)Math.Round(twips * 10.0 / size), -50, 50) : 0);
+ }
+
+ private (string? Latin, string? EastAsian) Fonts(RunProps r)
+ {
+ string? Theme(string? theme) => theme switch
+ {
+ null => null,
+ _ when theme.StartsWith("major", StringComparison.Ordinal) => theme.EndsWith("EastAsia", StringComparison.Ordinal) ? _majorFont.EastAsian : _majorFont.Latin,
+ _ => theme.EndsWith("EastAsia", StringComparison.Ordinal) ? _minorFont.EastAsian : _minorFont.Latin,
+ };
+ var latin = Theme(r.AsciiTheme) ?? r.Ascii;
+ var eastAsian = Theme(r.EastAsiaTheme) ?? r.EastAsia;
+ return (latin, eastAsian ?? latin);
+ }
+
+ /// <summary>List definition for a Word numbering instance (one per numId, shared by all its paragraphs).</summary>
+ private HNumbering? Numbering(string? numId)
+ {
+ if (numId is null or "0" || !_numberingLevels.TryGetValue(numId, out var levels))
+ return null;
+ if (_numberings.TryGetValue(numId, out var existing))
+ return existing;
+
+ var numbering = new HNumbering();
+ foreach (var level in levels)
+ {
+ var bullet = level.Format == "bullet";
+ numbering.Levels.Add(bullet
+ ? new HNumberingLevel("DIGIT", BulletText(level.Text), level.Start, Bullet: true)
+ : new HNumberingLevel(NumberFormat(level.Format), NumberText(level.Text, level.Format), level.Start, Bullet: false));
+ }
+ _numberings[numId] = numbering;
+ return numbering;
+ }
+
+ private static string NumberFormat(string wordFormat) => wordFormat switch
+ {
+ "upperRoman" => "ROMAN_CAPITAL",
+ "lowerRoman" => "ROMAN_SMALL",
+ "upperLetter" => "LATIN_CAPITAL",
+ "lowerLetter" => "LATIN_SMALL",
+ "ganada" => "HANGUL_SYLLABLE",
+ "chosung" => "HANGUL_JAMO",
+ "decimalEnclosedCircle" or "decimalEnclosedCircleChinese" => "CIRCLED_DIGIT",
+ "koreanDigital" or "koreanCounting" or "koreanLegal" or "koreanDigital2" => "HANGUL_PHONETIC",
+ "ideographDigital" or "chineseCounting" or "chineseCountingThousand" or "japaneseCounting" or "ideographTraditional" => "IDEOGRAPH",
+ _ => "DIGIT",
+ };
+
+ /// <summary>"%1.%2." → "^1.^2."; a "none" level keeps only its literal text.</summary>
+ private static string NumberText(string text, string format)
+ {
+ if (format == "none")
+ return string.Concat(text.Where(c => c != '%' && !char.IsDigit(c)));
+ var chars = text.ToCharArray();
+ for (var i = 0; i + 1 < chars.Length; i++)
+ {
+ if (chars[i] == '%' && char.IsDigit(chars[i + 1]))
+ chars[i] = '^';
+ }
+ return new string(chars);
+ }
+
+ /// <summary>Word bullets often use Symbol/Wingdings private-use code points; map them to Unicode.</summary>
+ private static string BulletText(string text) => text switch
+ {
+ "" or "\uF0B7" or "\uF09F" or "•" => "●",
+ "o" or "\uF06F" => "○",
+ "\uF0A7" or "\uF06E" or "▪" => "■",
+ "\uF0D8" => "➢",
+ "\uF076" => "❖",
+ "\uF0FC" => "✓",
+ "\uF071" => "❑",
+ "\uF075" or "\uF0A8" => "◆",
+ "-" or "–" or "\uF02D" => "-",
+ _ when text.Length > 0 && text[0] >= '\uF000' => "●",
+ _ => text,
+ };
+
+ /// <summary>
+ /// Colour of a w:shd: the fill, the pattern colour for "solid", and for "pctN" the pattern colour mixed into the
+ /// fill at N percent (Word's classic grey header cells are "pct10" or "pct15" with automatic colours).
+ /// </summary>
+ private static string? ShadingColor(XElement shd)
+ {
+ static (int R, int G, int B)? Rgb(string? hex) =>
+ hex is { Length: 6 } && int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)
+ ? ((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)
+ : null;
+ static string Hex((int R, int G, int B) c) => $"#{c.R:X2}{c.G:X2}{c.B:X2}";
+
+ var fill = Rgb(Attr(shd, "fill"));
+ var color = Rgb(Attr(shd, "color"));
+ var pattern = Val(shd);
+ if (pattern is null or "clear" or "nil")
+ return fill is { } f ? Hex(f) : null;
+ if (pattern == "solid")
+ return Hex(color ?? (0, 0, 0));
+ if (pattern.StartsWith("pct", StringComparison.Ordinal) && int.TryParse(pattern.AsSpan(3), out var percent))
+ {
+ var background = fill ?? (255, 255, 255);
+ var foreground = color ?? (0, 0, 0);
+ var t = Math.Clamp(percent, 0, 100) / 100.0;
+ return Hex(((int)Math.Round(background.R + (foreground.R - background.R) * t),
+ (int)Math.Round(background.G + (foreground.G - background.G) * t),
+ (int)Math.Round(background.B + (foreground.B - background.B) * t)));
+ }
+ return fill is { } other ? Hex(other) : null;
+ }
+
+ private static string? HighlightColor(string? name) => name switch
+ {
+ "yellow" => "#FFFF00",
+ "green" => "#00FF00",
+ "cyan" => "#00FFFF",
+ "magenta" => "#FF00FF",
+ "blue" => "#0000FF",
+ "red" => "#FF0000",
+ "darkBlue" => "#000080",
+ "darkCyan" => "#008080",
+ "darkGreen" => "#008000",
+ "darkMagenta" => "#800080",
+ "darkRed" => "#800000",
+ "darkYellow" => "#808000",
+ "darkGray" => "#808080",
+ "lightGray" => "#C0C0C0",
+ "black" => "#000000",
+ "white" => "#FFFFFF",
+ _ => null,
+ };
+
+ // ───────────────────────── XML helpers ─────────────────────────
+
+ private static string? Attr(XElement? element, string name) =>
+ (string?)element?.Attribute(W + name) ?? (string?)element?.Attribute(name);
+
+ private static string? Attr(XElement? element, string name, XNamespace ns) => (string?)element?.Attribute(ns + name);
+
+ private static string? Val(XElement? element) => Attr(element, "val");
+
+ private static int? Twips(XElement? element, string name) =>
+ double.TryParse(Attr(element, name), NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? (int)value : null;
+
+ private static long? Long(XElement? element, string name) =>
+ long.TryParse(Attr(element, name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null;
+
+ private static bool? Bool(XElement? element, string name) => Attr(element, name) switch
+ {
+ null => null,
+ "0" or "false" or "off" => false,
+ _ => true,
+ };
+
+ /// <summary>An on/off property element: present = on unless its val says otherwise; missing = inherit.</summary>
+ private static bool? Toggle(XElement parent, string name) =>
+ parent.Element(W + name) is not { } element ? null : Val(element) is not ("0" or "false" or "off" or "none");
+
+ private static string? NullIfEmpty(string? text) => string.IsNullOrWhiteSpace(text) ? null : text;
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
new file mode 100644
index 00000000..fcb818d9
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs
@@ -0,0 +1,187 @@
+// DOCX tables: grid column widths, merged cells (gridSpan / vMerge), borders from the table style, the table and
+// each cell, cell shading, vertical alignment, row heights and repeated header rows.
+
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal sealed partial class DocxReader
+{
+ private HTable ReadTable(XElement tbl)
+ {
+ var tblPr = tbl.Element(W + "tblPr");
+ var style = _styles.GetValueOrDefault(Val(tblPr?.Element(W + "tblStyle")) ?? _defaultTableStyle ?? "");
+ var styleChain = StyleChain(style);
+
+ var grid = tbl.Element(W + "tblGrid")?.Elements(W + "gridCol").Select(c => HwpxUnits.FromTwips(Twips(c, "w") ?? 0)).ToArray() ?? [];
+ var table = new HTable
+ {
+ ColumnWidths = grid.Length > 0 && grid.All(w => w > 0) ? grid : null,
+ ColumnCount = grid.Length,
+ Align = Val(tblPr?.Element(W + "jc")) switch
+ {
+ "center" => HAlign.Center,
+ "right" or "end" => HAlign.Right,
+ _ => HAlign.Left,
+ },
+ Indent = HwpxUnits.FromTwips(Twips(tblPr?.Element(W + "tblInd"), "w") ?? 0),
+ };
+
+ // Borders and cell margins: table style chain, then the table's own properties.
+ var borders = new Dictionary<string, HBorder>();
+ HInsets? margins = null;
+ foreach (var properties in styleChain.Select(s => s.TblPr).Append(tblPr))
+ {
+ ApplyBorders(properties?.Element(W + "tblBorders"), borders);
+ if (properties?.Element(W + "tblCellMar") is { } cellMar)
+ margins = CellMargins(cellMar, margins);
+ }
+ table.CellMargin = margins;
+ table.Borders = HBorders.Empty;
+
+ // Header row look from the table style ("firstRow" conditional formatting), when the table enables it.
+ var look = tblPr?.Element(W + "tblLook");
+ var firstRowLook = Attr(look, "firstRow") is { } firstRow ? firstRow is "1" or "true"
+ : int.TryParse(Val(look), System.Globalization.NumberStyles.HexNumber, null, out var mask) && (mask & 0x20) != 0;
+ var firstRowStyle = firstRowLook
+ ? styleChain.SelectMany(s => s.TableConditions).LastOrDefault(c => Attr(c, "type") == "firstRow")
+ : null;
+
+ var rows = tbl.Elements().SelectMany(e => e.Name == W + "tr" ? [e] : FlattenRows(e)).ToList();
+ // vMerge: the cell that restarts a vertical merge, per grid column.
+ var mergeOrigin = new Dictionary<int, HCell>();
+ for (var r = 0; r < rows.Count; r++)
+ {
+ var tr = rows[r];
+ var trPr = tr.Element(W + "trPr");
+ var row = new HRow { Header = trPr?.Element(W + "tblHeader") is { } header && Val(header) is not ("0" or "false") };
+ if (trPr?.Element(W + "trHeight") is { } height && Twips(height, "val") is > 0 and var h)
+ row.Height = HwpxUnits.FromTwips(h);
+
+ var column = Twips(trPr?.Element(W + "gridBefore"), "val") ?? 0;
+ foreach (var tc in tr.Elements().SelectMany(e => e.Name == W + "tc" ? [e] : FlattenCells(e)))
+ {
+ var tcPr = tc.Element(W + "tcPr");
+ var span = Math.Max(1, Twips(tcPr?.Element(W + "gridSpan"), "val") ?? 1);
+ var vMerge = tcPr?.Element(W + "vMerge");
+ if (vMerge is not null && Val(vMerge) is not "restart" && mergeOrigin.TryGetValue(column, out var origin))
+ {
+ origin.RowSpan++;
+ column += span;
+ continue;
+ }
+
+ var cell = new HCell { Column = column, ColSpan = span };
+ ReadBlocks(tc.Elements(), cell.Blocks);
+ cell.VerticalAlign = Val(tcPr?.Element(W + "vAlign")) switch
+ {
+ "center" => HVerticalAlign.Center,
+ "bottom" => HVerticalAlign.Bottom,
+ _ => HVerticalAlign.Top,
+ };
+
+ // Cell edges: outer table borders on the outside, inside borders between cells, cell overrides.
+ var isFirstRow = r == 0;
+ var isLastRow = r == rows.Count - 1;
+ var cellBorders = new Dictionary<string, HBorder>
+ {
+ ["left"] = borders.GetValueOrDefault(column == 0 ? "left" : "insideV", HBorder.None),
+ ["right"] = borders.GetValueOrDefault(column + span >= grid.Length ? "right" : "insideV", HBorder.None),
+ ["top"] = borders.GetValueOrDefault(isFirstRow ? "top" : "insideH", HBorder.None),
+ ["bottom"] = borders.GetValueOrDefault(isLastRow ? "bottom" : "insideH", HBorder.None),
+ };
+ string? fill = null;
+ foreach (var properties in styleChain.Select(s => s.TcPr).Append(r == 0 ? firstRowStyle?.Element(W + "tcPr") : null).Append(tcPr))
+ {
+ ApplyBorders(properties?.Element(W + "tcBorders"), cellBorders);
+ if (properties?.Element(W + "shd") is { } shd)
+ fill = ShadingColor(shd) ?? fill;
+ }
+ cell.Borders = new HBorders(cellBorders["left"], cellBorders["right"], cellBorders["top"], cellBorders["bottom"]);
+ cell.Fill = fill;
+
+ if (r == 0 && firstRowStyle?.Element(W + "rPr")?.Element(W + "b") is not null)
+ Embolden(cell.Blocks);
+
+ if (vMerge is not null)
+ mergeOrigin[column] = cell;
+ else
+ mergeOrigin.Remove(column);
+ row.Cells.Add(cell);
+ column += span;
+ }
+ table.Rows.Add(row);
+ table.ColumnCount = Math.Max(table.ColumnCount, column);
+ }
+ return table;
+ }
+
+ private List<Style> StyleChain(Style? style)
+ {
+ var chain = new List<Style>();
+ for (var current = style; current is not null && chain.Count < 20; current = current.BasedOn is { } b ? _styles.GetValueOrDefault(b) : null)
+ chain.Insert(0, current);
+ return chain;
+ }
+
+ private static IEnumerable<XElement> FlattenRows(XElement element) =>
+ element.Name == W + "sdt" ? element.Element(W + "sdtContent")?.Elements().SelectMany(e => e.Name == W + "tr" ? [e] : FlattenRows(e)) ?? []
+ : element.Name == W + "customXml" ? element.Elements().SelectMany(e => e.Name == W + "tr" ? [e] : FlattenRows(e))
+ : [];
+
+ private static IEnumerable<XElement> FlattenCells(XElement element) =>
+ element.Name == W + "sdt" ? element.Element(W + "sdtContent")?.Elements().SelectMany(e => e.Name == W + "tc" ? [e] : FlattenCells(e)) ?? []
+ : element.Name == W + "customXml" ? element.Elements().SelectMany(e => e.Name == W + "tc" ? [e] : FlattenCells(e))
+ : [];
+
+ private static void ApplyBorders(XElement? borders, Dictionary<string, HBorder> target)
+ {
+ foreach (var edge in borders?.Elements() ?? [])
+ {
+ var name = edge.Name.LocalName switch
+ {
+ "start" => "left",
+ "end" => "right",
+ var other => other,
+ };
+ target[name] = Border(edge);
+ }
+ }
+
+ /// <summary>A Word border (w:val style, w:sz in eighths of a point, w:color).</summary>
+ private static HBorder Border(XElement edge)
+ {
+ var style = Val(edge) switch
+ {
+ null or "nil" or "none" => HBorderStyle.None,
+ "dotted" => HBorderStyle.Dot,
+ "dashed" or "dashSmallGap" => HBorderStyle.Dash,
+ "dotDash" or "dotDotDash" => HBorderStyle.DashDot,
+ "double" or "triple" or "thinThickSmallGap" or "thickThinSmallGap" => HBorderStyle.Double,
+ _ => HBorderStyle.Solid,
+ };
+ var eighths = Twips(edge, "sz") ?? 4;
+ var color = Attr(edge, "color") is { Length: 6 } hex ? "#" + hex.ToUpperInvariant() : "#000000";
+ return new HBorder(style, eighths / 8.0 * 25.4 / 72, color);
+ }
+
+ private static HInsets CellMargins(XElement cellMar, HInsets? current)
+ {
+ int Get(string name, string alternative, int fallback) =>
+ HwpxUnits.FromTwips(Twips(cellMar.Element(W + name), "w") ?? Twips(cellMar.Element(W + alternative), "w") ?? fallback / 5);
+ var existing = current ?? new HInsets(540, 540, 0, 0);
+ return new HInsets(Get("left", "start", existing.Left), Get("right", "end", existing.Right), Get("top", "top", existing.Top), Get("bottom", "bottom", existing.Bottom));
+ }
+
+ private static void Embolden(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)
+ paragraph.Inlines[i] = new HText(text.Text, text.Format with { Bold = true });
+ }
+ }
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
new file mode 100644
index 00000000..3c45ecc6
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
@@ -0,0 +1,788 @@
+// DOCX (Office Open XML) → HDocument, read directly instead of through Pandoc so the layout survives:
+// page size and margins per section, columns, headers and footers with page numbers, text boxes, floating
+// pictures, paragraph and character formatting, tables with borders, shading and merged cells, lists,
+// footnotes and endnotes, bookmarks and hyperlinks (including the links of a Word table of contents).
+//
+// Split over partial files: this one walks the package and the text, DocxReader.Styles resolves formatting,
+// DocxReader.Tables and DocxReader.Drawing handle tables and graphic objects.
+
+using System.IO.Compression;
+using System.Text;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+/// <summary>Reads a .docx file into the HWPX document model.</summary>
+internal sealed partial class DocxReader
+{
+ private static readonly XNamespace W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
+ private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
+ private static readonly XNamespace PackageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
+ private static readonly XNamespace A = "http://schemas.openxmlformats.org/drawingml/2006/main";
+ private static readonly XNamespace Wp = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
+ private static readonly XNamespace Pic = "http://schemas.openxmlformats.org/drawingml/2006/picture";
+ private static readonly XNamespace Wps = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape";
+ private static readonly XNamespace Wpg = "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup";
+ private static readonly XNamespace Mc = "http://schemas.openxmlformats.org/markup-compatibility/2006";
+ private static readonly XNamespace V = "urn:schemas-microsoft-com:vml";
+ private static readonly XNamespace M = "http://schemas.openxmlformats.org/officeDocument/2006/math";
+ private static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/";
+
+ private readonly ZipArchive _zip;
+ private readonly string _mediaFolder;
+ private readonly Dictionary<string, Part?> _parts = [];
+ private readonly Dictionary<string, string> _media = [];
+ private readonly Dictionary<string, XElement> _footnotes = [];
+ private readonly Dictionary<string, XElement> _endnotes = [];
+ private readonly List<FieldState> _fields = [];
+ private Part? _footnotesPart;
+ private Part? _endnotesPart;
+ private bool _evenAndOddHeaders;
+
+ /// <summary>Line pitch (twips) of each section's document grid, 0 = none; see <see cref="SnapToGrid"/>.</summary>
+ private readonly List<int> _linePitches = [];
+ private int _sectionIndex;
+ private int _textBoxDepth;
+
+ /// <summary>The part being read; relationship ids (images, links) are resolved against it.</summary>
+ private Part _part;
+
+ private DocxReader(ZipArchive zip, string mediaFolder)
+ {
+ _zip = zip;
+ _mediaFolder = mediaFolder;
+ var mainPath = RelationshipsOf("")
+ .FirstOrDefault(r => r.Value.Type.EndsWith("/officeDocument", StringComparison.Ordinal)).Value.Target ?? "word/document.xml";
+ _part = LoadPart(mainPath) ?? throw new InvalidDataException("The file is not a Word document (no word/document.xml).");
+ }
+
+ /// <summary>Reads <paramref name="path"/>; embedded pictures are extracted into <paramref name="mediaFolder"/>.</summary>
+ public static HDocument Read(string path, string mediaFolder)
+ {
+ using var zip = ZipFile.OpenRead(path);
+ return new DocxReader(zip, mediaFolder).ReadDocument();
+ }
+
+ // ───────────────────────── Package ─────────────────────────
+
+ private sealed class Part(string path, XDocument xml, Dictionary<string, Relationship> relationships)
+ {
+ public string Path { get; } = path;
+ public XDocument Xml { get; } = xml;
+ public Dictionary<string, Relationship> Relationships { get; } = relationships;
+ }
+
+ private readonly record struct Relationship(string Type, string Target, bool External);
+
+ private Part? LoadPart(string path)
+ {
+ if (_parts.TryGetValue(path, out var cached))
+ return cached;
+ Part? part = null;
+ if (_zip.GetEntry(path) is { } entry)
+ {
+ using var stream = entry.Open();
+ // Whitespace matters: <w:t xml:space="preserve"> </w:t> is a real space.
+ part = new Part(path, XDocument.Load(stream, LoadOptions.PreserveWhitespace), RelationshipsOf(path));
+ }
+ _parts[path] = part;
+ return part;
+ }
+
+ /// <summary>Relationships of a part ("" = the package), with targets resolved to zip paths.</summary>
+ private Dictionary<string, Relationship> RelationshipsOf(string partPath)
+ {
+ var folder = partPath.Contains('/') ? partPath[..partPath.LastIndexOf('/')] : "";
+ var relsPath = partPath.Length == 0 ? "_rels/.rels" : $"{folder}/_rels/{partPath[(partPath.LastIndexOf('/') + 1)..]}.rels".TrimStart('/');
+ var result = new Dictionary<string, Relationship>();
+ if (_zip.GetEntry(relsPath) is not { } entry)
+ return result;
+ using var stream = entry.Open();
+ foreach (var rel in XDocument.Load(stream).Root?.Elements(PackageRelationships + "Relationship") ?? [])
+ {
+ var id = (string?)rel.Attribute("Id") ?? "";
+ var target = (string?)rel.Attribute("Target") ?? "";
+ var external = (string?)rel.Attribute("TargetMode") == "External";
+ result[id] = new Relationship((string?)rel.Attribute("Type") ?? "", external ? target : ResolvePath(folder, target), external);
+ }
+ return result;
+ }
+
+ 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);
+ }
+
+ private Part? RelatedPart(Part from, string typeSuffix) =>
+ from.Relationships.Values.FirstOrDefault(r => !r.External && r.Type.EndsWith(typeSuffix, StringComparison.Ordinal)) is { Target.Length: > 0 } rel
+ ? LoadPart(rel.Target)
+ : null;
+
+ /// <summary>Runs <paramref name="read"/> with relationship ids resolved against <paramref name="part"/>.</summary>
+ private T WithPart<T>(Part part, Func<T> read)
+ {
+ var previous = _part;
+ _part = part;
+ try
+ {
+ return read();
+ }
+ finally
+ {
+ _part = previous;
+ }
+ }
+
+ // ───────────────────────── Document and sections ─────────────────────────
+
+ private HDocument ReadDocument()
+ {
+ var main = _part;
+ LoadStyles(RelatedPart(main, "/styles"));
+ var theme = RelatedPart(main, "/theme");
+ LoadTheme(theme);
+ LoadThemeColors(theme);
+ LoadNumbering(RelatedPart(main, "/numbering"));
+ _evenAndOddHeaders = RelatedPart(main, "/settings")?.Xml.Root?.Element(W + "evenAndOddHeaders") is { } evenOdd && Val(evenOdd) is not ("0" or "false");
+ _footnotesPart = RelatedPart(main, "/footnotes");
+ _endnotesPart = RelatedPart(main, "/endnotes");
+ foreach (var note in _footnotesPart?.Xml.Root?.Elements(W + "footnote") ?? [])
+ _footnotes[Attr(note, "id") ?? ""] = note;
+ foreach (var note in _endnotesPart?.Xml.Root?.Elements(W + "endnote") ?? [])
+ _endnotes[Attr(note, "id") ?? ""] = note;
+
+ var document = new HDocument { Title = Title() };
+ var body = main.Xml.Root?.Element(W + "body") ?? throw new InvalidDataException("word/document.xml has no body.");
+
+ // A section ends with the paragraph whose properties hold its sectPr; the last one is the body's own sectPr.
+ // Paragraphs come before their sectPr, so collect the document grids first.
+ foreach (var element in Flatten(body.Elements()))
+ {
+ if (element.Name == W + "p" && element.Element(W + "pPr")?.Element(W + "sectPr") is { } sectionEnd)
+ _linePitches.Add(LinePitch(sectionEnd));
+ }
+ _linePitches.Add(LinePitch(body.Element(W + "sectPr")));
+
+ var blocks = new List<HBlock>();
+ var headers = new Dictionary<string, List<HBlock>>();
+ var footers = new Dictionary<string, List<HBlock>>();
+ foreach (var element in Flatten(body.Elements()))
+ {
+ if (element.Name == W + "sectPr")
+ continue;
+ ReadBlock(element, blocks);
+ if (element.Name == W + "p" && element.Element(W + "pPr")?.Element(W + "sectPr") is { } sectPr)
+ {
+ AddSection(document, blocks, sectPr, headers, footers);
+ blocks = [];
+ _sectionIndex++;
+ }
+ }
+ AddSection(document, blocks, body.Element(W + "sectPr"), headers, footers);
+ return document;
+ }
+
+ private string? Title()
+ {
+ var core = _zip.GetEntry("docProps/core.xml");
+ if (core is null)
+ return null;
+ using var stream = core.Open();
+ return NullIfEmpty(XDocument.Load(stream).Descendants(Dc + "title").FirstOrDefault()?.Value);
+ }
+
+ private void AddSection(HDocument document, List<HBlock> blocks, XElement? sectPr,
+ Dictionary<string, List<HBlock>> headers, Dictionary<string, List<HBlock>> footers)
+ {
+ var page = Page(sectPr);
+ var columns = Columns(sectPr);
+ var previous = document.Sections.LastOrDefault();
+
+ // Word uses continuous section breaks to change the number of columns mid-page. 한글 does that with a
+ // column definition inside the section, so keep one section when the paper does not change.
+ if (previous is not null && Val(sectPr?.Element(W + "type")) == "continuous" && previous.Page == page)
+ {
+ if (blocks.FirstOrDefault() is not HParagraph first)
+ blocks.Insert(0, first = new HParagraph());
+ first.ColumnsChange = columns;
+ previous.Blocks.AddRange(blocks);
+ return;
+ }
+
+ var section = new HSection { Page = page, Columns = columns };
+ section.Blocks.AddRange(blocks);
+
+ // Sections without their own header or footer reference inherit the previous section's.
+ foreach (var reference in sectPr?.Elements(W + "headerReference") ?? [])
+ headers[Attr(reference, "type") ?? "default"] = HeaderFooterBlocks(reference);
+ foreach (var reference in sectPr?.Elements(W + "footerReference") ?? [])
+ footers[Attr(reference, "type") ?? "default"] = HeaderFooterBlocks(reference);
+
+ void Add(Dictionary<string, List<HBlock>> source, List<HHeaderFooter> target)
+ {
+ if (_evenAndOddHeaders)
+ {
+ if (source.GetValueOrDefault("default") is { } odd)
+ AddHeaderFooter(target, HPageType.Odd, odd);
+ if (source.GetValueOrDefault("even") is { } even)
+ AddHeaderFooter(target, HPageType.Even, even);
+ }
+ else if (source.GetValueOrDefault("default") is { } both)
+ {
+ AddHeaderFooter(target, HPageType.Both, both);
+ }
+ }
+ Add(headers, section.Headers);
+ Add(footers, section.Footers);
+
+ // "Different first page": 한글 can only hide the header/footer on the first page, which is what an empty
+ // (or missing) first-page header means in Word.
+ if (sectPr?.Element(W + "titlePg") is { } titlePg && Val(titlePg) is not ("0" or "false"))
+ {
+ section.HideFirstHeader = IsBlank(headers.GetValueOrDefault("first"));
+ section.HideFirstFooter = IsBlank(footers.GetValueOrDefault("first"));
+ }
+ if (int.TryParse(Attr(sectPr?.Element(W + "pgNumType"), "start"), out var start))
+ section.StartPageNumber = start;
+
+ document.Sections.Add(section);
+ }
+
+ private static void AddHeaderFooter(List<HHeaderFooter> target, HPageType pages, List<HBlock> blocks)
+ {
+ var item = new HHeaderFooter(pages);
+ item.Blocks.AddRange(blocks);
+ target.Add(item);
+ }
+
+ private List<HBlock> HeaderFooterBlocks(XElement reference)
+ {
+ var blocks = new List<HBlock>();
+ if (Attr(reference, "id", R) is { } id && _part.Relationships.TryGetValue(id, out var rel) && LoadPart(rel.Target) is { } part)
+ {
+ WithPart(part, () =>
+ {
+ foreach (var element in Flatten(part.Xml.Root?.Elements() ?? []))
+ ReadBlock(element, blocks);
+ return 0;
+ });
+ }
+ return blocks;
+ }
+
+ private static bool IsBlank(List<HBlock>? blocks) =>
+ blocks is null || blocks.All(b => b is HParagraph p && p.Inlines.All(i => i is HText t && string.IsNullOrWhiteSpace(t.Text) || i is HBookmark));
+
+ private static HPage Page(XElement? sectPr)
+ {
+ var size = sectPr?.Element(W + "pgSz");
+ var margin = sectPr?.Element(W + "pgMar");
+ int Get(XElement? element, string name, int fallback) => Math.Abs(Twips(element, name) ?? fallback);
+
+ var width = Get(size, "w", 11906);
+ var height = Get(size, "h", 16838);
+ if (Attr(size, "orient") == "landscape" && width < height)
+ (width, height) = (height, width);
+
+ // Word: top = paper edge → body, header = paper edge → header text.
+ // 한글: top = paper edge → header, header = header area height (body starts at top + header).
+ var top = Get(margin, "top", 1440);
+ var bottom = Get(margin, "bottom", 1440);
+ var headerDistance = Math.Min(Get(margin, "header", 720), top);
+ var footerDistance = Math.Min(Get(margin, "footer", 720), bottom);
+ return new HPage(
+ Width: HwpxUnits.FromTwips(width),
+ Height: HwpxUnits.FromTwips(height),
+ Left: HwpxUnits.FromTwips(Get(margin, "left", 1440)),
+ Right: HwpxUnits.FromTwips(Get(margin, "right", 1440)),
+ Top: HwpxUnits.FromTwips(headerDistance),
+ Bottom: HwpxUnits.FromTwips(footerDistance),
+ Header: HwpxUnits.FromTwips(top - headerDistance),
+ Footer: HwpxUnits.FromTwips(bottom - footerDistance),
+ Gutter: HwpxUnits.FromTwips(Get(margin, "gutter", 0)));
+ }
+
+ /// <summary>Line pitch of a "lines" document grid (twips), or 0.</summary>
+ private static int LinePitch(XElement? sectPr)
+ {
+ var grid = sectPr?.Element(W + "docGrid");
+ return Attr(grid, "type") is "lines" or "linesAndChars" or "snapToChars" ? Twips(grid, "linePitch") ?? 0 : 0;
+ }
+
+ /// <summary>
+ /// Word's document grid ("lines") puts every line on a multiple of the grid pitch: a single-spaced 10 pt line
+ /// with an 18 pt grid is 18 pt high. 한글 has no such grid for body text, so the paragraph gets an "at least"
+ /// line spacing of the snapped height (larger content such as pictures can still grow the line).
+ /// </summary>
+ private void SnapToGrid(HParagraph paragraph, ParaProps props)
+ {
+ var pitch = _textBoxDepth > 0 || _sectionIndex >= _linePitches.Count ? 0 : _linePitches[_sectionIndex];
+ if (pitch <= 0 || props.SnapToGrid == false || props.LineRule is "exact" or "atLeast")
+ return;
+ var size = MaxFontSize(paragraph.Inlines) ?? paragraph.MarkFormat.Size ?? 1000;
+ var cell = HwpxUnits.FromTwips(pitch);
+ var natural = size * WordLineToHwpPercent / 100.0; // 1/100 pt = HWPUNIT
+ var lines = Math.Max(1, Math.Ceiling(natural / cell));
+ var multiple = (props.Line ?? 240) / 240.0;
+ paragraph.Format = paragraph.Format with { LineSpacing = new HLineSpacing(HLineSpacingKind.AtLeast, (int)Math.Round(lines * cell * multiple)) };
+ }
+
+ private static int? MaxFontSize(IEnumerable<HInline> inlines)
+ {
+ int? max = null;
+ foreach (var inline in inlines)
+ {
+ var size = inline switch
+ {
+ HText text => text.Format.Size,
+ HLink link => MaxFontSize(link.Content),
+ HField field => field.Format.Size,
+ _ => null,
+ };
+ if (size > (max ?? 0))
+ max = size;
+ }
+ return max;
+ }
+
+ private static HColumns Columns(XElement? sectPr)
+ {
+ var cols = sectPr?.Element(W + "cols");
+ var count = int.TryParse(Attr(cols, "num"), out var n) ? n : cols?.Elements(W + "col").Count() ?? 1;
+ if (count <= 1)
+ return HColumns.Single;
+ return new HColumns(Math.Min(count, 255), HwpxUnits.FromTwips(Twips(cols, "space") ?? 720), Bool(cols, "sep") == true);
+ }
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ /// <summary>Paragraphs and tables, looking through content controls, custom XML and tracked insertions.</summary>
+ private static IEnumerable<XElement> Flatten(IEnumerable<XElement> elements)
+ {
+ foreach (var element in elements)
+ {
+ var name = element.Name;
+ if (name == W + "sdt")
+ {
+ foreach (var inner in Flatten(element.Element(W + "sdtContent")?.Elements() ?? []))
+ yield return inner;
+ }
+ else if (name == W + "customXml" || name == W + "ins" || name == W + "moveTo")
+ {
+ foreach (var inner in Flatten(element.Elements()))
+ yield return inner;
+ }
+ else if (name == W + "p" || name == W + "tbl" || name == W + "sectPr")
+ {
+ yield return element;
+ }
+ }
+ }
+
+ private void ReadBlocks(IEnumerable<XElement> elements, List<HBlock> output)
+ {
+ foreach (var element in Flatten(elements))
+ ReadBlock(element, output);
+ }
+
+ private void ReadBlock(XElement element, List<HBlock> output)
+ {
+ if (element.Name == W + "p")
+ ReadParagraph(element, output);
+ else if (element.Name == W + "tbl")
+ output.Add(ReadTable(element));
+ }
+
+ // ───────────────────────── Paragraphs ─────────────────────────
+
+ /// <summary>
+ /// Builds the paragraph(s) for one w:p. A page or column break inside the text starts a new 한글 paragraph
+ /// (breaks are paragraph attributes there), so one Word paragraph can become several.
+ /// </summary>
+ private sealed class ParagraphBuilder
+ {
+ private readonly DocxReader _reader;
+ private readonly List<HBlock> _output;
+ private readonly HParaFormat _format;
+ private readonly HCharFormat _mark;
+ private readonly int _heading;
+ private readonly HListRef? _list;
+ private readonly ParaProps _props;
+ private readonly Stack<List<HInline>> _sinks = new();
+
+ public ParagraphBuilder(DocxReader reader, List<HBlock> output, ParaProps props, RunProps mark, XElement? pPr)
+ {
+ _reader = reader;
+ _props = props;
+ _output = output;
+ _format = reader.ParaFormat(props);
+ _mark = reader.CharFormat(mark);
+ _heading = reader.HeadingLevel(props, pPr);
+ _list = reader.Numbering(props.NumId) is { } numbering ? new HListRef(numbering, Math.Clamp(props.Ilvl ?? 0, 0, 8), Numbered: true) : null;
+ Current = NewParagraph(_list);
+ Current.PageBreakBefore = props.PageBreakBefore == true;
+
+ // A hyperlink field that started in an earlier paragraph (Word's table of contents) continues here.
+ if (reader._fields.LastOrDefault(f => f.Result && f.Target is not null) is { } field)
+ OpenLink(field.Target!);
+ }
+
+ public HParagraph Current { get; private set; }
+
+ public List<HInline> Sink => _sinks.Count > 0 ? _sinks.Peek() : Current.Inlines;
+
+ public void Add(HInline inline) => Sink.Add(inline);
+
+ public void OpenLink(string target)
+ {
+ var link = new HLink(target);
+ Sink.Add(link);
+ _sinks.Push(link.Content);
+ }
+
+ public void CloseLink()
+ {
+ if (_sinks.Count > 0)
+ _sinks.Pop();
+ }
+
+ /// <summary>Continues in a new paragraph that starts on a new page or column.</summary>
+ public void Break(bool page)
+ {
+ if (Current.Inlines.Count > 0)
+ {
+ Emit();
+ // The rest of a list item is not numbered again.
+ Current = NewParagraph(_list is null ? null : _list with { Numbered = false });
+ _sinks.Clear();
+ }
+ if (page)
+ Current.PageBreakBefore = true;
+ else
+ Current.ColumnBreakBefore = true;
+ }
+
+ public void Finish() => Emit();
+
+ private void Emit()
+ {
+ _reader.SnapToGrid(Current, _props);
+ _output.Add(Current);
+ }
+
+ private HParagraph NewParagraph(HListRef? list) =>
+ new() { Format = _format, MarkFormat = _mark, HeadingLevel = _heading, List = list };
+ }
+
+ private void ReadParagraph(XElement p, List<HBlock> output)
+ {
+ var pPr = p.Element(W + "pPr");
+ var (props, mark) = ParagraphProperties(pPr);
+ var builder = new ParagraphBuilder(this, output, props, mark, pPr);
+ // Run formatting starts from the paragraph style, not from the paragraph mark's direct formatting.
+ var styleRun = ResolveStyle(Val(pPr?.Element(W + "pStyle")) ?? _defaultParagraphStyle).Run;
+ ParagraphContent(p.Elements(), builder, styleRun);
+ builder.Finish();
+ }
+
+ private void ParagraphContent(IEnumerable<XElement> elements, ParagraphBuilder builder, RunProps styleRun)
+ {
+ foreach (var element in elements)
+ {
+ var name = element.Name.LocalName;
+ if (element.Name.Namespace == M)
+ {
+ if (name is "oMath" or "oMathPara")
+ builder.Add(new HText(string.Concat(element.Descendants(M + "t").Select(t => t.Value)), CharFormat(styleRun) with { Italic = true }));
+ continue;
+ }
+ if (element.Name.Namespace != W)
+ {
+ if (element.Name == Mc + "AlternateContent")
+ ParagraphContent(ChooseAlternative(element), builder, styleRun);
+ continue;
+ }
+ switch (name)
+ {
+ case "r":
+ Run(element, builder, styleRun);
+ break;
+ case "hyperlink":
+ {
+ var target = Attr(element, "id", R) is { } id && _part.Relationships.TryGetValue(id, out var rel) ? rel.Target
+ : Attr(element, "anchor") is { } anchor ? "#" + anchor
+ : null;
+ if (target is not null)
+ builder.OpenLink(target);
+ ParagraphContent(element.Elements(), builder, styleRun);
+ if (target is not null)
+ builder.CloseLink();
+ break;
+ }
+ case "fldSimple":
+ {
+ var field = new FieldState();
+ field.Instruction.Append(Attr(element, "instr"));
+ _fields.Add(field);
+ StartFieldResult(field, builder, CharFormat(styleRun));
+ ParagraphContent(element.Elements(), builder, styleRun);
+ EndField(builder);
+ break;
+ }
+ case "bookmarkStart":
+ if (Attr(element, "name") is { Length: > 0 } bookmark && bookmark != "_GoBack")
+ builder.Add(new HBookmark(bookmark));
+ break;
+ case "ins" or "moveTo" or "smartTag" or "customXml" or "dir" or "bdo":
+ ParagraphContent(element.Elements(), builder, styleRun);
+ break;
+ case "sdt":
+ ParagraphContent(element.Element(W + "sdtContent")?.Elements() ?? [], builder, styleRun);
+ break;
+ default:
+ break; // pPr, del, moveFrom, proofErr, permStart, commentRangeStart ...: no visible content
+ }
+ }
+ }
+
+ private void Run(XElement r, ParagraphBuilder builder, RunProps styleRun)
+ {
+ var props = RunProperties(r.Element(W + "rPr"), styleRun);
+ if (props.Hidden == true)
+ return;
+ var format = CharFormat(props);
+
+ foreach (var child in r.Elements())
+ {
+ if (child.Name == Mc + "AlternateContent")
+ {
+ foreach (var chosen in ChooseAlternative(child))
+ RunChild(chosen, builder, format);
+ continue;
+ }
+ RunChild(child, builder, format);
+ }
+ }
+
+ private void RunChild(XElement child, ParagraphBuilder builder, HCharFormat format)
+ {
+ if (child.Name.Namespace != W)
+ return;
+ switch (child.Name.LocalName)
+ {
+ case "t":
+ if (ShowsText())
+ builder.Add(new HText(child.Value, format));
+ break;
+ case "tab" or "ptab":
+ if (ShowsText())
+ builder.Add(new HTab(format));
+ break;
+ case "br":
+ if (!ShowsText())
+ break;
+ switch (Attr(child, "type"))
+ {
+ case "page":
+ builder.Break(page: true);
+ break;
+ case "column":
+ builder.Break(page: false);
+ break;
+ default:
+ builder.Add(new HLineBreak(format));
+ break;
+ }
+ break;
+ case "cr":
+ if (ShowsText())
+ builder.Add(new HLineBreak(format));
+ break;
+ case "noBreakHyphen":
+ if (ShowsText())
+ builder.Add(new HText("-", format));
+ break;
+ case "sym":
+ if (ShowsText() && int.TryParse(Attr(child, "char"), System.Globalization.NumberStyles.HexNumber, null, out var code))
+ builder.Add(new HText(BulletText(((char)code).ToString()), format));
+ break;
+ case "fldChar":
+ FieldChar(child, builder, format);
+ break;
+ case "instrText":
+ if (_fields.LastOrDefault() is { Result: false } field)
+ field.Instruction.Append(child.Value);
+ break;
+ case "drawing":
+ if (ShowsText())
+ {
+ foreach (var inline in Drawing(child))
+ builder.Add(inline);
+ }
+ break;
+ case "pict" or "object":
+ if (ShowsText())
+ {
+ foreach (var inline in Vml(child))
+ builder.Add(inline);
+ }
+ break;
+ case "footnoteReference":
+ if (Note(child, _footnotes, _footnotesPart, endnote: false) is { } footnote)
+ builder.Add(footnote);
+ break;
+ case "endnoteReference":
+ if (Note(child, _endnotes, _endnotesPart, endnote: true) is { } endnote)
+ builder.Add(endnote);
+ break;
+ default:
+ break; // footnoteRef (the number, 한글 adds its own), separator, lastRenderedPageBreak, delText ...
+ }
+ }
+
+ private HNote? Note(XElement reference, Dictionary<string, XElement> notes, Part? part, bool endnote)
+ {
+ if (part is null || !notes.TryGetValue(Attr(reference, "id") ?? "", out var element))
+ return null;
+ var note = new HNote(endnote);
+ WithPart(part, () =>
+ {
+ ReadBlocks(element.Elements(), note.Blocks);
+ return 0;
+ });
+ // Word notes start with the reference mark and a space; 한글 writes its own number.
+ if (note.Blocks.FirstOrDefault() is HParagraph first && first.Inlines.FirstOrDefault() is HText { Text: var text } leading)
+ {
+ var trimmed = text.TrimStart();
+ first.Inlines[0] = new HText(trimmed, leading.Format);
+ }
+ return note;
+ }
+
+ /// <summary>mc:AlternateContent: the Choice when it is DrawingML we understand, else the (VML) Fallback.</summary>
+ private static IEnumerable<XElement> ChooseAlternative(XElement alternate)
+ {
+ var choice = alternate.Elements(Mc + "Choice").FirstOrDefault(c => (string?)c.Attribute("Requires") is "wps" or "wpg" or "wp14" or "w14" or "a14" or "wpc");
+ return (choice ?? alternate.Element(Mc + "Fallback") ?? alternate.Elements(Mc + "Choice").FirstOrDefault())?.Elements() ?? [];
+ }
+
+ // ───────────────────────── Fields ─────────────────────────
+
+ /// <summary>A complex field (w:fldChar begin … separate … end) that may span runs and paragraphs.</summary>
+ private sealed class FieldState
+ {
+ public readonly StringBuilder Instruction = new();
+ public bool Result;
+ public bool Suppress;
+ public string? Target;
+ }
+
+ /// <summary>Field result text is shown unless we are inside an instruction or a field we replace (PAGE ...).</summary>
+ private bool ShowsText() => _fields.All(f => f.Result && !f.Suppress);
+
+ private void FieldChar(XElement fldChar, ParagraphBuilder builder, HCharFormat format)
+ {
+ switch (Attr(fldChar, "fldCharType"))
+ {
+ case "begin":
+ _fields.Add(new FieldState());
+ break;
+ case "separate":
+ if (_fields.LastOrDefault() is { Result: false } field)
+ StartFieldResult(field, builder, format);
+ break;
+ case "end":
+ if (_fields.LastOrDefault() is { Result: false } withoutResult)
+ StartFieldResult(withoutResult, builder, format);
+ EndField(builder);
+ break;
+ }
+ }
+
+ private void StartFieldResult(FieldState field, ParagraphBuilder builder, HCharFormat format)
+ {
+ field.Result = true;
+ var words = SplitInstruction(field.Instruction.ToString());
+ switch (words.FirstOrDefault()?.ToUpperInvariant())
+ {
+ case "HYPERLINK":
+ {
+ // HYPERLINK "url" [\l "bookmark"] or HYPERLINK \l "bookmark"
+ string? url = null, anchor = null;
+ for (var i = 1; i < words.Count; i++)
+ {
+ if (words[i] == "\\l" && i + 1 < words.Count)
+ anchor = words[++i];
+ else if (!words[i].StartsWith('\\') && url is null)
+ url = words[i];
+ else if (words[i].StartsWith('\\') && i + 1 < words.Count && !words[i + 1].StartsWith('\\'))
+ i++; // other switch with an argument (\o "tooltip", \t "frame")
+ }
+ field.Target = anchor is not null ? (url ?? "") + "#" + anchor : url;
+ if (field.Target is not null)
+ builder.OpenLink(field.Target);
+ break;
+ }
+ case "PAGE":
+ builder.Add(new HField(HFieldKind.PageNumber, format));
+ field.Suppress = true;
+ break;
+ case "NUMPAGES" or "SECTIONPAGES":
+ builder.Add(new HField(HFieldKind.TotalPages, format));
+ field.Suppress = true;
+ break;
+ }
+ }
+
+ private void EndField(ParagraphBuilder builder)
+ {
+ if (_fields.Count == 0)
+ return;
+ var field = _fields[^1];
+ _fields.RemoveAt(_fields.Count - 1);
+ if (field.Target is not null)
+ builder.CloseLink();
+ }
+
+ /// <summary>Splits a field instruction into words, keeping quoted arguments together.</summary>
+ private static List<string> SplitInstruction(string instruction)
+ {
+ var words = new List<string>();
+ var current = new StringBuilder();
+ var quoted = false;
+ foreach (var ch in instruction)
+ {
+ if (ch == '"')
+ {
+ quoted = !quoted;
+ continue;
+ }
+ if (char.IsWhiteSpace(ch) && !quoted)
+ {
+ if (current.Length > 0)
+ words.Add(current.ToString());
+ current.Clear();
+ continue;
+ }
+ current.Append(ch);
+ }
+ if (current.Length > 0)
+ words.Add(current.ToString());
+ return words;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
new file mode 100644
index 00000000..c9d7716e
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs
@@ -0,0 +1,141 @@
+// Anything → HWPX without Hancom Office: a reader turns the source into the HWPX document model and HwpxWriter
+// writes the OWPML package.
+// * DOCX is read directly (Docx/DocxReader), keeping page setup, headers/footers, columns, text boxes and formatting.
+// * TXT needs no reader: one paragraph per line.
+// * Markdown, 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.Infrastructure;
+using Filee.Engines.Office;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+/// <summary>Writes HWPX files with the built-in OWPML writer.</summary>
+public sealed class HwpxConverter(EngineEnvironment env) : IConverter
+{
+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
+
+ /// <summary>Filee format id → Pandoc reader name.</summary>
+ private static readonly Dictionary<string, string> PandocReaders = new()
+ {
+ ["odt"] = "odt",
+ ["rtf"] = "rtf",
+ ["html"] = "html",
+ ["md"] = "markdown",
+ };
+
+ private string? _pandoc;
+
+ public string Id => "hwpx-writer";
+ 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 EngineStatus GetStatus()
+ {
+ _pandoc = PandocConverter.Locate(env);
+ return EngineStatus.Available(_pandoc is null
+ ? "DOCX, TXT → HWPX. Markdown, HTML, ODT and RTF need Pandoc."
+ : $"DOCX, TXT; Markdown, HTML, ODT, RTF with Pandoc ({_pandoc})");
+ }
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ progress?.Report(0.1);
+ var media = Path.Combine(step.WorkDirectory, $"media-{Guid.NewGuid():N}");
+ var document = step.From switch
+ {
+ "docx" => DocxReader.Read(step.InputPath, media),
+ "txt" => TextDocument(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),
+ _ => await ReadWithPandocAsync(step, media, cancellationToken),
+ };
+ progress?.Report(0.6);
+
+ var output = step.Output.Allocate("hwpx");
+ if (output is null)
+ return [];
+ HwpxWriter.Write(document, output);
+ progress?.Report(1);
+ return [output];
+ }
+
+ 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 json = Path.Combine(step.WorkDirectory, $"ast-{Guid.NewGuid():N}.json");
+
+ // Working directory = the input's folder, so relative image paths in HTML / Markdown resolve.
+ var result = await ProcessRunner.RunAsync(pandoc,
+ [step.InputPath, "-f", PandocReaders[step.From], "-t", "json", "--extract-media=" + media, "-o", json],
+ Timeout, cancellationToken, workingDirectory: Path.GetDirectoryName(step.InputPath));
+ if (!File.Exists(json))
+ throw new InvalidOperationException($"Pandoc failed (exit {result.ExitCode}). {result.StandardError.Trim()}");
+ var ast = JsonNode.Parse(await File.ReadAllTextAsync(json, cancellationToken))
+ ?? throw new InvalidDataException("Pandoc produced an empty document.");
+ var inputFolder = Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!;
+ return PandocAstReader.Read(ast, target => ResolveImage(target, inputFolder));
+ }
+
+ /// <summary>Images extracted by Pandoc have absolute paths; HTML / Markdown may use paths relative to the input.</summary>
+ private static string? ResolveImage(string target, string inputFolder)
+ {
+ if (string.IsNullOrWhiteSpace(target) || target.Contains("://", StringComparison.Ordinal))
+ return null;
+ var path = Uri.UnescapeDataString(target);
+ foreach (var candidate in new[] { path, Path.Combine(inputFolder, path) })
+ {
+ try
+ {
+ if (File.Exists(candidate))
+ return Path.GetFullPath(candidate);
+ }
+ catch (ArgumentException) { }
+ }
+ return null;
+ }
+
+ /// <summary>Plain text: one paragraph per line, text kept verbatim.</summary>
+ internal static HDocument TextDocument(byte[] bytes)
+ {
+ var section = new HSection();
+ foreach (var line in DecodeText(bytes).Replace("\r\n", "\n").Split('\n'))
+ {
+ var paragraph = new HParagraph();
+ if (line.Length > 0)
+ paragraph.Inlines.Add(new HText(line, default));
+ section.Blocks.Add(paragraph);
+ }
+ var document = new HDocument();
+ document.Sections.Add(section);
+ return document;
+ }
+
+ /// <summary>UTF-8 (with or without BOM) or UTF-16 with BOM; anything else is read as CP949, common for Korean text.</summary>
+ internal static string DecodeText(byte[] bytes)
+ {
+ if (bytes is [0xFF, 0xFE, ..] or [0xFE, 0xFF, ..])
+ return new StreamReader(new MemoryStream(bytes), detectEncodingFromByteOrderMarks: true).ReadToEnd();
+ try
+ {
+ var text = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(bytes);
+ return text.Length > 0 && text[0] == '\uFEFF' ? text[1..] : text;
+ }
+ catch (DecoderFallbackException)
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ return Encoding.GetEncoding(949).GetString(bytes);
+ }
+ }
+
+ private static List<ConversionEdge> BuildEdges(bool pandoc)
+ {
+ List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "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
new file mode 100644
index 00000000..bc5dbf74
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -0,0 +1,385 @@
+// In-memory document model between the readers (DOCX, Pandoc AST, plain text) and HwpxWriter.
+//
+// Lengths are HWPUNIT (1/7200 inch) and font sizes are 1/100 pt, like OWPML itself. A null format field means
+// "inherit from the 한글 style" (the Pandoc reader only knows bold/italic/..., the DOCX reader knows everything).
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+/// <summary>A document ready to be written as HWPX.</summary>
+internal sealed class HDocument
+{
+ public string? Title { get; set; }
+ public List<HSection> Sections { get; } = [];
+}
+
+/// <summary>A run of pages sharing page setup, headers and footers (한글 "구역").</summary>
+internal sealed class HSection
+{
+ /// <summary>Paper and margins; null keeps the template's A4 page.</summary>
+ public HPage? Page { get; set; }
+
+ public HColumns Columns { get; set; } = HColumns.Single;
+ public List<HHeaderFooter> Headers { get; } = [];
+ public List<HHeaderFooter> Footers { get; } = [];
+
+ /// <summary>Hide header / footer on the first page (DOCX "different first page" with an empty first header).</summary>
+ public bool HideFirstHeader { get; set; }
+ public bool HideFirstFooter { get; set; }
+
+ /// <summary>Restart page numbering at this number; null continues from the previous section.</summary>
+ public int? StartPageNumber { get; set; }
+
+ public List<HBlock> Blocks { get; } = [];
+}
+
+/// <summary>Paper size and margins.</summary>
+/// <param name="Width">Paper width as printed (landscape pages are wider than tall).</param>
+/// <param name="Height">Paper height as printed.</param>
+/// <param name="Top">Paper edge to the header (한글 "위쪽"); the body starts at <c>Top + Header</c>.</param>
+/// <param name="Header">Height of the header area (한글 "머리말").</param>
+/// <param name="Bottom">Paper edge to the footer (한글 "아래쪽").</param>
+/// <param name="Footer">Height of the footer area (한글 "꼬리말").</param>
+internal sealed record HPage(int Width, int Height, int Left, int Right, int Top, int Bottom, int Header, int Footer, int Gutter)
+{
+ public bool Landscape => Width > Height;
+ public int TextWidth => Math.Max(2000, Width - Left - Right - Gutter);
+}
+
+/// <summary>Newspaper-style columns.</summary>
+internal sealed record HColumns(int Count, int Gap, bool Separator)
+{
+ public static readonly HColumns Single = new(1, 0, false);
+}
+
+/// <summary>Which pages a header or footer applies to.</summary>
+internal enum HPageType
+{
+ Both,
+ Even,
+ Odd,
+}
+
+internal sealed class HHeaderFooter(HPageType pages)
+{
+ public HPageType Pages { get; } = pages;
+ public List<HBlock> Blocks { get; } = [];
+}
+
+// ───────────────────────── Blocks ─────────────────────────
+
+internal abstract class HBlock;
+
+internal sealed class HParagraph : HBlock
+{
+ public HParaFormat Format { get; set; }
+
+ /// <summary>Format of the paragraph mark: decides the height of an empty paragraph.</summary>
+ public HCharFormat MarkFormat { get; set; }
+
+ /// <summary>1..9 for headings (mapped to the "Heading n" styles, which are outline levels in 한글), else 0.</summary>
+ public int HeadingLevel { get; set; }
+
+ /// <summary>List numbering of this paragraph, or null.</summary>
+ public HListRef? List { get; set; }
+
+ public bool PageBreakBefore { get; set; }
+ public bool ColumnBreakBefore { get; set; }
+
+ /// <summary>Columns change here without a new page (DOCX continuous section break); null = unchanged.</summary>
+ public HColumns? ColumnsChange { get; set; }
+
+ public List<HInline> Inlines { get; } = [];
+}
+
+/// <summary>A list a paragraph belongs to.</summary>
+/// <param name="Numbering">List definition (shared by all items of one list).</param>
+/// <param name="Level">0-based nesting level.</param>
+/// <param name="Numbered">False for continuation paragraphs of an item (no bullet or number).</param>
+internal sealed record HListRef(HNumbering Numbering, int Level, bool Numbered);
+
+/// <summary>A list definition: one entry per nesting level.</summary>
+internal sealed class HNumbering
+{
+ public List<HNumberingLevel> Levels { get; } = [];
+}
+
+/// <param name="Format">OWPML numFormat: DIGIT, LATIN_SMALL, HANGUL_SYLLABLE, ... (ignored for bullets).</param>
+/// <param name="Text">Number text with <c>^n</c> for the level-n counter ("^1.", "(^2)"), or the bullet character.</param>
+internal sealed record HNumberingLevel(string Format, string Text, int Start, bool Bullet);
+
+internal sealed class HTable : HBlock
+{
+ public List<HRow> Rows { get; } = [];
+
+ /// <summary>Absolute column widths; null = use <see cref="RelativeWidths"/> or share the text width equally.</summary>
+ public int[]? ColumnWidths { get; set; }
+
+ /// <summary>Column widths as fractions of the text width (Pandoc); zero entries share the rest.</summary>
+ public double[]? RelativeWidths { get; set; }
+
+ public int ColumnCount { get; set; }
+ public HAlign Align { get; set; } = HAlign.Left;
+ public int Indent { get; set; }
+
+ /// <summary>Cell padding; null = 한글 default.</summary>
+ public HInsets? CellMargin { get; set; }
+
+ /// <summary>Borders used where a cell does not define its own; null = thin solid grid.</summary>
+ public HBorders? Borders { get; set; }
+
+ public List<HBlock> Caption { get; } = [];
+}
+
+internal sealed class HRow
+{
+ public List<HCell> Cells { get; } = [];
+
+ /// <summary>Minimum row height; null = fit content.</summary>
+ public int? Height { get; set; }
+
+ public bool Header { get; set; }
+}
+
+internal sealed class HCell
+{
+ /// <summary>Grid column of the cell; -1 = right after the previous cell (row spans are skipped).</summary>
+ public int Column { get; set; } = -1;
+ public int RowSpan { get; set; } = 1;
+ public int ColSpan { get; set; } = 1;
+ public HVerticalAlign VerticalAlign { get; set; }
+ public string? Fill { get; set; }
+ public HBorders? Borders { get; set; }
+ public List<HBlock> Blocks { get; } = [];
+}
+
+internal enum HVerticalAlign
+{
+ Top,
+ Center,
+ Bottom,
+}
+
+internal readonly record struct HInsets(int Left, int Right, int Top, int Bottom);
+
+/// <summary>One border line. Width is in mm (snapped to the widths 한글 offers when written).</summary>
+internal readonly record struct HBorder(HBorderStyle Style, double WidthMm, string Color)
+{
+ public static readonly HBorder None = new(HBorderStyle.None, 0.1, "#000000");
+ public static readonly HBorder Thin = new(HBorderStyle.Solid, 0.12, "#000000");
+}
+
+internal enum HBorderStyle
+{
+ None,
+ Solid,
+ Dash,
+ Dot,
+ DashDot,
+ Double,
+}
+
+internal readonly record struct HBorders(HBorder Left, HBorder Right, HBorder Top, HBorder Bottom)
+{
+ public static readonly HBorders Grid = new(HBorder.Thin, HBorder.Thin, HBorder.Thin, HBorder.Thin);
+ public static readonly HBorders Empty = new(HBorder.None, HBorder.None, HBorder.None, HBorder.None);
+}
+
+// ───────────────────────── Inlines ─────────────────────────
+
+internal abstract class HInline;
+
+internal sealed class HText(string text, HCharFormat format) : HInline
+{
+ public string Text { get; } = text;
+ public HCharFormat Format { get; } = format;
+}
+
+internal sealed class HLineBreak(HCharFormat format) : HInline
+{
+ public HCharFormat Format { get; } = format;
+}
+
+internal sealed class HTab(HCharFormat format) : HInline
+{
+ public HCharFormat Format { get; } = format;
+}
+
+/// <summary>Hyperlink to a URL, or to a bookmark when the target starts with '#'.</summary>
+internal sealed class HLink(string target) : HInline
+{
+ public string Target { get; } = target;
+ public List<HInline> Content { get; } = [];
+}
+
+internal sealed class HBookmark(string name) : HInline
+{
+ public string Name { get; } = name;
+}
+
+internal sealed class HNote(bool endnote) : HInline
+{
+ public bool Endnote { get; } = endnote;
+ public List<HBlock> Blocks { get; } = [];
+}
+
+internal enum HFieldKind
+{
+ PageNumber,
+ TotalPages,
+}
+
+/// <summary>Automatic number (page number in headers and footers).</summary>
+internal sealed class HField(HFieldKind kind, HCharFormat format) : HInline
+{
+ public HFieldKind Kind { get; } = kind;
+ public HCharFormat Format { get; } = format;
+}
+
+/// <summary>Picture from a local file.</summary>
+internal sealed class HImage(string path) : HInline
+{
+ public string Path { get; } = path;
+
+ /// <summary>Display size; null = natural size (capped to the text width).</summary>
+ public int? Width { get; set; }
+ public int? Height { get; set; }
+
+ /// <summary>Position for floating pictures; null = inline, moves with the text like a character.</summary>
+ public HAnchor? Anchor { get; set; }
+}
+
+/// <summary>A box with its own paragraphs (DOCX text box, 한글 글상자).</summary>
+internal sealed class HTextBox : HInline
+{
+ public int Width { get; set; }
+ public int Height { get; set; }
+ public HAnchor? Anchor { get; set; }
+ public string? Fill { get; set; }
+ public HBorder Line { get; set; } = HBorder.Thin;
+ public HInsets Padding { get; set; } = new(283, 283, 283, 283);
+ public HVerticalAlign VerticalAlign { get; set; }
+ public List<HBlock> Blocks { get; } = [];
+}
+
+internal enum HShapeKind
+{
+ Rectangle,
+ Ellipse,
+ Line,
+}
+
+/// <summary>A drawing without text: rectangle, ellipse or straight line.</summary>
+internal sealed class HShape(HShapeKind kind) : HInline
+{
+ public HShapeKind Kind { get; } = kind;
+ public int Width { get; set; }
+ 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>Corner rounding of rectangles in percent (0 = square).</summary>
+ public int CornerRatio { get; set; }
+
+ /// <summary>Lines run from top-left to bottom-right unless flipped.</summary>
+ public bool FlipHorizontal { get; set; }
+ public bool FlipVertical { get; set; }
+}
+
+/// <summary>Linear gradient fill: colours from start to end, angle in degrees.</summary>
+internal sealed record HGradient(IReadOnlyList<string> Colors, int Angle);
+
+/// <summary>Position of a floating object.</summary>
+/// <param name="HorizontalRelativeTo">PAPER, PAGE (= margin box), COLUMN or PARA — OWPML horzRelTo.</param>
+/// <param name="HorizontalAlign">LEFT, CENTER, RIGHT, INSIDE, OUTSIDE — used with a zero offset.</param>
+/// <param name="VerticalRelativeTo">PAPER, PAGE or PARA — OWPML vertRelTo.</param>
+/// <param name="VerticalAlign">TOP, CENTER, BOTTOM, INSIDE, OUTSIDE.</param>
+/// <param name="Wrap">SQUARE, TOP_AND_BOTTOM, BEHIND_TEXT or IN_FRONT_OF_TEXT — OWPML textWrap.</param>
+internal sealed record HAnchor(
+ string HorizontalRelativeTo, string HorizontalAlign, int HorizontalOffset,
+ string VerticalRelativeTo, string VerticalAlign, int VerticalOffset,
+ string Wrap, bool AllowOverlap);
+
+// ───────────────────────── Formats ─────────────────────────
+
+internal enum HAlign
+{
+ Left,
+ Center,
+ Right,
+ Justify,
+ Distribute,
+}
+
+internal enum HLineSpacingKind
+{
+ /// <summary>Percent of the font size (한글 default is 160%).</summary>
+ Percent,
+ Fixed,
+ AtLeast,
+}
+
+internal readonly record struct HLineSpacing(HLineSpacingKind Kind, int Value);
+
+/// <summary>Paragraph formatting; null members keep the 한글 style's value.</summary>
+/// <param name="FirstLine">First line indent relative to <paramref name="Left"/>; negative = hanging indent.</param>
+internal readonly record struct HParaFormat(
+ HAlign? Align = null,
+ int? Left = null,
+ int? Right = null,
+ int? FirstLine = null,
+ int? Before = null,
+ int? After = null,
+ HLineSpacing? LineSpacing = null,
+ bool? KeepWithNext = null,
+ bool? KeepLines = null,
+ bool? WidowOrphan = null,
+ IReadOnlyList<HTabStop>? Tabs = null)
+{
+ public bool IsEmpty => this == default;
+
+ // Tab stop lists compare by content so equal formats share one paraPr.
+ public bool Equals(HParaFormat other) =>
+ Align == other.Align && Left == other.Left && Right == other.Right && FirstLine == other.FirstLine &&
+ Before == other.Before && After == other.After && LineSpacing == other.LineSpacing &&
+ KeepWithNext == other.KeepWithNext && KeepLines == other.KeepLines && WidowOrphan == other.WidowOrphan &&
+ (Tabs ?? []).SequenceEqual(other.Tabs ?? []);
+
+ public override int GetHashCode() =>
+ HashCode.Combine(Align, Left, Right, FirstLine, Before, After, LineSpacing, HashCode.Combine(KeepWithNext, KeepLines, WidowOrphan, Tabs?.Count ?? 0));
+}
+
+internal enum HTabKind
+{
+ Left,
+ Right,
+ Center,
+ Decimal,
+}
+
+/// <param name="Leader">OWPML line type of the leader: NONE, DOT, DASH, SOLID ...</param>
+internal readonly record struct HTabStop(int Position, HTabKind Kind, string Leader);
+
+/// <summary>Character formatting; null members keep the 한글 style's value.</summary>
+/// <param name="Size">Font size in 1/100 pt.</param>
+/// <param name="Font">Font for Latin text.</param>
+/// <param name="EastAsianFont">Font for Hangul / Hanja / Japanese text.</param>
+/// <param name="Color">Text colour "#RRGGBB".</param>
+/// <param name="Shade">Background (highlight) colour "#RRGGBB".</param>
+internal readonly record struct HCharFormat(
+ bool? Bold = null,
+ bool? Italic = null,
+ bool? Underline = null,
+ bool? Strike = null,
+ bool? Superscript = null,
+ bool? Subscript = null,
+ int? Size = null,
+ string? Font = null,
+ string? EastAsianFont = null,
+ string? Color = null,
+ string? Shade = null,
+ int? Spacing = null)
+{
+ public bool IsEmpty => this == default;
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxUnits.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxUnits.cs
new file mode 100644
index 00000000..5d095302
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxUnits.cs
@@ -0,0 +1,45 @@
+// Unit conversions shared by the HWPX readers and writer. HWPUNIT = 1/7200 inch.
+
+using System.Globalization;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal static class HwpxUnits
+{
+ public const double PerMm = 7200 / 25.4;
+ public const double PerPixel = 7200 / 96.0;
+
+ /// <summary>Word twips (1/1440 inch) → HWPUNIT.</summary>
+ public static int FromTwips(double twips) => (int)Math.Round(twips * 5);
+
+ /// <summary>DrawingML EMU (1/914400 inch) → HWPUNIT.</summary>
+ public static int FromEmu(double emu) => (int)Math.Round(emu / 127);
+
+ /// <summary>Points → HWPUNIT.</summary>
+ public static int FromPoints(double points) => (int)Math.Round(points * 100);
+
+ /// <summary>Parses a CSS-like length ("2in", "300px", "12pt", "50%") into HWPUNIT.</summary>
+ public static int? ParseLength(string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return null;
+ var text = value.Trim().ToLowerInvariant();
+ var split = 0;
+ while (split < text.Length && (char.IsDigit(text[split]) || text[split] is '.' or '-'))
+ split++;
+ if (!double.TryParse(text[..split], NumberStyles.Float, CultureInfo.InvariantCulture, out var number))
+ return null;
+ var mm = text[split..].Trim() switch
+ {
+ "in" => number * 25.4,
+ "cm" => number * 10,
+ "mm" => number,
+ "pt" => number * 25.4 / 72,
+ "pc" => number * 25.4 / 6,
+ "emu" => number / 36000,
+ "%" => number * 1.5, // % of a ~150 mm text width
+ _ => number * 25.4 / 96, // px or unitless
+ };
+ return (int)Math.Round(mm * PerMm);
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
new file mode 100644
index 00000000..46149b20
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
@@ -0,0 +1,410 @@
+// Section parts: page setup, columns, headers/footers, paragraphs, runs and tables.
+//
+// 한글 keeps page setup (secPr) and the column definition (colPr) in the first run of a section's first
+// paragraph; header and footer controls follow in the same run. Page and column breaks are paragraph attributes.
+
+using System.Text;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class HwpxWriter
+{
+ /// <summary>Width available to the content being written (text width, column, table cell or text box).</summary>
+ private int _width = 42520;
+
+ /// <summary>Distance from the paper edge to the text area of the current section (left, and top including the header).</summary>
+ private int _pageLeft = 7200;
+ private int _pageTop = 8505;
+
+ /// <summary>Style of plain paragraphs in the current container (body text, or footnote text inside notes).</summary>
+ private (string StyleId, string ParaPrId, string CharPrId) _base;
+
+ // ───────────────────────── Sections ─────────────────────────
+
+ private string Section(HSection section)
+ {
+ var secPr = new XElement(_templateSection.Descendants(Hp + "secPr").FirstOrDefault()
+ ?? throw new InvalidDataException("The template section has no secPr."));
+ var pagePr = secPr.Element(Hp + "pagePr");
+ var margin = pagePr?.Element(Hp + "margin");
+ if (section.Page is { } page && pagePr is not null && margin is not null)
+ {
+ // Width/height always describe the portrait sheet; "NARROWLY" turns it (landscape), "WIDELY" does not.
+ pagePr.SetAttributeValue("landscape", page.Landscape ? "NARROWLY" : "WIDELY");
+ pagePr.SetAttributeValue("width", Math.Min(page.Width, page.Height));
+ pagePr.SetAttributeValue("height", Math.Max(page.Width, page.Height));
+ margin.SetAttributeValue("left", page.Left);
+ margin.SetAttributeValue("right", page.Right);
+ margin.SetAttributeValue("top", page.Top);
+ margin.SetAttributeValue("bottom", page.Bottom);
+ margin.SetAttributeValue("header", page.Header);
+ margin.SetAttributeValue("footer", page.Footer);
+ margin.SetAttributeValue("gutter", page.Gutter);
+ }
+ if (secPr.Element(Hp + "visibility") is { } visibility)
+ {
+ visibility.SetAttributeValue("hideFirstHeader", section.HideFirstHeader ? 1 : 0);
+ visibility.SetAttributeValue("hideFirstFooter", section.HideFirstFooter ? 1 : 0);
+ }
+ secPr.Element(Hp + "startNum")?.SetAttributeValue("page", section.StartPageNumber ?? 0);
+
+ int Margin(string name, int fallback) => (int?)margin?.Attribute(name) ?? fallback;
+ var paperWidth = (int?)pagePr?.Attribute("width") ?? 59530;
+ var paperHeight = (int?)pagePr?.Attribute("height") ?? 84190;
+ var landscape = (string?)pagePr?.Attribute("landscape") == "NARROWLY";
+ var textWidth = Math.Max(2000, (landscape ? paperHeight : paperWidth) - Margin("left", 7200) - Margin("right", 7200) - Margin("gutter", 0));
+ _pageLeft = Margin("left", 7200) + Margin("gutter", 0);
+ _pageTop = Margin("top", 4255) + Margin("header", 4250);
+
+ var setup = new StringBuilder();
+ setup.Append(Inner(secPr));
+ setup.Append("<hp:ctrl>").Append(ColumnDefinition(section.Columns)).Append("</hp:ctrl>");
+
+ _base = (_normalStyleId, _normalParaPrId, _normalCharPrId);
+ _width = textWidth;
+ var controlId = 1;
+ foreach (var header in section.Headers)
+ setup.Append(HeaderFooter("header", header, controlId++, textWidth, Margin("header", 4250), "TOP"));
+ foreach (var footer in section.Footers)
+ setup.Append(HeaderFooter("footer", footer, controlId++, textWidth, Margin("footer", 2240), "BOTTOM"));
+
+ _width = ColumnWidth(textWidth, section.Columns);
+ var body = new StringBuilder(SectionOpenTag());
+ var blocks = section.Blocks.Count == 0 || section.Blocks[0] is not HParagraph
+ ? section.Blocks.Prepend(new HParagraph()).ToList()
+ : section.Blocks;
+ for (var i = 0; i < blocks.Count; i++)
+ {
+ if (blocks[i] is HParagraph { ColumnsChange: { } columns })
+ _width = ColumnWidth(textWidth, columns);
+ body.Append(Block(blocks[i], i == 0 ? $"<hp:run charPrIDRef=\"{_normalCharPrId}\">{setup}</hp:run>" : null));
+ }
+ return body.Append("</hs:sec>").ToString();
+ }
+
+ private static int ColumnWidth(int textWidth, HColumns columns) =>
+ columns.Count <= 1 ? textWidth : Math.Max(2000, (textWidth - columns.Gap * (columns.Count - 1)) / columns.Count);
+
+ private static string ColumnDefinition(HColumns columns)
+ {
+ var line = columns.Separator ? "<hp:colLine type=\"SOLID\" width=\"0.12 mm\" color=\"#000000\"/>" : "";
+ return $"<hp:colPr id=\"\" type=\"NEWSPAPER\" layout=\"LEFT\" colCount=\"{Math.Max(1, columns.Count)}\" sameSz=\"1\" sameGap=\"{(columns.Count > 1 ? columns.Gap : 0)}\">{line}</hp:colPr>";
+ }
+
+ private string HeaderFooter(string kind, HHeaderFooter item, int id, int textWidth, int textHeight, string verticalAlign)
+ {
+ var pages = item.Pages switch
+ {
+ HPageType.Even => "EVEN",
+ HPageType.Odd => "ODD",
+ _ => "BOTH",
+ };
+ return $"<hp:ctrl><hp:{kind} id=\"{id}\" applyPageType=\"{pages}\">" +
+ SubList(item.Blocks, verticalAlign, textWidth, textHeight) +
+ $"</hp:{kind}></hp:ctrl>";
+ }
+
+ /// <summary>Paragraph list of a header, footer, cell, text box or note.</summary>
+ private string SubList(List<HBlock> blocks, string verticalAlign, int textWidth = 0, int textHeight = 0, string? leadingRun = null)
+ {
+ var sb = new StringBuilder();
+ sb.Append($"<hp:subList id=\"\" textDirection=\"HORIZONTAL\" lineWrap=\"BREAK\" vertAlign=\"{verticalAlign}\" linkListIDRef=\"0\" linkListNextIDRef=\"0\" textWidth=\"{textWidth}\" textHeight=\"{textHeight}\" hasTextRef=\"0\" hasNumRef=\"0\">");
+ var list = blocks.Count == 0 || (leadingRun is not null && blocks[0] is not HParagraph) ? blocks.Prepend(new HParagraph()).ToList() : blocks;
+ for (var i = 0; i < list.Count; i++)
+ sb.Append(Block(list[i], i == 0 ? leadingRun : null));
+ return sb.Append("</hp:subList>").ToString();
+ }
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ /// <param name="leadingRun">Raw run placed first in the paragraph (section setup, note number).</param>
+ private string Block(HBlock block, string? leadingRun = null) => block switch
+ {
+ HParagraph paragraph => Paragraph(paragraph, leadingRun),
+ HTable table => Table(table, leadingRun),
+ _ => "",
+ };
+
+ private string Paragraph(HParagraph paragraph, string? leadingRun)
+ {
+ _plainText.AppendLine();
+ var (styleId, paraPrBase, charPrBase) = paragraph.HeadingLevel > 0 && _headings.TryGetValue(paragraph.HeadingLevel, out var heading)
+ ? heading
+ : _base;
+ var paraPrId = ParaPr(paraPrBase, paragraph.Format, paragraph.List);
+
+ var runs = new RunBuilder();
+ if (paragraph.ColumnsChange is { } columns)
+ runs.Control(_normalCharPrId, $"<hp:ctrl>{ColumnDefinition(columns)}</hp:ctrl>");
+ var size = LargestSize(paragraph.Inlines) ?? paragraph.MarkFormat.Size ?? BaseSize(charPrBase);
+ var tabs = new Queue<string>(TabElements(paragraph, size));
+ Inlines(paragraph.Inlines, runs, charPrBase, link: false, tabs);
+
+ var sb = new StringBuilder();
+ sb.Append($"<hp:p id=\"0\" paraPrIDRef=\"{paraPrId}\" styleIDRef=\"{styleId}\" pageBreak=\"{(paragraph.PageBreakBefore ? 1 : 0)}\" columnBreak=\"{(paragraph.ColumnBreakBefore ? 1 : 0)}\" merged=\"0\">");
+ sb.Append(leadingRun);
+ sb.Append(runs.Finish(CharPr(charPrBase, paragraph.MarkFormat), leadingRun is not null));
+ return sb.Append("</hp:p>").ToString();
+ }
+
+ /// <summary>
+ /// Collects runs: consecutive content with the same character shape shares one hp:run and one hp:t, and
+ /// controls (fields, bookmarks) and objects (pictures, tables, text boxes) go between the text parts.
+ /// </summary>
+ private sealed class RunBuilder
+ {
+ private readonly StringBuilder _output = new();
+ private readonly StringBuilder _items = new();
+ private string? _charPr;
+ private bool _textOpen;
+ private bool _endsWithObject;
+
+ public void Text(string charPr, string xml)
+ {
+ Switch(charPr);
+ if (!_textOpen)
+ {
+ _items.Append("<hp:t>");
+ _textOpen = true;
+ }
+ _items.Append(xml);
+ _endsWithObject = false;
+ }
+
+ public void Control(string charPr, string xml, bool isObject = false)
+ {
+ Switch(charPr);
+ CloseText();
+ _items.Append(xml);
+ _endsWithObject = isObject;
+ }
+
+ /// <summary>The runs; an empty paragraph still needs one run for 한글 to show it.</summary>
+ public string Finish(string emptyCharPr, bool hasLeadingRun)
+ {
+ Flush();
+ return _output.Length == 0 && !hasLeadingRun ? $"<hp:run charPrIDRef=\"{emptyCharPr}\"><hp:t/></hp:run>" : _output.ToString();
+ }
+
+ private void Switch(string charPr)
+ {
+ if (_charPr == charPr)
+ return;
+ Flush();
+ _charPr = charPr;
+ }
+
+ private void CloseText()
+ {
+ if (_textOpen)
+ _items.Append("</hp:t>");
+ _textOpen = false;
+ }
+
+ private void Flush()
+ {
+ if (_charPr is null)
+ return;
+ CloseText();
+ if (_endsWithObject)
+ _items.Append("<hp:t/>"); // as 한글 writes it after an object
+ _output.Append("<hp:run charPrIDRef=\"").Append(_charPr).Append("\">").Append(_items).Append("</hp:run>");
+ _items.Clear();
+ _charPr = null;
+ _endsWithObject = false;
+ }
+ }
+
+ /// <param name="tabs">Pre-computed inline tab elements of the paragraph, in order (see TabElements).</param>
+ private void Inlines(IEnumerable<HInline> inlines, RunBuilder runs, string charPrBase, bool link, Queue<string> tabs)
+ {
+ foreach (var inline in inlines)
+ {
+ switch (inline)
+ {
+ case HText text:
+ runs.Text(CharPr(charPrBase, text.Format, link), Escape(text.Text));
+ _plainText.Append(text.Text);
+ break;
+ case HLineBreak lineBreak:
+ runs.Text(CharPr(charPrBase, lineBreak.Format, link), "<hp:lineBreak/>");
+ _plainText.AppendLine();
+ break;
+ case HTab tab:
+ runs.Text(CharPr(charPrBase, tab.Format, link), tabs.Count > 0 ? tabs.Dequeue() : "<hp:tab width=\"4000\" leader=\"0\" type=\"1\"/>");
+ _plainText.Append('\t');
+ break;
+ case HLink hyperlink:
+ {
+ var id = NextId();
+ var format = hyperlink.Content.OfType<HText>().FirstOrDefault()?.Format ?? default;
+ var charPr = CharPr(charPrBase, format, link: true);
+ runs.Control(charPr, FieldBegin(id, hyperlink.Target));
+ Inlines(hyperlink.Content, runs, charPrBase, link: true, tabs);
+ runs.Control(charPr, $"<hp:ctrl><hp:fieldEnd beginIDRef=\"{id}\" fieldid=\"{HyperlinkFieldId}\"/></hp:ctrl>");
+ break;
+ }
+ case HBookmark bookmark:
+ runs.Control(charPrBase, $"<hp:ctrl><hp:bookmark name=\"{Escape(bookmark.Name)}\"/></hp:ctrl>");
+ break;
+ case HField field:
+ runs.Control(CharPr(charPrBase, field.Format), AutoNumber(field.Kind == HFieldKind.PageNumber ? "PAGE" : "TOTAL_PAGE", 1, ""));
+ break;
+ case HNote note:
+ runs.Control(charPrBase, Note(note));
+ break;
+ case HImage image:
+ if (Picture(image) is { } picture)
+ runs.Control(charPrBase, picture, isObject: true);
+ break;
+ case HTextBox box:
+ runs.Control(charPrBase, TextBox(box), isObject: true);
+ break;
+ case HShape shape:
+ runs.Control(charPrBase, Shape(shape), isObject: true);
+ break;
+ }
+ }
+ }
+
+ // ───────────────────────── Tables ─────────────────────────
+
+ private string Table(HTable table, string? leadingRun)
+ {
+ if (table.Rows.Count == 0)
+ return leadingRun is null ? "" : Paragraph(new HParagraph(), leadingRun);
+
+ var (placed, columnCount) = PlaceCells(table);
+
+ var available = Math.Max(4000, _width - table.Indent);
+ var widths = ColumnWidths(table, columnCount, available);
+ var totalWidth = widths.Sum();
+ var rowHeights = EstimateRowHeights(table, placed, widths);
+ var margin = table.CellMargin ?? new HInsets(510, 510, 141, 141);
+ var tableBorders = table.Borders ?? HBorders.Grid;
+ var headerRows = table.Rows.TakeWhile(r => r.Header).Count();
+
+ var sb = new StringBuilder();
+ var id = NextId();
+ sb.Append($"<hp:tbl id=\"{id}\" zOrder=\"0\" numberingType=\"TABLE\" textWrap=\"TOP_AND_BOTTOM\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" pageBreak=\"CELL\" repeatHeader=\"{(headerRows > 0 ? 1 : 0)}\" rowCnt=\"{table.Rows.Count}\" colCnt=\"{columnCount}\" cellSpacing=\"0\" borderFillIDRef=\"{BorderFillId(tableBorders, null)}\" noAdjust=\"0\">");
+ sb.Append($"<hp:sz width=\"{totalWidth}\" widthRelTo=\"ABSOLUTE\" height=\"{rowHeights.Sum()}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>");
+ var horizontalAlign = table.Align switch
+ {
+ HAlign.Center => "CENTER",
+ HAlign.Right => "RIGHT",
+ _ => "LEFT",
+ };
+ sb.Append($"<hp:pos treatAsChar=\"0\" affectLSpacing=\"0\" flowWithText=\"1\" allowOverlap=\"0\" holdAnchorAndSO=\"0\" vertRelTo=\"PARA\" horzRelTo=\"COLUMN\" vertAlign=\"TOP\" horzAlign=\"{horizontalAlign}\" vertOffset=\"0\" horzOffset=\"{(table.Align == HAlign.Left ? table.Indent : 0)}\"/>");
+ sb.Append("<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"1417\"/>");
+ sb.Append($"<hp:inMargin left=\"{margin.Left}\" right=\"{margin.Right}\" top=\"{margin.Top}\" bottom=\"{margin.Bottom}\"/>");
+
+ var outerWidth = _width;
+ for (var r = 0; r < placed.Count; r++)
+ {
+ sb.Append("<hp:tr>");
+ foreach (var (cell, column) in placed[r])
+ {
+ var width = 0;
+ for (var i = column; i < column + cell.ColSpan && i < widths.Length; i++)
+ width += widths[i];
+ var height = 0;
+ for (var i = r; i < r + cell.RowSpan && i < rowHeights.Length; i++)
+ height += rowHeights[i];
+
+ _width = Math.Max(1000, width - margin.Left - margin.Right);
+ var verticalAlign = cell.VerticalAlign switch
+ {
+ HVerticalAlign.Center => "CENTER",
+ HVerticalAlign.Bottom => "BOTTOM",
+ _ => "TOP",
+ };
+ sb.Append($"<hp:tc name=\"\" header=\"{(r < headerRows ? 1 : 0)}\" hasMargin=\"0\" protect=\"0\" editable=\"0\" dirty=\"0\" borderFillIDRef=\"{BorderFillId(cell.Borders ?? tableBorders, cell.Fill)}\">");
+ sb.Append(SubList(cell.Blocks, verticalAlign));
+ sb.Append($"<hp:cellAddr colAddr=\"{column}\" rowAddr=\"{r}\"/>");
+ sb.Append($"<hp:cellSpan colSpan=\"{cell.ColSpan}\" rowSpan=\"{cell.RowSpan}\"/>");
+ // Like 한글 itself: a merged cell is as tall as all the rows it spans.
+ sb.Append($"<hp:cellSz width=\"{width}\" height=\"{height}\"/>");
+ sb.Append($"<hp:cellMargin left=\"{margin.Left}\" right=\"{margin.Right}\" top=\"{margin.Top}\" bottom=\"{margin.Bottom}\"/>");
+ sb.Append("</hp:tc>");
+ }
+ sb.Append("</hp:tr>");
+ }
+ _width = outerWidth;
+ sb.Append("</hp:tbl>");
+
+ var runs = new RunBuilder();
+ runs.Control(_base.CharPrId, sb.ToString(), isObject: true);
+ var paragraph = $"<hp:p id=\"0\" paraPrIDRef=\"{_base.ParaPrId}\" styleIDRef=\"{_base.StyleId}\" pageBreak=\"0\" columnBreak=\"0\" merged=\"0\">{leadingRun}{runs.Finish(_base.CharPrId, leadingRun is not null)}</hp:p>";
+ return paragraph + string.Concat(table.Caption.Select(b => Block(b)));
+ }
+
+ /// <summary>
+ /// Grid position of every cell: explicit cell columns (DOCX) or the next free position (Pandoc), skipping
+ /// positions covered by cells spanning rows from above.
+ /// </summary>
+ private static (List<List<(HCell Cell, int Column)>> Placed, int Columns) PlaceCells(HTable table)
+ {
+ var placed = new List<List<(HCell, int)>>();
+ var occupied = new HashSet<(int Row, int Column)>();
+ var columnCount = table.ColumnCount;
+ for (var r = 0; r < table.Rows.Count; r++)
+ {
+ var row = new List<(HCell, int)>();
+ var column = 0;
+ foreach (var cell in table.Rows[r].Cells)
+ {
+ if (cell.Column >= 0)
+ column = cell.Column;
+ while (occupied.Contains((r, column)))
+ column++;
+ for (var dr = 0; dr < cell.RowSpan; dr++)
+ {
+ for (var dc = 0; dc < cell.ColSpan; dc++)
+ occupied.Add((r + dr, column + dc));
+ }
+ row.Add((cell, column));
+ column += cell.ColSpan;
+ columnCount = Math.Max(columnCount, column);
+ }
+ placed.Add(row);
+ }
+ return (placed, Math.Max(1, columnCount));
+ }
+
+ /// <summary>Column widths that fit <paramref name="available"/>: absolute (scaled down if too wide), relative or equal.</summary>
+ private static int[] ColumnWidths(HTable table, int columns, int available)
+ {
+ if (table.ColumnWidths is { Length: > 0 } absolute)
+ {
+ var widths = Enumerable.Range(0, columns).Select(i => i < absolute.Length ? absolute[i] : (int)absolute.Average()).ToArray();
+ var total = widths.Sum();
+ return total <= available ? widths : widths.Select(w => (int)((long)w * available / total)).ToArray();
+ }
+
+ var fractions = Enumerable.Range(0, columns).Select(i => table.RelativeWidths is { } rel && i < rel.Length ? rel[i] : 0).ToArray();
+ var known = fractions.Where(f => f > 0).Sum();
+ var unknown = fractions.Count(f => f <= 0);
+ var scale = known > 1 ? 1 / known : 1; // never exceed the text width
+ var rest = unknown == 0 ? 0 : Math.Max(0, 1 - known * scale) / unknown;
+ if (unknown > 0 && rest <= 0)
+ return Enumerable.Repeat(available / columns, columns).ToArray(); // explicit columns used all the width
+ return fractions.Select(f => (int)(available * (f > 0 ? f * scale : rest))).ToArray();
+ }
+
+ /// <summary>
+ /// Serializes an element with the usual prefixes (hp:, hc: ...) but without namespace declarations, which the
+ /// section root already makes. A detached element would otherwise be written with a default namespace
+ /// (&lt;secPr xmlns="..."&gt;), which 한글 and other HWPX readers that match prefixed names do not accept.
+ /// </summary>
+ private static string Inner(XElement element)
+ {
+ var copy = new XElement(element);
+ foreach (var (prefix, ns) in new[] { ("hp", Hp), ("hc", Hc), ("hh", Hh), ("hs", Hs) })
+ copy.SetAttributeValue(XNamespace.Xmlns + prefix, ns.NamespaceName);
+ var xml = copy.ToString(SaveOptions.DisableFormatting);
+ foreach (var (prefix, ns) in new[] { ("hp", Hp), ("hc", Hc), ("hh", Hh), ("hs", Hs) })
+ xml = xml.Replace($" xmlns:{prefix}=\"{ns.NamespaceName}\"", "", StringComparison.Ordinal);
+ return xml;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs
new file mode 100644
index 00000000..d9189b2c
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs
@@ -0,0 +1,485 @@
+// header.xml: fonts, character and paragraph shapes, list numberings, border/fill definitions and tab stops.
+// Everything is created on demand and cached, so equal formatting shares one definition like 한글 does.
+
+using System.Globalization;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class HwpxWriter
+{
+ private const string HwpUnitCharNamespace = "http://www.hancom.co.kr/hwpml/2016/HwpUnitChar";
+
+ /// <summary>Schema order of charPr children. New elements are inserted accordingly.</summary>
+ private static readonly string[] CharPrOrder =
+ ["fontRef", "ratio", "spacing", "relSz", "offset", "italic", "bold", "underline", "strikeout", "outline", "shadow", "emboss", "engrave", "supscript", "subscript"];
+
+ /// <summary>Line widths 한글 offers (mm); others are snapped to the nearest.</summary>
+ private static readonly double[] LineWidths = [0.1, 0.12, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0];
+
+ private static readonly string[] Languages = ["HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER"];
+
+ private readonly XElement _head;
+ private readonly Dictionary<(string BaseId, HCharFormat Format, bool Link), string> _charPrCache = [];
+ private readonly Dictionary<(string BaseId, HParaFormat Format, string? NumberingId, int Level, bool Numbered), string> _paraPrCache = [];
+ private readonly Dictionary<HNumbering, string> _numberingIds = [];
+ private readonly Dictionary<(HBorders Borders, string? Fill), string> _borderFills = [];
+ private readonly Dictionary<string, string> _tabPrIds = [];
+ private readonly Dictionary<(string Language, string Face), int> _fontIds = [];
+ private readonly Dictionary<int, (string StyleId, string ParaPrId, string CharPrId)> _headings = [];
+ private int _maxCharPr;
+ private int _maxParaPr;
+ private string _normalStyleId = "0";
+ private string _normalParaPrId = "0";
+ private string _normalCharPrId = "0";
+ private (string StyleId, string ParaPrId, string CharPrId)? _footnoteStyle;
+
+ private XElement RefList(string name) =>
+ _head.Descendants(Hh + name).FirstOrDefault() ?? throw new InvalidDataException($"header.xml has no {name}.");
+
+ private void InitializeHeader()
+ {
+ _maxCharPr = MaxId(_head.Descendants(Hh + "charPr"));
+ _maxParaPr = MaxId(_head.Descendants(Hh + "paraPr"));
+
+ // Numbering definitions live in refList, before paraProperties.
+ if (_head.Descendants(Hh + "numberings").FirstOrDefault() is null)
+ {
+ var refList = _head.Element(Hh + "refList") ?? _head;
+ var numberings = new XElement(Hh + "numberings", new XAttribute("itemCnt", 0));
+ if (refList.Element(Hh + "paraProperties") is { } paraProperties)
+ paraProperties.AddBeforeSelf(numberings);
+ else
+ refList.Add(numberings);
+ }
+
+ var styles = _head.Descendants(Hh + "style").ToList();
+ (string, string, string) Ids(XElement style) =>
+ ((string?)style.Attribute("id") ?? _normalStyleId,
+ (string?)style.Attribute("paraPrIDRef") ?? _normalParaPrId,
+ (string?)style.Attribute("charPrIDRef") ?? _normalCharPrId);
+
+ var normal = styles.FirstOrDefault(s => (string?)s.Attribute("id") == "0") ?? styles.FirstOrDefault();
+ if (normal is not null)
+ (_normalStyleId, _normalParaPrId, _normalCharPrId) = Ids(normal);
+
+ // "Heading 1".."Heading 9" by English style name; fall back to outline levels of paragraph properties.
+ foreach (var style in styles)
+ {
+ var name = (string?)style.Attribute("engName") ?? "";
+ if (name.StartsWith("Heading ", StringComparison.OrdinalIgnoreCase) &&
+ int.TryParse(name.AsSpan(8), out var level) && level is >= 1 and <= 9)
+ _headings[level] = Ids(style);
+ else if (name.Contains("footnote", StringComparison.OrdinalIgnoreCase))
+ _footnoteStyle = Ids(style);
+ }
+ if (_headings.Count == 0)
+ {
+ foreach (var paraPr in _head.Descendants(Hh + "paraPr"))
+ {
+ var heading = paraPr.Element(Hh + "heading");
+ if ((string?)heading?.Attribute("type") != "OUTLINE" || !int.TryParse((string?)heading.Attribute("level"), out var outline))
+ continue;
+ var paraPrId = (string?)paraPr.Attribute("id") ?? "0";
+ if (styles.FirstOrDefault(s => (string?)s.Attribute("paraPrIDRef") == paraPrId) is { } style)
+ _headings.TryAdd(outline + 1, Ids(style));
+ }
+ }
+ }
+
+ private string SerializeHeader(int sectionCount)
+ {
+ void Count(string container, string item)
+ {
+ if (_head.Descendants(Hh + container).FirstOrDefault() is { } element)
+ element.SetAttributeValue("itemCnt", element.Elements(Hh + item).Count());
+ }
+ Count("charProperties", "charPr");
+ Count("paraProperties", "paraPr");
+ Count("numberings", "numbering");
+ Count("borderFills", "borderFill");
+ Count("tabProperties", "tabPr");
+ _head.SetAttributeValue("secCnt", sectionCount);
+ return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + _head.ToString(SaveOptions.DisableFormatting);
+ }
+
+ // ───────────────────────── Fonts ─────────────────────────
+
+ /// <summary>Index of <paramref name="face"/> in the font list of <paramref name="language"/> (added if missing).</summary>
+ private int FontId(string language, string face)
+ {
+ if (_fontIds.TryGetValue((language, face), out var cached))
+ return cached;
+ var fontface = _head.Descendants(Hh + "fontface").FirstOrDefault(f => (string?)f.Attribute("lang") == language);
+ if (fontface is null)
+ return 0;
+ var existing = fontface.Elements(Hh + "font").FirstOrDefault(f => string.Equals((string?)f.Attribute("face"), face, StringComparison.OrdinalIgnoreCase));
+ int id;
+ if (existing is not null)
+ {
+ id = (int?)existing.Attribute("id") ?? 0;
+ }
+ else
+ {
+ id = fontface.Elements(Hh + "font").Count();
+ fontface.Add(new XElement(Hh + "font", new XAttribute("id", id), new XAttribute("face", face), new XAttribute("type", "TTF"), new XAttribute("isEmbedded", 0)));
+ fontface.SetAttributeValue("fontCnt", id + 1);
+ }
+ _fontIds[(language, face)] = id;
+ return id;
+ }
+
+ // ───────────────────────── Character shapes ─────────────────────────
+
+ /// <summary>Character shape id for <paramref name="baseId"/> with <paramref name="format"/> applied (created on demand).</summary>
+ private string CharPr(string baseId, HCharFormat format, bool link = false)
+ {
+ // Links without their own colour get the usual blue underline.
+ link = link && format.Color is null;
+ if (format.IsEmpty && !link)
+ return baseId;
+ if (_charPrCache.TryGetValue((baseId, format, link), out var cached))
+ return cached;
+
+ var source = _head.Descendants(Hh + "charPr").FirstOrDefault(c => (string?)c.Attribute("id") == baseId)
+ ?? _head.Descendants(Hh + "charPr").FirstOrDefault();
+ if (source is null)
+ return baseId;
+
+ var node = new XElement(source);
+ var id = (++_maxCharPr).ToString(CultureInfo.InvariantCulture);
+ node.SetAttributeValue("id", id);
+
+ if (format.Size is { } size)
+ node.SetAttributeValue("height", Math.Clamp(size, 100, 409600));
+ if (format.Color is { } color)
+ node.SetAttributeValue("textColor", color);
+ if (link)
+ node.SetAttributeValue("textColor", "#0000FF");
+ if (format.Shade is { } shade)
+ node.SetAttributeValue("shadeColor", shade);
+ if (format.Font is not null || format.EastAsianFont is not null)
+ {
+ var fontRef = EnsureChild(node, "fontRef");
+ foreach (var language in Languages)
+ {
+ var eastAsian = language is "HANGUL" or "HANJA" or "JAPANESE";
+ var face = eastAsian ? format.EastAsianFont ?? format.Font : format.Font ?? format.EastAsianFont;
+ if (face is not null)
+ fontRef.SetAttributeValue(language.ToLowerInvariant(), FontId(language, face));
+ }
+ }
+ if (format.Spacing is { } spacing)
+ {
+ var element = EnsureChild(node, "spacing");
+ foreach (var language in Languages)
+ element.SetAttributeValue(language.ToLowerInvariant(), spacing);
+ }
+ SetFlag(node, "bold", format.Bold);
+ SetFlag(node, "italic", format.Italic);
+ if (format.Underline is { } underlined || link)
+ {
+ var underline = EnsureChild(node, "underline");
+ var on = link || format.Underline == true;
+ underline.SetAttributeValue("type", on ? "BOTTOM" : "NONE");
+ underline.SetAttributeValue("shape", "SOLID");
+ underline.SetAttributeValue("color", link ? "#0000FF" : format.Color ?? "#000000");
+ }
+ if (format.Strike is { } strike)
+ {
+ var strikeout = EnsureChild(node, "strikeout");
+ strikeout.SetAttributeValue("shape", strike ? "SOLID" : "NONE");
+ strikeout.SetAttributeValue("color", format.Color ?? "#000000");
+ }
+ if (format.Superscript == true)
+ {
+ node.Element(Hh + "subscript")?.Remove();
+ EnsureChild(node, "supscript");
+ }
+ else if (format.Subscript == true)
+ {
+ node.Element(Hh + "supscript")?.Remove();
+ EnsureChild(node, "subscript");
+ }
+ else if (format.Superscript == false || format.Subscript == false)
+ {
+ node.Element(Hh + "supscript")?.Remove();
+ node.Element(Hh + "subscript")?.Remove();
+ }
+
+ RefList("charProperties").Add(node);
+ _charPrCache[(baseId, format, link)] = id;
+ return id;
+ }
+
+ private static void SetFlag(XElement charPr, string name, bool? value)
+ {
+ if (value == true)
+ EnsureChild(charPr, name);
+ else if (value == false)
+ charPr.Element(Hh + name)?.Remove();
+ }
+
+ /// <summary>Returns the child element, inserting it at its schema position if missing.</summary>
+ private static XElement EnsureChild(XElement charPr, string name)
+ {
+ if (charPr.Element(Hh + name) is { } existing)
+ return existing;
+ var element = new XElement(Hh + name);
+ var rank = Array.IndexOf(CharPrOrder, name);
+ var after = charPr.Elements().LastOrDefault(e => Array.IndexOf(CharPrOrder, e.Name.LocalName) is var r && r >= 0 && r < rank);
+ if (after is not null)
+ after.AddAfterSelf(element);
+ else
+ charPr.AddFirst(element);
+ return element;
+ }
+
+ // ───────────────────────── Paragraph shapes ─────────────────────────
+
+ /// <summary>Paragraph shape id for <paramref name="baseId"/> with a format and list numbering applied.</summary>
+ private string ParaPr(string baseId, HParaFormat format, HListRef? list)
+ {
+ var numberingId = list is null ? null : NumberingId(list.Numbering);
+ var key = (baseId, format, numberingId, list?.Level ?? 0, list?.Numbered ?? false);
+ if (format.IsEmpty && list is null)
+ return baseId;
+ if (_paraPrCache.TryGetValue(key, out var cached))
+ return cached;
+
+ var source = _head.Descendants(Hh + "paraPr").FirstOrDefault(p => (string?)p.Attribute("id") == baseId)
+ ?? _head.Descendants(Hh + "paraPr").First();
+ var node = new XElement(source);
+ var id = (++_maxParaPr).ToString(CultureInfo.InvariantCulture);
+ node.SetAttributeValue("id", id);
+
+ if (format.Align is { } align)
+ {
+ var element = node.Element(Hh + "align") ?? AddFirst(node, new XElement(Hh + "align", new XAttribute("vertical", "BASELINE")));
+ element.SetAttributeValue("horizontal", align switch
+ {
+ HAlign.Center => "CENTER",
+ HAlign.Right => "RIGHT",
+ HAlign.Justify => "JUSTIFY",
+ HAlign.Distribute => "DISTRIBUTE",
+ _ => "LEFT",
+ });
+ }
+
+ if (list is not null)
+ {
+ var heading = node.Element(Hh + "heading");
+ if (heading is null)
+ {
+ heading = new XElement(Hh + "heading");
+ if (node.Element(Hh + "align") is { } alignElement)
+ alignElement.AddAfterSelf(heading);
+ else
+ node.AddFirst(heading);
+ }
+ heading.SetAttributeValue("type", list.Numbered ? "NUMBER" : "NONE");
+ heading.SetAttributeValue("idRef", list.Numbered ? numberingId : "0");
+ heading.SetAttributeValue("level", list.Numbered ? list.Level : 0);
+ }
+
+ if (node.Element(Hh + "breakSetting") is { } breakSetting)
+ {
+ if (format.KeepWithNext is { } keepWithNext)
+ breakSetting.SetAttributeValue("keepWithNext", keepWithNext ? 1 : 0);
+ if (format.KeepLines is { } keepLines)
+ breakSetting.SetAttributeValue("keepLines", keepLines ? 1 : 0);
+ if (format.WidowOrphan is { } widowOrphan)
+ breakSetting.SetAttributeValue("widowOrphan", widowOrphan ? 1 : 0);
+ }
+
+ // List items without their own indentation hang the bullet in front of the text.
+ var left = format.Left;
+ var firstLine = format.FirstLine;
+ if (list is not null && left is null)
+ {
+ const int Hanging = 2000;
+ left = (list.Level + 1) * Hanging;
+ firstLine ??= list.Numbered ? -Hanging : 0;
+ }
+ SetSpacing(node, left, format.Right, firstLine, format.Before, format.After, format.LineSpacing);
+
+ if (format.Tabs is { Count: > 0 } tabs)
+ node.SetAttributeValue("tabPrIDRef", TabPrId(tabs));
+
+ RefList("paraProperties").Add(node);
+ _paraPrCache[key] = id;
+ return id;
+ }
+
+ private static XElement AddFirst(XElement parent, XElement child)
+ {
+ parent.AddFirst(child);
+ return child;
+ }
+
+ /// <summary>
+ /// Rewrites margins and line spacing. 한글 stores them twice: in hp:case (HwpUnitChar-aware readers, true
+ /// HWPUNIT) and in hp:default for older readers, where lengths are doubled (percentages are not).
+ /// </summary>
+ private static void SetSpacing(XElement paraPr, int? left, int? right, int? firstLine, int? before, int? after, HLineSpacing? lineSpacing)
+ {
+ var existingCase = paraPr.Descendants(Hp + "case").FirstOrDefault();
+ int Current(string name) => (int?)existingCase?.Descendants(Hc + name).FirstOrDefault()?.Attribute("value") ?? 0;
+ var existingLine = existingCase?.Element(Hh + "lineSpacing") ?? paraPr.Descendants(Hh + "lineSpacing").FirstOrDefault();
+
+ // The model (like Word) puts the first line at left + firstLine. 한글 differs for hanging indents: a
+ // negative "intent" keeps the first line at "left" and moves the other lines right by its size, so the
+ // left margin is reduced by the hanging amount (a positive intent works like Word's first-line indent).
+ var hwpLeft = left ?? Current("left");
+ if (left is not null && firstLine is < 0)
+ hwpLeft += firstLine.Value;
+ var values = new (string Name, int Value)[]
+ {
+ ("intent", firstLine ?? Current("intent")),
+ ("left", hwpLeft),
+ ("right", right ?? Current("right")),
+ ("prev", before ?? Current("prev")),
+ ("next", after ?? Current("next")),
+ };
+ var lineType = lineSpacing is { } ls ? ls.Kind switch
+ {
+ HLineSpacingKind.Fixed => "FIXED",
+ HLineSpacingKind.AtLeast => "AT_LEAST",
+ _ => "PERCENT",
+ } : (string?)existingLine?.Attribute("type") ?? "PERCENT";
+ var lineValue = lineSpacing?.Value ?? (int?)existingLine?.Attribute("value") ?? 160;
+
+ XElement Branch(XName name, int factor)
+ {
+ var line = lineType == "PERCENT" ? lineValue : lineValue * factor;
+ return new XElement(name,
+ new XElement(Hh + "margin", values.Select(v => new XElement(Hc + v.Name, new XAttribute("value", v.Value * factor), new XAttribute("unit", "HWPUNIT")))),
+ new XElement(Hh + "lineSpacing", new XAttribute("type", lineType), new XAttribute("value", line), new XAttribute("unit", "HWPUNIT")));
+ }
+
+ var switchElement = new XElement(Hp + "switch",
+ new XElement(Branch(Hp + "case", 1)).WithAttribute(Hp + "required-namespace", HwpUnitCharNamespace),
+ Branch(Hp + "default", 2));
+
+ paraPr.Elements(Hp + "switch").Remove();
+ paraPr.Elements(Hh + "margin").Remove();
+ paraPr.Elements(Hh + "lineSpacing").Remove();
+ // Order: align, heading, breakSetting, autoSpacing, switch, border.
+ var anchor = paraPr.Element(Hh + "autoSpacing") ?? paraPr.Element(Hh + "breakSetting") ?? paraPr.Element(Hh + "heading") ?? paraPr.Element(Hh + "align");
+ if (anchor is not null)
+ anchor.AddAfterSelf(switchElement);
+ else
+ paraPr.AddFirst(switchElement);
+ }
+
+ // ───────────────────────── Numbering ─────────────────────────
+
+ private string NumberingId(HNumbering numbering)
+ {
+ if (_numberingIds.TryGetValue(numbering, out var cached))
+ return cached;
+ var numberings = RefList("numberings");
+ var id = (MaxId(numberings.Elements(Hh + "numbering")) + 1).ToString(CultureInfo.InvariantCulture);
+ var element = new XElement(Hh + "numbering", new XAttribute("id", id),
+ new XAttribute("start", numbering.Levels.FirstOrDefault()?.Start ?? 1));
+ for (var i = 0; i < numbering.Levels.Count && i < 10; i++)
+ {
+ var level = numbering.Levels[i];
+ element.Add(new XElement(Hh + "paraHead",
+ new XAttribute("start", level.Start), new XAttribute("level", i + 1),
+ new XAttribute("align", "LEFT"), new XAttribute("useInstWidth", 1), new XAttribute("autoIndent", 0),
+ new XAttribute("widthAdjust", 0), new XAttribute("textOffsetType", "PERCENT"), new XAttribute("textOffset", 50),
+ new XAttribute("numFormat", level.Format), new XAttribute("charPrIDRef", 4294967295u), new XAttribute("checkable", 0),
+ level.Text));
+ }
+ numberings.Add(element);
+ _numberingIds[numbering] = id;
+ return id;
+ }
+
+ // ───────────────────────── Borders and fills ─────────────────────────
+
+ private string BorderFillId(HBorders borders, string? fill)
+ {
+ if (_borderFills.TryGetValue((borders, fill), out var cached))
+ return cached;
+ var container = RefList("borderFills");
+ var id = (MaxId(container.Elements(Hh + "borderFill")) + 1).ToString(CultureInfo.InvariantCulture);
+
+ XElement Line(string name, HBorder border) => new(Hh + name,
+ new XAttribute("type", LineType(border.Style)),
+ new XAttribute("width", LineWidth(border.WidthMm)),
+ new XAttribute("color", border.Color));
+
+ var element = new XElement(Hh + "borderFill",
+ new XAttribute("id", id), new XAttribute("threeD", 0), new XAttribute("shadow", 0),
+ new XAttribute("centerLine", "NONE"), new XAttribute("breakCellSeparateLine", 0),
+ new XElement(Hh + "slash", new XAttribute("type", "NONE"), new XAttribute("Crooked", 0), new XAttribute("isCounter", 0)),
+ new XElement(Hh + "backSlash", new XAttribute("type", "NONE"), new XAttribute("Crooked", 0), new XAttribute("isCounter", 0)),
+ Line("leftBorder", borders.Left), Line("rightBorder", borders.Right),
+ Line("topBorder", borders.Top), Line("bottomBorder", borders.Bottom),
+ new XElement(Hh + "diagonal", new XAttribute("type", "SOLID"), new XAttribute("width", "0.1 mm"), new XAttribute("color", "#000000")),
+ new XElement(Hc + "fillBrush",
+ new XElement(Hc + "winBrush", new XAttribute("faceColor", fill ?? "none"), new XAttribute("hatchColor", "#000000"), new XAttribute("alpha", 0))));
+ container.Add(element);
+ _borderFills[(borders, fill)] = id;
+ return id;
+ }
+
+ private static string LineType(HBorderStyle style) => style switch
+ {
+ HBorderStyle.None => "NONE",
+ HBorderStyle.Dash => "DASH",
+ HBorderStyle.Dot => "DOT",
+ HBorderStyle.DashDot => "DASH_DOT",
+ HBorderStyle.Double => "DOUBLE_SLIM",
+ _ => "SOLID",
+ };
+
+ /// <summary>Snaps a width in mm to the nearest width 한글 offers, e.g. "0.12 mm".</summary>
+ internal static string LineWidth(double mm)
+ {
+ var nearest = LineWidths.MinBy(w => Math.Abs(w - mm));
+ return nearest.ToString(nearest >= 1 ? "0.0" : "0.0#", CultureInfo.InvariantCulture) + " mm";
+ }
+
+ // ───────────────────────── Tab stops ─────────────────────────
+
+ private string TabPrId(IReadOnlyList<HTabStop> tabs)
+ {
+ var key = string.Join(';', tabs.Select(t => $"{t.Position},{t.Kind},{t.Leader}"));
+ if (_tabPrIds.TryGetValue(key, out var cached))
+ return cached;
+ var container = RefList("tabProperties");
+ var id = (MaxId(container.Elements(Hh + "tabPr")) + 1).ToString(CultureInfo.InvariantCulture);
+ var element = new XElement(Hh + "tabPr", new XAttribute("id", id), new XAttribute("autoTabLeft", 0), new XAttribute("autoTabRight", 0));
+ foreach (var tab in tabs)
+ {
+ var type = tab.Kind switch
+ {
+ HTabKind.Right => "RIGHT",
+ HTabKind.Center => "CENTER",
+ HTabKind.Decimal => "DECIMAL",
+ _ => "LEFT",
+ };
+ // Same doubling rule as paragraph margins: hp:default holds twice the value and no unit.
+ element.Add(new XElement(Hp + "switch",
+ new XElement(Hp + "case", new XAttribute(Hp + "required-namespace", HwpUnitCharNamespace),
+ new XElement(Hh + "tabItem", new XAttribute("pos", tab.Position), new XAttribute("type", type), new XAttribute("leader", tab.Leader), new XAttribute("unit", "HWPUNIT"))),
+ new XElement(Hp + "default",
+ new XElement(Hh + "tabItem", new XAttribute("pos", tab.Position * 2), new XAttribute("type", type), new XAttribute("leader", tab.Leader)))));
+ }
+ container.Add(element);
+ _tabPrIds[key] = id;
+ return id;
+ }
+}
+
+internal static class XElementExtensions
+{
+ public static XElement WithAttribute(this XElement element, XName name, object value)
+ {
+ element.SetAttributeValue(name, value);
+ return element;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
new file mode 100644
index 00000000..9018d333
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
@@ -0,0 +1,246 @@
+// Rough text measurement for the values 한글 files carry as layout caches: table row heights and the width
+// of inline tabs. 한글 lays the document out again when it opens it, but simpler readers (and previews)
+// use these values as they are, so they should be close to the real layout.
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class HwpxWriter
+{
+ /// <summary>Estimated width of <paramref name="text"/> at a font size (1/100 pt = HWPUNIT per em).</summary>
+ internal static double TextWidth(string text, int size)
+ {
+ double width = 0;
+ foreach (var ch in text)
+ {
+ // Average advances (em) of the fonts Korean documents use (\uB9D1\uC740 \uACE0\uB515, \uAD74\uB9BC, \uD568\uCD08\uB86C, Calibri ...).
+ width += ch switch
+ {
+ ' ' or '\u00A0' => 0.3,
+ '.' or ',' or ':' or ';' or '\'' or '!' or '|' or '(' or ')' or '[' or ']' or '-' => 0.3,
+ >= '\u2000' and <= '\u206F' => 0.5, // general punctuation (dashes, quotes, bullets)
+ >= '\u1100' => 0.92, // Hangul, CJK, full-width forms: about one em
+ >= '0' and <= '9' => 0.55,
+ >= 'A' and <= 'Z' => 0.65,
+ _ => 0.5,
+ } * size;
+ }
+ return width;
+ }
+
+ /// <summary>Base font size (1/100 pt) of the current container's plain paragraphs.</summary>
+ private int BaseSize(string charPrId) =>
+ (int?)_head.Descendants(Hh + "charPr").FirstOrDefault(c => (string?)c.Attribute("id") == charPrId)?.Attribute("height") ?? 1000;
+
+ /// <summary>Base line spacing (percent) of a paragraph shape.</summary>
+ private int BasePercent(string paraPrId)
+ {
+ var paraPr = _head.Descendants(Hh + "paraPr").FirstOrDefault(p => (string?)p.Attribute("id") == paraPrId);
+ var line = paraPr?.Descendants(Hh + "lineSpacing").FirstOrDefault();
+ return (string?)line?.Attribute("type") == "PERCENT" ? (int?)line.Attribute("value") ?? 160 : 160;
+ }
+
+ /// <summary>Estimated height of blocks laid out in <paramref name="width"/>.</summary>
+ private int EstimateHeight(IEnumerable<HBlock> blocks, int width)
+ {
+ var total = 0;
+ foreach (var block in blocks)
+ {
+ switch (block)
+ {
+ case HParagraph paragraph:
+ total += EstimateHeight(paragraph, width);
+ break;
+ case HTable table:
+ {
+ var (placed, columns) = PlaceCells(table);
+ total += EstimateRowHeights(table, placed, ColumnWidths(table, columns, width)).Sum();
+ break;
+ }
+ }
+ }
+ return total;
+ }
+
+ private int EstimateHeight(HParagraph paragraph, int width)
+ {
+ var (_, paraPrBase, charPrBase) = paragraph.HeadingLevel > 0 && _headings.TryGetValue(paragraph.HeadingLevel, out var heading) ? heading : _base;
+ var size = LargestSize(paragraph.Inlines) ?? paragraph.MarkFormat.Size ?? BaseSize(charPrBase);
+ var line = paragraph.Format.LineSpacing switch
+ {
+ { Kind: HLineSpacingKind.Fixed } fixedLine => fixedLine.Value,
+ { Kind: HLineSpacingKind.AtLeast } atLeast => Math.Max(atLeast.Value, size * 13 / 10),
+ { Kind: HLineSpacingKind.Percent } percent => size * percent.Value / 100,
+ _ => size * BasePercent(paraPrBase) / 100,
+ };
+ var available = Math.Max(1000, width - (paragraph.Format.Left ?? 0) - (paragraph.Format.Right ?? 0));
+
+ // Line breaks split the text; each piece wraps on its own. Objects add their own height.
+ var lines = 0;
+ double current = Math.Max(0, paragraph.Format.FirstLine ?? 0);
+ var objects = 0;
+ void Measure(IEnumerable<HInline> inlines)
+ {
+ foreach (var inline in inlines)
+ {
+ switch (inline)
+ {
+ case HText text:
+ current += TextWidth(text.Text, text.Format.Size ?? size);
+ break;
+ case HTab:
+ current += 4000;
+ break;
+ case HLineBreak:
+ lines += LinesFor(current, available);
+ current = 0;
+ break;
+ case HLink link:
+ Measure(link.Content);
+ break;
+ case HImage { Anchor: null } image:
+ objects += image.Height ?? 0;
+ break;
+ case HTextBox { Anchor: null } box:
+ objects += box.Height;
+ break;
+ }
+ }
+ }
+ Measure(paragraph.Inlines);
+ lines += LinesFor(current, available);
+ return lines * line + objects + (paragraph.Format.Before ?? 0) + (paragraph.Format.After ?? 0);
+ }
+
+ /// <summary>Wrapped lines for a text width; 5% slack so text that just fits is not pushed to a second line.</summary>
+ private static int LinesFor(double textWidth, int available) =>
+ Math.Max(1, (int)Math.Ceiling(textWidth / (available * 1.05)));
+
+ private static int? LargestSize(IEnumerable<HInline> inlines)
+ {
+ int? max = null;
+ foreach (var inline in inlines)
+ {
+ var size = inline switch
+ {
+ HText text => text.Format.Size,
+ HLink link => LargestSize(link.Content),
+ _ => null,
+ };
+ if (size > (max ?? 0))
+ max = size;
+ }
+ return max;
+ }
+
+ /// <summary>
+ /// Row heights: at least the row's own height, and tall enough for the estimated content of its cells.
+ /// Cells spanning rows spread their extra height over the last row they span.
+ /// </summary>
+ private int[] EstimateRowHeights(HTable table, List<List<(HCell Cell, int Column)>> placed, int[] widths)
+ {
+ var margin = table.CellMargin ?? new HInsets(510, 510, 141, 141);
+ var heights = table.Rows.Select(r => Math.Max(r.Height ?? 0, 0)).ToArray();
+ var outerBase = _base;
+ for (var pass = 0; pass < 2; pass++)
+ {
+ for (var r = 0; r < placed.Count; r++)
+ {
+ foreach (var (cell, column) in placed[r])
+ {
+ if ((pass == 0) != (cell.RowSpan == 1))
+ continue; // single-row cells first, then spans on top of them
+ var width = 0;
+ for (var i = column; i < column + cell.ColSpan && i < widths.Length; i++)
+ width += widths[i];
+ var needed = EstimateHeight(cell.Blocks.Count > 0 ? cell.Blocks : [new HParagraph()], Math.Max(1000, width - margin.Left - margin.Right))
+ + margin.Top + margin.Bottom;
+ var last = Math.Min(r + cell.RowSpan, heights.Length) - 1;
+ var have = 0;
+ for (var i = r; i <= last; i++)
+ have += heights[i];
+ if (needed > have)
+ heights[last] += needed - have;
+ }
+ }
+ }
+ _base = outerBase;
+ return heights.Select(h => Math.Max(h, 282)).ToArray();
+ }
+
+ // ───────────────────────── Tabs ─────────────────────────
+
+ /// <summary>
+ /// Type, leader and width of each inline tab of a paragraph, in order. Like 한글 and Word, a tab moves to the
+ /// first tab stop right of the text before it; without a stop it advances to the next default stop.
+ /// </summary>
+ private static List<string> TabElements(HParagraph paragraph, int size)
+ {
+ var result = new List<string>();
+ var stops = paragraph.Format.Tabs ?? [];
+ var left = paragraph.Format.Left ?? 0;
+ double x = left + (paragraph.Format.FirstLine ?? 0);
+ var pieces = new List<(HInline Inline, double Width)>();
+ void Flatten(IEnumerable<HInline> inlines)
+ {
+ foreach (var inline in inlines)
+ {
+ if (inline is HLink link)
+ Flatten(link.Content);
+ else
+ pieces.Add((inline, inline is HText text ? TextWidth(text.Text, text.Format.Size ?? size) : 0));
+ }
+ }
+ Flatten(paragraph.Inlines);
+
+ for (var i = 0; i < pieces.Count; i++)
+ {
+ switch (pieces[i].Inline)
+ {
+ case HText:
+ x += pieces[i].Width;
+ break;
+ case HLineBreak:
+ x = left;
+ break;
+ case HTab:
+ {
+ // Text up to the next tab or line break, for right / center aligned stops.
+ double following = 0;
+ for (var j = i + 1; j < pieces.Count && pieces[j].Inline is not (HTab or HLineBreak); j++)
+ following += pieces[j].Width;
+
+ var stop = stops.FirstOrDefault(s => s.Position > x + 1);
+ int type, leader;
+ double target;
+ if (stops.Count > 0 && stop.Position > x + 1)
+ {
+ (type, target) = stop.Kind switch
+ {
+ HTabKind.Right => (2, stop.Position - following),
+ HTabKind.Center => (3, stop.Position - following / 2),
+ HTabKind.Decimal => (4, stop.Position - following),
+ _ => (1, (double)stop.Position),
+ };
+ leader = stop.Leader switch
+ {
+ "SOLID" => 1,
+ "DOT" => 2,
+ "DASH" => 3,
+ _ => 0,
+ };
+ }
+ else
+ {
+ const int DefaultStop = 4000;
+ (type, leader, target) = (1, 0, (Math.Floor(x / DefaultStop) + 1) * DefaultStop);
+ }
+ var width = Math.Max(0, (int)(target - x));
+ result.Add($"<hp:tab width=\"{width}\" leader=\"{leader}\" type=\"{type}\"/>");
+ x += width;
+ break;
+ }
+ }
+ }
+ return result;
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
new file mode 100644
index 00000000..3e01461e
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
@@ -0,0 +1,294 @@
+// Objects inside runs: pictures (inline or floating), text boxes, footnotes/endnotes, hyperlinks, page numbers.
+// Child order follows files saved by 한글: object-specific children first, then sz / pos / outMargin.
+
+using System.Text;
+using ImageMagick;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed partial class HwpxWriter
+{
+ /// <summary>The fieldid 한글 gives every hyperlink field (control id "%hlk").</summary>
+ private const string HyperlinkFieldId = "627600491";
+
+ private const string IdentityRendering =
+ "<hp:renderingInfo><hc:transMatrix e1=\"1\" e2=\"0\" e3=\"0\" e4=\"0\" e5=\"1\" e6=\"0\"/><hc:scaMatrix e1=\"1\" e2=\"0\" e3=\"0\" e4=\"0\" e5=\"1\" e6=\"0\"/><hc:rotMatrix e1=\"1\" e2=\"0\" e3=\"0\" e4=\"0\" e5=\"1\" e6=\"0\"/></hp:renderingInfo>";
+
+ private int _footnotes;
+ private int _endnotes;
+ private int _zOrder;
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ private string? Picture(HImage image)
+ {
+ if (!File.Exists(image.Path))
+ return null; // missing image: skip rather than produce a broken reference
+
+ var (width, height) = (image.Width, image.Height);
+ if (width is null || height is null)
+ {
+ try
+ {
+ var info = new MagickImageInfo(image.Path);
+ // Pixels at 96 dpi, like Word and browsers show images without a physical size.
+ double pxW = info.Width, pxH = info.Height;
+ if (pxW > 0 && pxH > 0)
+ {
+ if (width is null && height is null)
+ (width, height) = ((int)(pxW * HwpxUnits.PerPixel), (int)(pxH * HwpxUnits.PerPixel));
+ else if (width is not null)
+ height = (int)(width.Value * pxH / pxW);
+ else
+ width = (int)(height!.Value * pxW / pxH);
+ }
+ }
+ catch (MagickException)
+ {
+ // Unknown format: fall through to a square placeholder size.
+ }
+ }
+ var w = Math.Max(1, width ?? 8504);
+ var h = Math.Max(1, height ?? w);
+ if (image.Anchor is null && w > _width)
+ {
+ // Inline pictures never overflow the text width.
+ h = (int)((long)h * _width / w);
+ w = _width;
+ }
+
+ var extension = Path.GetExtension(image.Path).TrimStart('.').ToLowerInvariant() switch
+ {
+ "jpeg" or "jpe" => "jpg",
+ var e => e,
+ };
+ var existing = _images.FindIndex(i => i.SourcePath == image.Path);
+ var binaryId = existing >= 0 ? _images[existing].Id : $"image{_images.Count + 1}";
+ if (existing < 0)
+ _images.Add((binaryId, image.Path, extension));
+
+ var id = NextId();
+ var wrap = image.Anchor?.Wrap ?? "TOP_AND_BOTTOM";
+ return $"<hp:pic id=\"{id}\" zOrder=\"{_zOrder++}\" numberingType=\"{(image.Anchor is null ? "NONE" : "PICTURE")}\" textWrap=\"{wrap}\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" href=\"\" groupLevel=\"0\" instid=\"{id}\" reverse=\"0\">" +
+ "<hp:offset x=\"0\" y=\"0\"/>" +
+ $"<hp:orgSz width=\"{w}\" height=\"{h}\"/><hp:curSz width=\"{w}\" height=\"{h}\"/>" +
+ "<hp:flip horizontal=\"0\" vertical=\"0\"/>" +
+ $"<hp:rotationInfo angle=\"0\" centerX=\"{w / 2}\" centerY=\"{h / 2}\" rotateimage=\"1\"/>" +
+ IdentityRendering +
+ $"<hc:img binaryItemIDRef=\"{binaryId}\" bright=\"0\" contrast=\"0\" effect=\"REAL_PIC\" alpha=\"0\"/>" +
+ $"<hp:imgRect><hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"{w}\" y=\"0\"/><hc:pt2 x=\"{w}\" y=\"{h}\"/><hc:pt3 x=\"0\" y=\"{h}\"/></hp:imgRect>" +
+ "<hp:imgClip left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/><hp:inMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/>" +
+ "<hp:imgDim dimwidth=\"0\" dimheight=\"0\"/><hp:effects/>" +
+ $"<hp:sz width=\"{w}\" widthRelTo=\"ABSOLUTE\" height=\"{h}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>" +
+ Position(image.Anchor) +
+ "<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/><hp:shapeComment/>" +
+ "</hp:pic>";
+ }
+
+ /// <summary>hp:pos: inline objects are laid out like a character; floating ones use the anchor.</summary>
+ private string Position(HAnchor? anchor)
+ {
+ if (anchor is null)
+ return "<hp:pos treatAsChar=\"1\" affectLSpacing=\"0\" flowWithText=\"1\" allowOverlap=\"1\" holdAnchorAndSO=\"0\" vertRelTo=\"PARA\" horzRelTo=\"COLUMN\" vertAlign=\"TOP\" horzAlign=\"LEFT\" vertOffset=\"0\" horzOffset=\"0\"/>";
+ anchor = NonNegative(anchor);
+ var flowWithText = anchor.VerticalRelativeTo == "PARA" ? 1 : 0;
+ return $"<hp:pos treatAsChar=\"0\" affectLSpacing=\"0\" flowWithText=\"{flowWithText}\" allowOverlap=\"{(anchor.AllowOverlap ? 1 : 0)}\" holdAnchorAndSO=\"0\" " +
+ $"vertRelTo=\"{anchor.VerticalRelativeTo}\" horzRelTo=\"{anchor.HorizontalRelativeTo}\" vertAlign=\"{anchor.VerticalAlign}\" horzAlign=\"{anchor.HorizontalAlign}\" " +
+ $"vertOffset=\"{anchor.VerticalOffset}\" horzOffset=\"{anchor.HorizontalOffset}\"/>";
+ }
+
+ /// <summary>
+ /// Object offsets are unsigned in the 한글 format (HWPUNIT), and readers fail on negative values. An object
+ /// reaching into the margin is re-anchored to the paper edge, which keeps it in place; one above its paragraph
+ /// (which has no paper-relative equivalent) moves down to the paragraph.
+ /// </summary>
+ private HAnchor NonNegative(HAnchor anchor)
+ {
+ if (anchor.HorizontalOffset < 0)
+ {
+ anchor = anchor.HorizontalRelativeTo is "PAGE" or "COLUMN" && anchor.HorizontalAlign == "LEFT"
+ ? anchor with { HorizontalRelativeTo = "PAPER", HorizontalOffset = Math.Max(0, _pageLeft + anchor.HorizontalOffset) }
+ : anchor with { HorizontalOffset = 0 };
+ }
+ if (anchor.VerticalOffset < 0)
+ {
+ anchor = anchor.VerticalRelativeTo == "PAGE" && anchor.VerticalAlign == "TOP"
+ ? anchor with { VerticalRelativeTo = "PAPER", VerticalOffset = Math.Max(0, _pageTop + anchor.VerticalOffset) }
+ : anchor with { VerticalOffset = 0 };
+ }
+ return anchor;
+ }
+
+ // ───────────────────────── Text boxes ─────────────────────────
+
+ private string TextBox(HTextBox box)
+ {
+ var id = NextId();
+ var (w, h) = (box.Width, box.Height);
+ var verticalAlign = box.VerticalAlign switch
+ {
+ HVerticalAlign.Center => "CENTER",
+ HVerticalAlign.Bottom => "BOTTOM",
+ _ => "TOP",
+ };
+
+ var outerWidth = _width;
+ _width = Math.Max(1000, w - box.Padding.Left - box.Padding.Right);
+ var content = SubList(box.Blocks, verticalAlign);
+ _width = outerWidth;
+
+ 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: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("<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($"<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>");
+ return sb.ToString();
+ }
+
+ // ───────────────────────── Shapes ─────────────────────────
+
+ private string Shape(HShape shape)
+ {
+ var id = NextId();
+ var w = Math.Max(1, shape.Width);
+ var h = Math.Max(1, shape.Height);
+ var (element, extra) = shape.Kind switch
+ {
+ HShapeKind.Ellipse => ("ellipse", " intervalDirty=\"0\" hasArcPr=\"0\" arcType=\"NORMAL\""),
+ HShapeKind.Line => ("line", " isReverseHV=\"0\""),
+ _ => ("rect", $" ratio=\"{shape.CornerRatio}\""),
+ };
+
+ var sb = new StringBuilder();
+ sb.Append($"<hp:{element} id=\"{id}\" zOrder=\"{_zOrder++}\" numberingType=\"NONE\" textWrap=\"{shape.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(shape.Line));
+ if (shape.Kind != HShapeKind.Line)
+ sb.Append(FillBrush(shape.Fill, shape.Gradient));
+ sb.Append("<hp:shadow type=\"NONE\" color=\"#B2B2B2\" offsetX=\"0\" offsetY=\"0\" alpha=\"0\"/>");
+ switch (shape.Kind)
+ {
+ case HShapeKind.Line:
+ {
+ // A line runs corner to corner of its box; flips choose which corners.
+ var (x1, x2) = shape.FlipHorizontal ? (shape.Width, 0) : (0, shape.Width);
+ var (y1, y2) = shape.FlipVertical ? (shape.Height, 0) : (0, shape.Height);
+ sb.Append($"<hc:startPt x=\"{x1}\" y=\"{y1}\"/><hc:endPt x=\"{x2}\" y=\"{y2}\"/>");
+ 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\"/>");
+ 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}\"/>");
+ break;
+ }
+ sb.Append($"<hp:sz width=\"{w}\" widthRelTo=\"ABSOLUTE\" height=\"{h}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>");
+ sb.Append(Position(shape.Anchor));
+ sb.Append("<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/>");
+ sb.Append($"</hp:{element}>");
+ return sb.ToString();
+ }
+
+ /// <summary>Outline of a drawing object; the width is in HWPUNIT here (33 ≈ 0.12 mm), not a named width.</summary>
+ private static string LineShape(HBorder line)
+ {
+ var none = line.Style == HBorderStyle.None;
+ var width = none ? 0 : Math.Max(1, (int)Math.Round(line.WidthMm * HwpxUnits.PerMm));
+ return $"<hp:lineShape color=\"{line.Color}\" width=\"{width}\" style=\"{(none ? "NONE" : LineType(line.Style))}\" endCap=\"FLAT\" headStyle=\"NORMAL\" tailStyle=\"NORMAL\" headfill=\"1\" tailfill=\"1\" headSz=\"MEDIUM_MEDIUM\" tailSz=\"MEDIUM_MEDIUM\" outlineStyle=\"NORMAL\" alpha=\"0\"/>";
+ }
+
+ /// <summary>hc:fillBrush holds exactly one of winBrush (solid) or gradation; no brush = transparent.</summary>
+ private static string FillBrush(string? fill, HGradient? gradient)
+ {
+ if (gradient is { Colors.Count: >= 2 })
+ {
+ var colors = string.Concat(gradient.Colors.Select(c => $"<hc:color value=\"{c}\"/>"));
+ return $"<hc:fillBrush><hc:gradation type=\"LINEAR\" angle=\"{gradient.Angle}\" centerX=\"50\" centerY=\"50\" step=\"255\" colorNum=\"{gradient.Colors.Count}\" stepCenter=\"50\" alpha=\"0\">{colors}</hc:gradation></hc:fillBrush>";
+ }
+ return fill is null ? "" : $"<hc:fillBrush><hc:winBrush faceColor=\"{fill}\" hatchColor=\"#000000\" alpha=\"0\"/></hc:fillBrush>";
+ }
+
+ // ───────────────────────── Notes ─────────────────────────
+
+ private string Note(HNote note)
+ {
+ var kind = note.Endnote ? "endNote" : "footNote";
+ var number = note.Endnote ? ++_endnotes : ++_footnotes;
+ var previousBase = _base;
+ _base = _footnoteStyle ?? _base;
+
+ // The number is an autoNum control at the start of the note's first paragraph (as 한글 writes it).
+ var numberRun = $"<hp:run charPrIDRef=\"{_base.CharPrId}\">" +
+ AutoNumber(note.Endnote ? "ENDNOTE" : "FOOTNOTE", number, ")") +
+ "<hp:t> </hp:t></hp:run>";
+ var content = SubList(note.Blocks, "TOP", leadingRun: numberRun);
+ _base = previousBase;
+ return $"<hp:ctrl><hp:{kind} number=\"{number}\" suffixChar=\"41\" instId=\"{NextId()}\">{content}</hp:{kind}></hp:ctrl>";
+ }
+
+ /// <summary>Automatic number: PAGE, TOTAL_PAGE, FOOTNOTE or ENDNOTE (<paramref name="number"/> is a display cache).</summary>
+ private static string AutoNumber(string type, int number, string suffix) =>
+ $"<hp:ctrl><hp:autoNum num=\"{number}\" numType=\"{type}\">" +
+ $"<hp:autoNumFormat type=\"DIGIT\" userChar=\"\" prefixChar=\"\" suffixChar=\"{Escape(suffix)}\" supscript=\"0\"/>" +
+ "</hp:autoNum></hp:ctrl>";
+
+ // ───────────────────────── Hyperlinks ─────────────────────────
+
+ /// <summary>
+ /// A HYPERLINK field as 한글 stores it: the target in "Command" with ':', '?', ';' and '#' escaped, followed by
+ /// a kind tail (";1;0;0;" web, ";2;0;0" mail, "?name;0;0;0;" bookmark in this document).
+ /// </summary>
+ private static string FieldBegin(int id, string target)
+ {
+ static string Escaped(string text) =>
+ string.Concat(text.Select(c => c is ':' or '?' or ';' or '#' ? "\\" + c : c.ToString()));
+
+ string command, category;
+ string? path = null;
+ if (target.StartsWith('#'))
+ {
+ command = "?" + Escaped(target[1..]) + ";0;0;0;";
+ category = "HWPHYPERLINK_TYPE_HWP";
+ }
+ else if (target.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase))
+ {
+ (command, path, category) = (target + ";2;0;0", target, "HWPHYPERLINK_TYPE_EMAIL");
+ }
+ else
+ {
+ (command, path, category) = (Escaped(target) + ";1;0;0;", target, "HWPHYPERLINK_TYPE_URL");
+ }
+
+ var parameters = new StringBuilder();
+ parameters.Append("<hp:integerParam name=\"Prop\">0</hp:integerParam>");
+ parameters.Append($"<hp:stringParam name=\"Command\">{Escape(command)}</hp:stringParam>");
+ if (path is not null)
+ parameters.Append($"<hp:stringParam name=\"Path\">{Escape(path)}</hp:stringParam>");
+ parameters.Append($"<hp:stringParam name=\"Category\">{category}</hp:stringParam>");
+ parameters.Append("<hp:stringParam name=\"TargetType\">HWPHYPERLINK_TARGET_BOOKMARK</hp:stringParam>");
+ parameters.Append("<hp:stringParam name=\"DocOpenType\">HWPHYPERLINK_JUMP_CURRENTTAB</hp:stringParam>");
+
+ return $"<hp:ctrl><hp:fieldBegin id=\"{id}\" type=\"HYPERLINK\" name=\"\" editable=\"0\" dirty=\"1\" zorder=\"-1\" fieldid=\"{HyperlinkFieldId}\">" +
+ $"<hp:parameters cnt=\"{(path is null ? 5 : 6)}\" name=\"\">{parameters}</hp:parameters></hp:fieldBegin></hp:ctrl>";
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs
new file mode 100644
index 00000000..5c2e1707
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.cs
@@ -0,0 +1,229 @@
+// Writes HWPX (한글 / OWPML, KS X 6101) packages from the HDocument model — no Hancom Office needed.
+//
+// The package layout, styles and the reference document blank.hwpx come from pypandoc-hwpx
+// (MIT, https://github.com/msjang/pypandoc-hwpx). Element order and attribute values follow files saved by
+// 한글 itself where the schema and 한글 disagree (see the notes in each partial file):
+// * HwpxWriter.cs package: mimetype first and stored, one section file per 한글 section, manifest;
+// * HwpxWriter.Header.cs header.xml: fonts, character/paragraph shapes, numberings, borders, tab stops;
+// * HwpxWriter.Body.cs sections (page setup, columns, headers/footers), paragraphs, runs and tables;
+// * HwpxWriter.Objects.cs pictures, text boxes, notes, hyperlinks, bookmarks and page numbers.
+
+using System.IO.Compression;
+using System.Security;
+using System.Text;
+using System.Xml.Linq;
+using ImageMagick;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+/// <summary>Converts an <see cref="HDocument"/> into an HWPX package.</summary>
+internal sealed partial class HwpxWriter
+{
+ private static readonly XNamespace Hh = "http://www.hancom.co.kr/hwpml/2011/head";
+ private static readonly XNamespace Hc = "http://www.hancom.co.kr/hwpml/2011/core";
+ private static readonly XNamespace Hp = "http://www.hancom.co.kr/hwpml/2011/paragraph";
+ private static readonly XNamespace Hs = "http://www.hancom.co.kr/hwpml/2011/section";
+
+ private static readonly HashSet<string> HwpImageTypes = ["png", "jpg", "gif", "bmp"];
+
+ private readonly List<(string Id, string SourcePath, string Extension)> _images = [];
+ private readonly StringBuilder _plainText = new();
+ private readonly XElement _templateSection;
+ private int _nextObjectId = 1_000_000;
+
+ private HwpxWriter(XDocument header, XDocument section)
+ {
+ _head = header.Root ?? throw new InvalidDataException("header.xml has no root element.");
+ _templateSection = section.Root ?? throw new InvalidDataException("section0.xml has no root element.");
+ InitializeHeader();
+ }
+
+ // ───────────────────────── Entry point ─────────────────────────
+
+ /// <summary>Writes <paramref name="document"/> as an HWPX file.</summary>
+ /// <param name="outputPath">HWPX file to create (replaced atomically).</param>
+ /// <param name="template">Reference HWPX supplying styles and the default page; the built-in blank.hwpx when null.</param>
+ public static void Write(HDocument document, string outputPath, Stream? template = null)
+ {
+ using var templateStream = template ?? OpenBuiltInTemplate();
+ using var buffer = new MemoryStream();
+ templateStream.CopyTo(buffer);
+ buffer.Position = 0;
+ using var reference = new ZipArchive(buffer, ZipArchiveMode.Read);
+
+ var writer = new HwpxWriter(
+ XDocument.Parse(ReadEntry(reference, "Contents/header.xml")),
+ XDocument.Parse(ReadEntry(reference, "Contents/section0.xml")));
+
+ var sections = document.Sections.Count > 0 ? document.Sections : [new HSection()];
+ var sectionXml = sections.Select(writer.Section).ToList();
+ writer.WritePackage(reference, outputPath, sectionXml, document.Title);
+ }
+
+ internal static Stream OpenBuiltInTemplate() =>
+ typeof(HwpxWriter).Assembly.GetManifestResourceStream("Filee.Engines.Hwpx.blank.hwpx")
+ ?? throw new InvalidOperationException("Embedded blank.hwpx is missing.");
+
+ // ───────────────────────── Package ─────────────────────────
+
+ private void WritePackage(ZipArchive reference, string outputPath, List<string> sections, string? title)
+ {
+ var header = SerializeHeader(sections.Count);
+ var temp = outputPath + ".tmp";
+ using (var file = File.Create(temp))
+ using (var output = new ZipArchive(file, ZipArchiveMode.Create))
+ {
+ // OCF rule: "mimetype" first and stored uncompressed.
+ WriteText(output, "mimetype", ReadEntry(reference, "mimetype"), CompressionLevel.NoCompression);
+
+ foreach (var entry in reference.Entries)
+ {
+ if (entry.FullName == "mimetype" || entry.FullName.EndsWith('/'))
+ continue;
+ switch (entry.FullName)
+ {
+ case "Contents/section0.xml":
+ for (var i = 0; i < sections.Count; i++)
+ WriteText(output, $"Contents/section{i}.xml", sections[i]);
+ break;
+ case "Contents/header.xml":
+ WriteText(output, entry.FullName, header);
+ break;
+ case "Contents/content.hpf":
+ WriteText(output, entry.FullName, BuildManifest(ReadEntry(reference, entry.FullName), sections.Count, title));
+ break;
+ case "META-INF/container.rdf":
+ WriteText(output, entry.FullName, BuildRdf(ReadEntry(reference, entry.FullName), sections.Count));
+ break;
+ case "Preview/PrvText.txt":
+ WriteText(output, entry.FullName, PreviewText());
+ break;
+ default:
+ using (var source = entry.Open())
+ using (var target = output.CreateEntry(entry.FullName, CompressionLevel.Optimal).Open())
+ source.CopyTo(target);
+ break;
+ }
+ }
+
+ foreach (var (id, path, extension) in _images)
+ {
+ var ext = HwpImageTypes.Contains(extension) ? extension : "png";
+ using var target = output.CreateEntry($"BinData/{id}.{ext}", CompressionLevel.Optimal).Open();
+ if (ext == extension)
+ {
+ using var source = File.OpenRead(path);
+ source.CopyTo(target);
+ }
+ else
+ {
+ // WEBP, TIFF, SVG, EMF, WMF ... → PNG, which 한글 always displays.
+ using var image = new MagickImage(path);
+ image.Write(target, MagickFormat.Png);
+ }
+ }
+ }
+ File.Move(temp, outputPath, overwrite: true);
+ }
+
+ /// <summary>Opening tag of a section part, declaring the same namespaces as header.xml (as 한글 does).</summary>
+ private string SectionOpenTag()
+ {
+ var namespaces = _head.Attributes().Where(a => a.IsNamespaceDeclaration).ToList();
+ if (!namespaces.Any(a => a.Value == Hs.NamespaceName))
+ namespaces.Add(new XAttribute(XNamespace.Xmlns + "hs", Hs.NamespaceName));
+ return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><hs:sec " + string.Join(' ', namespaces.Select(a => $"{a.Name.LocalName switch { "xmlns" => "xmlns", var n => "xmlns:" + n }}=\"{a.Value}\"")) + ">";
+ }
+
+ private string BuildManifest(string hpf, int sectionCount, string? title)
+ {
+ if (!string.IsNullOrWhiteSpace(title))
+ {
+ var start = hpf.IndexOf("<opf:title>", StringComparison.Ordinal);
+ var end = hpf.IndexOf("</opf:title>", StringComparison.Ordinal);
+ if (start >= 0 && end > start)
+ hpf = hpf[..(start + "<opf:title>".Length)] + Escape(title) + hpf[end..];
+ else
+ hpf = hpf.Replace("<opf:title/>", $"<opf:title>{Escape(title)}</opf:title>", StringComparison.Ordinal);
+ }
+
+ var items = new StringBuilder();
+ var spine = new StringBuilder();
+ for (var i = 1; i < sectionCount; i++)
+ {
+ items.Append($"<opf:item id=\"section{i}\" href=\"Contents/section{i}.xml\" media-type=\"application/xml\"/>");
+ spine.Append($"<opf:itemref idref=\"section{i}\" linear=\"yes\"/>");
+ }
+ foreach (var image in _images)
+ {
+ var ext = HwpImageTypes.Contains(image.Extension) ? image.Extension : "png";
+ var mime = ext switch { "jpg" => "image/jpeg", "gif" => "image/gif", "bmp" => "image/bmp", _ => "image/png" };
+ items.Append($"<opf:item id=\"{image.Id}\" href=\"BinData/{image.Id}.{ext}\" media-type=\"{mime}\" isEmbeded=\"1\"/>");
+ }
+ hpf = InsertAfter(hpf, "href=\"Contents/section0.xml\" media-type=\"application/xml\"/>", items.ToString())
+ ?? InsertBefore(hpf, "</opf:manifest>", items.ToString());
+ return InsertAfter(hpf, "<opf:itemref idref=\"section0\" linear=\"yes\"/>", spine.ToString())
+ ?? InsertBefore(hpf, "</opf:spine>", spine.ToString());
+ }
+
+ private static string BuildRdf(string rdf, int sectionCount)
+ {
+ var parts = new StringBuilder();
+ for (var i = 1; i < sectionCount; i++)
+ {
+ parts.Append($"<rdf:Description rdf:about=\"\"><ns0:hasPart xmlns:ns0=\"http://www.hancom.co.kr/hwpml/2016/meta/pkg#\" rdf:resource=\"Contents/section{i}.xml\"/></rdf:Description>");
+ parts.Append($"<rdf:Description rdf:about=\"Contents/section{i}.xml\"><rdf:type rdf:resource=\"http://www.hancom.co.kr/hwpml/2016/meta/pkg#SectionFile\"/></rdf:Description>");
+ }
+ return InsertBefore(rdf, "</rdf:RDF>", parts.ToString());
+ }
+
+ private static string? InsertAfter(string text, string marker, string insert)
+ {
+ var index = text.IndexOf(marker, StringComparison.Ordinal);
+ return index < 0 ? null : text.Insert(index + marker.Length, insert);
+ }
+
+ private static string InsertBefore(string text, string marker, string insert)
+ {
+ var index = text.LastIndexOf(marker, StringComparison.Ordinal);
+ return index < 0 ? text : text.Insert(index, insert);
+ }
+
+ private string PreviewText()
+ {
+ var text = _plainText.ToString().Trim();
+ return text.Length > 1000 ? text[..1000] : text;
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private int NextId() => _nextObjectId++;
+
+ private static int MaxId(IEnumerable<XElement> elements) =>
+ elements.Select(e => int.TryParse((string?)e.Attribute("id"), out var id) ? id : 0).DefaultIfEmpty(0).Max();
+
+ /// <summary>XML-escapes text and removes characters XML 1.0 does not allow (e.g. vertical tab from Word).</summary>
+ internal static string Escape(string text)
+ {
+ var clean = new StringBuilder(text.Length);
+ foreach (var ch in text)
+ {
+ if (ch is '\t' or '\n' or '\r' || (ch >= 0x20 && ch != 0xFFFE && ch != 0xFFFF))
+ clean.Append(ch);
+ }
+ return SecurityElement.Escape(clean.ToString()) ?? "";
+ }
+
+ private static string ReadEntry(ZipArchive archive, string name)
+ {
+ var entry = archive.GetEntry(name) ?? throw new InvalidDataException($"Reference HWPX has no {name}.");
+ using var reader = new StreamReader(entry.Open(), Encoding.UTF8);
+ return reader.ReadToEnd();
+ }
+
+ private static void WriteText(ZipArchive archive, string name, string text, CompressionLevel level = CompressionLevel.Optimal)
+ {
+ using var writer = new StreamWriter(archive.CreateEntry(name, level).Open(), new UTF8Encoding(false));
+ writer.Write(text);
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/PandocAstReader.cs b/src/Filee.Engines/Hwp/Hwpx/PandocAstReader.cs
new file mode 100644
index 00000000..2a3b1f72
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/PandocAstReader.cs
@@ -0,0 +1,393 @@
+// Pandoc JSON AST → HDocument. Used for Markdown, HTML, ODT and RTF, which Pandoc parses.
+//
+// The mapping follows pypandoc-hwpx (MIT, https://github.com/msjang/pypandoc-hwpx), extended so nothing is dropped
+// silently: BlockQuote, Div, Figure, LineBlock, DefinitionList, HorizontalRule, Span, Quoted, Cite, Strikeout,
+// SmallCaps and Math are converted too, and list numbering honours the Pandoc list style (1. / A. / i) / (a) ...).
+// Pandoc's model has no page setup or direct formatting, so those come from the HWPX template.
+
+using System.Text;
+using System.Text.Json.Nodes;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal sealed class PandocAstReader
+{
+ /// <summary>Indent per block quote level.</summary>
+ private const int QuoteIndent = 2000;
+
+ private static readonly HCharFormat Plain = default;
+ private readonly Func<string, string?> _resolveImage;
+
+ private PandocAstReader(Func<string, string?> resolveImage) => _resolveImage = resolveImage;
+
+ /// <summary>Converts the output of <c>pandoc -t json</c>.</summary>
+ /// <param name="resolveImage">Maps an image target from the AST to a local file, or null if unavailable.</param>
+ public static HDocument Read(JsonNode ast, Func<string, string?> resolveImage)
+ {
+ var reader = new PandocAstReader(resolveImage);
+ var document = new HDocument { Title = Title(ast["meta"]) };
+ var section = new HSection();
+ reader.Blocks(ast["blocks"] as JsonArray, section.Blocks, new Context());
+ document.Sections.Add(section);
+ return document;
+ }
+
+ /// <summary>List nesting and quote indentation of the blocks being read.</summary>
+ private readonly record struct Context(int ListLevel = 0, int Indent = 0);
+
+ // ───────────────────────── Blocks ─────────────────────────
+
+ private void Blocks(JsonArray? blocks, List<HBlock> output, Context context)
+ {
+ foreach (var block in blocks ?? [])
+ {
+ if (block is JsonObject)
+ Block(block, output, context);
+ }
+ }
+
+ private void Block(JsonNode block, List<HBlock> output, Context context)
+ {
+ var content = block["c"];
+ switch (Type(block))
+ {
+ case "Para":
+ case "Plain":
+ output.Add(Paragraph(content as JsonArray, context));
+ break;
+ case "Header":
+ output.Add(Heading(content!, context));
+ break;
+ case "BulletList":
+ List(content as JsonArray, Numbering(ordered: false, 1, "", ""), output, context);
+ break;
+ case "OrderedList":
+ {
+ var attrs = content?[0];
+ var numbering = Numbering(ordered: true, (int?)attrs?[0] ?? 1, Type(attrs?[1]), Type(attrs?[2]));
+ List(content?[1] as JsonArray, numbering, output, context);
+ break;
+ }
+ case "CodeBlock":
+ foreach (var line in ((string?)content?[1] ?? "").Split('\n'))
+ {
+ var paragraph = NewParagraph(context);
+ paragraph.Inlines.Add(new HText(line, Plain));
+ output.Add(paragraph);
+ }
+ break;
+ case "LineBlock":
+ foreach (var line in content as JsonArray ?? [])
+ output.Add(Paragraph(line as JsonArray, context));
+ break;
+ case "BlockQuote":
+ Blocks(content as JsonArray, output, context with { Indent = context.Indent + QuoteIndent });
+ break;
+ case "Div":
+ Blocks(content?[1] as JsonArray, output, context);
+ break;
+ case "Figure":
+ // [attr, caption [short, blocks], blocks]
+ Blocks(content?[2] as JsonArray, output, context);
+ Blocks(content?[1]?[1] as JsonArray, output, context);
+ break;
+ case "DefinitionList":
+ foreach (var item in content as JsonArray ?? [])
+ {
+ var term = NewParagraph(context);
+ Inlines(item?[0] as JsonArray, term.Inlines, new HCharFormat(Bold: true));
+ output.Add(term);
+ foreach (var definition in item?[1] as JsonArray ?? [])
+ Blocks(definition as JsonArray, output, context with { Indent = context.Indent + QuoteIndent });
+ }
+ break;
+ case "HorizontalRule":
+ output.Add(NewParagraph(context));
+ break;
+ case "Table":
+ output.Add(Table(content!, context));
+ break;
+ default:
+ break; // RawBlock and unknown blocks carry no document text
+ }
+ }
+
+ private static HParagraph NewParagraph(Context context) =>
+ new() { Format = context.Indent > 0 ? new HParaFormat(Left: context.Indent) : default };
+
+ private HParagraph Paragraph(JsonArray? inlines, Context context)
+ {
+ var paragraph = NewParagraph(context);
+ Inlines(inlines, paragraph.Inlines, Plain);
+ return paragraph;
+ }
+
+ private HParagraph Heading(JsonNode content, Context context)
+ {
+ var inlines = content[2] as JsonArray ?? [];
+ var paragraph = NewParagraph(context);
+ paragraph.HeadingLevel = Math.Clamp((int?)content[0] ?? 1, 1, 9);
+
+ // A line break at the very start of a heading means "column break" (pypandoc-hwpx convention).
+ paragraph.ColumnBreakBefore = inlines.Count > 0 && Type(inlines[0]) == "LineBreak";
+ Inlines(new JsonArray(inlines.Skip(paragraph.ColumnBreakBefore ? 1 : 0).Select(i => i?.DeepClone()).ToArray()),
+ paragraph.Inlines, Plain);
+
+ // Heading ids are link targets ("#id" links, e.g. a generated table of contents).
+ if ((string?)content[1]?[0] is { Length: > 0 } id)
+ paragraph.Inlines.Insert(0, new HBookmark(id));
+ return paragraph;
+ }
+
+ private static HNumbering Numbering(bool ordered, int start, string style, string delimiter)
+ {
+ string[] bullets = ["●", "○", "■"];
+ string[] defaultFormats = ["DIGIT", "LATIN_CAPITAL", "ROMAN_SMALL"];
+ var numbering = new HNumbering();
+ for (var level = 1; level <= 7; level++)
+ {
+ if (!ordered)
+ {
+ numbering.Levels.Add(new HNumberingLevel("DIGIT", bullets[(level - 1) % 3], 1, Bullet: true));
+ continue;
+ }
+ var format = style switch
+ {
+ "Decimal" => "DIGIT",
+ "LowerAlpha" => "LATIN_SMALL",
+ "UpperAlpha" => "LATIN_CAPITAL",
+ "LowerRoman" => "ROMAN_SMALL",
+ "UpperRoman" => "ROMAN_CAPITAL",
+ _ => defaultFormats[(level - 1) % 3],
+ };
+ var text = delimiter switch
+ {
+ "OneParen" => $"^{level})",
+ "TwoParens" => $"(^{level})",
+ _ => $"^{level}.",
+ };
+ numbering.Levels.Add(new HNumberingLevel(format, text, level == 1 ? Math.Max(1, start) : 1, Bullet: false));
+ }
+ return numbering;
+ }
+
+ private void List(JsonArray? items, HNumbering numbering, List<HBlock> output, Context context)
+ {
+ foreach (var item in items ?? [])
+ {
+ // Only the first paragraph of an item carries the bullet or number.
+ var first = true;
+ foreach (var block in item as JsonArray ?? [])
+ {
+ if (block is null)
+ continue;
+ switch (Type(block))
+ {
+ case "Para":
+ case "Plain":
+ {
+ var paragraph = Paragraph(block["c"] as JsonArray, context);
+ paragraph.List = new HListRef(numbering, context.ListLevel, Numbered: first);
+ output.Add(paragraph);
+ first = false;
+ break;
+ }
+ case "BulletList":
+ case "OrderedList":
+ Block(block, output, context with { ListLevel = context.ListLevel + 1 });
+ break;
+ default:
+ Block(block, output, context);
+ first = false;
+ break;
+ }
+ }
+ }
+ }
+
+ private HTable Table(JsonNode content, Context context)
+ {
+ // Pandoc ≥ 2.10: [attr, caption, colSpecs, head, bodies, foot]; row = [attr, cells];
+ // cell = [attr, align, rowspan, colspan, blocks]
+ var specs = content[2] as JsonArray ?? [];
+ var table = new HTable
+ {
+ ColumnCount = specs.Count,
+ RelativeWidths = specs.Select(s => Type(s?[1]) == "ColWidth" ? (double?)s![1]!["c"] ?? 0 : 0).ToArray(),
+ Indent = context.Indent,
+ };
+
+ void AddRows(JsonArray? rows, bool header)
+ {
+ foreach (var row in rows ?? [])
+ {
+ var hRow = new HRow { Header = header };
+ foreach (var cell in row?[1] as JsonArray ?? [])
+ {
+ if (cell is null)
+ continue;
+ var hCell = new HCell
+ {
+ RowSpan = Math.Max(1, (int?)cell[2] ?? 1),
+ ColSpan = Math.Max(1, (int?)cell[3] ?? 1),
+ };
+ Blocks(cell[4] as JsonArray, hCell.Blocks, new Context());
+ hRow.Cells.Add(hCell);
+ }
+ table.Rows.Add(hRow);
+ }
+ }
+
+ AddRows(content[3]?[1] as JsonArray, header: true);
+ foreach (var body in content[4] as JsonArray ?? [])
+ {
+ AddRows(body?[2] as JsonArray, header: false);
+ AddRows(body?[3] as JsonArray, header: false);
+ }
+ AddRows(content[5]?[1] as JsonArray, header: false);
+
+ Blocks(content[1]?[1] as JsonArray, table.Caption, context);
+ return table;
+ }
+
+ // ───────────────────────── Inlines ─────────────────────────
+
+ private void Inlines(JsonArray? inlines, List<HInline> output, HCharFormat format)
+ {
+ foreach (var inline in inlines ?? [])
+ {
+ if (inline is null)
+ continue;
+ var c = inline["c"];
+ switch (Type(inline))
+ {
+ case "Str":
+ output.Add(new HText((string?)c ?? "", format));
+ break;
+ case "Space":
+ case "SoftBreak":
+ output.Add(new HText(" ", format));
+ break;
+ case "LineBreak":
+ output.Add(new HLineBreak(format));
+ break;
+ case "Strong":
+ Inlines(c as JsonArray, output, format with { Bold = true });
+ break;
+ case "Emph":
+ Inlines(c as JsonArray, output, format with { Italic = true });
+ break;
+ case "Underline":
+ Inlines(c as JsonArray, output, format with { Underline = true });
+ break;
+ case "Strikeout":
+ Inlines(c as JsonArray, output, format with { Strike = true });
+ break;
+ case "Superscript":
+ Inlines(c as JsonArray, output, format with { Superscript = true, Subscript = null });
+ break;
+ case "Subscript":
+ Inlines(c as JsonArray, output, format with { Subscript = true, Superscript = null });
+ break;
+ case "SmallCaps":
+ Inlines(c as JsonArray, output, format);
+ break;
+ case "Span":
+ if ((string?)c?[0]?[0] is { Length: > 0 } spanId)
+ output.Add(new HBookmark(spanId));
+ Inlines(c?[1] as JsonArray, output, format);
+ break;
+ case "Cite":
+ Inlines(c?[1] as JsonArray, output, format);
+ break;
+ case "Quoted":
+ {
+ var (open, close) = Type(c?[0]) == "SingleQuote" ? ("‘", "’") : ("“", "”");
+ output.Add(new HText(open, format));
+ Inlines(c?[1] as JsonArray, output, format);
+ output.Add(new HText(close, format));
+ break;
+ }
+ case "Code":
+ output.Add(new HText((string?)c?[1] ?? "", format));
+ break;
+ case "Math":
+ output.Add(new HText((string?)c?[1] ?? "", format with { Italic = true }));
+ break;
+ case "Link":
+ {
+ var link = new HLink((string?)c?[2]?[0] ?? "");
+ Inlines(c?[1] as JsonArray, link.Content, format);
+ output.Add(link);
+ break;
+ }
+ case "Image":
+ if (Image(c!) is { } image)
+ output.Add(image);
+ break;
+ case "Note":
+ {
+ var note = new HNote(endnote: false);
+ Blocks(c as JsonArray, note.Blocks, new Context());
+ output.Add(note);
+ break;
+ }
+ default:
+ break; // RawInline: format-specific markup, nothing to show.
+ }
+ }
+ }
+
+ private HImage? Image(JsonNode content)
+ {
+ // [attr [id, classes, [[key, value]]], caption inlines, [target, title]]
+ var path = _resolveImage((string?)content[2]?[0] ?? "");
+ if (path is null || !File.Exists(path))
+ return null; // missing image: skip rather than produce a broken reference
+
+ var attributes = (content[0]?[2] as JsonArray ?? [])
+ .Where(kv => kv is JsonArray { Count: 2 })
+ .GroupBy(kv => (string?)kv![0] ?? "")
+ .ToDictionary(g => g.Key, g => (string?)g.First()![1]);
+ return new HImage(path)
+ {
+ Width = HwpxUnits.ParseLength(attributes.GetValueOrDefault("width")),
+ Height = HwpxUnits.ParseLength(attributes.GetValueOrDefault("height")),
+ };
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private static string? Title(JsonNode? meta)
+ {
+ var title = meta?["title"];
+ return Type(title) switch
+ {
+ "MetaInlines" => PlainText(title!["c"] as JsonArray),
+ "MetaString" => (string?)title!["c"],
+ _ => null,
+ };
+ }
+
+ private static string PlainText(JsonArray? inlines)
+ {
+ var sb = new StringBuilder();
+ foreach (var inline in inlines ?? [])
+ {
+ var c = inline?["c"];
+ switch (Type(inline))
+ {
+ case "Str": sb.Append((string?)c); break;
+ case "Space" or "SoftBreak" or "LineBreak": sb.Append(' '); break;
+ case "Code" or "Math": sb.Append((string?)c?[1]); break;
+ case "Link" or "Image" or "Span" or "Cite": sb.Append(PlainText(c?[1] as JsonArray)); break;
+ case "Quoted": sb.Append('"').Append(PlainText(c?[1] as JsonArray)).Append('"'); break;
+ case "Strong" or "Emph" or "Underline" or "Strikeout" or "Superscript" or "Subscript" or "SmallCaps":
+ sb.Append(PlainText(c as JsonArray)); break;
+ }
+ }
+ return sb.ToString();
+ }
+
+ private static string Type(JsonNode? node) => node is JsonObject obj ? (string?)obj["t"] ?? "" : "";
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/blank.hwpx b/src/Filee.Engines/Hwp/Hwpx/blank.hwpx
new file mode 100644
index 00000000..a690a1fd
Binary files /dev/null and b/src/Filee.Engines/Hwp/Hwpx/blank.hwpx differ
diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.cs
new file mode 100644
index 00000000..091dddc3
--- /dev/null
+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs
@@ -0,0 +1,68 @@
+// HWP / HWPX → PDF, HWP → HWPX and HWPX → HWP with the rhwp command line tool (MIT, https://github.com/edwardkim/rhwp).
+// Bundled under engines/rhwp. Works without Hancom Office, so there is no automation approval dialog.
+
+using Filee.Core.Conversion;
+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
+{
+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
+ private string? _exe;
+
+ public string Id => "rhwp";
+ public string DisplayName => "rhwp";
+ public int MaxParallelism => 2;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("hwp", "pdf"),
+ new("hwpx", "pdf"),
+ // Lossless within the 한글 document model; anything → HWP goes through the HWPX writer first.
+ new("hwp", "hwpx"),
+ new("hwpx", "hwp"),
+ ];
+
+ public EngineStatus GetStatus()
+ {
+ _exe = Locate();
+ return _exe is null ? EngineStatus.Unavailable("engine.reason.not_installed") : EngineStatus.Available(_exe);
+ }
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var exe = _exe ?? Locate() ?? throw new InvalidOperationException("rhwp was not found.");
+ var temp = Path.Combine(step.WorkDirectory, $"rhwp-{Guid.NewGuid():N}.{step.To}");
+ string[] arguments = step.To switch
+ {
+ "pdf" => ["export-pdf", step.InputPath, "-o", temp],
+ "hwpx" => ["export-hwpx", step.InputPath, temp],
+ "hwp" => ["convert", step.InputPath, temp],
+ _ => throw new NotSupportedException(step.To),
+ };
+
+ progress?.Report(0.1);
+ var result = await ProcessRunner.RunAsync(exe, arguments, Timeout, cancellationToken);
+ if (!File.Exists(temp) || new FileInfo(temp).Length == 0)
+ throw new InvalidOperationException($"rhwp failed (exit {result.ExitCode}). {result.StandardError.Trim()}");
+
+ var target = step.Output.Allocate(step.To);
+ if (target is null)
+ return [];
+ File.Move(temp, target, overwrite: true);
+ progress?.Report(1);
+ 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"));
+ }
+}
diff --git a/src/Filee.Engines/Hwp/UnhwpConverter.cs b/src/Filee.Engines/Hwp/UnhwpConverter.cs
new file mode 100644
index 00000000..184f5da7
--- /dev/null
+++ b/src/Filee.Engines/Hwp/UnhwpConverter.cs
@@ -0,0 +1,72 @@
+// HWP / HWPX → plain text, Markdown or HTML with Unhwp (MIT, native library shipped in the NuGet package).
+
+using System.Net;
+using Filee.Core.Conversion;
+using Markdig;
+using Unhwp;
+
+namespace Filee.Engines.Hwp;
+
+/// <summary>Extracts the text content of HWP documents.</summary>
+public sealed class UnhwpConverter : IConverter
+{
+ private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
+
+ public string Id => "unhwp";
+ public string DisplayName => "Unhwp";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ new("hwp", "txt"), new("hwpx", "txt"),
+ new("hwp", "md"), new("hwpx", "md"),
+ new("hwp", "html", 14), new("hwpx", "html", 14),
+ ];
+
+ public EngineStatus GetStatus()
+ {
+ // The native library only ships for win-x64, osx-x64/arm64 and linux-x64.
+ var arch = System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture;
+ var supported = arch == System.Runtime.InteropServices.Architecture.X64
+ || (OperatingSystem.IsMacOS() && arch == System.Runtime.InteropServices.Architecture.Arm64);
+ return supported ? EngineStatus.Available() : EngineStatus.Unavailable("engine.reason.unsupported_platform");
+ }
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ using var document = UnhwpDocument.ParseFile(step.InputPath);
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.5);
+
+ var content = step.To switch
+ {
+ "txt" => document.ToText(),
+ "md" => document.ToMarkdown(new MarkdownOptions { IncludeFrontmatter = false }),
+ "html" => ToHtml(document.ToMarkdown(new MarkdownOptions()), document.Title ?? Path.GetFileNameWithoutExtension(step.InputPath)),
+ _ => throw new NotSupportedException(step.To),
+ };
+
+ var path = step.Output.Allocate(step.To);
+ if (path is null)
+ return [];
+ File.WriteAllText(path, content, new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: step.To == "txt"));
+ progress?.Report(1);
+ return [path];
+ }, cancellationToken);
+
+ private static string ToHtml(string markdown, string title) =>
+ $$"""
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <title>{{WebUtility.HtmlEncode(title)}}</title>
+ <style>body{font-family:'Noto Sans KR','Malgun Gothic',sans-serif;max-width:860px;margin:2rem auto;line-height:1.7;padding:0 1rem}table{border-collapse:collapse}td,th{border:1px solid #ccc;padding:4px 8px}</style>
+ </head>
+ <body>
+ {{Markdown.ToHtml(markdown, Pipeline)}}
+ </body>
+ </html>
+ """;
+}
diff --git a/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs b/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs
new file mode 100644
index 00000000..2263dba9
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/AutomationProcessGuard.cs
@@ -0,0 +1,82 @@
+// 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/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.cs
new file mode 100644
index 00000000..ace46435
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs
@@ -0,0 +1,51 @@
+// Engines that are downloaded on demand instead of being bundled with the installer (they are large), and the
+// pinned download list they come from (engines.json, shared with build/fetch-engines.ps1).
+
+using System.Text.Json;
+
+namespace Filee.Engines.Infrastructure;
+
+/// <summary>One download from engines.json.</summary>
+/// <param name="Kind">"zip" (extracted), "msi" (administrative install, no system changes) or "oxt" (LibreOffice extension).</param>
+/// <param name="Size">Download size in bytes.</param>
+public sealed record EngineComponent(string Id, string Version, string Url, string Sha256, long Size, string Kind);
+
+/// <summary>A set of components the user installs together, e.g. LibreOffice with its HWP import filter and Java.</summary>
+/// <param name="Components">Installed in this order (the LibreOffice extension needs LibreOffice first).</param>
+/// <param name="InstalledSize">Approximate size on disk in bytes, shown before installing.</param>
+/// <param name="ConverterIds">Engines (<see cref="Filee.Core.Conversion.IConverter.Id"/>) the package provides.</param>
+public sealed record EnginePackage(string Id, IReadOnlyList<string> Components, long InstalledSize, IReadOnlyList<string> ConverterIds);
+
+public static class EngineDownloads
+{
+ /// <summary>Every component of engines.json by id.</summary>
+ public static IReadOnlyDictionary<string, EngineComponent> Components { get; } = Load();
+
+ /// <summary>
+ /// Packages offered in Settings → Engines and on first run. rhwp is not listed: it is small and bundled.
+ /// </summary>
+ public static IReadOnlyList<EnginePackage> Packages { get; } =
+ [
+ new("libreoffice", ["libreoffice", "h2orestart", "jre"], 1_265_000_000, ["libreoffice"]),
+ new("pandoc", ["pandoc"], 236_000_000, ["pandoc"]),
+ ];
+
+ /// <summary>Total download size of a package in bytes.</summary>
+ public static long DownloadSize(EnginePackage package) => package.Components.Sum(c => Components[c].Size);
+
+ private static Dictionary<string, EngineComponent> Load()
+ {
+ using var stream = typeof(EngineDownloads).Assembly.GetManifestResourceStream("Filee.Engines.engines.json")
+ ?? throw new InvalidOperationException("Embedded engines.json is missing.");
+ using var json = JsonDocument.Parse(stream);
+ return json.RootElement.GetProperty("components").EnumerateObject().ToDictionary(
+ p => p.Name,
+ p => new EngineComponent(
+ p.Name,
+ p.Value.GetProperty("version").GetString()!,
+ p.Value.GetProperty("url").GetString()!,
+ p.Value.GetProperty("sha256").GetString()!,
+ p.Value.GetProperty("size").GetInt64(),
+ p.Value.GetProperty("kind").GetString()!));
+ }
+}
diff --git a/src/Filee.Engines/Infrastructure/EngineEnvironment.cs b/src/Filee.Engines/Infrastructure/EngineEnvironment.cs
new file mode 100644
index 00000000..cf00ba7a
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/EngineEnvironment.cs
@@ -0,0 +1,80 @@
+// Shared context for engines: where bundled tools live and which custom paths the user configured.
+
+namespace Filee.Engines.Infrastructure;
+
+/// <summary>Environment information passed to every engine.</summary>
+public sealed class EngineEnvironment
+{
+ /// <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; }
+
+ /// <summary>
+ /// Per-user folder for engines downloaded on demand (see <see cref="EngineInstaller"/>):
+ /// %LOCALAPPDATA%\Filee\engines. It is outside the app folder, so app updates keep it, and inside Filee's
+ /// install root, so uninstalling removes it.
+ /// </summary>
+ public static string DownloadRoot { get; set; } =
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Filee", "engines");
+
+ /// <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.
+ /// </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;
+ 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)
+ {
+ 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 null;
+ }
+
+ /// <summary>Returns the first path that exists as a file.</summary>
+ public static string? FirstExisting(params string?[] candidates) =>
+ candidates.FirstOrDefault(c => !string.IsNullOrWhiteSpace(c) && File.Exists(c));
+}
diff --git a/src/Filee.Engines/Infrastructure/EngineInstaller.cs b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
new file mode 100644
index 00000000..4515af24
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
@@ -0,0 +1,309 @@
+// Downloads, verifies and unpacks optional engines into the per-user engines folder (EngineEnvironment.DownloadRoot).
+//
+// * Every download is checked against the SHA-256 pinned in engines.json before anything is unpacked.
+// * Unpacking happens in a staging folder that replaces the engine folder only when complete, so a failed or
+// cancelled install never leaves a half-installed engine behind.
+// * The LibreOffice MSI is unpacked with an administrative install (msiexec /a): files only, no registry entries,
+// no admin rights. Parts headless conversion never uses (help, gallery, most dictionaries) are removed.
+// * A marker file with the component's hash records what is installed, so an engines.json update is detected.
+
+using System.Diagnostics;
+using System.IO.Compression;
+using System.Security.Cryptography;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
+
+namespace Filee.Engines.Infrastructure;
+
+public enum EngineInstallStage
+{
+ Downloading,
+ Unpacking,
+}
+
+/// <summary>Progress of an install: <paramref name="Fraction"/> covers the whole package (0..1).</summary>
+public readonly record struct EngineInstallProgress(EngineInstallStage Stage, string ComponentId, double Fraction);
+
+/// <summary>Installs and removes <see cref="EnginePackage"/>s.</summary>
+public sealed class EngineInstaller
+{
+ private const string MarkerName = ".filee-component";
+ private static readonly TimeSpan MsiTimeout = TimeSpan.FromMinutes(15);
+
+ private readonly string _root;
+ private readonly HttpClient _http;
+ private readonly IReadOnlyDictionary<string, EngineComponent> _components;
+ private readonly ILogger _logger;
+
+ /// <param name="root">Folder that receives one sub folder per engine (default: EngineEnvironment.DownloadRoot).</param>
+ /// <param name="components">Download list; engines.json when null (tests pass their own).</param>
+ public EngineInstaller(HttpClient http, string? root = null, IReadOnlyDictionary<string, EngineComponent>? components = null, ILogger? logger = null)
+ {
+ _http = http;
+ _root = root ?? EngineEnvironment.DownloadRoot;
+ _components = components ?? EngineDownloads.Components;
+ _logger = logger ?? NullLogger.Instance;
+ }
+
+ /// <summary>True when every component is installed (any version).</summary>
+ public bool IsInstalled(EnginePackage package) => package.Components.All(c => Marker(c) is not null);
+
+ /// <summary>True when every component is installed in the version engines.json pins.</summary>
+ public bool IsUpToDate(EnginePackage package) =>
+ package.Components.All(c => string.Equals(Marker(c), _components[c].Sha256, StringComparison.OrdinalIgnoreCase));
+
+ /// <summary>Downloads and unpacks the components that are missing or outdated.</summary>
+ public async Task InstallAsync(EnginePackage package, IProgress<EngineInstallProgress>? progress, CancellationToken cancellationToken)
+ {
+ var pending = package.Components
+ .Where(c => !string.Equals(Marker(c), _components[c].Sha256, StringComparison.OrdinalIgnoreCase))
+ .Select(c => _components[c])
+ .ToList();
+ var total = Math.Max(1, pending.Sum(c => c.Size));
+ long done = 0;
+ Directory.CreateDirectory(_root);
+
+ foreach (var component in pending)
+ {
+ var offset = done;
+ var file = await DownloadAsync(component,
+ bytes => progress?.Report(new EngineInstallProgress(EngineInstallStage.Downloading, component.Id, Math.Min(1, (offset + bytes) / (double)total))),
+ cancellationToken);
+ try
+ {
+ progress?.Report(new EngineInstallProgress(EngineInstallStage.Unpacking, component.Id, Math.Min(1, (offset + component.Size) / (double)total)));
+ await UnpackAsync(component, file, cancellationToken);
+ }
+ finally
+ {
+ TryDelete(file);
+ }
+ done += component.Size;
+ _logger.LogInformation("Installed engine component {Component} {Version}", component.Id, component.Version);
+ }
+ }
+
+ /// <summary>Removes the package's folders. Fails if an engine is running (its files are locked).</summary>
+ public void Uninstall(EnginePackage package)
+ {
+ foreach (var id in package.Components)
+ {
+ var folder = FolderOf(id);
+ if (Directory.Exists(folder))
+ Directory.Delete(folder, recursive: true);
+ }
+ }
+
+ // ───────────────────────── Download ─────────────────────────
+
+ private async Task<string> DownloadAsync(EngineComponent component, Action<long> reportBytes, CancellationToken cancellationToken)
+ {
+ var downloads = Path.Combine(_root, ".downloads");
+ Directory.CreateDirectory(downloads);
+ var file = Path.Combine(downloads, $"{component.Id}-{component.Version}{Path.GetExtension(new Uri(component.Url).AbsolutePath)}");
+ var partial = file + ".part";
+
+ using var response = await GetFollowingRedirectsAsync(new Uri(component.Url), cancellationToken);
+ response.EnsureSuccessStatusCode();
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ await using (var source = await response.Content.ReadAsStreamAsync(cancellationToken))
+ await using (var target = File.Create(partial))
+ {
+ var buffer = new byte[1 << 16];
+ long received = 0;
+ var lastReport = Stopwatch.StartNew();
+ int read;
+ while ((read = await source.ReadAsync(buffer, cancellationToken)) > 0)
+ {
+ await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
+ hash.AppendData(buffer, 0, read);
+ received += read;
+ if (lastReport.ElapsedMilliseconds > 150)
+ {
+ reportBytes(received);
+ lastReport.Restart();
+ }
+ }
+ reportBytes(received);
+ }
+
+ var actual = Convert.ToHexString(hash.GetHashAndReset());
+ if (!string.Equals(actual, component.Sha256, StringComparison.OrdinalIgnoreCase))
+ {
+ TryDelete(partial);
+ throw new InvalidDataException($"{component.Id}: checksum mismatch (expected {component.Sha256}, got {actual}). The download was discarded.");
+ }
+ File.Move(partial, file, overwrite: true);
+ return file;
+ }
+
+ /// <summary>
+ /// Follows redirects itself: download sites send users to mirrors, some of them plain HTTP, which HttpClient
+ /// never follows from HTTPS. That is safe here because every file is checked against its pinned SHA-256.
+ /// The HttpClient should be created with automatic redirects off.
+ /// </summary>
+ private async Task<HttpResponseMessage> GetFollowingRedirectsAsync(Uri url, CancellationToken cancellationToken)
+ {
+ for (var hop = 0; ; hop++)
+ {
+ var response = await _http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ if ((int)response.StatusCode is >= 300 and < 400 && response.Headers.Location is { } location && hop < 10)
+ {
+ url = location.IsAbsoluteUri ? location : new Uri(url, location);
+ response.Dispose();
+ continue;
+ }
+ return response;
+ }
+ }
+
+ // ───────────────────────── Unpack ─────────────────────────
+
+ private async Task UnpackAsync(EngineComponent component, string file, CancellationToken cancellationToken)
+ {
+ // Short name: LibreOffice's own folder structure is deep, and msiexec fails beyond MAX_PATH (260 chars).
+ var staging = Path.Combine(_root, "~" + Guid.NewGuid().ToString("N")[..6]);
+ try
+ {
+ switch (component.Kind)
+ {
+ case "zip":
+ ZipFile.ExtractToDirectory(file, staging);
+ Replace(component.Id, SingleRoot(staging));
+ break;
+ case "msi":
+ await UnpackMsiAsync(file, staging, Path.Combine(Path.GetTempPath(), "filee-msiexec.log"), cancellationToken);
+ var soffice = Directory.EnumerateFiles(staging, "soffice.exe", SearchOption.AllDirectories).FirstOrDefault()
+ ?? throw new InvalidDataException("soffice.exe not found in the LibreOffice package.");
+ var libreOffice = Path.GetDirectoryName(Path.GetDirectoryName(soffice)!)!; // folder with program/, share/
+ TrimLibreOffice(libreOffice);
+ Replace(component.Id, libreOffice);
+ break;
+ case "oxt":
+ // LibreOffice registers bundled extensions (plain folders under share/extensions) on start-up.
+ var extensions = Path.Combine(FolderOf("libreoffice"), "share", "extensions");
+ if (!Directory.Exists(extensions))
+ throw new InvalidOperationException($"{component.Id} needs LibreOffice, which is not installed.");
+ ZipFile.ExtractToDirectory(file, staging);
+ var target = FolderOf(component.Id);
+ if (Directory.Exists(target))
+ Directory.Delete(target, recursive: true);
+ Directory.Move(staging, target);
+ break;
+ default:
+ throw new NotSupportedException($"Unknown engine package kind '{component.Kind}'.");
+ }
+ File.WriteAllText(Path.Combine(FolderOf(component.Id), MarkerName), component.Sha256);
+ }
+ finally
+ {
+ if (Directory.Exists(staging))
+ Directory.Delete(staging, recursive: true);
+ }
+ }
+
+ private static async Task UnpackMsiAsync(string msi, string target, string log, CancellationToken cancellationToken)
+ {
+ if (!OperatingSystem.IsWindows())
+ throw new PlatformNotSupportedException("The LibreOffice package is a Windows installer.");
+ Directory.CreateDirectory(target);
+ // msiexec parses its own command line: the property value must be quoted as TARGETDIR="...", so the
+ // argument list escaping of ProcessRunner cannot be used here.
+ using var process = Process.Start(new ProcessStartInfo("msiexec.exe", $"/a \"{msi}\" /qn /l*v \"{log}\" TARGETDIR=\"{target}\"")
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ }) ?? throw new InvalidOperationException("msiexec could not be started.");
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(MsiTimeout);
+ try
+ {
+ await process.WaitForExitAsync(timeout.Token);
+ }
+ catch (OperationCanceledException)
+ {
+ process.Kill(entireProcessTree: true);
+ throw;
+ }
+ if (process.ExitCode != 0)
+ {
+ throw new InvalidOperationException(process.ExitCode switch
+ {
+ 1618 => "Another installation is running. Try again when it has finished.",
+ _ => $"Unpacking LibreOffice failed (msiexec exit code {process.ExitCode}, log: {log}).",
+ });
+ }
+ }
+
+ /// <summary>
+ /// Removes what headless conversion never uses (~500 MB): help, readmes, the MSI copy, the gallery and spelling
+ /// dictionaries except English and Korean (their hyphenation patterns affect page layout in PDF export).
+ /// </summary>
+ internal static void TrimLibreOffice(string root)
+ {
+ foreach (var folder in new[] { "help", "readmes", Path.Combine("share", "gallery") })
+ {
+ var path = Path.Combine(root, folder);
+ if (Directory.Exists(path))
+ Directory.Delete(path, recursive: true);
+ }
+ foreach (var msi in Directory.EnumerateFiles(root, "*.msi"))
+ File.Delete(msi);
+ var extensions = Path.Combine(root, "share", "extensions");
+ if (Directory.Exists(extensions))
+ {
+ foreach (var dictionary in Directory.EnumerateDirectories(extensions, "dict-*"))
+ {
+ if (Path.GetFileName(dictionary) is not ("dict-en" or "dict-ko"))
+ Directory.Delete(dictionary, recursive: true);
+ }
+ }
+ }
+
+ /// <summary>An archive with a single top-level folder is unpacked without that extra level.</summary>
+ private static string SingleRoot(string folder)
+ {
+ var entries = Directory.GetFileSystemEntries(folder);
+ return entries.Length == 1 && Directory.Exists(entries[0]) ? entries[0] : folder;
+ }
+
+ /// <summary>Makes <paramref name="source"/> the engine folder, replacing a previous version.</summary>
+ private void Replace(string id, string source)
+ {
+ var target = FolderOf(id);
+ if (Directory.Exists(target))
+ Directory.Delete(target, recursive: true);
+ Directory.Move(source, target);
+ }
+
+ // ───────────────────────── Layout ─────────────────────────
+
+ /// <summary>Folder of a component; the LibreOffice extension lives inside LibreOffice.</summary>
+ private string FolderOf(string id) => _components.TryGetValue(id, out var component) && component.Kind == "oxt"
+ ? Path.Combine(_root, "libreoffice", "share", "extensions", ExtensionFolder(id))
+ : Path.Combine(_root, id);
+
+ private static string ExtensionFolder(string id) => id switch
+ {
+ "h2orestart" => "H2Orestart",
+ _ => id,
+ };
+
+ /// <summary>Hash of the installed version, or null when not installed.</summary>
+ private string? Marker(string id)
+ {
+ var marker = Path.Combine(FolderOf(id), MarkerName);
+ return File.Exists(marker) ? File.ReadAllText(marker).Trim() : null;
+ }
+
+ private static void TryDelete(string file)
+ {
+ try
+ {
+ File.Delete(file);
+ }
+ catch (IOException)
+ {
+ }
+ }
+}
diff --git a/src/Filee.Engines/Infrastructure/ProcessRunner.cs b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
new file mode 100644
index 00000000..7590192f
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
@@ -0,0 +1,81 @@
+// Runs command line engines (LibreOffice, rhwp, ...) with a timeout, cancellation and captured output.
+
+using System.Diagnostics;
+using System.Text;
+
+namespace Filee.Engines.Infrastructure;
+
+/// <summary>Result of an external process.</summary>
+public sealed record ProcessResult(int ExitCode, string StandardOutput, string StandardError);
+
+/// <summary>Helper for starting external tools safely.</summary>
+public static class ProcessRunner
+{
+ /// <summary>
+ /// Starts <paramref name="executable"/> with the given arguments (no shell, arguments are escaped),
+ /// waits for it to exit and kills the whole process tree on timeout or cancellation.
+ /// </summary>
+ public static async Task<ProcessResult> RunAsync(
+ string executable,
+ IEnumerable<string> arguments,
+ TimeSpan timeout,
+ CancellationToken cancellationToken,
+ string? workingDirectory = null,
+ IDictionary<string, string>? environment = null)
+ {
+ var psi = new ProcessStartInfo(executable)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = Encoding.UTF8,
+ StandardErrorEncoding = Encoding.UTF8,
+ WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(executable) ?? "",
+ };
+ foreach (var arg in arguments)
+ psi.ArgumentList.Add(arg);
+ if (environment is not null)
+ foreach (var (key, value) in environment)
+ psi.Environment[key] = value;
+
+ using var process = new Process { StartInfo = psi };
+ var stdout = new StringBuilder();
+ var stderr = new StringBuilder();
+ process.OutputDataReceived += (_, e) => { if (e.Data is not null) lock (stdout) stdout.AppendLine(e.Data); };
+ process.ErrorDataReceived += (_, e) => { if (e.Data is not null) lock (stderr) stderr.AppendLine(e.Data); };
+
+ if (!process.Start())
+ throw new InvalidOperationException($"Could not start {executable}.");
+ process.BeginOutputReadLine();
+ process.BeginErrorReadLine();
+
+ using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeoutCts.CancelAfter(timeout);
+ try
+ {
+ await process.WaitForExitAsync(timeoutCts.Token);
+ }
+ catch (OperationCanceledException)
+ {
+ TryKill(process);
+ cancellationToken.ThrowIfCancellationRequested();
+ throw new TimeoutException($"{Path.GetFileName(executable)} did not finish within {timeout.TotalSeconds:0} s.");
+ }
+
+ // Make sure the async output readers have drained.
+ process.WaitForExit();
+ return new ProcessResult(process.ExitCode, stdout.ToString(), stderr.ToString());
+ }
+
+ private static void TryKill(Process process)
+ {
+ try
+ {
+ if (!process.HasExited)
+ process.Kill(entireProcessTree: true);
+ }
+ catch (InvalidOperationException) { }
+ catch (System.ComponentModel.Win32Exception) { }
+ }
+}
diff --git a/src/Filee.Engines/Infrastructure/StaThread.cs b/src/Filee.Engines/Infrastructure/StaThread.cs
new file mode 100644
index 00000000..ce5afe7c
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/StaThread.cs
@@ -0,0 +1,38 @@
+// 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/Infrastructure/engines.json b/src/Filee.Engines/Infrastructure/engines.json
new file mode 100644
index 00000000..02d25ed7
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/engines.json
@@ -0,0 +1,40 @@
+{
+ "_comment": "Downloadable conversion engines: pinned URL + SHA-256. Used by the app (Settings > Engines, first-run setup) and by build/fetch-engines.ps1. Bumping a version = change url, sha256 and size together.",
+ "components": {
+ "rhwp": {
+ "version": "0.8.6",
+ "url": "https://github.com/edwardkim/rhwp/releases/download/v0.8.6/rhwp-v0.8.6-windows-x86_64.zip",
+ "sha256": "867E0A84B778EBDA92B88433EDE301818EAEA21E7D58EB77FF9A732F41D170D9",
+ "size": 10270410,
+ "kind": "zip"
+ },
+ "pandoc": {
+ "version": "3.12",
+ "url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-windows-x86_64.zip",
+ "sha256": "2A77EBC2517D13E95056E76B1CD5B574CFE958AC61AA6058117D80C22CA19B79",
+ "size": 42114462,
+ "kind": "zip"
+ },
+ "jre": {
+ "version": "21.0.12.1",
+ "url": "https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.12.1%2B1/OpenJDK21U-jre_x64_windows_hotspot_21.0.12.1_1.zip",
+ "sha256": "D35F31E712F0FCF6AC5A093EDC90204FBFF22F720BA3950BD09D331D5E621636",
+ "size": 48999141,
+ "kind": "zip"
+ },
+ "libreoffice": {
+ "version": "26.2.6",
+ "url": "https://download.documentfoundation.org/libreoffice/stable/26.2.6/win/x86_64/LibreOffice_26.2.6_Win_x86-64.msi",
+ "sha256": "F9877032FD908BEB9C0DDF06DF4AF5C2E85F419C42E14876C4CCE5AAE5FB2660",
+ "size": 373252096,
+ "kind": "msi"
+ },
+ "h2orestart": {
+ "version": "0.7.14",
+ "url": "https://github.com/ebandal/H2Orestart/releases/download/v0.7.14/H2Orestart.oxt",
+ "sha256": "CBEA23BC37861361BBC534BC0675E5BC67B36F712072490F82A9BF410D7C04D8",
+ "size": 606257,
+ "kind": "oxt"
+ }
+ }
+}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
new file mode 100644
index 00000000..fc905bb0
--- /dev/null
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -0,0 +1,180 @@
+// Shared ImageMagick logic: applies preset ImageOptions and writes frames in the requested format.
+// Used by MagickImageConverter and by PdfiumConverter (PDF pages → images).
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+
+namespace Filee.Engines.Magick;
+
+internal static class ImageEncoder
+{
+ /// <summary>Image formats ImageMagick can read.</summary>
+ public static readonly string[] Readable = ["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif", "heic"];
+
+ /// <summary>
+ /// Image formats ImageMagick can write. HEIC is missing on purpose: the bundled build has no HEVC encoder
+ /// (patent licensing), so we offer AVIF instead.
+ /// </summary>
+ public static readonly string[] Writable = ["png", "jpg", "webp", "tiff", "bmp", "gif", "ico", "avif"];
+
+ /// <summary>Formats that store several frames/pages in one file.</summary>
+ private static readonly HashSet<string> MultiFrame = ["tiff", "gif"];
+
+ /// <summary>Formats without an alpha channel: transparent pixels are flattened onto the background colour.</summary>
+ private static readonly HashSet<string> NoAlpha = ["jpg"];
+
+ public static MagickFormat ToMagickFormat(string formatId) => formatId switch
+ {
+ "png" => MagickFormat.Png,
+ "jpg" => MagickFormat.Jpeg,
+ "webp" => MagickFormat.WebP,
+ "tiff" => MagickFormat.Tiff,
+ "bmp" => MagickFormat.Bmp,
+ "gif" => MagickFormat.Gif,
+ "ico" => MagickFormat.Icon,
+ "avif" => MagickFormat.Avif,
+ "heic" => MagickFormat.Heic,
+ _ => throw new NotSupportedException($"ImageMagick cannot handle '{formatId}'."),
+ };
+
+ /// <summary>
+ /// Chooses which frames of a (possibly multi-frame) source are converted.
+ /// ICO: the largest icon. GIF → single-frame target: the first frame. Otherwise: all frames/pages.
+ /// </summary>
+ public static List<IMagickImage<byte>> SelectFrames(MagickImageCollection images, string sourceFormat, string targetFormat)
+ {
+ if (sourceFormat == "gif")
+ images.Coalesce(); // GIF frames can be partial; coalescing makes every frame a full image
+
+ var frames = images.ToList();
+ if (frames.Count <= 1)
+ return frames;
+ if (sourceFormat == "ico")
+ return [frames.OrderByDescending(f => (long)f.Width * f.Height).First()];
+ if (sourceFormat == "gif" && !MultiFrame.Contains(targetFormat))
+ return [frames[0]];
+ return frames;
+ }
+
+ /// <summary>Applies resize / colour / metadata options to one frame.</summary>
+ public static void ApplyOptions(IMagickImage<byte> image, ImageOptions options, string targetFormat)
+ {
+ image.AutoOrient();
+
+ switch (options.Resize)
+ {
+ case ResizeMode.Percent when options.ResizePercent is > 0 and not 100:
+ image.Resize(new Percentage(options.ResizePercent));
+ break;
+ case ResizeMode.LongEdge when options.LongEdge > 0:
+ // Greater = only shrink images that are larger than the box, never upscale.
+ image.Resize(new MagickGeometry((uint)options.LongEdge, (uint)options.LongEdge) { Greater = true });
+ break;
+ }
+
+ if (options.Grayscale)
+ image.Grayscale();
+
+ if (options.Dpi is > 0)
+ image.Density = new Density(options.Dpi.Value, options.Dpi.Value, DensityUnit.PixelsPerInch);
+
+ if (!options.KeepMetadata)
+ image.Strip();
+
+ if (NoAlpha.Contains(targetFormat) && image.HasAlpha)
+ {
+ image.BackgroundColor = ParseColor(options.Background);
+ image.Alpha(AlphaOption.Remove);
+ }
+
+ var quality = (uint)Math.Clamp(options.Quality, 1, 100);
+ switch (targetFormat)
+ {
+ case "jpg":
+ case "avif":
+ image.Quality = quality;
+ break;
+ case "webp":
+ image.Quality = quality;
+ if (options.WebpLossless)
+ image.Settings.SetDefine(MagickFormat.WebP, "lossless", true);
+ break;
+ case "tiff":
+ image.Settings.Compression = options.TiffCompression switch
+ {
+ TiffCompression.Lzw => CompressionMethod.LZW,
+ TiffCompression.Zip => CompressionMethod.Zip,
+ _ => CompressionMethod.NoCompression,
+ };
+ break;
+ case "ico":
+ PrepareIcon(image, options);
+ break;
+ }
+ }
+
+ /// <summary>
+ /// Writes frames using the allocator. Multi-frame targets get one file; other targets get one file per frame
+ /// with a <c>_p{n}</c> suffix when there is more than one frame.
+ /// </summary>
+ public static List<string> Write(IReadOnlyList<IMagickImage<byte>> frames, string targetFormat, IOutputAllocator output)
+ {
+ var written = new List<string>();
+ var format = ToMagickFormat(targetFormat);
+
+ if (frames.Count > 1 && MultiFrame.Contains(targetFormat))
+ {
+ var path = output.Allocate(targetFormat);
+ if (path is null)
+ return written;
+ using var collection = new MagickImageCollection();
+ foreach (var frame in frames)
+ collection.Add(frame.Clone());
+ collection.Write(path, format);
+ written.Add(path);
+ return written;
+ }
+
+ for (var i = 0; i < frames.Count; i++)
+ {
+ var path = output.Allocate(targetFormat, frames.Count > 1 ? $"_p{i + 1}" : null);
+ if (path is null)
+ continue;
+ frames[i].Write(path, format);
+ written.Add(path);
+ }
+ return written;
+ }
+
+ private static void PrepareIcon(IMagickImage<byte> image, ImageOptions options)
+ {
+ // Icons must be square: pad the shorter side with transparency, then let ImageMagick
+ // generate every requested size inside one .ico file.
+ var side = Math.Max(image.Width, image.Height);
+ if (image.Width != image.Height)
+ {
+ image.BackgroundColor = MagickColors.Transparent;
+ image.Extent(side, side, Gravity.Center);
+ }
+ if (side > 256)
+ image.Resize(256, 256);
+
+ var sizes = options.IcoSizes.Where(s => s is > 0 and <= 256).Distinct().OrderDescending().ToList();
+ if (sizes.Count == 0)
+ sizes = [256, 48, 32, 16];
+ image.Settings.SetDefine(MagickFormat.Icon, "auto-resize", string.Join(',', sizes));
+ }
+
+ private static MagickColor ParseColor(string hex)
+ {
+ try
+ {
+ return new MagickColor(string.IsNullOrWhiteSpace(hex) ? "#FFFFFF" : hex);
+ }
+ catch (ArgumentException)
+ {
+ return new MagickColor("#FFFFFF");
+ }
+ }
+}
diff --git a/src/Filee.Engines/Magick/MagickImageConverter.cs b/src/Filee.Engines/Magick/MagickImageConverter.cs
new file mode 100644
index 00000000..e425a3b5
--- /dev/null
+++ b/src/Filee.Engines/Magick/MagickImageConverter.cs
@@ -0,0 +1,42 @@
+// Raster image ↔ raster image conversion with ImageMagick (Magick.NET, Apache-2.0).
+
+using Filee.Core.Conversion;
+using ImageMagick;
+
+namespace Filee.Engines.Magick;
+
+/// <summary>Converts between PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF and HEIC (read only).</summary>
+public sealed class MagickImageConverter : IConverter
+{
+ public string Id => "magick";
+ public string DisplayName => "ImageMagick";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ (from source in ImageEncoder.Readable
+ from target in ImageEncoder.Writable
+ select new ConversionEdge(source, target)).ToList();
+
+ public EngineStatus GetStatus() =>
+ EngineStatus.Available($"ImageMagick {MagickNET.ImageMagickVersion}");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ using var images = new MagickImageCollection(step.InputPath);
+ cancellationToken.ThrowIfCancellationRequested();
+ progress?.Report(0.3);
+
+ var frames = ImageEncoder.SelectFrames(images, step.From, step.To);
+ foreach (var frame in frames)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ ImageEncoder.ApplyOptions(frame, step.Preset.Image, step.To);
+ }
+ progress?.Report(0.7);
+
+ var written = ImageEncoder.Write(frames, step.To, step.Output);
+ progress?.Report(1);
+ return written;
+ }, cancellationToken);
+}
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
new file mode 100644
index 00000000..e7f686a4
--- /dev/null
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -0,0 +1,197 @@
+// 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.
+//
+// Gotchas handled here:
+// * Each concurrent soffice process needs its own user profile (-env:UserInstallation), otherwise
+// conversions silently fail with exit code 1.
+// * soffice writes <outdir>/<input name>.<ext>; we convert into a private folder and move the result.
+// * Always use a timeout: a document with a modal dialog would otherwise hang forever.
+// * HWP/HWPX import needs the H2Orestart extension (GPL-3.0), pre-installed into the bundled copy.
+
+using System.Collections.Concurrent;
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+using Microsoft.Win32;
+
+namespace Filee.Engines.Office;
+
+/// <summary>DOCX / DOC / ODT / RTF / XLSX / PPTX / HWP(X) conversions through LibreOffice.</summary>
+public sealed class LibreOfficeConverter : IConverter
+{
+ private const int Workers = 2;
+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(3);
+
+ private static readonly string[] Writer = ["docx", "doc", "odt", "rtf"];
+ private static readonly string[] Calc = ["xlsx", "xls", "ods", "csv"];
+ private static readonly string[] Impress = ["pptx", "ppt", "odp"];
+
+ private readonly EngineEnvironment _env;
+ private readonly ConcurrentBag<int> _freeProfiles = new(Enumerable.Range(0, Workers));
+ private string? _soffice;
+ private bool _hasHwpFilter;
+
+ public LibreOfficeConverter(EngineEnvironment env)
+ {
+ _env = env;
+ Locate();
+ Edges = BuildEdges(_hasHwpFilter);
+ }
+
+ public string Id => "libreoffice";
+ public string DisplayName => "LibreOffice";
+ public int MaxParallelism => Workers;
+ public IReadOnlyList<ConversionEdge> Edges { get; private set; }
+
+ public EngineStatus GetStatus()
+ {
+ Locate();
+ Edges = BuildEdges(_hasHwpFilter);
+ return _soffice is null
+ ? EngineStatus.Unavailable("engine.reason.not_installed")
+ : EngineStatus.Available(_soffice + (_hasHwpFilter ? " (+H2Orestart)" : ""));
+ }
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var soffice = _soffice ?? throw new InvalidOperationException("LibreOffice was not found.");
+ if (!_freeProfiles.TryTake(out var slot))
+ slot = Random.Shared.Next(Workers); // should not happen thanks to MaxParallelism
+
+ try
+ {
+ var profileDir = Path.Combine(_env.DataDirectory, "libreoffice-profiles", $"worker-{slot}");
+ Directory.CreateDirectory(profileDir);
+ var outDir = Path.Combine(step.WorkDirectory, "lo-" + Guid.NewGuid().ToString("N")[..8]);
+ Directory.CreateDirectory(outDir);
+
+ progress?.Report(0.1);
+ var args = new List<string>
+ {
+ "--headless", "--norestore", "--nologo", "--nodefault", "--nolockcheck", "--nofirststartwizard",
+ "-env:UserInstallation=" + new Uri(profileDir).AbsoluteUri,
+ };
+ // The HWP import filter (H2Orestart) is written in Java: point LibreOffice at the bundled JRE.
+ if (EngineEnvironment.FindBundled("jre") is { } jre)
+ args.Add("-env:UNO_JAVA_JFW_JREHOME=" + new Uri(jre + Path.DirectorySeparatorChar).AbsoluteUri);
+ args.AddRange(["--convert-to", FilterFor(step.From, step.To, step.Preset.Document.PdfA), "--outdir", outDir, step.InputPath]);
+
+ var result = await ProcessRunner.RunAsync(soffice, args, Timeout, cancellationToken);
+ var produced = Directory.EnumerateFiles(outDir).FirstOrDefault(f => new FileInfo(f).Length > 0);
+ if (produced is null)
+ throw new InvalidOperationException(
+ $"LibreOffice produced no output (exit {result.ExitCode}). {result.StandardError.Trim()}");
+
+ var target = step.Output.Allocate(step.To);
+ if (target is null)
+ return [];
+ File.Move(produced, target, overwrite: true);
+ progress?.Report(1);
+ return [target];
+ }
+ finally
+ {
+ _freeProfiles.Add(slot);
+ }
+ }
+
+ /// <summary>Maps a target format to a LibreOffice <c>--convert-to</c> filter specification.</summary>
+ internal static string FilterFor(string from, string to, bool pdfA)
+ {
+ var family = Calc.Contains(from) ? "calc" : Impress.Contains(from) ? "impress" : "writer";
+ return to switch
+ {
+ // PDF/A-2b via the JSON filter options syntax (LibreOffice 7.4+).
+ "pdf" when pdfA => $"pdf:{family}_pdf_Export:{{\"SelectPdfVersion\":{{\"type\":\"long\",\"value\":\"2\"}}}}",
+ "pdf" => $"pdf:{family}_pdf_Export",
+ "docx" => "docx:MS Word 2007 XML",
+ "doc" => "doc:MS Word 97",
+ "odt" => "odt",
+ "rtf" => "rtf:Rich Text Format",
+ "txt" => "txt:Text (encoded):UTF8",
+ "html" when family == "calc" => "html:HTML (StarCalc)",
+ "html" => "html:HTML (StarWriter)",
+ "xlsx" => "xlsx:Calc MS Excel 2007 XML",
+ "xls" => "xls:MS Excel 97",
+ "ods" => "ods",
+ "csv" => "csv:Text - txt - csv (StarCalc):44,34,76",
+ "pptx" => "pptx:Impress MS PowerPoint 2007 XML",
+ "ppt" => "ppt:MS PowerPoint 97",
+ "odp" => "odp",
+ _ => to,
+ };
+ }
+
+ private static List<ConversionEdge> BuildEdges(bool hwp)
+ {
+ var edges = new List<ConversionEdge>();
+ void Add(IEnumerable<string> sources, IEnumerable<string> targets, int cost)
+ {
+ foreach (var s in sources)
+ foreach (var t in targets)
+ if (s != t)
+ 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);
+ if (hwp)
+ Add(["hwp", "hwpx"], ["pdf", "docx", "odt", "rtf"], 18);
+ return edges;
+ }
+
+ /// <summary>Finds soffice: user path → bundled copy → system installation.</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"));
+
+ _hasHwpFilter = _soffice is not null && HasH2Orestart(_soffice);
+ }
+
+ /// <summary>Detects the H2Orestart extension in the installation (shared) extension folders.</summary>
+ private static bool HasH2Orestart(string soffice)
+ {
+ try
+ {
+ var root = Directory.GetParent(Path.GetDirectoryName(soffice)!)!.FullName;
+ foreach (var sub in new[] { "share/uno_packages", "share/extensions", "Resources/uno_packages", "Resources/extensions" })
+ {
+ var dir = Path.Combine(root, sub);
+ if (Directory.Exists(dir) &&
+ Directory.EnumerateFileSystemEntries(dir, "*H2Orestart*", SearchOption.AllDirectories).Any())
+ return true;
+ }
+ }
+ catch (IOException) { }
+ 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/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.cs
new file mode 100644
index 00000000..6d83bd41
--- /dev/null
+++ b/src/Filee.Engines/Office/PandocConverter.cs
@@ -0,0 +1,87 @@
+// 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.
+
+using Filee.Core.Conversion;
+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
+{
+ private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
+
+ private static readonly Dictionary<string, string> Readers = new()
+ {
+ ["md"] = "markdown",
+ ["html"] = "html",
+ ["docx"] = "docx",
+ ["odt"] = "odt",
+ ["rtf"] = "rtf",
+ };
+
+ private static readonly Dictionary<string, string> Writers = new()
+ {
+ ["md"] = "gfm",
+ ["html"] = "html",
+ ["docx"] = "docx",
+ ["odt"] = "odt",
+ ["rtf"] = "rtf",
+ ["txt"] = "plain",
+ };
+
+ private string? _pandoc;
+
+ public string Id => "pandoc";
+ public string DisplayName => "Pandoc";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ // 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.
+ .. 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);
+ 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 output = step.Output.Allocate(step.To);
+ if (output is null)
+ return [];
+
+ progress?.Report(0.1);
+ List<string> args = [step.InputPath, "-f", Readers[step.From], "-t", Writers[step.To], "-o", output];
+ if (step.To == "html")
+ args.Add("--standalone");
+ if (step.To is "md" or "html")
+ args.Add("--extract-media=" + Path.Combine(Path.GetDirectoryName(output)!, Path.GetFileNameWithoutExtension(output) + "_files"));
+
+ var result = await ProcessRunner.RunAsync(pandoc, args, Timeout, cancellationToken,
+ workingDirectory: Path.GetDirectoryName(Path.GetFullPath(step.InputPath)));
+ if (!File.Exists(output))
+ throw new InvalidOperationException($"Pandoc failed (exit {result.ExitCode}). {result.StandardError.Trim()}");
+ progress?.Report(1);
+ 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"));
+ }
+}
diff --git a/src/Filee.Engines/Office/WordComConverter.cs b/src/Filee.Engines/Office/WordComConverter.cs
new file mode 100644
index 00000000..128265bf
--- /dev/null
+++ b/src/Filee.Engines/Office/WordComConverter.cs
@@ -0,0 +1,114 @@
+// 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
+ 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/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
new file mode 100644
index 00000000..ad4e62af
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
@@ -0,0 +1,165 @@
+// Builds PDFs from images, splits / extracts PDF pages, and merges PDFs (PDFsharp, MIT).
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Magick;
+using ImageMagick;
+using PdfSharp.Drawing;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>Image → PDF, PDF → PDF (split / page range) and PDF merging.</summary>
+public sealed class PdfSharpConverter : IConverter, IPdfMerger
+{
+ private const double PointsPerInch = 72.0;
+ private const double MillimetresPerInch = 25.4;
+
+ public string Id => "pdfsharp";
+ public string DisplayName => "PDFsharp";
+ public int MaxParallelism => 0;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ [
+ .. ImageEncoder.Readable.Select(source => new ConversionEdge(source, "pdf")),
+ new("pdf", "pdf"),
+ ];
+
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run(() => step.From == "pdf"
+ ? SplitOrExtract(step, progress, cancellationToken)
+ : ImageToPdf(step, progress, cancellationToken), cancellationToken);
+
+ public Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken) =>
+ Task.Run(() =>
+ {
+ using var output = new PdfDocument();
+ foreach (var input in inputPaths)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ using var source = PdfReader.Open(input, PdfDocumentOpenMode.Import);
+ foreach (var page in source.Pages)
+ output.AddPage(page);
+ }
+ output.Save(outputPath);
+ }, cancellationToken);
+
+ /// <summary>Places every frame of an image (TIFF pages, ...) on its own PDF page.</summary>
+ private static IReadOnlyList<string> ImageToPdf(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
+ {
+ var options = step.Preset.Image;
+ var pdfOptions = step.Preset.Pdf;
+ using var images = new MagickImageCollection(step.InputPath);
+ var frames = ImageEncoder.SelectFrames(images, step.From, "pdf");
+
+ using var document = new PdfDocument();
+ for (var i = 0; i < frames.Count; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ var frame = frames[i];
+ var dpi = frame.Density.Units == DensityUnit.PixelsPerInch && frame.Density.X > 0 ? frame.Density.X
+ : frame.Density.Units == DensityUnit.PixelsPerCentimeter && frame.Density.X > 0 ? frame.Density.X * 2.54
+ : 96.0;
+
+ // "pdf" as target: resize / grayscale / metadata apply, no format-specific encoding settings.
+ ImageEncoder.ApplyOptions(frame, options, "pdf");
+ using var stream = EncodeForPdf(frame, step.From, options);
+ using var ximage = XImage.FromStream(stream);
+
+ var imageWidthPt = frame.Width / dpi * PointsPerInch;
+ var imageHeightPt = frame.Height / dpi * PointsPerInch;
+ var page = document.AddPage();
+ var (pageWidth, pageHeight) = PageSize(pdfOptions.PageSize, imageWidthPt > imageHeightPt);
+ if (pdfOptions.PageSize == PdfPageSize.FitImage)
+ (pageWidth, pageHeight) = (imageWidthPt, imageHeightPt);
+ page.Width = XUnit.FromPoint(pageWidth);
+ page.Height = XUnit.FromPoint(pageHeight);
+
+ // Fit the image inside the page margins, keeping its aspect ratio, centred.
+ var margin = pdfOptions.PageSize == PdfPageSize.FitImage ? 0 : pdfOptions.MarginMm / MillimetresPerInch * PointsPerInch;
+ var boxWidth = pageWidth - 2 * margin;
+ var boxHeight = pageHeight - 2 * margin;
+ var scale = Math.Min(boxWidth / imageWidthPt, boxHeight / imageHeightPt);
+ var drawWidth = imageWidthPt * scale;
+ var drawHeight = imageHeightPt * scale;
+
+ using (var gfx = XGraphics.FromPdfPage(page))
+ gfx.DrawImage(ximage, margin + (boxWidth - drawWidth) / 2, margin + (boxHeight - drawHeight) / 2, drawWidth, drawHeight);
+
+ progress?.Report((i + 1.0) / frames.Count);
+ }
+
+ var path = step.Output.Allocate("pdf");
+ if (path is null)
+ return [];
+ document.Save(path);
+ return [path];
+ }
+
+ /// <summary>PDF → PDF: split into single pages, or extract the configured page range.</summary>
+ private static IReadOnlyList<string> SplitOrExtract(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
+ {
+ using var source = PdfReader.Open(step.InputPath, PdfDocumentOpenMode.Import);
+ var pages = PageRange.Parse(step.Preset.Pdf.PageRange, source.PageCount);
+ var written = new List<string>();
+
+ if (step.Preset.Pdf.SplitPages)
+ {
+ for (var i = 0; i < pages.Count; i++)
+ {
+ ct.ThrowIfCancellationRequested();
+ using var single = new PdfDocument();
+ single.AddPage(source.Pages[pages[i]]);
+ var path = step.Output.Allocate("pdf", $"_p{pages[i] + 1}");
+ if (path is null)
+ continue;
+ single.Save(path);
+ written.Add(path);
+ progress?.Report((i + 1.0) / pages.Count);
+ }
+ return written;
+ }
+
+ using var extract = new PdfDocument();
+ foreach (var index in pages)
+ extract.AddPage(source.Pages[index]);
+ var output = step.Output.Allocate("pdf");
+ if (output is null)
+ return [];
+ extract.Save(output);
+ return [output];
+ }
+
+ /// <summary>
+ /// Encodes a frame for embedding. JPEG sources stay JPEG (no generational loss beyond one re-encode at high quality);
+ /// everything else is embedded losslessly as PNG.
+ /// </summary>
+ private static MemoryStream EncodeForPdf(IMagickImage<byte> frame, string sourceFormat, ImageOptions options)
+ {
+ var stream = new MemoryStream();
+ if (sourceFormat == "jpg" && !frame.HasAlpha)
+ {
+ frame.Quality = (uint)Math.Clamp(Math.Max(options.Quality, 85), 1, 100);
+ frame.Write(stream, MagickFormat.Jpeg);
+ }
+ else
+ {
+ frame.Write(stream, MagickFormat.Png);
+ }
+ stream.Position = 0;
+ return stream;
+ }
+
+ private static (double Width, double Height) PageSize(PdfPageSize size, bool landscape)
+ {
+ var (w, h) = size switch
+ {
+ PdfPageSize.Letter => (612.0, 792.0),
+ _ => (595.28, 841.89), // A4
+ };
+ return landscape ? (h, w) : (w, h);
+ }
+}
diff --git a/src/Filee.Engines/Pdf/PdfiumConverter.cs b/src/Filee.Engines/Pdf/PdfiumConverter.cs
new file mode 100644
index 00000000..02c1b0f9
--- /dev/null
+++ b/src/Filee.Engines/Pdf/PdfiumConverter.cs
@@ -0,0 +1,94 @@
+// Renders PDF pages to raster images with PDFium (via PDFtoImage, MIT / PDFium BSD-3).
+
+using Filee.Core.Conversion;
+using Filee.Engines.Magick;
+using ImageMagick;
+using PDFtoImage;
+using SkiaSharp;
+
+// PDFtoImage marks its API for the platforms PDFium ships for (Windows, macOS, Linux, mobile).
+// Filee only targets desktop platforms that are all covered.
+#pragma warning disable CA1416
+
+namespace Filee.Engines.Pdf;
+
+/// <summary>PDF → PNG / JPG / WEBP / TIFF / BMP / GIF / AVIF / ICO.</summary>
+public sealed class PdfiumConverter : IConverter
+{
+ private static readonly HashSet<string> MultiPageTargets = ["tiff", "gif"];
+
+ public string Id => "pdfium";
+ public string DisplayName => "PDFium";
+
+ /// <summary>PDFium is not thread-safe.</summary>
+ public int MaxParallelism => 1;
+
+ public IReadOnlyList<ConversionEdge> Edges { get; } =
+ ImageEncoder.Writable.Select(target => new ConversionEdge("pdf", target)).ToList();
+
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
+ Task.Run<IReadOnlyList<string>>(() =>
+ {
+ var pdf = File.ReadAllBytes(step.InputPath);
+ var pageCount = Conversion.GetPageCount(pdf, null);
+ var pages = PageRange.Parse(step.Preset.Pdf.PageRange, pageCount);
+ var dpi = Math.Clamp(step.Preset.Pdf.RenderDpi, 36, 1200);
+ var options = new RenderOptions(Dpi: dpi, WithAnnotations: true, WithFormFill: true, BackgroundColor: SKColors.White);
+ var written = new List<string>();
+ var collected = new List<IMagickImage<byte>>();
+
+ try
+ {
+ var index = 0;
+ foreach (var bitmap in Conversion.ToImages(pdf, pages, null, options))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var pageNumber = pages[index] + 1;
+ index++;
+
+ var frame = ToMagick(bitmap, dpi);
+ ImageEncoder.ApplyOptions(frame, step.Preset.Image, step.To);
+
+ if (MultiPageTargets.Contains(step.To))
+ {
+ collected.Add(frame); // one multi-page file, written after the loop
+ }
+ else
+ {
+ using (frame)
+ {
+ var path = step.Output.Allocate(step.To, pages.Count > 1 ? $"_p{pageNumber}" : null);
+ if (path is not null)
+ {
+ frame.Write(path, ImageEncoder.ToMagickFormat(step.To));
+ written.Add(path);
+ }
+ }
+ }
+ progress?.Report((double)index / pages.Count);
+ }
+
+ if (collected.Count > 0)
+ written.AddRange(ImageEncoder.Write(collected, step.To, step.Output));
+ }
+ finally
+ {
+ foreach (var frame in collected)
+ frame.Dispose();
+ }
+ return written;
+ }, cancellationToken);
+
+ private static MagickImage ToMagick(SKBitmap bitmap, int dpi)
+ {
+ using (bitmap)
+ using (var data = bitmap.Encode(SKEncodedImageFormat.Png, 100))
+ {
+ var image = new MagickImage(data.ToArray());
+ image.Density = new Density(dpi, dpi, DensityUnit.PixelsPerInch);
+ return image;
+ }
+ }
+}
diff --git a/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj b/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj
new file mode 100644
index 00000000..b57db909
--- /dev/null
+++ b/src/Filee.Platform.Windows/Filee.Platform.Windows.csproj
@@ -0,0 +1,16 @@
+<!--
+ Filee.Platform.Windows: Windows implementation of IPlatformServices
+ (Explorer detection & selection, context menu, auto-start, system metrics).
+ Targets plain net10.0 so the cross-platform app can reference it; every entry point is guarded
+ with [SupportedOSPlatform("windows")] and only used when OperatingSystem.IsWindows() is true.
+-->
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <RootNamespace>Filee.Platform.Windows</RootNamespace>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/src/Filee.Platform.Windows/NativeMethods.cs b/src/Filee.Platform.Windows/NativeMethods.cs
new file mode 100644
index 00000000..8fcef88d
--- /dev/null
+++ b/src/Filee.Platform.Windows/NativeMethods.cs
@@ -0,0 +1,49 @@
+// Win32 P/Invoke declarations used by the Windows platform layer. Keep this list minimal.
+
+using System.Runtime.InteropServices;
+
+namespace Filee.Platform.Windows;
+
+internal static partial class NativeMethods
+{
+ public const int SM_CXDRAG = 68;
+ public const uint GA_ROOT = 2;
+ public const uint SPI_GETCLIENTAREAANIMATION = 0x1042;
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct POINT
+ {
+ public int X;
+ public int Y;
+ }
+
+ [LibraryImport("user32.dll")]
+ public static partial nint WindowFromPoint(POINT point);
+
+ [LibraryImport("user32.dll")]
+ public static partial nint GetAncestor(nint hwnd, uint flags);
+
+ [LibraryImport("user32.dll")]
+ public static partial nint GetForegroundWindow();
+
+ [LibraryImport("user32.dll")]
+ public static partial uint GetWindowThreadProcessId(nint hwnd, out uint processId);
+
+ [LibraryImport("user32.dll", EntryPoint = "GetClassNameW", StringMarshalling = StringMarshalling.Utf16)]
+ public static partial int GetClassName(nint hwnd, [Out] char[] className, int maxCount);
+
+ [LibraryImport("user32.dll")]
+ public static partial int GetSystemMetrics(int index);
+
+ [LibraryImport("user32.dll", EntryPoint = "SystemParametersInfoW")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static partial bool SystemParametersInfo(uint action, uint param, [MarshalAs(UnmanagedType.Bool)] out bool value, uint winIni);
+
+ /// <summary>Returns the Win32 class name of a window ("CabinetWClass" for Explorer, ...).</summary>
+ public static string ClassNameOf(nint hwnd)
+ {
+ var buffer = new char[256];
+ var length = GetClassName(hwnd, buffer, buffer.Length);
+ return length > 0 ? new string(buffer, 0, length) : "";
+ }
+}
diff --git a/src/Filee.Platform.Windows/WindowsPlatformServices.cs b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
new file mode 100644
index 00000000..81db09aa
--- /dev/null
+++ b/src/Filee.Platform.Windows/WindowsPlatformServices.cs
@@ -0,0 +1,214 @@
+// Windows implementation of IPlatformServices.
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using Filee.Core.Platform;
+using Microsoft.Win32;
+
+namespace Filee.Platform.Windows;
+
+/// <summary>Explorer integration, auto-start and system settings on Windows.</summary>
+[SupportedOSPlatform("windows")]
+public sealed class WindowsPlatformServices : IPlatformServices
+{
+ private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
+ private const string ContextMenuKey = @"Software\Classes\*\shell\Filee";
+ private const string AppName = "Filee";
+
+ /// <summary>Window classes that belong to Explorer windows and the desktop.</summary>
+ private static readonly HashSet<string> FileManagerClasses = new(StringComparer.Ordinal)
+ {
+ "CabinetWClass", // File Explorer window
+ "ExploreWClass", // legacy Explorer
+ "Progman", // desktop
+ "WorkerW", // desktop (when wallpaper slideshow / Win+Tab created a WorkerW)
+ };
+
+ public bool IsFileManagerAt(int x, int y)
+ {
+ var root = RootWindowAt(x, y);
+ if (root == 0)
+ return false;
+ return FileManagerClasses.Contains(NativeMethods.ClassNameOf(root))
+ || string.Equals(ProcessNameOf(root), "explorer", StringComparison.OrdinalIgnoreCase);
+ }
+
+ public string? ProcessNameAt(int x, int y)
+ {
+ var root = RootWindowAt(x, y);
+ return root == 0 ? null : ProcessNameOf(root);
+ }
+
+ /// <summary>
+ /// Reads the selection of the foreground Explorer window through the Shell automation object.
+ /// Must be called on an STA thread (the Avalonia UI thread is STA).
+ /// </summary>
+ public IReadOnlyList<string> GetFileManagerSelection()
+ {
+ var foreground = NativeMethods.GetForegroundWindow();
+ if (foreground == 0)
+ return [];
+
+ var type = Type.GetTypeFromProgID("Shell.Application");
+ if (type is null)
+ return [];
+
+ dynamic? shell = null;
+ try
+ {
+ shell = Activator.CreateInstance(type)!;
+ dynamic windows = shell.Windows();
+ int count = windows.Count;
+
+ // With Explorer tabs (Windows 11) several entries share one HWND. The active tab is the one
+ // that has a selection in practice, so take the first matching window with selected items.
+ for (var i = 0; i < count; i++)
+ {
+ dynamic? window = windows.Item(i);
+ if (window is null)
+ continue;
+ try
+ {
+ if ((nint)(long)window.HWND != foreground)
+ continue;
+ dynamic items = window.Document.SelectedItems();
+ var paths = new List<string>();
+ foreach (dynamic item in items)
+ {
+ string path = item.Path;
+ if (File.Exists(path))
+ paths.Add(path);
+ }
+ if (paths.Count > 0)
+ return paths;
+ }
+ catch (COMException) { }
+ catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { } // e.g. Internet Explorer windows
+ }
+ }
+ catch (COMException)
+ {
+ }
+ finally
+ {
+ if (shell is not null)
+ Marshal.FinalReleaseComObject(shell);
+ }
+ return [];
+ }
+
+ public int SystemDragThreshold => Math.Max(2, NativeMethods.GetSystemMetrics(NativeMethods.SM_CXDRAG));
+
+ public bool PrefersReducedMotion =>
+ NativeMethods.SystemParametersInfo(NativeMethods.SPI_GETCLIENTAREAANIMATION, 0, out var enabled, 0) && !enabled;
+
+ public void SetStartWithSystem(bool enabled, string executablePath)
+ {
+ using var key = Registry.CurrentUser.CreateSubKey(RunKey);
+ if (enabled)
+ key.SetValue(AppName, $"\"{executablePath}\" --background");
+ else
+ key.DeleteValue(AppName, throwOnMissingValue: false);
+ }
+
+ /// <summary>
+ /// Registers a per-user "Convert with Filee" verb for all files (no admin rights needed) and a Send To shortcut.
+ /// On Windows 11 the verb appears under "Show more options"; a top-level entry needs a packaged
+ /// IExplorerCommand, which is planned for a later version.
+ /// </summary>
+ public void SetContextMenu(bool enabled, string executablePath, string label)
+ {
+ if (!enabled)
+ {
+ Registry.CurrentUser.DeleteSubKeyTree(ContextMenuKey, throwOnMissingSubKey: false);
+ TryDelete(SendToShortcutPath);
+ return;
+ }
+
+ using (var verb = Registry.CurrentUser.CreateSubKey(ContextMenuKey))
+ {
+ verb.SetValue("MUIVerb", label);
+ verb.SetValue("Icon", $"\"{executablePath}\",0");
+ // "Player": Explorer invokes the verb once per selected file; the running instance
+ // collects the calls (see SingleInstance / --convert handling in the app).
+ verb.SetValue("MultiSelectModel", "Player");
+ using var command = verb.CreateSubKey("command");
+ command.SetValue(null, $"\"{executablePath}\" --convert \"%1\"");
+ }
+
+ CreateShortcut(SendToShortcutPath, executablePath, "--convert", label);
+ }
+
+ public void RevealInFileManager(string path)
+ {
+ var args = File.Exists(path) ? $"/select,\"{path}\"" : $"\"{path}\"";
+ Process.Start(new ProcessStartInfo("explorer.exe", args) { UseShellExecute = true });
+ }
+
+ private static string SendToShortcutPath =>
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SendTo), "Filee.lnk");
+
+ private static nint RootWindowAt(int x, int y)
+ {
+ var hwnd = NativeMethods.WindowFromPoint(new NativeMethods.POINT { X = x, Y = y });
+ return hwnd == 0 ? 0 : NativeMethods.GetAncestor(hwnd, NativeMethods.GA_ROOT);
+ }
+
+ private static string? ProcessNameOf(nint hwnd)
+ {
+ NativeMethods.GetWindowThreadProcessId(hwnd, out var pid);
+ if (pid == 0)
+ return null;
+ try
+ {
+ using var process = Process.GetProcessById((int)pid);
+ return process.ProcessName;
+ }
+ catch (ArgumentException)
+ {
+ return null;
+ }
+ catch (InvalidOperationException)
+ {
+ return null;
+ }
+ }
+
+ /// <summary>Creates a .lnk file through the WScript.Shell automation object.</summary>
+ private static void CreateShortcut(string shortcutPath, string target, string arguments, string description)
+ {
+ var type = Type.GetTypeFromProgID("WScript.Shell");
+ if (type is null)
+ return;
+ dynamic? shell = null;
+ try
+ {
+ shell = Activator.CreateInstance(type)!;
+ dynamic link = shell.CreateShortcut(shortcutPath);
+ link.TargetPath = target;
+ link.Arguments = arguments;
+ link.Description = description;
+ link.IconLocation = target + ",0";
+ link.Save();
+ }
+ catch (COMException)
+ {
+ }
+ finally
+ {
+ if (shell is not null)
+ Marshal.FinalReleaseComObject(shell);
+ }
+ }
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ File.Delete(path);
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+}
diff --git a/tests/Filee.App.Tests/DonutGeometryTests.cs b/tests/Filee.App.Tests/DonutGeometryTests.cs
new file mode 100644
index 00000000..b503192b
--- /dev/null
+++ b/tests/Filee.App.Tests/DonutGeometryTests.cs
@@ -0,0 +1,48 @@
+using Avalonia;
+using Filee.App.Controls;
+
+namespace Filee.App.Tests;
+
+public class DonutGeometryTests
+{
+ private static readonly Point C = new(200, 200);
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(5)]
+ [InlineData(8)]
+ [InlineData(12)]
+ public void Slices_cover_the_full_circle(int count)
+ {
+ Assert.Equal(2 * Math.PI, DonutGeometry.Span(count) * count, 6);
+
+ // Every direction maps to exactly one slice, and each slice's centre maps back to itself.
+ for (var i = 0; i < count; i++)
+ Assert.Equal(i, DonutGeometry.IndexAt(DonutGeometry.MidAngle(i, count), count));
+ for (var deg = 0; deg < 360; deg++)
+ Assert.InRange(DonutGeometry.IndexAt(deg * Math.PI / 180, count), 0, count - 1);
+ }
+
+ [Fact]
+ public void First_slice_is_centred_at_twelve_o_clock()
+ {
+ // Straight up belongs to slice 0; slightly left of up still belongs to slice 0 (it straddles the top).
+ Assert.Equal(0, DonutGeometry.HitTest(C, new Point(200, 80), 60, 150, 6).Index);
+ Assert.Equal(0, DonutGeometry.HitTest(C, new Point(190, 80), 60, 150, 6).Index);
+ // Right side (3 o'clock) with 4 slices is slice 1, bottom is 2, left is 3.
+ Assert.Equal(1, DonutGeometry.HitTest(C, new Point(320, 200), 60, 150, 4).Index);
+ Assert.Equal(2, DonutGeometry.HitTest(C, new Point(200, 320), 60, 150, 4).Index);
+ Assert.Equal(3, DonutGeometry.HitTest(C, new Point(80, 200), 60, 150, 4).Index);
+ }
+
+ [Fact]
+ public void Hole_ring_and_outside_are_classified()
+ {
+ Assert.Equal(DonutHitKind.Center, DonutGeometry.HitTest(C, new Point(210, 205), 60, 150, 6).Kind);
+ Assert.Equal(DonutHitKind.Segment, DonutGeometry.HitTest(C, new Point(200, 100), 60, 150, 6).Kind);
+ Assert.Equal(DonutHitKind.Outside, DonutGeometry.HitTest(C, new Point(200, 10), 60, 150, 6).Kind);
+ Assert.Equal(DonutHitKind.Segment, DonutGeometry.HitTest(C, new Point(200, 45), 60, 150, 6, slack: 8).Kind);
+ Assert.Equal(DonutHitKind.EmptyRing, DonutGeometry.HitTest(C, new Point(200, 100), 60, 150, 0).Kind);
+ }
+}
diff --git a/tests/Filee.App.Tests/DonutLabelPlacementTests.cs b/tests/Filee.App.Tests/DonutLabelPlacementTests.cs
new file mode 100644
index 00000000..1ebbce2a
--- /dev/null
+++ b/tests/Filee.App.Tests/DonutLabelPlacementTests.cs
@@ -0,0 +1,96 @@
+// Pixel-level check that slice labels sit on their slice's centre line.
+// Regression: labels were centred on the measured text width while being laid out centred in a wider box,
+// so short labels drifted right (reported with a screenshot of the donut editor).
+
+using System.Runtime.InteropServices;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media;
+using Avalonia.Threading;
+using Filee.App.Controls;
+
+namespace Filee.App.Tests;
+
+public class DonutLabelPlacementTests
+{
+ private const double OuterRadius = 150;
+ private const double HoleRatio = 0.42;
+
+ [AvaloniaFact]
+ public void Labels_are_centred_on_their_slices()
+ {
+ TestServices.EnsureInitialized("en");
+ var donut = new DonutMenu
+ {
+ OuterRadius = OuterRadius,
+ HoleRatio = HoleRatio,
+ Items =
+ [
+ new DonutItem { Id = "a", Label = "PNG" },
+ new DonutItem { Id = "b", Label = "JPG" },
+ new DonutItem { Id = "c", Label = "PDF" },
+ new DonutItem { Id = "d", Label = "ICO" },
+ ],
+ SliceBrush = Brushes.White,
+ CenterBrush = Brushes.White,
+ Foreground = Brushes.Black,
+ };
+ var window = new Window { Content = donut, SizeToContent = SizeToContent.WidthAndHeight, Background = Brushes.White };
+ window.Show();
+ for (var i = 0; i < 10; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ }
+
+ var (pixels, width, height) = Read(window.CaptureRenderedFrame()!);
+ var origin = donut.TranslatePoint(new Point(0, 0), window)!.Value;
+ var center = new Point(origin.X + donut.Bounds.Width / 2, origin.Y + donut.Bounds.Height / 2);
+ var labelRadius = (OuterRadius + OuterRadius * HoleRatio) / 2;
+
+ for (var i = 0; i < 4; i++)
+ {
+ var anchor = DonutGeometry.PointAt(center, labelRadius, DonutGeometry.MidAngle(i, 4));
+ var (cx, cy) = DarkCentroid(pixels, width, height, anchor, 34);
+ Assert.True(Math.Abs(cx - anchor.X) < 3, $"slice {i}: text centre x {cx:0.0} vs slice centre {anchor.X:0.0}");
+ Assert.True(Math.Abs(cy - anchor.Y) < 5, $"slice {i}: text centre y {cy:0.0} vs slice centre {anchor.Y:0.0}");
+ }
+ window.Close();
+ }
+
+ /// <summary>Average position of dark (text) pixels in a square around <paramref name="at"/>.</summary>
+ private static (double X, double Y) DarkCentroid(byte[] bgra, int width, int height, Point at, int half)
+ {
+ double sx = 0, sy = 0;
+ var n = 0;
+ for (var y = Math.Max(0, (int)at.Y - half); y < Math.Min(height, (int)at.Y + half); y++)
+ {
+ for (var x = Math.Max(0, (int)at.X - half); x < Math.Min(width, (int)at.X + half); x++)
+ {
+ var o = (y * width + x) * 4;
+ var luminance = 0.0722 * bgra[o] + 0.7152 * bgra[o + 1] + 0.2126 * bgra[o + 2];
+ if (luminance < 110)
+ {
+ sx += x;
+ sy += y;
+ n++;
+ }
+ }
+ }
+ Assert.True(n > 20, $"no label found near {at}");
+ return (sx / n, sy / n);
+ }
+
+ private static (byte[] Pixels, int Width, int Height) Read(Avalonia.Media.Imaging.WriteableBitmap bitmap)
+ {
+ using var buffer = bitmap.Lock();
+ var width = buffer.Size.Width;
+ var height = buffer.Size.Height;
+ var pixels = new byte[width * height * 4];
+ for (var row = 0; row < height; row++)
+ Marshal.Copy(buffer.Address + row * buffer.RowBytes, pixels, row * width * 4, width * 4);
+ return (pixels, width, height);
+ }
+}
diff --git a/tests/Filee.App.Tests/DonutProgressTests.cs b/tests/Filee.App.Tests/DonutProgressTests.cs
new file mode 100644
index 00000000..39af024a
--- /dev/null
+++ b/tests/Filee.App.Tests/DonutProgressTests.cs
@@ -0,0 +1,156 @@
+// The donut's progress ring: timing rules and rendered states (running / ✓ / !).
+
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Media.Imaging;
+using Avalonia.Threading;
+using Filee.App.Controls;
+using Filee.App.Services;
+
+namespace Filee.App.Tests;
+
+public class DonutProgressTests
+{
+ private const double Frame = 1 / 60.0;
+
+ private static (Window Window, DonutMenu Donut) Create()
+ {
+ TestServices.EnsureInitialized("ko");
+ var donut = new DonutMenu
+ {
+ Items = new[] { "PNG", "JPG", "WEBP", "PDF", "TIFF", "BMP" }.Select(l => new DonutItem { Id = l, Label = l }).ToList(),
+ };
+ var window = new Window { Content = donut, SizeToContent = SizeToContent.WidthAndHeight };
+ window.Show();
+ Dispatcher.UIThread.RunJobs();
+ return (window, donut);
+ }
+
+ /// <summary>Steps the animation clock until <paramref name="until"/> is true or the time budget runs out.</summary>
+ private static double Run(DonutMenu donut, Func<bool> until, double maxSeconds = 10)
+ {
+ var elapsed = 0.0;
+ while (!until() && elapsed < maxSeconds)
+ {
+ donut.Advance(Frame);
+ elapsed += Frame;
+ }
+ return elapsed;
+ }
+
+ [AvaloniaFact]
+ public void Fast_success_still_shows_the_ring_then_a_check_then_finishes()
+ {
+ var (window, donut) = Create();
+ var done = false;
+
+ donut.BeginProgress();
+ donut.CompleteProgress(DonutProgressOutcome.Succeeded, () => done = true); // finished instantly
+
+ var untilCheck = Run(donut, () => donut.ShownOutcome is not null);
+ Assert.Equal(DonutProgressOutcome.Succeeded, donut.ShownOutcome);
+ Assert.True(untilCheck >= 0.6, $"check appeared after {untilCheck:0.00}s; the ring must be visible for at least 0.6s");
+ Assert.False(done);
+
+ var untilDone = Run(donut, () => done);
+ Assert.True(done);
+ Assert.InRange(untilDone, 0.9, 1.6); // hold + fade
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Hand_off_to_the_toast_is_quick()
+ {
+ var (window, donut) = Create();
+ var done = false;
+ donut.BeginProgress();
+ donut.SetProgress(0.3);
+ Run(donut, () => false, 1.0);
+
+ donut.HandOffProgress(() => done = true);
+ var elapsed = Run(donut, () => done);
+
+ Assert.True(done);
+ Assert.True(elapsed < 0.4);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Opening_the_donut_again_leaves_progress_mode()
+ {
+ var (window, donut) = Create();
+ donut.BeginProgress();
+ Assert.True(donut.IsInProgressMode);
+
+ donut.PlayOpenAnimation();
+
+ Assert.False(donut.IsInProgressMode);
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Reduced_motion_skips_animation_but_keeps_the_check_visible_for_a_moment()
+ {
+ var (window, donut) = Create(); // applies the theme, which sets Motion from settings: switch it off afterwards
+ Motion.Set(false);
+ try
+ {
+ var done = false;
+ donut.BeginProgress();
+ donut.CompleteProgress(DonutProgressOutcome.Succeeded, () => done = true);
+
+ donut.Advance(Frame);
+ Assert.False(done);
+ var elapsed = Run(donut, () => done);
+ Assert.True(done);
+ Assert.InRange(elapsed, 1.0, 2.0); // min ring time + hold, no animation time
+ window.Close();
+ }
+ finally
+ {
+ Motion.Set(true);
+ }
+ }
+
+ [AvaloniaFact]
+ public void Ring_states_render()
+ {
+ var (window, donut) = Create();
+
+ donut.BeginProgress();
+ donut.SetProgress(0.42);
+ Run(donut, () => false, 1.2);
+ Save(window, "progress-running.png");
+
+ donut.CompleteProgress(DonutProgressOutcome.Succeeded, () => { });
+ Run(donut, () => donut.ShownOutcome is not null);
+ Run(donut, () => false, 0.4); // let the ✓ pop settle
+ Save(window, "progress-success.png");
+
+ donut.BeginProgress();
+ donut.SetProgress(0.6);
+ Run(donut, () => false, 1.0);
+ donut.CompleteProgress(DonutProgressOutcome.Failed, () => { });
+ Run(donut, () => donut.ShownOutcome is not null);
+ Run(donut, () => false, 0.4);
+ Save(window, "progress-failed.png");
+
+ // Mid-collapse frame, to see the slices being sucked in.
+ donut.PlayOpenAnimation();
+ Run(donut, () => false, 0.6);
+ donut.BeginProgress();
+ Run(donut, () => false, 0.15);
+ Save(window, "progress-collapsing.png");
+ window.Close();
+ }
+
+ private static void Save(Window window, string name)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ var frame = window.CaptureRenderedFrame()!;
+ using var stream = File.Create(Path.Combine(TestServices.ScreenshotDirectory, name));
+ frame.Save(stream, new PngBitmapEncoderOptions());
+ }
+}
diff --git a/tests/Filee.App.Tests/Filee.App.Tests.csproj b/tests/Filee.App.Tests/Filee.App.Tests.csproj
new file mode 100644
index 00000000..690f9b48
--- /dev/null
+++ b/tests/Filee.App.Tests/Filee.App.Tests.csproj
@@ -0,0 +1,22 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <IsPackable>false</IsPackable>
+ <IsTestProject>true</IsTestProject>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\src\Filee.App\Filee.App.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" />
+ <PackageReference Include="xunit.v3" />
+ <PackageReference Include="xunit.runner.visualstudio" />
+ <PackageReference Include="Avalonia.Headless.XUnit" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Using Include="Xunit" />
+ </ItemGroup>
+</Project>
diff --git a/tests/Filee.App.Tests/GestureDetectorTests.cs b/tests/Filee.App.Tests/GestureDetectorTests.cs
new file mode 100644
index 00000000..c448b943
--- /dev/null
+++ b/tests/Filee.App.Tests/GestureDetectorTests.cs
@@ -0,0 +1,140 @@
+using Filee.App.Services.Triggers;
+using Filee.Core.Settings;
+
+namespace Filee.App.Tests;
+
+public class GestureDetectorTests
+{
+ private static GestureDetector Create(params TriggerGesture[] gestures)
+ {
+ var detector = new GestureDetector { SystemDragThreshold = 4 };
+ detector.Configure(gestures);
+ return detector;
+ }
+
+ private static readonly TriggerGesture CtrlDrag = new() { Kind = TriggerKind.Drag, Modifiers = ModifierKeys.Ctrl, Button = TriggerMouseButton.Left };
+
+ [Fact]
+ public void Drag_fires_after_threshold_with_exact_modifiers()
+ {
+ var detector = Create(CtrlDrag);
+ var started = 0;
+ detector.DragStarted += (_, _, _) => started++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 100, 100, ModifierKeys.Ctrl);
+ detector.MouseMove(102, 101, ModifierKeys.Ctrl);
+ Assert.Equal(0, started);
+ detector.MouseMove(110, 100, ModifierKeys.Ctrl);
+ detector.MouseMove(150, 100, ModifierKeys.Ctrl);
+ Assert.Equal(1, started);
+ }
+
+ [Fact]
+ public void Wrong_modifiers_or_button_do_not_fire()
+ {
+ var detector = Create(CtrlDrag);
+ var started = 0;
+ detector.DragStarted += (_, _, _) => started++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.Ctrl | ModifierKeys.Shift);
+ detector.MouseMove(50, 0, ModifierKeys.Ctrl | ModifierKeys.Shift);
+ detector.MouseUp(TriggerMouseButton.Left, 50, 0);
+ detector.MouseDown(TriggerMouseButton.Right, 0, 0, ModifierKeys.Ctrl);
+ detector.MouseMove(50, 0, ModifierKeys.Ctrl);
+
+ Assert.Equal(0, started);
+ }
+
+ [Fact]
+ public void Modifier_pressed_after_the_drag_started_still_fires_once()
+ {
+ var detector = Create(CtrlDrag);
+ var started = 0;
+ detector.DragStarted += (_, _, _) => started++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.None);
+ detector.MouseMove(30, 0, ModifierKeys.None, TriggerMouseButton.Left);
+ detector.MouseMove(40, 0, ModifierKeys.Ctrl, TriggerMouseButton.Left);
+ detector.MouseMove(50, 0, ModifierKeys.Ctrl, TriggerMouseButton.Left);
+
+ Assert.Equal(1, started);
+ }
+
+ [Fact]
+ public void Drag_end_is_reported_only_after_a_drag_started()
+ {
+ var detector = Create(CtrlDrag);
+ var ended = 0;
+ detector.DragEnded += (_, _) => ended++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.Ctrl);
+ detector.MouseUp(TriggerMouseButton.Left, 0, 0); // a click, not a drag
+ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.Ctrl);
+ detector.MouseMove(60, 0, ModifierKeys.Ctrl);
+ detector.MouseUp(TriggerMouseButton.Left, 60, 0);
+
+ Assert.Equal(1, ended);
+ }
+
+ [Fact]
+ public void Scope_filter_blocks_gestures()
+ {
+ var detector = Create(CtrlDrag);
+ detector.ScopeFilter = (_, x, _) => x < 1000;
+ var started = 0;
+ detector.DragStarted += (_, _, _) => started++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 2000, 0, ModifierKeys.Ctrl);
+ detector.MouseMove(2100, 0, ModifierKeys.Ctrl);
+
+ Assert.Equal(0, started);
+ }
+
+ [Fact]
+ public void Paused_detector_ignores_everything()
+ {
+ var detector = Create(CtrlDrag, new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Key = "Space" });
+ detector.Paused = true;
+ var fired = 0;
+ detector.DragStarted += (_, _, _) => fired++;
+ detector.KeyChordTriggered += (_, _, _) => fired++;
+
+ detector.MouseDown(TriggerMouseButton.Left, 0, 0, ModifierKeys.Ctrl);
+ detector.MouseMove(80, 0, ModifierKeys.Ctrl);
+ detector.KeyDown("Space", ModifierKeys.Ctrl | ModifierKeys.Alt);
+
+ Assert.Equal(0, fired);
+ }
+
+ [Fact]
+ public void Key_chord_uses_last_cursor_position()
+ {
+ var detector = Create(new TriggerGesture { Kind = TriggerKind.KeyChord, Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt, Key = "Space" });
+ (int X, int Y)? at = null;
+ detector.KeyChordTriggered += (_, x, y) => at = (x, y);
+
+ detector.MouseMove(321, 654, ModifierKeys.None);
+ detector.KeyDown("space", ModifierKeys.Ctrl | ModifierKeys.Alt);
+
+ Assert.Equal((321, 654), at);
+ }
+
+ [Fact]
+ public void Hold_fires_when_timer_elapses_without_movement()
+ {
+ var detector = Create(new TriggerGesture { Kind = TriggerKind.Hold, Modifiers = ModifierKeys.Alt, Button = TriggerMouseButton.Middle });
+ long token = 0;
+ var held = 0;
+ detector.HoldTimerRequested += (t, _) => token = t;
+ detector.HoldTriggered += (_, _, _) => held++;
+
+ detector.MouseDown(TriggerMouseButton.Middle, 10, 10, ModifierKeys.Alt);
+ detector.HoldElapsed(token);
+ Assert.Equal(1, held);
+
+ detector.MouseDown(TriggerMouseButton.Middle, 10, 10, ModifierKeys.Alt);
+ detector.MouseMove(60, 10, ModifierKeys.Alt); // moving cancels a hold
+ detector.HoldElapsed(token);
+ Assert.Equal(1, held);
+ }
+}
diff --git a/tests/Filee.App.Tests/LocalizationResourceTests.cs b/tests/Filee.App.Tests/LocalizationResourceTests.cs
new file mode 100644
index 00000000..50c6e39a
--- /dev/null
+++ b/tests/Filee.App.Tests/LocalizationResourceTests.cs
@@ -0,0 +1,31 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless.XUnit;
+
+namespace Filee.App.Tests;
+
+public class LocalizationResourceTests
+{
+ [AvaloniaFact]
+ public void Strings_are_available_as_application_resources()
+ {
+ TestServices.EnsureInitialized("ko");
+ Assert.True(Application.Current!.TryGetResource("home.title", null, out var value));
+ Assert.Equal("홈", value);
+ }
+
+ [AvaloniaFact]
+ public void DynamicResource_in_xaml_resolves_and_follows_language_changes()
+ {
+ TestServices.EnsureInitialized("en");
+ var text = new TextBlock();
+ text.Bind(TextBlock.TextProperty, text.GetResourceObservable("home.title"));
+ var window = new Window { Content = text };
+ window.Show();
+ Assert.Equal("Home", text.Text);
+
+ TestServices.EnsureInitialized("ko");
+ Assert.Equal("홈", text.Text);
+ window.Close();
+ }
+}
diff --git a/tests/Filee.App.Tests/LocalizationTests.cs b/tests/Filee.App.Tests/LocalizationTests.cs
new file mode 100644
index 00000000..efef6284
--- /dev/null
+++ b/tests/Filee.App.Tests/LocalizationTests.cs
@@ -0,0 +1,70 @@
+using System.Text.Json;
+using System.Text.RegularExpressions;
+
+namespace Filee.App.Tests;
+
+/// <summary>Keeps en / ko / zh-CN in sync so no language silently falls back to English.</summary>
+public partial class LocalizationTests
+{
+ private static string I18nDirectory
+ {
+ get
+ {
+ var dir = new DirectoryInfo(AppContext.BaseDirectory);
+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Filee.slnx")))
+ dir = dir.Parent;
+ return Path.Combine(dir!.FullName, "src", "Filee.App", "Assets", "i18n");
+ }
+ }
+
+ private static Dictionary<string, string> Load(string code) =>
+ JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(Path.Combine(I18nDirectory, code + ".json")))!;
+
+ public static TheoryData<string> Languages => new() { "ko", "zh-CN" };
+
+ [Theory]
+ [MemberData(nameof(Languages))]
+ public void Every_language_has_exactly_the_english_keys(string code)
+ {
+ var english = Load("en").Keys.ToHashSet();
+ var other = Load(code).Keys.ToHashSet();
+
+ Assert.Empty(english.Except(other));
+ Assert.Empty(other.Except(english));
+ }
+
+ [Theory]
+ [MemberData(nameof(Languages))]
+ public void Format_placeholders_match_english(string code)
+ {
+ var english = Load("en");
+ foreach (var (key, value) in Load(code))
+ Assert.True(
+ Placeholders(english[key]).SetEquals(Placeholders(value)),
+ $"{code}:{key} placeholders differ from English");
+ }
+
+ [Fact]
+ public void Every_key_used_in_xaml_exists()
+ {
+ var english = Load("en");
+ var src = Path.GetFullPath(Path.Combine(I18nDirectory, "..", ".."));
+ var missing = Directory.EnumerateFiles(src, "*.axaml", SearchOption.AllDirectories)
+ .SelectMany(f => DynamicResourceKey().Matches(File.ReadAllText(f)).Select(m => m.Groups[1].Value))
+ .Where(k => k.Contains('.') && !k.StartsWith("Icon.", StringComparison.Ordinal))
+ .Where(k => !english.ContainsKey(k))
+ .Distinct()
+ .ToList();
+
+ Assert.Empty(missing);
+ }
+
+ private static HashSet<string> Placeholders(string text) =>
+ PlaceholderPattern().Matches(text).Select(m => m.Value).ToHashSet();
+
+ [GeneratedRegex(@"\{\d+\}")]
+ private static partial Regex PlaceholderPattern();
+
+ [GeneratedRegex(@"\{DynamicResource ([\w.]+)\}")]
+ private static partial Regex DynamicResourceKey();
+}
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
new file mode 100644
index 00000000..2c78b06f
--- /dev/null
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -0,0 +1,138 @@
+// Renders real windows headlessly (Skia) to catch XAML / binding errors and to produce screenshots
+// in bin/.../screenshots for visual review.
+
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Threading;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+using Filee.App.Views;
+using Filee.Core.Settings;
+
+namespace Filee.App.Tests;
+
+public class RenderTests
+{
+ public static TheoryData<string, string> Pages => new()
+ {
+ { "home", "en" }, { "general", "en" }, { "triggers", "en" }, { "toolbar", "en" },
+ { "presets", "en" }, { "theme", "en" }, { "engines", "en" }, { "about", "en" },
+ { "toolbar", "ko" }, { "home", "ko" }, { "presets", "zh-CN" }, { "toolbar", "zh-CN" }, { "home", "zh-CN" },
+ };
+
+ [AvaloniaTheory]
+ [MemberData(nameof(Pages))]
+ public void Main_window_pages_render(string page, string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>());
+ vm.Navigate(page);
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };
+ window.Show();
+ Pump();
+
+ Assert.NotNull(window.FindControl<ScrollViewer>("PageScroller"));
+ Save(window, $"page-{page}-{language}.png");
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Donut_toolbar_renders_for_images()
+ {
+ TestServices.EnsureInitialized("ko");
+ var files = new[] { @"C:\photos\a.jpg", @"C:\photos\b.jpg", @"C:\photos\c.jpg" };
+ var vm = AppHost.Get<RadialViewModel>();
+ vm.Load(files, clickMode: true);
+ var window = new RadialWindow { DataContext = vm };
+ window.Show();
+ window.DonutControl.SetExternalHighlight(1);
+ Pump();
+
+ Assert.Equal(8, vm.Items.Count);
+ Assert.Equal("JPG 3개", vm.CenterTitle);
+ Save(window, "donut-images-ko.png");
+ window.Close();
+ }
+
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ public void First_run_engine_setup_renders(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var vm = new EngineSetupViewModel(AppHost.Get<EngineDownloadService>(), AppHost.Get<Filee.Core.Localization.ILocalizer>());
+ var window = new EngineSetupWindow { DataContext = vm };
+ 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));
+ Save(window, $"engine-setup-{language}.png");
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Donut_toolbar_waits_for_files_in_drag_mode()
+ {
+ TestServices.EnsureInitialized("en");
+ var vm = AppHost.Get<RadialViewModel>();
+ vm.ResetForDrag();
+ var window = new RadialWindow { DataContext = vm };
+ window.Show();
+ Pump();
+
+ Assert.Empty(vm.Items);
+ Save(window, "donut-drag-waiting.png");
+ window.Close();
+ }
+
+ [AvaloniaFact]
+ public void Dark_theme_with_custom_accent_renders()
+ {
+ TestServices.EnsureInitialized("en");
+ var theme = new ThemeSettings { Mode = ThemeMode.Dark, Accent = "#1D9E75", CornerRadius = 22 };
+ AppHost.Get<ThemeService>().Apply(theme, "en");
+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>());
+ vm.Navigate("toolbar");
+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };
+ window.Show();
+ Pump();
+
+ Save(window, "page-toolbar-dark.png");
+ window.Close();
+ AppHost.Get<ThemeService>().Apply(new ThemeSettings(), "en");
+ }
+
+ [AvaloniaFact]
+ public void Preset_popup_renders()
+ {
+ TestServices.EnsureInitialized("ko");
+ var preset = AppHost.Get<UserDataStore>().FindPreset("jpg-70")!;
+ var window = new PresetEditorWindow { DataContext = new PresetEditorViewModel(preset, AppHost.Get<Filee.Core.Localization.ILocalizer>()) };
+ window.Show();
+ Pump();
+
+ Save(window, "preset-popup-ko.png");
+ window.Close();
+ }
+
+ private static void Pump()
+ {
+ // Let layout, bindings and a few animation frames run.
+ for (var i = 0; i < 40; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ }
+ }
+
+ private static void Save(Window window, string name)
+ {
+ var frame = window.CaptureRenderedFrame();
+ Assert.NotNull(frame);
+ using var stream = File.Create(Path.Combine(TestServices.ScreenshotDirectory, name));
+ frame.Save(stream, new Avalonia.Media.Imaging.PngBitmapEncoderOptions());
+ }
+}
diff --git a/tests/Filee.App.Tests/TestApp.cs b/tests/Filee.App.Tests/TestApp.cs
new file mode 100644
index 00000000..734ac843
--- /dev/null
+++ b/tests/Filee.App.Tests/TestApp.cs
@@ -0,0 +1,61 @@
+using Avalonia;
+using Avalonia.Headless;
+using Filee.App;
+using Filee.App.Services;
+using Filee.Core.Settings;
+
+[assembly: AvaloniaTestApplication(typeof(Filee.App.Tests.TestAppBuilder))]
+
+namespace Filee.App.Tests;
+
+/// <summary>Headless Avalonia with real Skia rendering so views can be captured as images.</summary>
+public static class TestAppBuilder
+{
+ public static AppBuilder BuildAvaloniaApp() =>
+ AppBuilder.Configure<App>()
+ .UseSkia()
+ .UseHarfBuzz()
+ .ConfigureFonts(fonts => fonts.AddFontCollection(new FileeFontCollection()))
+ .UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false });
+}
+
+/// <summary>Builds the service container once against a throw-away data folder (never touches %APPDATA%).</summary>
+internal static class TestServices
+{
+ private static Application? _initializedFor;
+
+ public static string DataDirectory { get; } =
+ Path.Combine(Path.GetTempPath(), "filee-app-tests", Guid.NewGuid().ToString("N")[..8]);
+
+ /// <summary>
+ /// The headless runner may create a new Application per test, so services (and the localization
+ /// dictionary attached to Application.Resources) are rebuilt whenever the application changes.
+ /// </summary>
+ public static void EnsureInitialized(string language = "en")
+ {
+ var app = Application.Current!;
+ if (!ReferenceEquals(_initializedFor, app))
+ {
+ AppHost.Build(DataDirectory);
+ AppHost.Get<UserDataStore>().Load();
+ AppHost.Get<LocalizationService>().Attach(app);
+ _initializedFor = app;
+ }
+
+ var store = AppHost.Get<UserDataStore>();
+ store.Settings.Language = language;
+ AppHost.Get<LocalizationService>().SetLanguage(language);
+ AppHost.Get<ThemeService>().Apply(store.Settings.Theme, language);
+ }
+
+ /// <summary>Where rendered screenshots go: tests/Filee.App.Tests/bin/.../screenshots.</summary>
+ public static string ScreenshotDirectory
+ {
+ get
+ {
+ var dir = Path.Combine(AppContext.BaseDirectory, "screenshots");
+ Directory.CreateDirectory(dir);
+ return dir;
+ }
+ }
+}
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
new file mode 100644
index 00000000..abf3168c
--- /dev/null
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -0,0 +1,70 @@
+using Filee.Core.Conversion;
+
+namespace Filee.Core.Tests;
+
+/// <summary>Test double: "converts" by writing the input name and target format into the output file.</summary>
+internal sealed class FakeConverter(string id, params ConversionEdge[] edges) : IConverter
+{
+ public string Id => id;
+ public string DisplayName => id;
+ public IReadOnlyList<ConversionEdge> Edges => edges;
+ public int MaxParallelism => 0;
+ public bool Available { get; set; } = true;
+
+ /// <summary>Number of output files per input (simulates multi-page outputs).</summary>
+ public int OutputsPerInput { get; set; } = 1;
+
+ public bool Throw { get; set; }
+
+ public EngineStatus GetStatus() => Available ? EngineStatus.Available() : EngineStatus.Unavailable("engine.reason.not_installed");
+
+ public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ if (Throw)
+ throw new InvalidOperationException("boom");
+
+ var written = new List<string>();
+ for (var i = 0; i < OutputsPerInput; i++)
+ {
+ var path = step.Output.Allocate(step.To, OutputsPerInput > 1 ? $"_p{i + 1}" : null);
+ if (path is null)
+ continue;
+ File.WriteAllText(path, $"{Path.GetFileName(step.InputPath)}→{step.To} by {id}");
+ written.Add(path);
+ }
+ progress?.Report(1);
+ return Task.FromResult<IReadOnlyList<string>>(written);
+ }
+}
+
+internal sealed class FakeMerger : IPdfMerger
+{
+ public List<string> Inputs { get; } = [];
+
+ public Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, CancellationToken cancellationToken)
+ {
+ Inputs.AddRange(inputPaths);
+ File.WriteAllText(outputPath, string.Join("|", inputPaths.Select(Path.GetFileName)));
+ return Task.CompletedTask;
+ }
+}
+
+/// <summary>Creates and removes a unique temp directory.</summary>
+internal sealed class TempDir : IDisposable
+{
+ public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "filee-tests", Guid.NewGuid().ToString("N")[..8]);
+
+ public TempDir() => Directory.CreateDirectory(Path);
+
+ public string File(string name, string content = "x")
+ {
+ var full = System.IO.Path.Combine(Path, name);
+ System.IO.File.WriteAllText(full, content);
+ return full;
+ }
+
+ public void Dispose()
+ {
+ try { Directory.Delete(Path, true); } catch (IOException) { }
+ }
+}
diff --git a/tests/Filee.Core.Tests/Filee.Core.Tests.csproj b/tests/Filee.Core.Tests/Filee.Core.Tests.csproj
new file mode 100644
index 00000000..5d5a32a9
--- /dev/null
+++ b/tests/Filee.Core.Tests/Filee.Core.Tests.csproj
@@ -0,0 +1,21 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <IsPackable>false</IsPackable>
+ <IsTestProject>true</IsTestProject>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\src\Filee.Core\Filee.Core.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" />
+ <PackageReference Include="xunit.v3" />
+ <PackageReference Include="xunit.runner.visualstudio" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Using Include="Xunit" />
+ </ItemGroup>
+</Project>
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
new file mode 100644
index 00000000..fa784876
--- /dev/null
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -0,0 +1,147 @@
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+
+namespace Filee.Core.Tests;
+
+public class JobQueueTests
+{
+ private static async Task<ConversionJob> Run(JobQueue queue, IReadOnlyList<string> sources, Preset preset)
+ {
+ var job = new ConversionJob(sources, preset, "Test");
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ [Fact]
+ public async Task Converts_every_file()
+ {
+ using var dir = new TempDir();
+ var a = dir.File("a.jpg");
+ var b = dir.File("b.jpg");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+
+ var job = await Run(queue, [a, b], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "a.png")));
+ Assert.True(File.Exists(Path.Combine(dir.Path, "b.png")));
+ Assert.Equal(1, job.Progress);
+ }
+
+ [Fact]
+ public async Task Multi_step_route_keeps_intermediates_out_of_the_output_folder()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("doc.hwpx");
+ var catalog = new ConverterCatalog([
+ new FakeConverter("rhwp", new ConversionEdge("hwpx", "pdf")),
+ new FakeConverter("pdfium", new ConversionEdge("pdf", "png")) { OutputsPerInput = 2 },
+ ]);
+ await using var queue = new JobQueue(catalog);
+
+ var job = await Run(queue, [source], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(["doc.hwpx", "doc_p1.png", "doc_p2.png"], Directory.GetFiles(dir.Path).Select(Path.GetFileName).Order(StringComparer.Ordinal));
+ }
+
+ [Fact]
+ public async Task Failures_are_isolated_per_file()
+ {
+ using var dir = new TempDir();
+ var ok = dir.File("a.jpg");
+ var unsupported = dir.File("b.xyz");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+
+ var job = await Run(queue, [ok, unsupported], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.CompletedWithErrors, job.State);
+ Assert.Equal("error.unsupported_source", job.Files[1].ErrorKey);
+ }
+
+ [Fact]
+ public async Task No_route_is_reported()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([]));
+
+ var job = await Run(queue, [dir.File("a.docx")], new Preset { TargetFormat = "hwpx" });
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Equal("error.no_route", job.Files[0].ErrorKey);
+ }
+
+ [Fact]
+ public async Task Engine_exceptions_mark_the_file_failed()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("x", new ConversionEdge("jpg", "png")) { Throw = true }]));
+
+ var job = await Run(queue, [dir.File("a.jpg")], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.Equal("error.conversion_failed", job.Files[0].ErrorKey);
+ }
+
+ [Fact]
+ public async Task Same_as_source_target_reencodes_in_place_format()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("a.jpg");
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "jpg"))]));
+
+ var job = await Run(queue, [source], new Preset { TargetFormat = BuiltInData.SameAsSource, Output = { FileNamePattern = "{name}_50" } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "a_50.jpg")));
+ Assert.Equal("x", File.ReadAllText(source)); // source untouched
+ }
+
+ [Fact]
+ public async Task Merge_converts_to_pdf_then_merges_in_order()
+ {
+ using var dir = new TempDir();
+ var first = dir.File("1.jpg");
+ var second = dir.File("2.pdf");
+ var third = dir.File("3.png");
+ var merger = new FakeMerger();
+ var catalog = new ConverterCatalog([new FakeConverter("pdfsharp", new ConversionEdge("jpg", "pdf"), new ConversionEdge("png", "pdf"))]);
+ await using var queue = new JobQueue(catalog, merger);
+
+ var job = await Run(queue, [first, second, third],
+ new Preset { TargetFormat = "pdf", Pdf = { MergeIntoSingle = true }, Output = { FileNamePattern = "{name}_merged" } });
+
+ Assert.Equal(JobState.Completed, job.State);
+ var merged = Path.Combine(dir.Path, "1_merged.pdf");
+ Assert.Equal("1.pdf|2.pdf|3.pdf", File.ReadAllText(merged));
+ Assert.Equal(second, merger.Inputs[1]); // existing PDFs are merged as-is
+ }
+
+ [Fact]
+ public async Task Parallel_files_with_the_same_name_do_not_collide()
+ {
+ using var dir = new TempDir();
+ var a = dir.File("same.jpg");
+ var b = dir.File("same.png");
+ var catalog = new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "webp"), new ConversionEdge("png", "webp"))]);
+ await using var queue = new JobQueue(catalog);
+
+ var job = await Run(queue, [a, b], new Preset { TargetFormat = "webp" });
+
+ Assert.Equal(2, job.Outputs.Distinct().Count());
+ }
+
+ [Fact]
+ public async Task Enqueue_runs_in_background_and_raises_finished()
+ {
+ using var dir = new TempDir();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]));
+ var finished = new TaskCompletionSource<ConversionJob>();
+ queue.JobFinished += (_, job) => finished.TrySetResult(job);
+
+ queue.Enqueue([dir.File("a.jpg")], new Preset { TargetFormat = "png" }, "PNG");
+ var done = await finished.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
+
+ Assert.Equal(JobState.Completed, done.State);
+ }
+}
diff --git a/tests/Filee.Core.Tests/OutputPathResolverTests.cs b/tests/Filee.Core.Tests/OutputPathResolverTests.cs
new file mode 100644
index 00000000..2675df42
--- /dev/null
+++ b/tests/Filee.Core.Tests/OutputPathResolverTests.cs
@@ -0,0 +1,89 @@
+using Filee.Core.Presets;
+
+namespace Filee.Core.Tests;
+
+public class OutputPathResolverTests
+{
+ private static readonly DateTime Now = new(2026, 9, 30, 14, 5, 9);
+
+ private static OutputPathResolver.Tokens Tokens(string source, int index = 1) => new(source, "PNG", index, Now);
+
+ [Fact]
+ public void Default_pattern_keeps_the_source_name()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("photo.jpg");
+
+ var path = OutputPathResolver.Resolve(new OutputRule(), Tokens(source), "png", File.Exists);
+
+ Assert.Equal(Path.Combine(dir.Path, "photo.png"), path);
+ }
+
+ [Fact]
+ public void Existing_file_gets_a_number_by_default()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("photo.jpg");
+ dir.File("photo.png");
+
+ var path = OutputPathResolver.Resolve(new OutputRule(), Tokens(source), "png", File.Exists);
+
+ Assert.Equal(Path.Combine(dir.Path, "photo (2).png"), path);
+ }
+
+ [Fact]
+ public void Overwrite_and_skip_policies()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("photo.jpg");
+ var existing = dir.File("photo.png");
+
+ Assert.Equal(existing, OutputPathResolver.Resolve(new OutputRule { Conflict = ConflictPolicy.Overwrite }, Tokens(source), "png", File.Exists));
+ Assert.Null(OutputPathResolver.Resolve(new OutputRule { Conflict = ConflictPolicy.Skip }, Tokens(source), "png", File.Exists));
+ }
+
+ [Theory]
+ [InlineData(ConflictPolicy.Overwrite)]
+ [InlineData(ConflictPolicy.Skip)]
+ [InlineData(ConflictPolicy.Rename)]
+ public void The_source_file_is_never_overwritten(ConflictPolicy policy)
+ {
+ using var dir = new TempDir();
+ var source = dir.File("photo.jpg");
+
+ var path = OutputPathResolver.Resolve(new OutputRule { Conflict = policy }, Tokens(source), "jpg", File.Exists);
+
+ Assert.Equal(Path.Combine(dir.Path, "photo (2).jpg"), path);
+ }
+
+ [Fact]
+ public void Tokens_are_expanded_and_invalid_characters_removed()
+ {
+ var rule = new OutputRule { FileNamePattern = "{name}_{preset}_{date}_{index}:?" };
+ var path = OutputPathResolver.Resolve(rule, Tokens(Path.Combine("C:", "x", "a.jpg"), 3), "png", _ => false);
+
+ Assert.Equal("a_PNG_20260930_3__.png", Path.GetFileName(path));
+ }
+
+ [Fact]
+ public void Subfolder_name_supports_tokens()
+ {
+ using var dir = new TempDir();
+ var source = dir.File("report.pdf");
+ var rule = new OutputRule { Location = OutputLocation.Subfolder, SubfolderName = "{name}" };
+
+ var path = OutputPathResolver.Resolve(rule, Tokens(source), "pdf", File.Exists, "_p1");
+
+ Assert.Equal(Path.Combine(dir.Path, "report", "report_p1.pdf"), path);
+ }
+
+ [Fact]
+ public void Custom_folder_is_used_when_set()
+ {
+ var rule = new OutputRule { Location = OutputLocation.CustomFolder, CustomFolder = Path.Combine("D:", "out") };
+
+ var path = OutputPathResolver.Resolve(rule, Tokens(Path.Combine("C:", "in", "a.jpg")), "png", _ => false);
+
+ Assert.Equal(Path.Combine("D:", "out", "a.png"), path);
+ }
+}
diff --git a/tests/Filee.Core.Tests/RoutePlannerTests.cs b/tests/Filee.Core.Tests/RoutePlannerTests.cs
new file mode 100644
index 00000000..766fd035
--- /dev/null
+++ b/tests/Filee.Core.Tests/RoutePlannerTests.cs
@@ -0,0 +1,99 @@
+using Filee.Core.Conversion;
+
+namespace Filee.Core.Tests;
+
+public class RoutePlannerTests
+{
+ [Fact]
+ public void Direct_edge_is_used()
+ {
+ var magick = new FakeConverter("magick", new ConversionEdge("jpg", "png"));
+ var route = new RoutePlanner([magick]).Plan("jpg", "png");
+
+ Assert.NotNull(route);
+ Assert.Single(route.Steps);
+ Assert.Same(magick, route.Steps[0].Converter);
+ }
+
+ [Fact]
+ public void Two_step_route_is_found()
+ {
+ var rhwp = new FakeConverter("rhwp", new ConversionEdge("hwpx", "pdf"));
+ var pdfium = new FakeConverter("pdfium", new ConversionEdge("pdf", "png"));
+
+ var route = new RoutePlanner([rhwp, pdfium]).Plan("hwpx", "png");
+
+ Assert.NotNull(route);
+ Assert.Equal(["hwpx→pdf", "pdf→png"], route.Steps.Select(s => $"{s.From}→{s.To}"));
+ }
+
+ [Fact]
+ public void Cheaper_route_wins()
+ {
+ var slow = new FakeConverter("slow", new ConversionEdge("docx", "pdf", 30));
+ var fast = new FakeConverter("fast", new ConversionEdge("docx", "pdf", 10));
+
+ var route = new RoutePlanner([slow, fast]).Plan("docx", "pdf");
+
+ Assert.Equal("fast", route!.Steps[0].Converter.Id);
+ }
+
+ [Fact]
+ public void Priority_breaks_ties()
+ {
+ var word = new FakeConverter("word", new ConversionEdge("docx", "pdf"));
+ var libre = new FakeConverter("libreoffice", new ConversionEdge("docx", "pdf"));
+
+ var route = new RoutePlanner([word, libre], c => c.Id == "word" ? 5 : 0).Plan("docx", "pdf");
+
+ Assert.Equal("libreoffice", route!.Steps[0].Converter.Id);
+ }
+
+ [Fact]
+ public void Same_format_requires_self_edge()
+ {
+ var withSelf = new FakeConverter("magick", new ConversionEdge("jpg", "jpg"));
+ var withoutSelf = new FakeConverter("other", new ConversionEdge("jpg", "png"), new ConversionEdge("png", "jpg"));
+
+ Assert.NotNull(new RoutePlanner([withSelf]).Plan("jpg", "jpg"));
+ Assert.Null(new RoutePlanner([withoutSelf]).Plan("jpg", "jpg"));
+ }
+
+ [Fact]
+ public void Impossible_conversion_returns_null()
+ {
+ var magick = new FakeConverter("magick", new ConversionEdge("jpg", "png"));
+ Assert.Null(new RoutePlanner([magick]).Plan("docx", "png"));
+ }
+
+ [Fact]
+ public void Routes_longer_than_max_steps_are_rejected()
+ {
+ var chain = new FakeConverter("chain",
+ new ConversionEdge("a", "b"), new ConversionEdge("b", "c"),
+ new ConversionEdge("c", "d"), new ConversionEdge("d", "e"));
+
+ Assert.NotNull(new RoutePlanner([chain]).Plan("a", "d"));
+ Assert.Null(new RoutePlanner([chain]).Plan("a", "e"));
+ }
+
+ [Fact]
+ public void Catalog_excludes_unavailable_engines()
+ {
+ var missing = new FakeConverter("missing", new ConversionEdge("docx", "hwpx")) { Available = false };
+ var catalog = new ConverterCatalog([missing]);
+
+ Assert.False(catalog.CreatePlanner().CanConvert("docx", "hwpx"));
+ }
+
+ [Fact]
+ public void A_planner_can_assume_an_optional_engine_is_installed()
+ {
+ var office = new FakeConverter("office", new ConversionEdge("xlsx", "pdf")) { Available = false };
+ var images = new FakeConverter("images", new ConversionEdge("pdf", "png"));
+ var catalog = new ConverterCatalog([office, images]);
+
+ Assert.False(catalog.CreatePlanner().CanConvert("xlsx", "png"));
+ Assert.True(catalog.CreatePlanner(["office"]).CanConvert("xlsx", "png"));
+ }
+}
diff --git a/tests/Filee.Core.Tests/SmallParsersTests.cs b/tests/Filee.Core.Tests/SmallParsersTests.cs
new file mode 100644
index 00000000..2c0ded75
--- /dev/null
+++ b/tests/Filee.Core.Tests/SmallParsersTests.cs
@@ -0,0 +1,87 @@
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+
+namespace Filee.Core.Tests;
+
+public class PageRangeTests
+{
+ [Theory]
+ [InlineData("", 5, new[] { 0, 1, 2, 3, 4 })]
+ [InlineData("2", 5, new[] { 1 })]
+ [InlineData("2-4", 5, new[] { 1, 2, 3 })]
+ [InlineData("4-", 5, new[] { 3, 4 })]
+ [InlineData("-2", 5, new[] { 0, 1 })]
+ [InlineData("5,1, 3", 5, new[] { 0, 2, 4 })]
+ [InlineData("4-2", 5, new[] { 1, 2, 3 })]
+ [InlineData("9-12", 5, new[] { 0, 1, 2, 3, 4 })] // nothing valid → everything
+ [InlineData("x, 2", 5, new[] { 1 })]
+ public void Parses_ranges(string expression, int pages, int[] expected) =>
+ Assert.Equal(expected, PageRange.Parse(expression, pages));
+}
+
+public class FormatRegistryTests
+{
+ [Theory]
+ [InlineData("a.JPEG", "jpg")]
+ [InlineData("b.tif", "tiff")]
+ [InlineData("c.HWPX", "hwpx")]
+ [InlineData(".md", "md")]
+ public void Detects_formats(string path, string id) => Assert.Equal(id, FormatRegistry.Detect(path)?.Id);
+
+ [Fact]
+ public void Unknown_extension_is_null() => Assert.Null(FormatRegistry.Detect("x.xyz"));
+
+ [Fact]
+ public void Extensions_are_unique() =>
+ Assert.Equal(
+ FormatRegistry.Known.SelectMany(f => f.Extensions).Count(),
+ FormatRegistry.Known.SelectMany(f => f.Extensions).Distinct(StringComparer.OrdinalIgnoreCase).Count());
+}
+
+public class ProfileSelectorTests
+{
+ private readonly List<ToolbarProfile> _profiles = BuiltInData.CreateProfiles();
+
+ [Fact]
+ public void Picks_profile_matching_all_files() =>
+ Assert.Equal("images", ProfileSelector.Select(_profiles, ["a.jpg", "b.PNG"])!.Id);
+
+ [Fact]
+ public void Mixed_files_use_the_fallback() =>
+ Assert.Equal("mixed", ProfileSelector.Select(_profiles, ["a.jpg", "b.docx"])!.Id);
+
+ [Fact]
+ public void Unknown_files_use_the_fallback() =>
+ Assert.Equal("mixed", ProfileSelector.Select(_profiles, ["a.xyz"])!.Id);
+}
+
+public class BuiltInDataTests
+{
+ [Fact]
+ public void Profiles_only_reference_existing_presets()
+ {
+ var ids = BuiltInData.CreatePresets().Select(p => p.Id).ToHashSet();
+ foreach (var profile in BuiltInData.CreateProfiles())
+ Assert.All(profile.PresetIds, id => Assert.Contains(id, ids));
+ }
+
+ [Fact]
+ public void Preset_ids_are_unique()
+ {
+ var presets = BuiltInData.CreatePresets();
+ Assert.Equal(presets.Count, presets.Select(p => p.Id).Distinct().Count());
+ }
+
+ [Fact]
+ public void Exactly_one_fallback_profile() =>
+ Assert.Single(BuiltInData.CreateProfiles(), p => p.IsFallback);
+
+ [Fact]
+ public void Preset_targets_are_known_formats()
+ {
+ foreach (var preset in BuiltInData.CreatePresets())
+ Assert.True(preset.TargetFormat == BuiltInData.SameAsSource || FormatRegistry.FindById(preset.TargetFormat) is not null, preset.Id);
+ }
+}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
new file mode 100644
index 00000000..ce2f520e
--- /dev/null
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -0,0 +1,101 @@
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class UserDataStoreTests
+{
+ [Fact]
+ public void Round_trips_settings_presets_and_profiles()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ store.Settings.Language = "ko";
+ store.Settings.Theme.Accent = "#1D9E75";
+ store.Settings.Triggers[0].Modifiers = ModifierKeys.Alt | ModifierKeys.Shift;
+ store.Presets.Add(new Preset { Id = "mine", Name = "Mine", TargetFormat = "webp", Image = { Quality = 42 } });
+ store.Profiles[0].PresetIds.Insert(0, "mine");
+ store.SaveSettings();
+ store.SaveLibrary();
+
+ var reloaded = new UserDataStore(dir.Path);
+ reloaded.Load();
+
+ Assert.Equal("ko", reloaded.Settings.Language);
+ Assert.Equal("#1D9E75", reloaded.Settings.Theme.Accent);
+ Assert.Equal(ModifierKeys.Alt | ModifierKeys.Shift, reloaded.Settings.Triggers[0].Modifiers);
+ Assert.Equal(42, reloaded.FindPreset("mine")!.Image.Quality);
+ Assert.Equal("mine", reloaded.Profiles[0].PresetIds[0]);
+ }
+
+ [Fact]
+ public void Version_1_settings_are_upgraded_to_the_current_engine_list()
+ {
+ using var dir = new TempDir();
+ File.WriteAllText(Path.Combine(dir.Path, "settings.json"),
+ """{ "schemaVersion": 1, "enginePriority": ["magick", "word", "hancom", "libreoffice"] }""");
+
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+
+ Assert.Equal(["magick", "word", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);
+ Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);
+ }
+
+ [Fact]
+ public void Enums_are_stored_as_strings()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ store.SaveSettings();
+
+ var json = File.ReadAllText(Path.Combine(dir.Path, "settings.json"));
+ Assert.Contains("\"Drag\"", json);
+ }
+
+ [Fact]
+ public void Corrupt_file_falls_back_to_defaults_and_is_kept()
+ {
+ using var dir = new TempDir();
+ File.WriteAllText(Path.Combine(dir.Path, "presets.json"), "{ not json");
+
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+
+ Assert.NotEmpty(store.Presets);
+ Assert.True(File.Exists(Path.Combine(dir.Path, "presets.json.broken")));
+ }
+
+ [Fact]
+ public void Dangling_preset_references_are_removed()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ store.Profiles[0].PresetIds.Add("does-not-exist");
+ store.SaveLibrary();
+
+ Assert.DoesNotContain("does-not-exist", store.Profiles[0].PresetIds);
+ }
+
+ [Fact]
+ public void Export_then_import_restores_presets()
+ {
+ using var dir = new TempDir();
+ var store = new UserDataStore(dir.Path);
+ store.Load();
+ store.Presets.Add(new Preset { Id = "shared", Name = "Shared", TargetFormat = "png" });
+ var bundle = Path.Combine(dir.Path, "bundle.json");
+ store.Export(bundle);
+
+ using var other = new TempDir();
+ var target = new UserDataStore(other.Path);
+ target.Load();
+ target.Import(bundle);
+
+ Assert.NotNull(target.FindPreset("shared"));
+ Assert.Single(target.Profiles, p => p.IsFallback);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/DocumentEngineTests.cs b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
new file mode 100644
index 00000000..fd9f4aea
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocumentEngineTests.cs
@@ -0,0 +1,118 @@
+// Tests for engines that depend on external software (LibreOffice, rhwp, Word).
+// They skip automatically when the engine is not available, so CI stays green without them.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Office;
+
+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>
+ 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)");
+ return engine!;
+ }
+
+ private void SkipUnlessAvailable(string id)
+ {
+ var status = fx.Catalog.StatusOf(Engine(id));
+ Assert.SkipUnless(status.IsAvailable, $"{id} not available ({status.ReasonKey})");
+ }
+
+ [Theory]
+ [InlineData("docx", "pdf", false, "pdf:writer_pdf_Export")]
+ [InlineData("xlsx", "pdf", false, "pdf:calc_pdf_Export")]
+ [InlineData("docx", "pdf", true, "pdf:writer_pdf_Export:{\"SelectPdfVersion\":{\"type\":\"long\",\"value\":\"2\"}}")]
+ [InlineData("odt", "docx", false, "docx:MS Word 2007 XML")]
+ [InlineData("xlsx", "html", false, "html:HTML (StarCalc)")]
+ public void LibreOffice_filter_names(string from, string to, bool pdfA, string expected) =>
+ Assert.Equal(expected, LibreOfficeConverter.FilterFor(from, to, pdfA));
+
+ [Fact]
+ public async Task LibreOffice_txt_to_docx_and_pdf()
+ {
+ SkipUnlessAvailable("libreoffice");
+ var dir = fx.NewFolder();
+ var txt = Path.Combine(dir, "note.txt");
+ await File.WriteAllTextAsync(txt, "Filee 변환 테스트\n文件转换测试\nHello", TestContext.Current.CancellationToken);
+
+ var docx = await fx.ConvertAsync([txt], new Preset { TargetFormat = "docx" });
+ Assert.Equal(JobState.Completed, docx.State);
+
+ var pdf = await fx.ConvertAsync([docx.Outputs.Single()], new Preset { TargetFormat = "pdf" });
+ Assert.Equal(JobState.Completed, pdf.State);
+ Assert.True(new FileInfo(pdf.Outputs.Single()).Length > 1000);
+ }
+
+ [Fact]
+ public async Task Hwpx_to_pdf()
+ {
+ Assert.SkipUnless(fx.Converters.Any(c => c.Id is "rhwp" or "libreoffice" && fx.Catalog.StatusOf(c).IsAvailable), "no HWPX renderer");
+ var hwpx = await fx.MakeHwpxAsync(fx.NewFolder());
+
+ var job = await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "pdf" });
+
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ Assert.True(new FileInfo(job.Outputs.Single()).Length > 1000);
+ }
+
+ [Fact]
+ public async Task Hwpx_to_text()
+ {
+ SkipUnlessAvailable("unhwp");
+ var hwpx = await fx.MakeHwpxAsync(fx.NewFolder());
+
+ var job = await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "txt" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Contains("두 번째 문단입니다", await File.ReadAllTextAsync(job.Outputs.Single(), TestContext.Current.CancellationToken));
+ }
+
+ [Fact]
+ public async Task Rhwp_converts_between_hwpx_and_hwp()
+ {
+ SkipUnlessAvailable("rhwp");
+ var hwpx = await fx.MakeHwpxAsync(fx.NewFolder());
+
+ var hwp = await fx.ConvertAsync([hwpx], new Preset { TargetFormat = "hwp" });
+ Assert.True(hwp.State == JobState.Completed, string.Join("; ", hwp.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ // HWP 5.0 is an OLE compound file.
+ var header = new byte[8];
+ await using (var stream = File.OpenRead(hwp.Outputs.Single()))
+ await stream.ReadExactlyAsync(header, TestContext.Current.CancellationToken);
+ Assert.Equal([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1], header);
+
+ var back = await fx.ConvertAsync([hwp.Outputs.Single()], new Preset { TargetFormat = "hwpx" });
+ Assert.Equal(JobState.Completed, back.State);
+ Assert.Equal("rhwp", Assert.Single(fx.Catalog.CreatePlanner().Plan("hwp", "hwpx")!.Steps).Converter.Id);
+ using var document = Unhwp.UnhwpDocument.ParseFile(back.Outputs.Single());
+ Assert.Contains("두 번째 문단입니다", document.ToText());
+ }
+
+ [Fact]
+ public async Task LibreOffice_with_H2Orestart_reads_hwpx()
+ {
+ SkipUnlessAvailable("libreoffice");
+ var libreOffice = Engine("libreoffice");
+ Assert.SkipUnless(libreOffice.Edges.Any(e => e.From == "hwpx"), "H2Orestart extension not installed");
+ var dir = fx.NewFolder();
+ var hwpx = await fx.MakeHwpxAsync(dir);
+ var output = Path.Combine(dir, "from-hwpx.docx");
+
+ // Call the engine directly: the planner may prefer another HWPX reader.
+ var written = await libreOffice.ConvertAsync(
+ new ConversionStep(hwpx, "hwpx", "docx", new Preset(), new SinglePath(output), dir), null, TestContext.Current.CancellationToken);
+
+ Assert.Equal(output, written.Single());
+ Assert.True(new FileInfo(output).Length > 2000);
+ }
+
+ private sealed class SinglePath(string path) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => path;
+ }
+}
diff --git a/tests/Filee.Engines.Tests/DocxBuilder.cs b/tests/Filee.Engines.Tests/DocxBuilder.cs
new file mode 100644
index 00000000..b2eab2a3
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxBuilder.cs
@@ -0,0 +1,169 @@
+// Builds small .docx files for tests, so DOCX → HWPX features can be tested without sample documents.
+
+using System.IO.Compression;
+using System.Text;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>A minimal WordprocessingML package: body XML plus optional styles, numbering, headers, notes and media.</summary>
+internal sealed class DocxBuilder
+{
+ public const string Namespaces =
+ "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" " +
+ "xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" " +
+ "xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" " +
+ "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" " +
+ "xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" " +
+ "xmlns:wps=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\" " +
+ "xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" " +
+ "xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" " +
+ "xmlns:v=\"urn:schemas-microsoft-com:vml\" " +
+ "xmlns:w10=\"urn:schemas-microsoft-com:office:word\"";
+
+ /// <summary>A4 portrait, 1 inch margins, header/footer 0.5 inch.</summary>
+ public const string DefaultPage = "<w:pgSz w:w=\"11906\" w:h=\"16838\"/><w:pgMar w:top=\"1440\" w:right=\"1440\" w:bottom=\"1440\" w:left=\"1440\" w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/>";
+
+ private readonly List<(string Id, string Type, string Target, bool External)> _relationships = [];
+ private readonly Dictionary<string, string> _parts = [];
+ private readonly Dictionary<string, byte[]> _media = [];
+
+ /// <summary>Content of w:body (paragraphs and tables), without the final sectPr.</summary>
+ public StringBuilder Body { get; } = new();
+
+ /// <summary>Children of the body's final w:sectPr.</summary>
+ public string SectionProperties { get; set; } = DefaultPage;
+
+ public string Styles { get; set; } = """
+ <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="맑은 고딕" w:eastAsia="맑은 고딕" w:hAnsi="맑은 고딕"/><w:sz w:val="20"/></w:rPr></w:rPrDefault>
+ <w:pPrDefault><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>
+ <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>
+ <w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:pPr><w:outlineLvl w:val="0"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style>
+ <w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style>
+ <w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:tblPr><w:tblBorders>
+ <w:top w:val="single" w:sz="4" w:color="000000"/><w:left w:val="single" w:sz="4" w:color="000000"/><w:bottom w:val="single" w:sz="4" w:color="000000"/>
+ <w:right w:val="single" w:sz="4" w:color="000000"/><w:insideH w:val="single" w:sz="4" w:color="000000"/><w:insideV w:val="single" w:sz="4" w:color="000000"/>
+ </w:tblBorders></w:tblPr></w:style>
+ """;
+
+ public string? Numbering { get; set; }
+ public string? Settings { get; set; }
+
+ public DocxBuilder Paragraph(string xml)
+ {
+ Body.Append(xml);
+ return this;
+ }
+
+ /// <summary>Adds a PNG and returns its relationship id.</summary>
+ public string Image(byte[] png)
+ {
+ var name = $"media/image{_media.Count + 1}.png";
+ _media["word/" + name] = png;
+ return Relationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", name);
+ }
+
+ public string Hyperlink(string url) =>
+ Relationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", url, external: true);
+
+ /// <summary>Adds a header part (content of w:hdr) and returns its relationship id.</summary>
+ public string Header(string paragraphs) => Part("header", $"<w:hdr {Namespaces}>{paragraphs}</w:hdr>");
+
+ public string Footer(string paragraphs) => Part("footer", $"<w:ftr {Namespaces}>{paragraphs}</w:ftr>");
+
+ /// <summary>Footnotes (w:footnote elements with ids ≥ 1; the separators are added).</summary>
+ public void Footnotes(string notes) =>
+ Part("footnotes", $"<w:footnotes {Namespaces}><w:footnote w:type=\"separator\" w:id=\"-1\"><w:p><w:r><w:separator/></w:r></w:p></w:footnote>{notes}</w:footnotes>");
+
+ public string Save(string path)
+ {
+ if (Numbering is not null)
+ Part("numbering", $"<w:numbering {Namespaces}>{Numbering}</w:numbering>");
+ if (Settings is not null)
+ Part("settings", $"<w:settings {Namespaces}>{Settings}</w:settings>");
+ Part("styles", $"<w:styles {Namespaces}>{Styles}</w:styles>");
+
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ void Write(string name, string text)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(name).Open(), new UTF8Encoding(false));
+ writer.Write(text);
+ }
+
+ var overrides = string.Concat(_parts.Keys.Select(p => $"<Override PartName=\"/word/{p}\" ContentType=\"{ContentType(p)}\"/>"));
+ Write("[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\"/>" +
+ "<Default Extension=\"png\" ContentType=\"image/png\"/>" +
+ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/>" +
+ overrides + "</Types>");
+ Write("_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=\"word/document.xml\"/></Relationships>");
+ Write("word/_rels/document.xml.rels",
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
+ string.Concat(_relationships.Select(r => $"<Relationship Id=\"{r.Id}\" Type=\"{r.Type}\" Target=\"{System.Security.SecurityElement.Escape(r.Target)}\"{(r.External ? " TargetMode=\"External\"" : "")}/>")) +
+ "</Relationships>");
+ Write("word/document.xml",
+ $"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><w:document {Namespaces}><w:body>{Body}<w:sectPr>{SectionProperties}</w:sectPr></w:body></w:document>");
+ foreach (var (name, xml) in _parts)
+ Write("word/" + name, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + xml);
+ foreach (var (name, bytes) in _media)
+ {
+ using var stream = zip.CreateEntry(name).Open();
+ stream.Write(bytes);
+ }
+ return path;
+ }
+
+ private string Part(string kind, string xml)
+ {
+ var name = kind is "header" or "footer" ? $"{kind}{_parts.Keys.Count(k => k.StartsWith(kind, StringComparison.Ordinal)) + 1}.xml" : $"{kind}.xml";
+ _parts[name] = xml;
+ return Relationship($"http://schemas.openxmlformats.org/officeDocument/2006/relationships/{kind}", name);
+ }
+
+ private string Relationship(string type, string target, bool external = false)
+ {
+ var id = $"rId{_relationships.Count + 10}";
+ _relationships.Add((id, type, target, external));
+ return id;
+ }
+
+ private static string ContentType(string part) => part switch
+ {
+ "styles.xml" => "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
+ "numbering.xml" => "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
+ "settings.xml" => "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
+ "footnotes.xml" => "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
+ _ when part.StartsWith("header", StringComparison.Ordinal) => "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
+ _ => "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
+ };
+
+ // ───────── snippets ─────────
+
+ public static string P(string runs, string pPr = "") => $"<w:p><w:pPr>{pPr}</w:pPr>{runs}</w:p>";
+
+ public static string R(string text, string rPr = "") => $"<w:r><w:rPr>{rPr}</w:rPr><w:t xml:space=\"preserve\">{System.Security.SecurityElement.Escape(text)}</w:t></w:r>";
+
+ /// <summary>A complex field (PAGE, NUMPAGES ...) with a cached result.</summary>
+ public static string Field(string instruction, string result) =>
+ $"<w:r><w:fldChar w:fldCharType=\"begin\"/></w:r><w:r><w:instrText xml:space=\"preserve\"> {instruction} </w:instrText></w:r>" +
+ $"<w:r><w:fldChar w:fldCharType=\"separate\"/></w:r>{R(result)}<w:r><w:fldChar w:fldCharType=\"end\"/></w:r>";
+
+ /// <summary>A floating DrawingML object (wp:anchor) around <paramref name="graphic"/> (a:graphicData content).</summary>
+ public static string Anchor(string graphicUri, string graphic, long cx, long cy, string horizontal, string vertical, string wrap = "<wp:wrapSquare wrapText=\"bothSides\"/>") =>
+ $"<w:r><w:drawing><wp:anchor distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\" simplePos=\"0\" relativeHeight=\"1\" behindDoc=\"0\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">" +
+ $"<wp:simplePos x=\"0\" y=\"0\"/>{horizontal}{vertical}<wp:extent cx=\"{cx}\" cy=\"{cy}\"/>{wrap}<wp:docPr id=\"1\" name=\"obj\"/>" +
+ $"<a:graphic><a:graphicData uri=\"{graphicUri}\">{graphic}</a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>";
+
+ public static string Picture(string relationshipId, long cx, long cy) =>
+ $"<pic:pic><pic:nvPicPr><pic:cNvPr id=\"1\" name=\"p\"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed=\"{relationshipId}\"/></pic:blipFill>" +
+ $"<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"rect\"/></pic:spPr></pic:pic>";
+
+ public static string InlinePicture(string relationshipId, long cx, long cy) =>
+ $"<w:r><w:drawing><wp:inline><wp:extent cx=\"{cx}\" cy=\"{cy}\"/><wp:docPr id=\"2\" name=\"i\"/><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
+ Picture(relationshipId, cx, cy) + "</a:graphicData></a:graphic></wp:inline></w:drawing></w:r>";
+
+ public const string PictureUri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
+ public const string ShapeUri = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape";
+}
diff --git a/tests/Filee.Engines.Tests/DocxToHwpxTests.cs b/tests/Filee.Engines.Tests/DocxToHwpxTests.cs
new file mode 100644
index 00000000..a972d884
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxToHwpxTests.cs
@@ -0,0 +1,309 @@
+// DOCX → HWPX with the built-in reader and writer: layout that Pandoc-based conversion loses (page setup,
+// headers/footers, columns, sections, text boxes, shapes, floating pictures, formatting, table borders) must
+// arrive in the OWPML structure 한글 uses. Every file is also checked for package validity and rendered by rhwp.
+
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+using static Filee.Engines.Tests.DocxBuilder;
+using static Filee.Engines.Tests.HwpxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class DocxToHwpxTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private async Task<string> ConvertAsync(DocxBuilder docx, string name, int? expectImages = 0)
+ {
+ var path = docx.Save(Path.Combine(fx.NewFolder(), name + ".docx"));
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = "hwpx" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ var hwpx = job.Outputs.Single();
+ ValidPackage(hwpx, expectImages);
+ await ReadableByH2OrestartAsync(fx, hwpx);
+ return hwpx;
+ }
+
+ private static int Int(XElement element, string attribute) => (int)element.Attribute(attribute)!;
+
+ [Fact]
+ public async Task Page_setup_headers_footers_and_page_numbers()
+ {
+ var docx = new DocxBuilder();
+ var header = docx.Header(P(R("머리말 제목"), "<w:jc w:val=\"right\"/>"));
+ var footer = docx.Footer(P(R("- ") + Field("PAGE", "1") + R(" / ") + Field("NUMPAGES", "3") + R(" -"), "<w:jc w:val=\"center\"/>"));
+ docx.Paragraph(P(R("가로 방향 본문")));
+ docx.SectionProperties =
+ $"<w:headerReference w:type=\"default\" r:id=\"{header}\"/><w:footerReference w:type=\"default\" r:id=\"{footer}\"/>" +
+ "<w:pgSz w:w=\"16838\" w:h=\"11906\" w:orient=\"landscape\"/>" +
+ "<w:pgMar w:top=\"1985\" w:right=\"1134\" w:bottom=\"1418\" w:left=\"1134\" w:header=\"851\" w:footer=\"851\" w:gutter=\"0\"/><w:titlePg/>";
+
+ var hwpx = await ConvertAsync(docx, "page-setup");
+ var section = Xml(hwpx);
+
+ // Landscape: portrait-sized sheet turned by "NARROWLY".
+ var pagePr = section.Descendants(Hp + "pagePr").Single();
+ Assert.Equal("NARROWLY", (string?)pagePr.Attribute("landscape"));
+ Assert.Equal((11906 * 5, 16838 * 5), (Int(pagePr, "width"), Int(pagePr, "height")));
+ // Word measures the body from the paper edge; 한글 stacks header area on top of the top margin.
+ var margin = pagePr.Element(Hp + "margin")!;
+ Assert.Equal(851 * 5, Int(margin, "top"));
+ Assert.Equal((1985 - 851) * 5, Int(margin, "header"));
+ Assert.Equal(851 * 5, Int(margin, "bottom"));
+ Assert.Equal((1418 - 851) * 5, Int(margin, "footer"));
+ Assert.Equal(1134 * 5, Int(margin, "left"));
+
+ var headerControl = section.Descendants(Hp + "header").Single();
+ Assert.Equal("BOTH", (string?)headerControl.Attribute("applyPageType"));
+ Assert.Contains("머리말 제목", headerControl.Value);
+ var footerControl = section.Descendants(Hp + "footer").Single();
+ var numbers = footerControl.Descendants(Hp + "autoNum").Select(a => (string?)a.Attribute("numType")).ToList();
+ Assert.Equal(["PAGE", "TOTAL_PAGE"], numbers);
+ Assert.DoesNotContain("3", string.Concat(footerControl.Descendants(Hp + "t").Select(t => t.Value))); // cached field results are dropped
+
+ // "Different first page" without a first-page header hides header and footer on page 1.
+ var visibility = section.Descendants(Hp + "visibility").Single();
+ Assert.Equal(("1", "1"), ((string?)visibility.Attribute("hideFirstHeader"), (string?)visibility.Attribute("hideFirstFooter")));
+ RenderWithRhwp(fx, hwpx, "docx-page-setup");
+ }
+
+ [Fact]
+ public async Task Columns_change_within_a_section_and_new_paper_starts_a_new_section()
+ {
+ var docx = new DocxBuilder()
+ .Paragraph(P(R("한 단 본문")))
+ .Paragraph(P(R("첫 구역 끝"), $"<w:sectPr>{DefaultPage}</w:sectPr>"))
+ .Paragraph(P(R("두 단 왼쪽")))
+ .Paragraph(P(R("두 단 끝"), $"<w:sectPr><w:type w:val=\"continuous\"/>{DefaultPage}<w:cols w:num=\"2\" w:space=\"720\" w:sep=\"1\"/></w:sectPr>"))
+ .Paragraph(P(R("레터 용지")));
+ docx.SectionProperties = "<w:type w:val=\"nextPage\"/><w:pgSz w:w=\"12240\" w:h=\"15840\"/><w:pgMar w:top=\"1440\" w:right=\"1440\" w:bottom=\"1440\" w:left=\"1440\" w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/>";
+
+ var hwpx = await ConvertAsync(docx, "sections");
+
+ var first = Xml(hwpx);
+ var columnChange = ParagraphWith(first, "두 단 왼쪽").Descendants(Hp + "colPr").Single();
+ Assert.Equal((2, 3600), (Int(columnChange, "colCount"), Int(columnChange, "sameGap")));
+ Assert.NotNull(columnChange.Element(Hp + "colLine"));
+ Assert.Equal(1, Int(first.Descendants(Hp + "colPr").First(), "colCount"));
+
+ var second = Xml(hwpx, "Contents/section1.xml");
+ var pagePr = second.Descendants(Hp + "pagePr").Single();
+ Assert.Equal(("WIDELY", 61200, 79200), ((string)pagePr.Attribute("landscape")!, Int(pagePr, "width"), Int(pagePr, "height")));
+ Assert.Contains("레터 용지", second.Value);
+ Assert.Equal(2, RenderWithRhwp(fx, hwpx, "docx-sections") ?? 2);
+ }
+
+ [Fact]
+ public async Task Paragraph_and_character_formatting_lists_and_document_grid()
+ {
+ var docx = new DocxBuilder
+ {
+ Numbering = """
+ <w:abstractNum w:abstractNumId="1">
+ <w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="400" w:hanging="400"/></w:pPr></w:lvl>
+ <w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="ganada"/><w:lvlText w:val="%2)"/><w:pPr><w:ind w:left="800" w:hanging="400"/></w:pPr></w:lvl>
+ </w:abstractNum>
+ <w:abstractNum w:abstractNumId="2"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="&#xF0B7;"/><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol"/></w:rPr></w:lvl></w:abstractNum>
+ <w:num w:numId="1"><w:abstractNumId w:val="1"/></w:num>
+ <w:num w:numId="2"><w:abstractNumId w:val="2"/></w:num>
+ """,
+ SectionProperties = DefaultPage + "<w:docGrid w:type=\"lines\" w:linePitch=\"360\"/>",
+ };
+ docx.Paragraph(P(R("가운데 제목"), "<w:pStyle w:val=\"Heading1\"/><w:jc w:val=\"center\"/>"))
+ .Paragraph(P(R("굵은 빨강", "<w:b/><w:color w:val=\"FF0000\"/><w:sz w:val=\"28\"/><w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Arial\" w:eastAsia=\"굴림\"/>") +
+ R(" 형광펜", "<w:highlight w:val=\"yellow\"/>") + R(" 무늬", "<w:shd w:val=\"pct25\" w:color=\"auto\" w:fill=\"auto\"/>"),
+ "<w:ind w:left=\"720\" w:hanging=\"360\"/><w:spacing w:before=\"240\" w:after=\"120\"/>"))
+ .Paragraph(P(R("첫 항목"), "<w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"1\"/></w:numPr>"))
+ .Paragraph(P(R("하위 항목"), "<w:numPr><w:ilvl w:val=\"1\"/><w:numId w:val=\"1\"/></w:numPr>"))
+ .Paragraph(P(R("글머리 항목"), "<w:numPr><w:ilvl w:val=\"0\"/><w:numId w:val=\"2\"/></w:numPr>"))
+ .Paragraph(P(R("2") + R("016-06-15")));
+
+ var hwpx = await ConvertAsync(docx, "formatting");
+ var section = Xml(hwpx);
+ var head = Xml(hwpx, "Contents/header.xml");
+ XElement ParaPr(XElement paragraph) => head.Descendants(Hh + "paraPr").Single(p => (string?)p.Attribute("id") == (string?)paragraph.Attribute("paraPrIDRef"));
+ XElement CharPr(XElement run) => head.Descendants(Hh + "charPr").Single(c => (string?)c.Attribute("id") == (string?)run.Attribute("charPrIDRef"));
+ int Margin(XElement paraPr, string branch, string name) =>
+ (int)paraPr.Descendants(Hp + branch).Single().Descendants(Hc + name).Single().Attribute("value")!;
+
+ var title = ParagraphWith(section, "가운데 제목");
+ var headingStyle = head.Descendants(Hh + "style").Single(s => (string?)s.Attribute("engName") == "Heading 1");
+ Assert.Equal((string?)headingStyle.Attribute("id"), (string?)title.Attribute("styleIDRef"));
+ Assert.Equal("CENTER", (string?)ParaPr(title).Element(Hh + "align")!.Attribute("horizontal"));
+
+ var red = CharPr(RunWith(section, "굵은 빨강"));
+ Assert.Equal(("1400", "#FF0000"), ((string)red.Attribute("height")!, (string)red.Attribute("textColor")!));
+ Assert.NotNull(red.Element(Hh + "bold"));
+ string Font(string language) =>
+ (string)head.Descendants(Hh + "fontface").Single(f => (string?)f.Attribute("lang") == language)
+ .Elements(Hh + "font").Single(f => (string?)f.Attribute("id") == (string?)red.Element(Hh + "fontRef")!.Attribute(language.ToLowerInvariant())).Attribute("face")!;
+ Assert.Equal(("Arial", "굴림"), (Font("LATIN"), Font("HANGUL")));
+ Assert.Equal("#FFFF00", (string?)CharPr(RunWith(section, "형광펜")).Attribute("shadeColor"));
+ Assert.Equal("#BFBFBF", (string?)CharPr(RunWith(section, "무늬")).Attribute("shadeColor")); // 25% black on white
+
+ // Hanging indent (Word: text at 0.5", first line at 0.25"). 한글 keeps a hanging paragraph's first line at
+ // "left" and indents the rest, so left is the first-line position. hp:default repeats the values doubled.
+ var indented = ParaPr(ParagraphWith(section, "굵은 빨강"));
+ Assert.Equal((1800, -1800, 1200, 600), (Margin(indented, "case", "left"), Margin(indented, "case", "intent"), Margin(indented, "case", "prev"), Margin(indented, "case", "next")));
+ Assert.Equal((3600, -3600), (Margin(indented, "default", "left"), Margin(indented, "default", "intent")));
+
+ // Word's 18 pt document grid: 10 pt lines become 18 pt, 14 pt lines need two grid lines.
+ var gridLine = ParaPr(ParagraphWith(section, "첫 항목")).Descendants(Hp + "case").Single().Element(Hh + "lineSpacing")!;
+ Assert.Equal(("AT_LEAST", 1800), ((string)gridLine.Attribute("type")!, Int(gridLine, "value")));
+ Assert.Equal(3600, Int(indented.Descendants(Hp + "case").Single().Element(Hh + "lineSpacing")!, "value"));
+
+ // Lists: Word levels map to 한글 numbering levels; bullets use a symbol instead of a counter.
+ var item = ParaPr(ParagraphWith(section, "첫 항목")).Element(Hh + "heading")!;
+ var subItem = ParaPr(ParagraphWith(section, "하위 항목")).Element(Hh + "heading")!;
+ Assert.Equal(("NUMBER", 0, 1), ((string)item.Attribute("type")!, Int(item, "level"), Int(subItem, "level")));
+ var numbering = head.Descendants(Hh + "numbering").Single(n => (string?)n.Attribute("id") == (string?)item.Attribute("idRef"));
+ var levels = numbering.Elements(Hh + "paraHead").Take(2).Select(h => ((string?)h.Attribute("numFormat"), h.Value)).ToList();
+ Assert.Equal([("DIGIT", "^1."), ("HANGUL_SYLLABLE", "^2)")], levels);
+ var bullet = ParaPr(ParagraphWith(section, "글머리 항목")).Element(Hh + "heading")!;
+ Assert.Equal("●", head.Descendants(Hh + "numbering").Single(n => (string?)n.Attribute("id") == (string?)bullet.Attribute("idRef")).Elements(Hh + "paraHead").First().Value);
+
+ // Runs split by Word but formatted alike become one text run.
+ Assert.Contains(section.Descendants(Hp + "t"), t => t.Value == "2016-06-15");
+ RenderWithRhwp(fx, hwpx, "docx-formatting");
+ }
+
+ [Fact]
+ public async Task Tables_keep_merged_cells_borders_and_shading()
+ {
+ var cell = (string content, string tcPr) => $"<w:tc><w:tcPr>{tcPr}</w:tcPr>{P(R(content))}</w:tc>";
+ var docx = new DocxBuilder().Paragraph(
+ "<w:tbl><w:tblPr><w:tblStyle w:val=\"TableGrid\"/><w:jc w:val=\"center\"/></w:tblPr>" +
+ "<w:tblGrid><w:gridCol w:w=\"2000\"/><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"2000\"/></w:tblGrid>" +
+ "<w:tr><w:trPr><w:tblHeader/></w:trPr>" + cell("가로 병합", "<w:gridSpan w:val=\"2\"/><w:shd w:val=\"pct10\" w:color=\"auto\" w:fill=\"auto\"/>") +
+ cell("세로 병합", "<w:vMerge w:val=\"restart\"/><w:vAlign w:val=\"center\"/>") + "</w:tr>" +
+ "<w:tr>" + cell("A", "") + cell("B", "") + cell("", "<w:vMerge/>") + "</w:tr>" +
+ "<w:tr>" + cell("C", "<w:tcBorders><w:bottom w:val=\"double\" w:sz=\"12\" w:color=\"FF0000\"/></w:tcBorders>") + cell("D", "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"FFF2CC\"/>") + cell("E", "") + "</w:tr>" +
+ "</w:tbl>" + P(""));
+
+ var hwpx = await ConvertAsync(docx, "table");
+ var section = Xml(hwpx);
+ var table = section.Descendants(Hp + "tbl").Single();
+ Assert.Equal((3, 3, "1"), (Int(table, "rowCnt"), Int(table, "colCnt"), (string?)table.Attribute("repeatHeader")));
+ Assert.Equal("CENTER", (string?)table.Element(Hp + "pos")!.Attribute("horzAlign"));
+
+ var cells = table.Descendants(Hp + "tc").Select(tc => new
+ {
+ Text = tc.Element(Hp + "subList")!.Value,
+ Row = Int(tc.Element(Hp + "cellAddr")!, "rowAddr"),
+ Column = Int(tc.Element(Hp + "cellAddr")!, "colAddr"),
+ RowSpan = Int(tc.Element(Hp + "cellSpan")!, "rowSpan"),
+ ColSpan = Int(tc.Element(Hp + "cellSpan")!, "colSpan"),
+ Width = Int(tc.Element(Hp + "cellSz")!, "width"),
+ BorderFill = HeadItem(hwpx, "borderFill", (string)tc.Attribute("borderFillIDRef")!),
+ VerticalAlign = (string?)tc.Element(Hp + "subList")!.Attribute("vertAlign"),
+ }).ToList();
+ // Every grid position is covered exactly once.
+ var covered = cells.SelectMany(c => Enumerable.Range(c.Row, c.RowSpan).SelectMany(r => Enumerable.Range(c.Column, c.ColSpan).Select(col => (r, col)))).ToList();
+ Assert.Equal(9, covered.Distinct().Count());
+ Assert.Equal(9, covered.Count);
+
+ var wide = cells.Single(c => c.Text == "가로 병합");
+ Assert.Equal((2, 25000), (wide.ColSpan, wide.Width));
+ Assert.Equal("#E6E6E6", (string?)wide.BorderFill.Descendants(Hc + "winBrush").Single().Attribute("faceColor"));
+ var tall = cells.Single(c => c.Text == "세로 병합");
+ Assert.Equal((2, "CENTER"), (tall.RowSpan, tall.VerticalAlign));
+ var bottom = cells.Single(c => c.Text == "C").BorderFill.Element(Hh + "bottomBorder")!;
+ Assert.Equal(("DOUBLE_SLIM", "#FF0000"), ((string)bottom.Attribute("type")!, (string)bottom.Attribute("color")!));
+ Assert.Equal("SOLID", (string?)cells.Single(c => c.Text == "A").BorderFill.Element(Hh + "leftBorder")!.Attribute("type"));
+ Assert.Equal("#FFF2CC", (string?)cells.Single(c => c.Text == "D").BorderFill.Descendants(Hc + "winBrush").Single().Attribute("faceColor"));
+ RenderWithRhwp(fx, hwpx, "docx-table");
+ }
+
+ [Fact]
+ public async Task Text_boxes_shapes_and_floating_pictures()
+ {
+ var docx = new DocxBuilder();
+ using var image = new MagickImage(MagickColors.MediumPurple, 120, 60);
+ var picture = docx.Image(image.ToByteArray(MagickFormat.Png));
+ const string Column = "<wp:positionH relativeFrom=\"column\"><wp:posOffset>0</wp:posOffset></wp:positionH>";
+ const string Paragraph = "<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>0</wp:posOffset></wp:positionV>";
+ string Shape(string geometry, string fill, string line, long cx, long cy, string text = "") =>
+ $"<wps:wsp><wps:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{cx}\" cy=\"{cy}\"/></a:xfrm><a:prstGeom prst=\"{geometry}\"/>{fill}{line}</wps:spPr>" +
+ (text.Length > 0 ? $"<wps:txbx><w:txbxContent>{P(R(text))}</w:txbxContent></wps:txbx>" : "") + "<wps:bodyPr anchor=\"ctr\"/></wps:wsp>";
+
+ docx.Paragraph(P(Anchor(PictureUri, Picture(picture, 914400, 457200), 914400, 457200,
+ "<wp:positionH relativeFrom=\"page\"><wp:posOffset>914400</wp:posOffset></wp:positionH>", Paragraph) + R("그림 옆에 흐르는 글")))
+ .Paragraph(P(InlinePicture(picture, 457200, 457200)))
+ .Paragraph(P(Anchor(PictureUri, Picture(picture, 457200, 457200), 457200, 457200,
+ "<wp:positionH relativeFrom=\"margin\"><wp:posOffset>-635000</wp:posOffset></wp:positionH>",
+ "<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>-127000</wp:posOffset></wp:positionV>") + R("여백으로 나간 그림")))
+ .Paragraph(P(Anchor(ShapeUri,
+ Shape("rect", "<a:solidFill><a:srgbClr val=\"FFF2CC\"/></a:solidFill>", "<a:ln w=\"12700\"><a:solidFill><a:srgbClr val=\"C00000\"/></a:solidFill></a:ln>", 1828800, 914400, "글상자 안의 글"),
+ 1828800, 914400, "<wp:positionH relativeFrom=\"margin\"><wp:align>center</wp:align></wp:positionH>",
+ "<wp:positionV relativeFrom=\"page\"><wp:posOffset>3600000</wp:posOffset></wp:positionV>", "<wp:wrapTopAndBottom/>")))
+ .Paragraph(P(Anchor(ShapeUri, Shape("line", "", "<a:ln w=\"25400\"><a:solidFill><a:srgbClr val=\"4F81BD\"/></a:solidFill></a:ln>", 3000000, 0),
+ 3000000, 0, Column, Paragraph, "<wp:wrapNone/>")))
+ .Paragraph(P(Anchor(ShapeUri,
+ Shape("rect", "<a:gradFill><a:gsLst><a:gs pos=\"0\"><a:srgbClr val=\"99CCFF\"/></a:gs><a:gs pos=\"100000\"><a:srgbClr val=\"FFFFFF\"/></a:gs></a:gsLst><a:lin ang=\"0\"/></a:gradFill>", "<a:ln><a:noFill/></a:ln>", 2000000, 180000),
+ 2000000, 180000, Column, Paragraph, "<wp:wrapNone/>")));
+
+ var hwpx = await ConvertAsync(docx, "objects", expectImages: 1); // one picture used twice is stored once
+ var section = Xml(hwpx);
+
+ var pictures = section.Descendants(Hp + "pic").ToList();
+ var floating = pictures.Single(p => (string?)p.Element(Hp + "pos")!.Attribute("treatAsChar") == "0" && Int(p.Element(Hp + "pos")!, "horzOffset") == 7200);
+ Assert.Equal(("SQUARE", "PAPER", 7200), ((string)floating.Attribute("textWrap")!, (string)floating.Element(Hp + "pos")!.Attribute("horzRelTo")!, Int(floating.Element(Hp + "pos")!, "horzOffset")));
+ Assert.Single(pictures, p => (string?)p.Element(Hp + "pos")!.Attribute("treatAsChar") == "1");
+ // Negative offsets are not allowed in 한글 files: into the margin → measured from the paper edge instead.
+ var outside = pictures.Single(p => (string?)p.Element(Hp + "pos")!.Attribute("horzRelTo") == "PAPER" && Int(p.Element(Hp + "pos")!, "horzOffset") != 7200).Element(Hp + "pos")!;
+ Assert.Equal((1440 * 5 - 5000, 0), (Int(outside, "horzOffset"), Int(outside, "vertOffset")));
+ Assert.DoesNotContain(section.Descendants(Hp + "pos"), p => Int(p, "horzOffset") < 0 || Int(p, "vertOffset") < 0);
+
+ var textBox = section.Descendants(Hp + "rect").Single(r => r.Element(Hp + "drawText") is not null);
+ Assert.Contains("글상자 안의 글", textBox.Element(Hp + "drawText")!.Value);
+ Assert.Equal("CENTER", (string?)textBox.Descendants(Hp + "subList").First().Attribute("vertAlign"));
+ Assert.Equal("#FFF2CC", (string?)textBox.Descendants(Hc + "winBrush").Single().Attribute("faceColor"));
+ Assert.Equal(("#C00000", 100), ((string)textBox.Element(Hp + "lineShape")!.Attribute("color")!, Int(textBox.Element(Hp + "lineShape")!, "width")));
+ var position = textBox.Element(Hp + "pos")!;
+ Assert.Equal(("PAGE", "CENTER", "PAPER", 28346), ((string)position.Attribute("horzRelTo")!, (string)position.Attribute("horzAlign")!, (string)position.Attribute("vertRelTo")!, Int(position, "vertOffset")));
+ Assert.Equal("TOP_AND_BOTTOM", (string?)textBox.Attribute("textWrap"));
+
+ var line = section.Descendants(Hp + "line").Single();
+ Assert.Equal(23622, Int(line.Element(Hc + "endPt")!, "x"));
+ Assert.Equal("#4F81BD", (string?)line.Element(Hp + "lineShape")!.Attribute("color"));
+ var gradient = section.Descendants(Hp + "rect").Single(r => r.Element(Hp + "drawText") is null).Descendants(Hc + "gradation").Single();
+ Assert.Equal(["#99CCFF", "#FFFFFF"], gradient.Elements(Hc + "color").Select(c => (string)c.Attribute("value")!));
+ RenderWithRhwp(fx, hwpx, "docx-objects");
+ }
+
+ [Fact]
+ public async Task Notes_links_bookmarks_and_page_breaks()
+ {
+ var docx = new DocxBuilder();
+ docx.Footnotes("<w:footnote w:id=\"1\"><w:p><w:r><w:footnoteRef/></w:r>" + R(" 각주 설명") + "</w:p></w:footnote>");
+ var url = docx.Hyperlink("https://example.com/a?b=1");
+ docx.Paragraph(P("<w:bookmarkStart w:id=\"0\" w:name=\"intro\"/>" + R("소개") + "<w:bookmarkEnd w:id=\"0\"/>", "<w:pStyle w:val=\"Heading1\"/>"))
+ .Paragraph(P(R("본문") + "<w:r><w:footnoteReference w:id=\"1\"/></w:r>" +
+ $"<w:hyperlink r:id=\"{url}\">" + R("웹 링크", "<w:rStyle w:val=\"Hyperlink\"/>") + "</w:hyperlink>" +
+ "<w:hyperlink w:anchor=\"intro\">" + R("소개로 이동") + "</w:hyperlink>"))
+ .Paragraph(P(R("앞 쪽") + "<w:r><w:br w:type=\"page\"/></w:r>" + R("다음 쪽")));
+
+ var hwpx = await ConvertAsync(docx, "notes-links");
+ var section = Xml(hwpx);
+
+ // The note number is an autoNum control at the start of the note's first paragraph.
+ var note = section.Descendants(Hp + "footNote").Single();
+ var firstRun = note.Descendants(Hp + "p").First().Elements(Hp + "run").First();
+ Assert.Equal("FOOTNOTE", (string?)firstRun.Descendants(Hp + "autoNum").Single().Attribute("numType"));
+ Assert.Contains("각주 설명", note.Value);
+
+ string Parameter(XElement field, string name) => field.Descendants().Single(p => (string?)p.Attribute("name") == name).Value;
+ var links = section.Descendants(Hp + "fieldBegin").ToList();
+ var web = links.Single(l => Parameter(l, "Category") == "HWPHYPERLINK_TYPE_URL");
+ Assert.Equal("https\\://example.com/a\\?b=1;1;0;0;", Parameter(web, "Command"));
+ Assert.Equal("https://example.com/a?b=1", Parameter(web, "Path"));
+ var bookmarkLink = links.Single(l => Parameter(l, "Category") == "HWPHYPERLINK_TYPE_HWP");
+ Assert.Equal("?intro;0;0;0;", Parameter(bookmarkLink, "Command"));
+ Assert.Equal("intro", (string?)section.Descendants(Hp + "bookmark").Single().Attribute("name"));
+ Assert.Equal(2, section.Descendants(Hp + "fieldEnd").Count());
+
+ Assert.Equal("1", (string?)ParagraphWith(section, "다음 쪽").Attribute("pageBreak"));
+ Assert.Equal("0", (string?)ParagraphWith(section, "앞 쪽").Attribute("pageBreak"));
+ Assert.Equal(2, RenderWithRhwp(fx, hwpx, "docx-notes-links") ?? 2);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/EngineFixture.cs b/tests/Filee.Engines.Tests/EngineFixture.cs
new file mode 100644
index 00000000..516394a1
--- /dev/null
+++ b/tests/Filee.Engines.Tests/EngineFixture.cs
@@ -0,0 +1,82 @@
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+using Filee.Engines;
+using Filee.Engines.Infrastructure;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+/// <summary>Real engines + a temp folder with generated sample files.</summary>
+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();
+ Catalog = new ConverterCatalog(Converters) { Priority = new AppSettings().EnginePriority };
+ }
+
+ public string Root { get; } = Path.Combine(Path.GetTempPath(), "filee-engine-tests", Guid.NewGuid().ToString("N")[..8]);
+ public IReadOnlyList<IConverter> Converters { get; }
+ public ConverterCatalog Catalog { get; }
+
+ /// <summary>Writes a small 한글 document with the built-in HWPX writer (no external engine needed).</summary>
+ public async Task<string> MakeHwpxAsync(string folder)
+ {
+ var txt = Path.Combine(folder, "sample.txt");
+ await File.WriteAllTextAsync(txt, "Filee 한글 문서 테스트\n\n두 번째 문단입니다. 文件转换 Hello");
+ var job = await ConvertAsync([txt], new Preset { TargetFormat = "hwpx" });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ /// <summary>Creates a fresh sub folder for one test.</summary>
+ public string NewFolder()
+ {
+ var dir = Path.Combine(Root, Guid.NewGuid().ToString("N")[..6]);
+ Directory.CreateDirectory(dir);
+ return dir;
+ }
+
+ /// <summary>Writes a 320×200 gradient image with a transparent corner in the given format.</summary>
+ public static string MakeImage(string folder, string name, MagickFormat format, uint width = 320, uint height = 200)
+ {
+ using var image = new MagickImage("gradient:#7F77DD-#1D9E75", width, height);
+ image.Alpha(AlphaOption.Set);
+ // Punch a fully transparent 40×40 hole in the top-left corner (RGBA = 0).
+ using (var pixels = image.GetPixels())
+ pixels.SetArea(0, 0, 40, 40, new byte[40 * 40 * image.ChannelCount]);
+ var path = Path.Combine(folder, name);
+ image.Write(path, format);
+ return path;
+ }
+
+ /// <summary>Writes a multi-page TIFF.</summary>
+ public static string MakeMultiPageTiff(string folder, int pages)
+ {
+ using var collection = new MagickImageCollection();
+ for (var i = 0; i < pages; i++)
+ collection.Add(new MagickImage(i % 2 == 0 ? MagickColors.Coral : MagickColors.Teal, 120, 80));
+ var path = Path.Combine(folder, "pages.tiff");
+ collection.Write(path, MagickFormat.Tiff);
+ return path;
+ }
+
+ public async Task<ConversionJob> ConvertAsync(IReadOnlyList<string> sources, Preset preset)
+ {
+ await using var queue = new JobQueue(Catalog, EngineRegistry.FindPdfMerger(Converters));
+ var job = new ConversionJob(sources, preset, preset.Name);
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ public void Dispose()
+ {
+ try { Directory.Delete(Root, true); } catch (IOException) { }
+ }
+}
diff --git a/tests/Filee.Engines.Tests/EngineInstallerTests.cs b/tests/Filee.Engines.Tests/EngineInstallerTests.cs
new file mode 100644
index 00000000..be0133de
--- /dev/null
+++ b/tests/Filee.Engines.Tests/EngineInstallerTests.cs
@@ -0,0 +1,179 @@
+// Optional engine downloads without the network: a fake HTTP handler serves generated archives.
+
+using System.IO.Compression;
+using System.Net;
+using System.Security.Cryptography;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Tests;
+
+public sealed class EngineInstallerTests : IDisposable
+{
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "filee-installer-" + Guid.NewGuid().ToString("N")[..8]);
+
+ public void Dispose()
+ {
+ try { Directory.Delete(_root, true); } catch (IOException) { }
+ }
+
+ /// <summary>Serves byte arrays by URL; a string value is a redirect target.</summary>
+ private sealed class FakeServer(Dictionary<string, object> content) : HttpMessageHandler
+ {
+ public List<string> Requests { get; } = [];
+
+ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+ {
+ var url = request.RequestUri!.ToString();
+ Requests.Add(url);
+ var response = content.GetValueOrDefault(url) switch
+ {
+ byte[] bytes => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) },
+ string location => new HttpResponseMessage(HttpStatusCode.Found) { Headers = { Location = new Uri(location) } },
+ _ => new HttpResponseMessage(HttpStatusCode.NotFound),
+ };
+ return Task.FromResult(response);
+ }
+ }
+
+ private static byte[] Zip(params (string Path, string Text)[] files)
+ {
+ using var buffer = new MemoryStream();
+ using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
+ {
+ foreach (var (path, text) in files)
+ {
+ using var writer = new StreamWriter(zip.CreateEntry(path).Open());
+ writer.Write(text);
+ }
+ }
+ return buffer.ToArray();
+ }
+
+ private static EngineComponent Component(string id, string kind, byte[] bytes, string? sha256 = null) =>
+ new(id, "1.0", $"https://example.test/{id}.{kind}", sha256 ?? Convert.ToHexString(SHA256.HashData(bytes)), bytes.Length, kind);
+
+ private EngineInstaller Installer(FakeServer server, params EngineComponent[] components) =>
+ new(new HttpClient(server), _root, components.ToDictionary(c => c.Id));
+
+ [Fact]
+ public async Task Zip_engines_are_verified_unpacked_without_their_top_folder_and_reported()
+ {
+ var archive = Zip(("tool-1.0/tool.exe", "binary"), ("tool-1.0/readme.txt", "hello"));
+ var component = Component("tool", "zip", archive);
+ var server = new FakeServer(new() { [component.Url] = archive });
+ var installer = Installer(server, component);
+ var package = new EnginePackage("tool", ["tool"], 1000, ["tool"]);
+ var reports = new List<EngineInstallProgress>();
+
+ Assert.False(installer.IsInstalled(package));
+ await installer.InstallAsync(package, new SyncProgress(reports.Add), TestContext.Current.CancellationToken);
+
+ Assert.True(File.Exists(Path.Combine(_root, "tool", "tool.exe")));
+ Assert.True(installer.IsInstalled(package));
+ Assert.True(installer.IsUpToDate(package));
+ Assert.Contains(reports, r => r.Stage == EngineInstallStage.Unpacking);
+ Assert.Equal(1.0, reports.Where(r => r.Stage == EngineInstallStage.Downloading).Max(r => r.Fraction), 3);
+ // Nothing is left over from downloading or unpacking.
+ Assert.Equal(["tool"], Directory.GetDirectories(_root).Select(Path.GetFileName).Where(n => !n!.StartsWith(".downloads", StringComparison.Ordinal)));
+ Assert.Empty(Directory.GetFiles(Path.Combine(_root, ".downloads")));
+
+ // An installed, up-to-date package is not downloaded again.
+ await installer.InstallAsync(package, null, TestContext.Current.CancellationToken);
+ Assert.Single(server.Requests);
+
+ installer.Uninstall(package);
+ Assert.False(Directory.Exists(Path.Combine(_root, "tool")));
+ }
+
+ [Fact]
+ public async Task A_download_with_the_wrong_checksum_is_rejected_and_nothing_is_installed()
+ {
+ var archive = Zip(("tool.exe", "binary"));
+ var component = Component("tool", "zip", archive, sha256: new string('0', 64));
+ var installer = Installer(new FakeServer(new() { [component.Url] = archive }), component);
+ var package = new EnginePackage("tool", ["tool"], 1000, ["tool"]);
+
+ var error = await Assert.ThrowsAsync<InvalidDataException>(() => installer.InstallAsync(package, null, TestContext.Current.CancellationToken));
+
+ Assert.Contains("checksum", error.Message);
+ Assert.False(installer.IsInstalled(package));
+ Assert.False(Directory.Exists(Path.Combine(_root, "tool")));
+ Assert.Empty(Directory.GetFiles(Path.Combine(_root, ".downloads")));
+ }
+
+ [Fact]
+ public async Task Redirects_to_plain_http_mirrors_are_followed_because_the_hash_is_checked()
+ {
+ var archive = Zip(("tool.exe", "binary"));
+ var component = Component("tool", "zip", archive);
+ var server = new FakeServer(new()
+ {
+ [component.Url] = "https://example.test/mirror-list",
+ ["https://example.test/mirror-list"] = "http://mirror.example.test/tool.zip",
+ ["http://mirror.example.test/tool.zip"] = archive,
+ });
+ var installer = Installer(server, component);
+
+ await installer.InstallAsync(new EnginePackage("tool", ["tool"], 1, ["tool"]), null, TestContext.Current.CancellationToken);
+
+ Assert.Equal(3, server.Requests.Count);
+ Assert.True(File.Exists(Path.Combine(_root, "tool", "tool.exe")));
+ }
+
+ [Fact]
+ public async Task LibreOffice_extensions_go_into_the_installed_LibreOffice_and_need_it()
+ {
+ var oxt = Zip(("description.xml", "<description/>"), ("H2Orestart.jar", "jar"));
+ var extension = Component("h2orestart", "oxt", oxt);
+ var server = new FakeServer(new() { [extension.Url] = oxt });
+ var installer = Installer(server, extension);
+ var package = new EnginePackage("filter", ["h2orestart"], 1, []);
+
+ await Assert.ThrowsAsync<InvalidOperationException>(() => installer.InstallAsync(package, null, TestContext.Current.CancellationToken));
+
+ Directory.CreateDirectory(Path.Combine(_root, "libreoffice", "share", "extensions"));
+ await installer.InstallAsync(package, null, TestContext.Current.CancellationToken);
+ Assert.True(File.Exists(Path.Combine(_root, "libreoffice", "share", "extensions", "H2Orestart", "H2Orestart.jar")));
+ Assert.True(installer.IsInstalled(package));
+ }
+
+ [Fact]
+ public void LibreOffice_is_trimmed_to_what_headless_conversion_needs()
+ {
+ var root = Path.Combine(_root, "lo");
+ foreach (var folder in new[] { "help", "readmes", "program", "share/gallery", "share/extensions/dict-en", "share/extensions/dict-ko", "share/extensions/dict-fr", "share/extensions/H2Orestart" })
+ Directory.CreateDirectory(Path.Combine(root, folder));
+ File.WriteAllText(Path.Combine(root, "LibreOffice.msi"), "");
+
+ EngineInstaller.TrimLibreOffice(root);
+
+ var remaining = Directory.EnumerateDirectories(root, "*", SearchOption.AllDirectories)
+ .Select(d => Path.GetRelativePath(root, d).Replace('\\', '/')).Order(StringComparer.Ordinal).ToList();
+ Assert.Equal(["program", "share", "share/extensions", "share/extensions/H2Orestart", "share/extensions/dict-en", "share/extensions/dict-ko"], remaining);
+ Assert.Empty(Directory.GetFiles(root));
+ }
+
+ [Fact]
+ public void Every_package_component_is_pinned_in_the_manifest()
+ {
+ foreach (var package in EngineDownloads.Packages)
+ {
+ foreach (var id in package.Components)
+ {
+ var component = EngineDownloads.Components[id];
+ Assert.StartsWith("https://", component.Url);
+ Assert.Matches("^[0-9A-F]{64}$", component.Sha256);
+ Assert.True(component.Size > 0);
+ }
+ Assert.True(EngineDownloads.DownloadSize(package) > 0);
+ }
+ // rhwp is bundled with the installer, but its download is pinned in the same list.
+ Assert.Contains("rhwp", EngineDownloads.Components.Keys);
+ }
+
+ /// <summary>IProgress that reports synchronously (Progress&lt;T&gt; would post to the thread pool).</summary>
+ private sealed class SyncProgress(Action<EngineInstallProgress> report) : IProgress<EngineInstallProgress>
+ {
+ public void Report(EngineInstallProgress value) => report(value);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
new file mode 100644
index 00000000..348333fd
--- /dev/null
+++ b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
@@ -0,0 +1,21 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <IsPackable>false</IsPackable>
+ <IsTestProject>true</IsTestProject>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\src\Filee.Engines\Filee.Engines.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.NET.Test.Sdk" />
+ <PackageReference Include="xunit.v3" />
+ <PackageReference Include="xunit.runner.visualstudio" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Using Include="Xunit" />
+ </ItemGroup>
+</Project>
diff --git a/tests/Filee.Engines.Tests/HwpxAssert.cs b/tests/Filee.Engines.Tests/HwpxAssert.cs
new file mode 100644
index 00000000..28f3af47
--- /dev/null
+++ b/tests/Filee.Engines.Tests/HwpxAssert.cs
@@ -0,0 +1,153 @@
+// Shared checks for HWPX files written by Filee: package structure, id references, and a render with rhwp.
+
+using System.IO.Compression;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Tests;
+
+internal static class HwpxAssert
+{
+ public static readonly XNamespace Hh = "http://www.hancom.co.kr/hwpml/2011/head";
+ public static readonly XNamespace Hp = "http://www.hancom.co.kr/hwpml/2011/paragraph";
+ public static readonly XNamespace Hc = "http://www.hancom.co.kr/hwpml/2011/core";
+
+ /// <summary>
+ /// The package is what 한글 expects: mimetype first and stored, well-formed parts, item counts that match,
+ /// every id reference resolvable, one manifest entry per section and picture.
+ /// </summary>
+ public static void ValidPackage(string hwpx, int? expectImages = null)
+ {
+ // mimetype must be the first entry and stored (compression method 0 in the local file header).
+ using (var raw = File.OpenRead(hwpx))
+ {
+ var header = new byte[38];
+ raw.ReadExactly(header);
+ Assert.Equal(0, BitConverter.ToUInt16(header, 8));
+ Assert.Equal("mimetype", System.Text.Encoding.ASCII.GetString(header, 30, 8));
+ }
+
+ using var zip = ZipFile.OpenRead(hwpx);
+ Assert.Equal("application/hwp+zip", new StreamReader(zip.GetEntry("mimetype")!.Open()).ReadToEnd());
+ foreach (var entry in zip.Entries.Where(e => e.FullName.EndsWith(".xml") || e.FullName.EndsWith(".hpf") || e.FullName.EndsWith(".rdf")))
+ XDocument.Load(entry.Open()); // throws if malformed
+
+ var head = XDocument.Load(zip.GetEntry("Contents/header.xml")!.Open()).Root!;
+ var sectionEntries = zip.Entries.Where(e => e.FullName.StartsWith("Contents/section", StringComparison.Ordinal)).ToList();
+ Assert.Equal(sectionEntries.Count, (int)head.Attribute("secCnt")!);
+ var sections = sectionEntries.Select(e => XDocument.Load(e.Open()).Root!).ToList();
+
+ foreach (var (container, item) in new[] { ("charProperties", "charPr"), ("paraProperties", "paraPr"), ("numberings", "numbering"), ("borderFills", "borderFill"), ("tabProperties", "tabPr") })
+ {
+ var element = head.Descendants(Hh + container).Single();
+ Assert.Equal(element.Elements(Hh + item).Count(), (int)element.Attribute("itemCnt")!);
+ }
+ foreach (var fontface in head.Descendants(Hh + "fontface"))
+ {
+ var count = fontface.Elements(Hh + "font").Count();
+ Assert.Equal(count, (int)fontface.Attribute("fontCnt")!);
+ var language = ((string)fontface.Attribute("lang")!).ToLowerInvariant();
+ Assert.All(head.Descendants(Hh + "fontRef"), r => Assert.InRange((int)r.Attribute(language)!, 0, count - 1));
+ }
+
+ HashSet<string> Ids(string name) => head.Descendants(Hh + name).Select(e => (string)e.Attribute("id")!).ToHashSet();
+ var charIds = Ids("charPr");
+ var paraIds = Ids("paraPr");
+ var numberingIds = Ids("numbering");
+ var borderFillIds = Ids("borderFill");
+ var tabIds = Ids("tabPr");
+ foreach (var section in sections)
+ {
+ Assert.All(section.Descendants(Hp + "run"), r => Assert.Contains((string)r.Attribute("charPrIDRef")!, charIds));
+ Assert.All(section.Descendants(Hp + "p"), p => Assert.Contains((string)p.Attribute("paraPrIDRef")!, paraIds));
+ Assert.All(section.Descendants().Where(e => e.Name.LocalName is "tbl" or "tc"), e => Assert.Contains((string)e.Attribute("borderFillIDRef")!, borderFillIds));
+ // Page setup lives in the first run of each section.
+ Assert.NotNull(section.Descendants(Hp + "run").First().Element(Hp + "secPr"));
+ }
+ Assert.All(head.Descendants(Hh + "heading").Where(h => (string?)h.Attribute("type") == "NUMBER"),
+ h => Assert.Contains((string)h.Attribute("idRef")!, numberingIds));
+ Assert.All(head.Descendants(Hh + "paraPr"), p => Assert.Contains((string)p.Attribute("tabPrIDRef")!, tabIds));
+
+ var manifest = new StreamReader(zip.GetEntry("Contents/content.hpf")!.Open()).ReadToEnd();
+ Assert.All(sectionEntries, s => Assert.Contains(s.FullName, manifest));
+ var images = zip.Entries.Where(e => e.FullName.StartsWith("BinData/", StringComparison.Ordinal)).ToList();
+ if (expectImages is { } expected)
+ Assert.Equal(expected, images.Count);
+ Assert.All(images, i => Assert.Contains(i.FullName, manifest));
+ var imageIds = images.Select(i => Path.GetFileNameWithoutExtension(i.Name)).ToHashSet();
+ foreach (var section in sections)
+ Assert.All(section.Descendants(Hc + "img"), img => Assert.Contains((string)img.Attribute("binaryItemIDRef")!, imageIds));
+ }
+
+ public static XElement Xml(string hwpx, string entry = "Contents/section0.xml")
+ {
+ using var zip = ZipFile.OpenRead(hwpx);
+ return XDocument.Load(zip.GetEntry(entry)!.Open(), LoadOptions.PreserveWhitespace).Root!;
+ }
+
+ /// <summary>The header element with the given id.</summary>
+ public static XElement HeadItem(string hwpx, string name, string id) =>
+ Xml(hwpx, "Contents/header.xml").Descendants(Hh + name).Single(e => (string?)e.Attribute("id") == id);
+
+ /// <summary>The paragraph containing <paramref name="text"/>.</summary>
+ public static XElement ParagraphWith(XElement root, string text) =>
+ root.Descendants(Hp + "p").Last(p => p.Elements(Hp + "run").Elements(Hp + "t").Any(t => t.Value.Contains(text, StringComparison.Ordinal)));
+
+ /// <summary>The run whose own text contains <paramref name="text"/>.</summary>
+ public static XElement RunWith(XElement root, string text) =>
+ root.Descendants(Hp + "run").First(r => r.Elements(Hp + "t").Any(t => t.Value.Contains(text, StringComparison.Ordinal)));
+
+ /// <summary>Renders with rhwp (independent HWPX engine) when available and keeps a PNG of page 1 for review.</summary>
+ /// <returns>Number of pages, or null when rhwp is not available.</returns>
+ public static int? RenderWithRhwp(EngineFixture fx, string hwpx, string name)
+ {
+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");
+ // The PNG preview uses PDFium, which the analyzer only knows for desktop/mobile platforms.
+ if (!fx.Catalog.StatusOf(rhwp).IsAvailable || !OperatingSystem.IsWindows())
+ return null;
+ var pdf = Path.Combine(Path.GetDirectoryName(hwpx)!, name + ".pdf");
+ var written = rhwp.ConvertAsync(new ConversionStep(hwpx, "hwpx", "pdf", new Preset(), new FixedPath(pdf), Path.GetDirectoryName(hwpx)!),
+ null, TestContext.Current.CancellationToken).GetAwaiter().GetResult();
+ Assert.True(new FileInfo(written.Single()).Length > 1000);
+
+ var shots = Path.Combine(AppContext.BaseDirectory, "hwpx-renders");
+ Directory.CreateDirectory(shots);
+ var bytes = File.ReadAllBytes(pdf);
+ using var page = PDFtoImage.Conversion.ToImage(bytes, 0, null, new PDFtoImage.RenderOptions(Dpi: 72));
+ using var data = page.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100);
+ File.WriteAllBytes(Path.Combine(shots, name + ".png"), data.ToArray());
+ return PDFtoImage.Conversion.GetPageCount(bytes);
+ }
+
+ /// <summary>
+ /// Opens the file with LibreOffice + H2Orestart, a third independent HWPX reader (Java), when installed.
+ /// It is strict where 한글 is strict too, e.g. about element prefixes and negative object offsets.
+ /// </summary>
+ public static async Task ReadableByH2OrestartAsync(EngineFixture fx, string hwpx)
+ {
+ var libreOffice = fx.Converters.Single(c => c.Id == "libreoffice");
+ if (!fx.Catalog.StatusOf(libreOffice).IsAvailable || !libreOffice.Edges.Any(e => e.From == "hwpx"))
+ return;
+ var odt = Path.ChangeExtension(hwpx, ".h2o.odt");
+ // Tests run in parallel; the job queue normally limits LibreOffice to its worker profiles.
+ await LibreOfficeGate.WaitAsync(TestContext.Current.CancellationToken);
+ try
+ {
+ var written = await libreOffice.ConvertAsync(new ConversionStep(hwpx, "hwpx", "odt", new Preset(), new FixedPath(odt), Path.GetDirectoryName(hwpx)!),
+ null, TestContext.Current.CancellationToken);
+ Assert.True(new FileInfo(written.Single()).Length > 1000);
+ }
+ finally
+ {
+ LibreOfficeGate.Release();
+ }
+ }
+
+ private static readonly SemaphoreSlim LibreOfficeGate = new(1, 1);
+
+ private sealed class FixedPath(string path) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => path;
+ }
+}
diff --git a/tests/Filee.Engines.Tests/HwpxWriterTests.cs b/tests/Filee.Engines.Tests/HwpxWriterTests.cs
new file mode 100644
index 00000000..77339fad
--- /dev/null
+++ b/tests/Filee.Engines.Tests/HwpxWriterTests.cs
@@ -0,0 +1,186 @@
+// HWPX from Markdown / HTML (Pandoc AST → OWPML) and plain text, plus the writer's small helpers.
+// Output is checked structurally, read back with Unhwp and rendered with rhwp. DOCX has its own tests
+// (DocxToHwpxTests) because it is read without Pandoc.
+
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Settings;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Office;
+using ImageMagick;
+using Unhwp;
+using static Filee.Engines.Tests.HwpxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class HwpxWriterTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private const string Markdown = """
+ ---
+ title: Filee 변환 테스트
+ ---
+
+ # 첫 번째 제목
+
+ 일반 문단에 **굵게**, *기울임*, ~~취소선~~, H~2~O, x^2^ 그리고 [링크](https://example.com) 가 있습니다.[^1]
+
+ ## 두 번째 제목
+
+ > 인용문도 사라지면 안 됩니다.
+
+ 3. 셋째부터 시작
+ 4. 다음 항목
+ - 중첩 글머리
+ - 두 번째 글머리
+
+ a. 알파벳 목록
+ b. 둘째
+
+ | 이름 | 값 |
+ |------|----|
+ | 표 셀 | 42 |
+
+ ![로고](logo.png)
+
+ ```
+ 코드 블록
+ ```
+
+ [^1]: 각주 내용입니다.
+ """;
+
+ private void SkipUnlessPandoc() =>
+ Assert.SkipUnless(PandocConverter.Locate(new Infrastructure.EngineEnvironment(_ => null, fx.Root)) is not null,
+ "Pandoc not found (pwsh build/fetch-engines.ps1 -Only pandoc)");
+
+ private async Task<string> ConvertAsync(string input, string target = "hwpx")
+ {
+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });
+ var errors = string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));
+ Assert.True(job.State == JobState.Completed, errors);
+ return job.Outputs.Single();
+ }
+
+ [Fact]
+ public async Task Markdown_becomes_a_valid_hwpx_that_other_readers_understand()
+ {
+ SkipUnlessPandoc();
+ var dir = fx.NewFolder();
+ using (var logo = new MagickImage(MagickColors.MediumPurple, 240, 120))
+ logo.Write(Path.Combine(dir, "logo.png"));
+ var md = Path.Combine(dir, "문서.md");
+ await File.WriteAllTextAsync(md, Markdown, TestContext.Current.CancellationToken);
+
+ var hwpx = await ConvertAsync(md);
+
+ ValidPackage(hwpx, expectImages: 1);
+ using var document = UnhwpDocument.ParseFile(hwpx);
+ var text = document.ToText();
+ foreach (var expected in new[] { "첫 번째 제목", "굵게", "취소선", "인용문도 사라지면 안 됩니다", "셋째부터 시작", "중첩 글머리", "표 셀", "42", "코드 블록" })
+ Assert.Contains(expected, text);
+
+ // Unhwp's plain text skips footnotes, so check the footnote in the section XML.
+ var footnote = Xml(hwpx).Descendants(Hp + "footNote").Single();
+ Assert.Contains("각주 내용입니다", footnote.Value);
+ RenderWithRhwp(fx, hwpx, "hwpx-from-markdown");
+ }
+
+ [Fact]
+ public async Task Html_tables_with_merged_cells_keep_a_consistent_grid()
+ {
+ SkipUnlessPandoc();
+ var dir = fx.NewFolder();
+ var html = Path.Combine(dir, "table.html");
+ // Spans stay inside the body: Pandoc truncates a rowspan that would cross from a <th> header row into the body.
+ await File.WriteAllTextAsync(html, """
+ <table>
+ <tr><td rowspan="2">세로 병합</td><td colspan="2">가로 병합</td></tr>
+ <tr><td>B</td><td>C</td></tr>
+ <tr><td>D</td><td>E</td><td>F</td></tr>
+ </table>
+ """, TestContext.Current.CancellationToken);
+
+ var hwpx = await ConvertAsync(html);
+
+ ValidPackage(hwpx, expectImages: 0);
+ var cells = Xml(hwpx).Descendants(Hp + "tc").Select(tc => (
+ Row: (int)tc.Element(Hp + "cellAddr")!.Attribute("rowAddr")!, Col: (int)tc.Element(Hp + "cellAddr")!.Attribute("colAddr")!,
+ RowSpan: (int)tc.Element(Hp + "cellSpan")!.Attribute("rowSpan")!, ColSpan: (int)tc.Element(Hp + "cellSpan")!.Attribute("colSpan")!,
+ Height: (int)tc.Element(Hp + "cellSz")!.Attribute("height")!)).ToList();
+ // Every grid position of the 3×3 table is covered exactly once.
+ var covered = cells.SelectMany(c => Enumerable.Range(c.Row, c.RowSpan).SelectMany(r => Enumerable.Range(c.Col, c.ColSpan).Select(col => (r, col)))).ToList();
+ Assert.Equal(9, covered.Count);
+ Assert.Equal(9, covered.Distinct().Count());
+ // Merged cells are as tall as the rows they span (as 한글 writes them).
+ var rowHeight = (int row) => cells.First(c => c.Row == row && c.RowSpan == 1).Height;
+ Assert.Equal(rowHeight(0) + rowHeight(1), cells.Single(c => c.RowSpan == 2).Height);
+ RenderWithRhwp(fx, hwpx, "hwpx-merged-table");
+ }
+
+ [Fact]
+ public async Task Plain_text_needs_no_pandoc()
+ {
+ var dir = fx.NewFolder();
+ var txt = Path.Combine(dir, "메모.txt");
+ await File.WriteAllTextAsync(txt, "첫 줄\n\n세 번째 줄 <태그> & 기호\u000B", TestContext.Current.CancellationToken);
+
+ var hwpx = await ConvertAsync(txt);
+
+ ValidPackage(hwpx, expectImages: 0);
+ using var document = UnhwpDocument.ParseFile(hwpx);
+ Assert.Contains("세 번째 줄 <태그> & 기호", document.ToText());
+ }
+
+ [Fact]
+ public void Korean_text_files_in_the_legacy_code_page_are_decoded()
+ {
+ Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+ const string Text = "한글 텍스트 파일";
+ Assert.Equal(Text, HwpxConverter.DecodeText(Encoding.GetEncoding(949).GetBytes(Text)));
+ Assert.Equal(Text, HwpxConverter.DecodeText([0xEF, 0xBB, 0xBF, .. Encoding.UTF8.GetBytes(Text)]));
+ Assert.Equal(Text, HwpxConverter.DecodeText(Encoding.Unicode.GetPreamble().Concat(Encoding.Unicode.GetBytes(Text)).ToArray()));
+ }
+
+ [Fact]
+ public void Docx_is_written_by_the_built_in_writer_in_one_step()
+ {
+ var catalog = new ConverterCatalog(fx.Converters) { Priority = new AppSettings().EnginePriority };
+ var route = catalog.CreatePlanner().Plan("docx", "hwpx");
+ Assert.Equal("hwpx-writer", Assert.Single(route!.Steps).Converter.Id);
+ }
+
+ [Theory]
+ [InlineData("2in", 14400)]
+ [InlineData("96px", 7200)]
+ [InlineData("10mm", 2834)]
+ [InlineData("1cm", 2834)]
+ [InlineData("12pt", 1200)]
+ [InlineData("abc", null)]
+ [InlineData(null, null)]
+ public void Lengths_are_converted_to_hwpunit(string? value, int? expected)
+ {
+ var actual = HwpxUnits.ParseLength(value);
+ if (expected is null)
+ Assert.Null(actual);
+ else
+ Assert.InRange(actual!.Value, expected.Value - 2, expected.Value + 2);
+ }
+
+ [Theory]
+ [InlineData(0.1, "0.1 mm")]
+ [InlineData(0.13, "0.12 mm")]
+ [InlineData(0.353, "0.4 mm")]
+ [InlineData(1.2, "1.0 mm")]
+ [InlineData(9, "5.0 mm")]
+ public void Line_widths_snap_to_the_widths_hangul_offers(double mm, string expected) =>
+ Assert.Equal(expected, HwpxWriter.LineWidth(mm));
+
+ [Fact]
+ public void Text_is_escaped_and_invalid_xml_characters_removed() =>
+ Assert.Equal("a &lt;b&gt; &amp; c", HwpxWriter.Escape("a <b> & c\u000B\u0001"));
+
+ [Fact]
+ public void Hangul_is_measured_wider_than_latin_text() =>
+ Assert.True(HwpxWriter.TextWidth("가나다", 1000) > HwpxWriter.TextWidth("abc", 1000) * 1.5);
+}
diff --git a/tests/Filee.Engines.Tests/ImageAndPdfTests.cs b/tests/Filee.Engines.Tests/ImageAndPdfTests.cs
new file mode 100644
index 00000000..e6baf35d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/ImageAndPdfTests.cs
@@ -0,0 +1,154 @@
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using ImageMagick;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Tests;
+
+public class ImageAndPdfTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static void AssertDone(ConversionJob job)
+ {
+ var errors = string.Join("; ", job.Files.Where(f => f.State == FileState.Failed).Select(f => $"{f.ErrorKey} {f.ErrorDetail}"));
+ Assert.True(job.State == JobState.Completed, $"{job.State}: {errors}");
+ Assert.All(job.Outputs, o => Assert.True(new FileInfo(o).Length > 0, o));
+ }
+
+ [Theory]
+ [InlineData("jpg", MagickFormat.Jpeg)]
+ [InlineData("webp", MagickFormat.WebP)]
+ [InlineData("tiff", MagickFormat.Tiff)]
+ [InlineData("bmp", MagickFormat.Bmp)]
+ [InlineData("gif", MagickFormat.Gif)]
+ [InlineData("avif", MagickFormat.Avif)]
+ public async Task Png_converts_to(string target, MagickFormat expected)
+ {
+ var dir = fx.NewFolder();
+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png);
+
+ var job = await fx.ConvertAsync([source], new Preset { Name = target, TargetFormat = target });
+
+ AssertDone(job);
+ using var result = new MagickImage(job.Outputs.Single());
+ Assert.Equal(expected, result.Format);
+ Assert.Equal(320u, result.Width);
+ }
+
+ [Fact]
+ public async Task Jpg_output_flattens_transparency_and_applies_quality()
+ {
+ var dir = fx.NewFolder();
+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png);
+
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "jpg", Image = { Quality = 40, Background = "#FF0000" } });
+
+ AssertDone(job);
+ using var result = new MagickImage(job.Outputs.Single());
+ Assert.False(result.HasAlpha);
+ Assert.InRange(result.Quality, 35u, 45u);
+ var corner = result.GetPixels().GetPixel(5, 5).ToColor()!;
+ Assert.True(corner.R > 200 && corner.G < 60, "transparent corner should become the background colour");
+ }
+
+ [Fact]
+ public async Task Resize_by_long_edge_and_percent()
+ {
+ var dir = fx.NewFolder();
+ var source = EngineFixture.MakeImage(dir, "a.png", MagickFormat.Png, 1000, 500);
+
+ var longEdge = await fx.ConvertAsync([source], new Preset { TargetFormat = "png", Image = { Resize = ResizeMode.LongEdge, LongEdge = 400 }, Output = { FileNamePattern = "{name}_le" } });
+ var percent = await fx.ConvertAsync([source], new Preset { TargetFormat = BuiltInData.SameAsSource, Image = { Resize = ResizeMode.Percent, ResizePercent = 50 }, Output = { FileNamePattern = "{name}_50" } });
+
+ AssertDone(longEdge);
+ AssertDone(percent);
+ using (var a = new MagickImage(longEdge.Outputs.Single())) Assert.Equal((400u, 200u), (a.Width, a.Height));
+ using (var b = new MagickImage(percent.Outputs.Single())) Assert.Equal((500u, 250u), (b.Width, b.Height));
+ }
+
+ [Fact]
+ public async Task Ico_contains_several_sizes()
+ {
+ var dir = fx.NewFolder();
+ var source = EngineFixture.MakeImage(dir, "logo.png", MagickFormat.Png, 300, 200);
+
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "ico", Image = { IcoSizes = [64, 32, 16] } });
+
+ AssertDone(job);
+ using var icons = new MagickImageCollection(job.Outputs.Single());
+ Assert.Equal([64u, 32u, 16u], icons.Select(i => i.Width));
+ }
+
+ [Fact]
+ public async Task Multi_page_tiff_to_png_writes_one_file_per_page()
+ {
+ var dir = fx.NewFolder();
+ var source = EngineFixture.MakeMultiPageTiff(dir, 3);
+
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "png" });
+
+ AssertDone(job);
+ Assert.Equal(["pages_p1.png", "pages_p2.png", "pages_p3.png"], job.Outputs.Select(Path.GetFileName).Order(StringComparer.Ordinal));
+ }
+
+ [Fact]
+ public async Task Images_to_pdf_and_back()
+ {
+ var dir = fx.NewFolder();
+ var tiff = EngineFixture.MakeMultiPageTiff(dir, 2);
+
+ var toPdf = await fx.ConvertAsync([tiff], new Preset { TargetFormat = "pdf" });
+ AssertDone(toPdf);
+ using (var pdf = PdfReader.Open(toPdf.Outputs.Single(), PdfDocumentOpenMode.Import))
+ Assert.Equal(2, pdf.PageCount);
+
+ var toPng = await fx.ConvertAsync([toPdf.Outputs.Single()], new Preset { TargetFormat = "png", Pdf = { RenderDpi = 72 }, Output = { FileNamePattern = "{name}_render" } });
+ AssertDone(toPng);
+ Assert.Equal(2, toPng.Outputs.Count());
+ }
+
+ [Fact]
+ public async Task Pdf_to_multi_page_tiff()
+ {
+ var dir = fx.NewFolder();
+ var pdf = (await fx.ConvertAsync([EngineFixture.MakeMultiPageTiff(dir, 3)], new Preset { TargetFormat = "pdf" })).Outputs.Single();
+
+ var job = await fx.ConvertAsync([pdf], new Preset { TargetFormat = "tiff", Pdf = { RenderDpi = 72 }, Output = { FileNamePattern = "{name}_back" } });
+
+ AssertDone(job);
+ using var pages = new MagickImageCollection(job.Outputs.Single());
+ Assert.Equal(3, pages.Count);
+ }
+
+ [Fact]
+ public async Task Merge_images_into_one_pdf()
+ {
+ var dir = fx.NewFolder();
+ var a = EngineFixture.MakeImage(dir, "1.jpg", MagickFormat.Jpeg);
+ var b = EngineFixture.MakeImage(dir, "2.png", MagickFormat.Png);
+ var c = EngineFixture.MakeMultiPageTiff(dir, 2);
+
+ var job = await fx.ConvertAsync([a, b, c], new Preset { TargetFormat = "pdf", Pdf = { MergeIntoSingle = true, PageSize = PdfPageSize.A4, MarginMm = 10 }, Output = { FileNamePattern = "{name}_merged" } });
+
+ AssertDone(job);
+ using var pdf = PdfReader.Open(job.Outputs.Single(), PdfDocumentOpenMode.Import);
+ Assert.Equal(4, pdf.PageCount);
+ Assert.Equal("1_merged.pdf", Path.GetFileName(job.Outputs.Single()));
+ }
+
+ [Fact]
+ public async Task Split_pdf_by_page_range()
+ {
+ var dir = fx.NewFolder();
+ var pdf = (await fx.ConvertAsync([EngineFixture.MakeMultiPageTiff(dir, 4)], new Preset { TargetFormat = "pdf" })).Outputs.Single();
+
+ var job = await fx.ConvertAsync([pdf], new Preset
+ {
+ TargetFormat = "pdf",
+ Pdf = { SplitPages = true, PageRange = "2-3" },
+ Output = { Location = OutputLocation.Subfolder, SubfolderName = "{name}" },
+ });
+
+ AssertDone(job);
+ Assert.Equal(["pages_p2.pdf", "pages_p3.pdf"], job.Outputs.Select(Path.GetFileName).Order(StringComparer.Ordinal));
+ }
+}