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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Filee 1.0.1: Markdown without Pandoc, steady progress, update notices
KnifeLemoncf7f96cd9073
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ac004e1a..e2bff27f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -7,7 +7,7 @@ Thanks for helping! Filee is built to be easy to extend: most contributions touc1. 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+ HTML / Markdown ↔ Word; Markdown → HTML, TXT and HWPX work without it). Without `-Only` it also downloads LibreOffice with H2Orestart and Java (~420 MB). Engines in therepository'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`.diff --git a/Directory.Build.props b/Directory.Build.propsindex bbcf45dd..a261b5a0 100644--- a/Directory.Build.props+++ b/Directory.Build.props@@ -14,7 +14,7 @@parameters of a member is fine (CS1573). --><NoWarn>$(NoWarn);CS1591;CS1573</NoWarn>- <Version>1.0.0</Version>+ <Version>1.0.1</Version><Product>Filee</Product><Authors>Filee contributors</Authors><Copyright>Copyright (c) Filee contributors</Copyright>diff --git a/README.ko.md b/README.ko.mdindex 93dd9f92..bb6abbc8 100644--- a/README.ko.md+++ b/README.ko.md@@ -64,7 +64,8 @@| **스프레드시트·프레젠테이션**: XLSX, XLS, ODS, CSV, PPTX, PPT, ODP | PDF와 서로 변환 || **텍스트**: TXT, 마크다운, HTML | DOCX, HWPX, PDF |-오피스 문서와 마크다운은 추가 엔진(LibreOffice, Pandoc)을 씁니다. 처음 실행할 때 받을지 물어봐요.+마크다운 → PDF·HWPX·HTML·TXT는 설치하자마자 됩니다. 오피스 문서는 LibreOffice, HTML과 마크다운 ↔ 워드는 Pandoc을+쓰는데, 둘 다 처음 실행할 때 받을지 물어보는 추가 엔진입니다.HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)에 있습니다.## 스크린샷@@ -94,8 +95,9 @@ HWPX를 어떻게 만들고 검증하는지는 [docs/ENGINES.md](docs/ENGINES.md(Windows 10/11, 64비트). 다른 버전은 [Releases](https://github.com/KnifeLemon/Filee/releases)에 있습니다.- **설치 파일은 가볍습니다.** 이미지, PDF, HWP/HWPX, DOCX → HWPX는 설치하자마자 바로 변환됩니다.-- **큰 엔진은 골라서 설치합니다.** 처음 실행하면 LibreOffice(오피스 문서, 약 420MB)와 Pandoc(마크다운·HTML, 약 42MB)을 받을지 묻습니다. 나중에 설정 → 변환 엔진에서 언제든 설치하거나 지울 수 있습니다.-- **업데이트는 자동입니다.** Filee는 GitHub Releases에서 스스로 업데이트합니다.+- **큰 엔진은 골라서 설치합니다.** 처음 실행하면 LibreOffice(오피스 문서, 약 420MB)와 Pandoc(HTML·마크다운 ↔ 워드, 약 42MB)을 받을지 묻습니다. 나중에 설정 → 변환 엔진에서 언제든 설치하거나 지울 수 있습니다.+- **업데이트는 알려 드려요.** 새 버전이 나오면 메뉴 하단, 알림, 트레이 메뉴에 표시되고 누르면 최신 릴리스 페이지가+ 열립니다. 새 설치 파일을 실행하면 설정은 그대로 유지돼요.macOS 지원은 계획 중입니다.diff --git a/README.md b/README.mdindex ee12705d..e202c0fe 100644--- a/README.md+++ b/README.md@@ -67,7 +67,8 @@| **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.+Markdown → PDF, HWPX, HTML and TXT work out of the box. Office documents use LibreOffice, and HTML / Markdown ↔ Word use+Pandoc: optional engines that Filee offers to download on first start.How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).## Screenshots@@ -97,8 +98,9 @@ How HWPX is written and checked: [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer).(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.+- **Large engines are optional.** On first start Filee offers LibreOffice for office documents (~420 MB) and Pandoc for HTML and Markdown ↔ Word (~42 MB). You can install or remove them any time in Settings → Engines.+- **You hear about updates.** When a new release is out, Filee says so at the bottom of the menu, in a notice and in+ the tray menu, and opens the latest release to download it. Run the new installer; your settings are kept.macOS support is planned.diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 342a632d..f2adab56 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -64,7 +64,8 @@| **表格与演示文稿**:XLSX、XLS、ODS、CSV、PPTX、PPT、ODP | PDF 及互相转换 || **文本**:TXT、Markdown、HTML | DOCX、HWPX、PDF |-办公文档和 Markdown 使用可选引擎(LibreOffice、Pandoc),Filee 会在首次启动时询问是否下载。+Markdown → PDF、HWPX、HTML、TXT 装好即用。办公文档使用 LibreOffice,HTML 与 Markdown ↔ Word 使用 Pandoc,+这两个可选引擎会在首次启动时询问是否下载。HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)。## 截图@@ -94,8 +95,9 @@ HWPX 的写入与验证方式见 [docs/ENGINES.md](docs/ENGINES.md#hwpx-writer)(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 自动更新。+- **大型引擎按需下载。** 首次启动时会询问是否下载 LibreOffice(办公文档,约 420 MB)和 Pandoc(HTML 与 Markdown ↔ Word,约 42 MB);之后可随时在“设置 → 转换引擎”中安装或删除。+- **有更新会提醒你。** 新版本发布后,Filee 会在菜单底部、通知和托盘菜单中提示,点击即可打开最新发布页面下载。+ 运行新的安装程序即可更新,设置会保留。macOS 版本正在计划中。diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 47f1b5e7..4375e62d 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -21,7 +21,7 @@┌──────────────────────────── 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 │+ │ HwpxWriter (DOCX / Markdown / Pandoc AST → HWPX) · Markdig · Pandoc · Word COM │└────────────────────────────────────────────────────────────────────────────────────┘```diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex ac54550e..cae324dc 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -10,10 +10,11 @@ or remove the optional engines.| 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 |+| Markdown (Markdig) | built in (library) | **Markdown → HTML, TXT** (and → PDF / DOCX through the HWPX writer, rhwp or LibreOffice) |+| **HWPX writer** | built in | **DOCX, TXT, Markdown → HWPX**; HTML, ODT, RTF → HWPX with Pandoc || 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 |+| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT || Microsoft Word | used if installed | best-fidelity DOCX → PDF, PDF → DOCX |Engines found on the system (an installed LibreOffice, `soffice`/`rhwp`/`pandoc` on PATH) are used when Filee's own@@ -55,9 +56,11 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an- 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).+- **Markdown** is parsed with Markdig (`MarkdownReader.cs`): headings, emphasis, code, lists (1. / a. / i. with+ start numbers), task lists, quotes, tables with spans, links, images, footnotes and math. No Pandoc needed.+- **HTML, ODT, RTF** are parsed by Pandoc into its JSON AST (`PandocAstReader.cs`, following+ [pypandoc-hwpx](https://github.com/msjang/pypandoc-hwpx)).+- Markdown and Pandoc keep 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:diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 832513c8..d65b90cf 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -61,6 +61,8 @@ public partial class App : ApplicationAppHost.Get<TrayService>().Create(this);AppHost.Get<WindowService>().EnsureToast();+ // Once LibreOffice is installed: prepare its profiles while the user isn't converting yet.+ AppHost.Get<EngineDownloadService>().WarmUpInBackground(TimeSpan.FromSeconds(10));// Later launches (context menu, Send To, double-clicking the exe) forward their arguments here.if (Program.Instance is { } instance)@@ -76,7 +78,25 @@ public partial class App : Application};HandleCommandLine(Program.Options, firstLaunch: true);- _ = CheckForUpdatesAsync(store.Settings);+ WatchForUpdates(store);+ }++ /// <summary>+ /// Looks for new releases in the background. A new version shows up at the bottom of the navigation and in the+ /// tray menu; the bottom-right notice appears once per version.+ /// </summary>+ private static void WatchForUpdates(UserDataStore store)+ {+ var updates = AppHost.Get<UpdateService>();+ updates.UpdateFound += (_, version) =>+ {+ if (store.Settings.NotifiedUpdateVersion == version)+ return;+ store.Settings.NotifiedUpdateVersion = version;+ store.SaveSettings();+ AppHost.Get<WindowService>().ShowUpdateNotice(version);+ };+ updates.StartPeriodicChecks(() => store.Settings.CheckForUpdates, TimeSpan.FromSeconds(20));}/// <summary>Applies everything derived from settings. Called at start-up and whenever settings are saved.</summary>@@ -148,11 +168,4 @@ public partial class App : ApplicationAppHost.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/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 5c15a081..25b90768 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -15,6 +15,7 @@"tray.pause": "Pause shortcuts","tray.resume": "Resume shortcuts","tray.quit": "Quit",+ "tray.update": "Download update ({0})","tray.tooltip": "Filee — hold {0} and drag files","home.title": "Home",@@ -60,6 +61,7 @@"profile.pdf": "PDF","profile.office": "Office documents","profile.hwp": "HWP / HWPX",+ "profile.text": "Text & Markdown","profile.mixed": "Mixed files","preset.half_size": "Half size",@@ -76,9 +78,12 @@"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.update_none": "You're up to date ({0})",+ "update.sidebar": "Update to {0}",+ "update.notice_title": "Filee {0} is available",+ "update.notice_text": "Download the new installer from GitHub and run it to update. Your settings are kept.",+ "update.download": "Download",+ "update.later": "Later","general.data_folder": "Settings folder","general.open_data_folder": "Open","general.library": "Presets and toolbars",@@ -225,8 +230,8 @@"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.pandoc.name": "Pandoc (HTML and Markdown ↔ Word)",+ "engines.package.pandoc.description": "Markdown ↔ DOCX, ODT and RTF, and HTML, ODT and RTF → HWPX. Markdown → PDF, HWPX, HTML and TXT, and DOCX → HWPX work without it.","engines.package.size": "Download {0} · {1} on disk","engines.install": "Install","engines.cancel": "Cancel",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex edb6d09b..fb888ce6 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -15,6 +15,7 @@"tray.pause": "단축키 일시 중지","tray.resume": "단축키 다시 사용","tray.quit": "종료",+ "tray.update": "업데이트 받기 ({0})","tray.tooltip": "Filee — {0} 누른 채 파일 드래그","home.title": "홈",@@ -60,6 +61,7 @@"profile.pdf": "PDF","profile.office": "오피스 문서","profile.hwp": "HWP / HWPX",+ "profile.text": "텍스트·마크다운","profile.mixed": "혼합 파일","preset.half_size": "50% 축소",@@ -76,9 +78,12 @@"general.check_updates": "자동으로 업데이트 확인","general.check_now": "지금 확인","general.update_available": "{0} 버전을 사용할 수 있어요",- "general.update_none": "최신 버전이에요",- "general.update_dev": "업데이트는 설치된 버전에서만 사용할 수 있어요",- "general.update_install": "업데이트 후 다시 시작",+ "general.update_none": "최신 버전이에요 ({0})",+ "update.sidebar": "{0} 업데이트",+ "update.notice_title": "Filee {0} 버전이 나왔어요",+ "update.notice_text": "GitHub에서 새 설치 파일을 받아 실행하면 업데이트돼요. 설정은 그대로 유지됩니다.",+ "update.download": "다운로드",+ "update.later": "나중에","general.data_folder": "설정 폴더","general.open_data_folder": "열기","general.library": "프리셋과 툴바",@@ -225,8 +230,8 @@"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.pandoc.name": "Pandoc (HTML·마크다운 ↔ 워드)",+ "engines.package.pandoc.description": "마크다운 ↔ DOCX·ODT·RTF 변환과 HTML·ODT·RTF → HWPX 변환을 추가합니다. 마크다운 → PDF·HWPX·HTML·TXT와 DOCX → HWPX는 없어도 됩니다.","engines.package.size": "다운로드 {0} · 설치 후 {1}","engines.install": "설치","engines.cancel": "취소",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex de34fa45..f86ad0e4 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -15,6 +15,7 @@"tray.pause": "暂停快捷方式","tray.resume": "恢复快捷方式","tray.quit": "退出",+ "tray.update": "下载更新({0})","tray.tooltip": "Filee — 按住 {0} 拖动文件","home.title": "首页",@@ -60,6 +61,7 @@"profile.pdf": "PDF","profile.office": "办公文档","profile.hwp": "HWP / HWPX",+ "profile.text": "文本与 Markdown","profile.mixed": "混合文件","preset.half_size": "缩小 50%",@@ -76,9 +78,12 @@"general.check_updates": "自动检查更新","general.check_now": "立即检查","general.update_available": "有新版本 {0}",- "general.update_none": "已是最新版本",- "general.update_dev": "仅安装版支持更新",- "general.update_install": "更新并重启",+ "general.update_none": "已是最新版本({0})",+ "update.sidebar": "更新到 {0}",+ "update.notice_title": "Filee {0} 已发布",+ "update.notice_text": "从 GitHub 下载新的安装程序并运行即可更新,设置会保留。",+ "update.download": "下载",+ "update.later": "稍后","general.data_folder": "设置文件夹","general.open_data_folder": "打开","general.library": "预设与工具栏",@@ -225,8 +230,8 @@"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.pandoc.name": "Pandoc(HTML 与 Markdown ↔ Word)",+ "engines.package.pandoc.description": "支持 Markdown ↔ DOCX、ODT、RTF,以及 HTML、ODT、RTF → HWPX。Markdown → PDF、HWPX、HTML、TXT 和 DOCX → HWPX 无需此引擎。","engines.package.size": "下载 {0} · 占用 {1}","engines.install": "安装","engines.cancel": "取消",diff --git a/src/Filee.App/Controls/MarkdownView.cs b/src/Filee.App/Controls/MarkdownView.csnew file mode 100644index 00000000..4b2a20fa--- /dev/null+++ b/src/Filee.App/Controls/MarkdownView.cs@@ -0,0 +1,274 @@+// Shows a small Markdown document with the app's styles: headings, paragraphs, lists, tables, links, code.+// Made for the third-party notices on the About page, not as a general Markdown viewer (no images or HTML).++using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Documents;+using Avalonia.Layout;+using Avalonia.Media;+using Markdig;+using Markdig.Extensions.Tables;+using Markdig.Syntax;+using Markdig.Syntax.Inlines;++namespace Filee.App.Controls;++/// <summary>Renders <see cref="Markdown"/> as a stack of text blocks, tables and link buttons.</summary>+public sealed class MarkdownView : StackPanel+{+ public static readonly StyledProperty<string?> MarkdownProperty =+ AvaloniaProperty.Register<MarkdownView, string?>(nameof(Markdown));++ /// <summary>Skips the first level-1 heading (the page around the view shows its own title).</summary>+ public static readonly StyledProperty<bool> SkipTitleProperty =+ AvaloniaProperty.Register<MarkdownView, bool>(nameof(SkipTitle));++ private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()+ .UsePipeTables().UseAutoLinks().UseEmphasisExtras().Build();++ private static readonly FontFamily Monospace = new("Cascadia Mono, Consolas, Menlo, monospace");++ static MarkdownView()+ {+ MarkdownProperty.Changed.AddClassHandler<MarkdownView>((view, _) => view.Rebuild());+ SkipTitleProperty.Changed.AddClassHandler<MarkdownView>((view, _) => view.Rebuild());+ }++ public MarkdownView() => Spacing = 10;++ public string? Markdown+ {+ get => GetValue(MarkdownProperty);+ set => SetValue(MarkdownProperty, value);+ }++ public bool SkipTitle+ {+ get => GetValue(SkipTitleProperty);+ set => SetValue(SkipTitleProperty, value);+ }++ private void Rebuild()+ {+ Children.Clear();+ if (string.IsNullOrWhiteSpace(Markdown))+ return;+ var skipTitle = SkipTitle;+ foreach (var block in Markdig.Markdown.Parse(Markdown, Pipeline))+ {+ if (skipTitle && block is HeadingBlock { Level: 1 })+ {+ skipTitle = false;+ continue;+ }+ if (Create(block) is { } control)+ Children.Add(control);+ }+ }++ private static Control? Create(Block block) => block switch+ {+ HeadingBlock heading => Heading(heading),+ ParagraphBlock paragraph => Text(paragraph.Inline),+ ListBlock list => List(list),+ Table table => TableGrid(table),+ QuoteBlock quote => Quote(quote),+ CodeBlock code => Code(code),+ ThematicBreakBlock => Themed(new Border { Height = 1, Margin = new Thickness(0, 4) }, Border.BackgroundProperty, "SubtleBorderBrush"),+ _ => null,+ };++ private static Control Heading(HeadingBlock heading)+ {+ var text = Text(heading.Inline);+ text.FontWeight = FontWeight.SemiBold;+ text.FontSize = heading.Level switch { 1 => 18, 2 => 14.5, _ => 13.5 };+ text.Margin = new Thickness(0, heading.Level <= 2 ? 8 : 4, 0, 0);+ return text;+ }++ /// <summary>A selectable paragraph; links become inline buttons that open the browser.</summary>+ private static SelectableTextBlock Text(ContainerInline? inlines)+ {+ var block = new SelectableTextBlock { TextWrapping = TextWrapping.Wrap, FontSize = 13 };+ if (inlines is not null)+ AddInlines(block.Inlines!, inlines, bold: false, italic: false);+ return block;+ }++ private static void AddInlines(InlineCollection target, ContainerInline container, bool bold, bool italic)+ {+ foreach (var inline in container)+ {+ switch (inline)+ {+ case LiteralInline literal:+ target.Add(Styled(new Run(literal.Content.ToString()), bold, italic));+ break;+ case CodeInline code:+ target.Add(Styled(new Run(code.Content) { FontFamily = Monospace }, bold, italic));+ break;+ case LineBreakInline lineBreak:+ target.Add(lineBreak.IsHard ? new LineBreak() : new Run(" "));+ break;+ case EmphasisInline emphasis:+ AddInlines(target, emphasis,+ bold || emphasis.DelimiterChar is '*' or '_' && emphasis.DelimiterCount >= 2,+ italic || emphasis.DelimiterChar is '*' or '_' && emphasis.DelimiterCount is 1 or 3);+ break;+ case LinkInline { IsImage: false } link when Uri.TryCreate(link.Url, UriKind.Absolute, out var uri):+ target.Add(new InlineUIContainer(Link(PlainText(link), uri)) { BaselineAlignment = BaselineAlignment.TextBottom });+ break;+ case AutolinkInline autolink when Uri.TryCreate(autolink.Url, UriKind.Absolute, out var uri):+ target.Add(new InlineUIContainer(Link(autolink.Url, uri)) { BaselineAlignment = BaselineAlignment.TextBottom });+ break;+ case HtmlEntityInline entity:+ target.Add(new Run(entity.Transcoded.ToString()));+ break;+ case ContainerInline other:+ AddInlines(target, other, bold, italic);+ break;+ }+ }+ }++ private static Run Styled(Run run, bool bold, bool italic)+ {+ if (bold)+ run.FontWeight = FontWeight.SemiBold;+ if (italic)+ run.FontStyle = FontStyle.Italic;+ return run;+ }++ private static HyperlinkButton Link(string text, Uri uri)+ {+ var button = new HyperlinkButton+ {+ NavigateUri = uri,+ Padding = new Thickness(0),+ Content = new TextBlock { Text = text, FontSize = 12.5, TextWrapping = TextWrapping.Wrap },+ };+ ToolTip.SetTip(button, uri.AbsoluteUri);+ return button;+ }++ private static string PlainText(ContainerInline container) =>+ string.Concat(container.Descendants<LiteralInline>().Select(l => l.Content.ToString()));++ private static Control List(ListBlock list)+ {+ var panel = new StackPanel { Spacing = 4, Margin = new Thickness(4, 0, 0, 0) };+ var number = int.TryParse(list.OrderedStart, out var start) ? start : 1;+ foreach (var item in list.OfType<ListItemBlock>())+ {+ var content = new StackPanel { Spacing = 4 };+ foreach (var block in item)+ if (Create(block) is { } control)+ content.Children.Add(control);+ var marker = new TextBlock { Text = list.IsOrdered ? $"{number++}." : "•", FontSize = 13, MinWidth = 18 };+ var row = new DockPanel();+ DockPanel.SetDock(marker, Dock.Left);+ row.Children.Add(marker);+ row.Children.Add(content);+ panel.Children.Add(row);+ }+ return panel;+ }++ /// <summary>A grid with a bold header row and a line between rows; column widths follow the text lengths.</summary>+ private static Control TableGrid(Table table)+ {+ var rows = table.OfType<TableRow>().ToList();+ var columns = rows.Count == 0 ? 0 : rows.Max(r => r.Count);+ var grid = new Grid();+ for (var c = 0; c < columns; c++)+ {+ var longest = rows.Select(r => c < r.Count ? PlainLength((TableCell)r[c]) : 0).DefaultIfEmpty(0).Max();+ grid.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(Math.Clamp(longest, 8, 40), GridUnitType.Star)));+ }+ for (var r = 0; r < rows.Count; r++)+ {+ grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));+ var cells = rows[r].OfType<TableCell>().ToList();+ for (var c = 0; c < cells.Count && c < columns; c++)+ {+ var content = Cell(cells[c], rows[r].IsHeader);+ var border = new Border+ {+ Child = content,+ Padding = new Thickness(8, 6),+ BorderThickness = new Thickness(0, 0, 0, r == rows.Count - 1 ? 0 : 1),+ };+ Themed(border, Border.BorderBrushProperty, "SubtleBorderBrush");+ if (rows[r].IsHeader)+ Themed(border, Border.BackgroundProperty, "SurfaceAltBrush");+ Grid.SetRow(border, r);+ Grid.SetColumn(border, c);+ grid.Children.Add(border);+ }+ }+ var frame = new Border+ {+ Child = grid,+ BorderThickness = new Thickness(1),+ CornerRadius = new CornerRadius(8),+ ClipToBounds = true,+ };+ return Themed(frame, Border.BorderBrushProperty, "SubtleBorderBrush");+ }++ private static Control Cell(TableCell cell, bool header)+ {+ // A cell holding only a URL becomes a link button (the "Project" column of the notices).+ var inline = cell.OfType<ParagraphBlock>().FirstOrDefault()?.Inline;+ var only = inline?.FirstChild is { } first && first.NextSibling is null ? first : null;+ if (only is AutolinkInline autolink && Uri.TryCreate(autolink.Url, UriKind.Absolute, out var autoUri))+ return Link(autolink.Url, autoUri);+ if (only is LinkInline { IsImage: false } link && Uri.TryCreate(link.Url, UriKind.Absolute, out var linkUri))+ return Link(PlainText(link), linkUri);++ var text = Text(inline);+ text.FontSize = 12.5;+ if (header)+ text.FontWeight = FontWeight.SemiBold;+ return text;+ }++ private static int PlainLength(TableCell cell) =>+ cell.Descendants<LiteralInline>().Sum(l => l.Content.Length) + cell.Descendants<AutolinkInline>().Sum(a => a.Url.Length);++ private static Control Quote(QuoteBlock quote)+ {+ var panel = new StackPanel { Spacing = 6 };+ foreach (var block in quote)+ if (Create(block) is { } control)+ panel.Children.Add(control);+ var border = new Border { Child = panel, BorderThickness = new Thickness(3, 0, 0, 0), Padding = new Thickness(12, 2, 0, 2) };+ return Themed(border, Border.BorderBrushProperty, "AccentSoftBrush");+ }++ private static Control Code(CodeBlock code)+ {+ var border = new Border+ {+ Padding = new Thickness(10, 8),+ CornerRadius = new CornerRadius(6),+ Child = new SelectableTextBlock+ {+ Text = code.Lines.ToString(),+ FontFamily = Monospace,+ FontSize = 12,+ TextWrapping = TextWrapping.Wrap,+ },+ };+ return Themed(border, Border.BackgroundProperty, "SurfaceAltBrush");+ }++ /// <summary>Binds a brush property to a theme resource, so light / dark and accent changes apply live.</summary>+ private static T Themed<T>(T control, AvaloniaProperty property, string resource) where T : Control+ {+ control.Bind(property, control.GetResourceObservable(resource));+ return control;+ }+}diff --git a/src/Filee.App/Filee.App.csproj b/src/Filee.App/Filee.App.csprojindex cde86697..f0d8952b 100644--- a/src/Filee.App/Filee.App.csproj+++ b/src/Filee.App/Filee.App.csproj@@ -27,6 +27,7 @@<PrivateAssets Condition="'$(Configuration)' != 'Debug'">All</PrivateAssets></PackageReference><PackageReference Include="CommunityToolkit.Mvvm" />+ <PackageReference Include="Markdig" /><PackageReference Include="Microsoft.Extensions.Logging" /><PackageReference Include="SharpHook" /><PackageReference Include="Velopack" />diff --git a/src/Filee.App/Services/EngineDownloadService.cs b/src/Filee.App/Services/EngineDownloadService.csindex bc430f57..aa878c94 100644--- a/src/Filee.App/Services/EngineDownloadService.cs+++ b/src/Filee.App/Services/EngineDownloadService.cs@@ -5,6 +5,7 @@ using CommunityToolkit.Mvvm.ComponentModel;using Filee.Core.Conversion;using Filee.Core.Localization;using Filee.Engines.Infrastructure;+using Filee.Engines.Office;using Microsoft.Extensions.Logging;namespace Filee.App.Services;@@ -85,6 +86,7 @@ public sealed class EngineDownloadServiceprivate readonly ConverterCatalog _catalog;private readonly ILogger<EngineDownloadService> _logger;private readonly SemaphoreSlim _oneAtATime = new(1, 1);+ private int _warmingUp;public EngineDownloadService(ConverterCatalog catalog, ILocalizer loc, ILogger<EngineDownloadService> logger){@@ -143,6 +145,8 @@ public sealed class EngineDownloadService}state.Status = EnginePackageStatus.Installed;_catalog.Refresh();+ if (state.Package.ConverterIds.Contains("libreoffice"))+ WarmUpInBackground(TimeSpan.Zero);}catch (OperationCanceledException){@@ -162,6 +166,38 @@ public sealed class EngineDownloadServicepublic void Cancel(EnginePackageState state) => state.Cancellation?.Cancel();+ /// <summary>+ /// Prepares LibreOffice's worker profiles in the background, so the first document conversion is as quick as the+ /// following ones (LibreOffice's first start with a new profile takes 2-3× longer). One run at a time; does+ /// nothing when LibreOffice is missing or already prepared.+ /// </summary>+ public void WarmUpInBackground(TimeSpan delay)+ {+ if (Interlocked.Exchange(ref _warmingUp, 1) == 1)+ return;+ _ = Task.Run(async () =>+ {+ try+ {+ await Task.Delay(delay);+ foreach (var libreOffice in _catalog.All.OfType<LibreOfficeConverter>())+ {+ var prepared = await libreOffice.WarmUpAsync();+ if (prepared > 0)+ _logger.LogInformation("Prepared {Count} LibreOffice profile(s)", prepared);+ }+ }+ catch (Exception ex)+ {+ _logger.LogWarning(ex, "Preparing LibreOffice failed");+ }+ finally+ {+ Interlocked.Exchange(ref _warmingUp, 0);+ }+ });+ }+/// <summary>Removes a package. Returns false when its files are in use (a conversion is running).</summary>public bool Uninstall(EnginePackageState state){diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.csindex 135ca94d..e3f11a87 100644--- a/src/Filee.App/Services/RadialController.cs+++ b/src/Filee.App/Services/RadialController.cs@@ -29,8 +29,11 @@ public sealed class RadialController(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);+ /// <summary>+ /// How long the ring shows a running job before the toast window takes over. Long enough for a typical office+ /// document (LibreOffice needs a few seconds), so the user sees it finish where they dropped it.+ /// </summary>+ private static readonly TimeSpan HandOffAfter = TimeSpan.FromSeconds(5);private RadialWindow? _window;private bool _visible;diff --git a/src/Filee.App/Services/TrayService.cs b/src/Filee.App/Services/TrayService.csindex 50dd634f..7141968a 100644--- a/src/Filee.App/Services/TrayService.cs+++ b/src/Filee.App/Services/TrayService.cs@@ -1,4 +1,4 @@-// System tray icon: open settings, pause gestures, quit.+// System tray icon: open settings, pause gestures, download a new version, quit.using Avalonia;using Avalonia.Controls;@@ -9,10 +9,10 @@ using Filee.Core.Settings;namespace Filee.App.Services;-public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowService windows)+public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowService windows, UpdateService updates){private TrayIcon? _tray;- private NativeMenuItem? _open, _pause, _quit;+ private NativeMenuItem? _open, _pause, _quit, _update;public void Create(Application app){@@ -27,6 +27,8 @@ public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowServi};_quit = new NativeMenuItem();_quit.Click += (_, _) => (app.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();+ _update = new NativeMenuItem();+ _update.Click += (_, _) => updates.OpenDownloadPage();_tray = new TrayIcon{@@ -40,12 +42,28 @@ public sealed class TrayService(UserDataStore store, ILocalizer loc, WindowServiRefresh();loc.LanguageChanged += (_, _) => Refresh();store.SettingsChanged += (_, _) => Refresh();+ updates.PropertyChanged += (_, e) =>+ {+ if (e.PropertyName == nameof(UpdateService.LatestVersion))+ Refresh();+ };}private void Refresh(){- if (_tray is null)+ if (_tray?.Menu is not { } menu)return;+ // "Download update (x.y.z)" sits at the top of the menu while a newer release is out.+ if (updates.LatestVersion is { } latest)+ {+ _update!.Header = loc.Format("tray.update", latest);+ if (!menu.Items.Contains(_update))+ menu.Items.Insert(0, _update);+ }+ else+ {+ menu.Items.Remove(_update!);+ }_open!.Header = loc["tray.open"];_pause!.Header = store.Settings.Paused ? loc["tray.resume"] : loc["tray.pause"];_quit!.Header = loc["tray.quit"];diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.csindex a8d141de..2e1da19c 100644--- a/src/Filee.App/Services/UpdateService.cs+++ b/src/Filee.App/Services/UpdateService.cs@@ -1,16 +1,36 @@-// In-app updates from GitHub Releases via Velopack. Only works in installed builds (not when run from the IDE).+// Update check against GitHub Releases. When a newer version is out the app says so (sidebar, notice, tray) and sends+// the user to the latest release page to download it; running the new installer updates Filee in place and keeps the+// settings. Works in every build, also when run from source.+using System.Diagnostics;+using System.Net.Http.Headers;using System.Reflection;+using System.Text.Json;+using Avalonia.Threading;+using CommunityToolkit.Mvvm.ComponentModel;using Microsoft.Extensions.Logging;using Velopack;using Velopack.Sources;namespace Filee.App.Services;-public sealed class UpdateService(ILogger<UpdateService> log)+public sealed partial class UpdateService : ObservableObject{+ /// <summary>How often a running Filee (it lives in the tray for days) looks for a new version.</summary>+ private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(6);++ private readonly ILogger<UpdateService> _log;+ private readonly HttpClient _http;private UpdateManager? _manager;- private UpdateInfo? _pending;+ private DispatcherTimer? _timer;++ public UpdateService(ILogger<UpdateService> log)+ {+ _log = log;+ _http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };+ _http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Filee", CurrentVersion));+ _http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json");+ }/// <summary>GitHub repository from Directory.Build.props (FileeRepositoryUrl).</summary>public static string RepositoryUrl =>@@ -21,48 +41,116 @@ public sealed class UpdateService(ILogger<UpdateService> log)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;+ /// <summary>Page with the newest installer.</summary>+ public static string LatestReleaseUrl => RepositoryUrl.TrimEnd('/') + "/releases/latest";++ /// <summary>The newer version found by the last check (e.g. "1.0.2"), or null when up to date / unknown.</summary>+ [ObservableProperty]+ [NotifyPropertyChangedFor(nameof(IsUpdateAvailable))]+ private string? _latestVersion;++ public bool IsUpdateAvailable => LatestVersion is not null;++ /// <summary>Raised on the UI thread when a check finds a newer version than before.</summary>+ public event EventHandler<string>? UpdateFound;- private UpdateManager? Manager+ /// <summary>False when running from source (no Velopack installation). Keeps dev builds out of the registry.</summary>+ public bool IsInstalled{get{try{- return _manager ??= new UpdateManager(new GithubSource(RepositoryUrl, null, false));+ _manager ??= new UpdateManager(new GithubSource(RepositoryUrl, null, false));+ return _manager.IsInstalled;}catch (Exception ex){- log.LogWarning(ex, "Update manager unavailable");- return null;+ _log.LogWarning(ex, "Velopack locator unavailable");+ return false;}}}- /// <summary>Returns the new version string, or null if up to date / not installed / offline.</summary>- public async Task<string?> CheckAsync()+ /// <summary>Checks the latest release now. Returns the newer version, or null when up to date or offline.</summary>+ public async Task<string?> CheckAsync(CancellationToken cancellationToken = default){- if (!IsInstalled)- return null;try{- _pending = await Manager!.CheckForUpdatesAsync();- return _pending?.TargetFullRelease.Version.ToString();+ var api = RepositoryUrl.TrimEnd('/').Replace("https://github.com/", "https://api.github.com/repos/", StringComparison.OrdinalIgnoreCase)+ + "/releases/latest";+ using var response = await _http.GetAsync(api, cancellationToken);+ if (!response.IsSuccessStatusCode)+ {+ _log.LogInformation("Update check: {Status}", response.StatusCode); // e.g. 404 before the first release+ return LatestVersion;+ }+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);+ using var json = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);+ var tag = json.RootElement.TryGetProperty("tag_name", out var value) ? value.GetString() : null;+ var newer = IsNewer(tag, CurrentVersion) ? Normalize(tag!) : null;+ await Dispatcher.UIThread.InvokeAsync(() => Publish(newer));+ return newer;}- catch (Exception ex)+ catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or InvalidOperationException){- log.LogWarning(ex, "Update check failed");- return null;+ _log.LogInformation("Update check failed: {Message}", ex.Message);+ return LatestVersion;}}- /// <summary>Downloads the pending update and restarts into it.</summary>- public async Task ApplyAsync()+ /// <summary>Checks shortly after start and then every few hours while <paramref name="enabled"/> says so.</summary>+ public void StartPeriodicChecks(Func<bool> enabled, TimeSpan firstDelay){- if (_pending is null || Manager is null)+ if (_timer is not null)return;- await Manager.DownloadUpdatesAsync(_pending);- Manager.ApplyUpdatesAndRestart(_pending);+ _timer = new DispatcherTimer { Interval = firstDelay };+ _timer.Tick += async (_, _) =>+ {+ _timer.Interval = CheckInterval;+ if (enabled())+ await CheckAsync();+ };+ _timer.Start();+ }++ /// <summary>Opens the latest release page in the browser.</summary>+ public void OpenDownloadPage()+ {+ try+ {+ Process.Start(new ProcessStartInfo(LatestReleaseUrl) { UseShellExecute = true });+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException)+ {+ _log.LogWarning(ex, "Could not open {Url}", LatestReleaseUrl);+ }}++ private void Publish(string? newer)+ {+ var previous = LatestVersion;+ LatestVersion = newer;+ if (newer is not null && newer != previous)+ UpdateFound?.Invoke(this, newer);+ }++ /// <summary>True when release tag <paramref name="tag"/> ("v1.2.0") is a higher version than <paramref name="current"/>.</summary>+ internal static bool IsNewer(string? tag, string current) =>+ TryParse(tag, out var latest) && TryParse(current, out var installed) && latest > installed;++ /// <summary>"v1.2" / "1.2.0-beta+abc" → 1.2.0 (missing parts are 0, suffixes ignored).</summary>+ internal static bool TryParse(string? text, out Version version)+ {+ version = new Version(0, 0, 0);+ if (string.IsNullOrWhiteSpace(text))+ return false;+ var core = text.Trim().TrimStart('v', 'V').Split('-', '+')[0];+ if (!Version.TryParse(core.Contains('.') ? core : core + ".0", out var parsed))+ return false;+ version = new Version(parsed.Major, parsed.Minor, Math.Max(0, parsed.Build));+ return true;+ }++ private static string Normalize(string tag) => TryParse(tag, out var version) ? version.ToString(3) : tag;}diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.csindex 6fb0eec2..48de1278 100644--- a/src/Filee.App/Services/WindowService.cs+++ b/src/Filee.App/Services/WindowService.cs@@ -18,6 +18,7 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)private MainWindow? _main;private ToastWindow? _toast;private EngineSetupWindow? _engineSetup;+ private UpdateNoticeWindow? _updateNotice;public MainWindow? Main => _main;@@ -58,6 +59,25 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)_toast ??= new ToastWindow { DataContext = services.GetRequiredService<ConversionService>() };}+ /// <summary>Shows the "new version available" card in the bottom-right corner (above a visible toast).</summary>+ public void ShowUpdateNotice(string version)+ {+ _updateNotice?.Close();+ var notice = new UpdateNoticeWindow(services.GetRequiredService<UpdateService>(), loc.Format("update.notice_title", version))+ {+ BottomOffset = _toast is { IsVisible: true } toast+ ? (int)Math.Ceiling(toast.Bounds.Height * (toast.Screens.Primary?.Scaling ?? 1))+ : 0,+ };+ notice.Closed += (_, _) =>+ {+ if (_updateNotice == notice)+ _updateNotice = null;+ };+ _updateNotice = notice;+ notice.Show();+ }+/// <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){diff --git a/src/Filee.App/Styles/Icons.axaml b/src/Filee.App/Styles/Icons.axamlindex c30c7f3b..d67ae116 100644--- a/src/Filee.App/Styles/Icons.axaml+++ b/src/Filee.App/Styles/Icons.axaml@@ -20,6 +20,7 @@<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.Download">M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z</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>diff --git a/src/Filee.App/ViewModels/MainWindowViewModel.cs b/src/Filee.App/ViewModels/MainWindowViewModel.csindex 4e38ea87..2ab6fe70 100644--- a/src/Filee.App/ViewModels/MainWindowViewModel.cs+++ b/src/Filee.App/ViewModels/MainWindowViewModel.cs@@ -4,6 +4,8 @@ using Avalonia;using Avalonia.Controls;using Avalonia.Media;using CommunityToolkit.Mvvm.ComponentModel;+using CommunityToolkit.Mvvm.Input;+using Filee.App.Services;using Filee.App.ViewModels.Pages;using Filee.Core.Localization;using Microsoft.Extensions.DependencyInjection;@@ -26,10 +28,19 @@ public sealed partial class NavItem(string key, string titleKey, string iconKey,public sealed partial class MainWindowViewModel : ObservableObject{private readonly IServiceProvider _services;+ private readonly ILocalizer _loc;- public MainWindowViewModel(IServiceProvider services, ILocalizer loc)+ public MainWindowViewModel(IServiceProvider services, ILocalizer loc, UpdateService updates){_services = services;+ _loc = loc;+ Updates = updates;+ updates.PropertyChanged += (_, e) =>+ {+ if (e.PropertyName == nameof(UpdateService.LatestVersion))+ RefreshVersionTexts();+ };+ RefreshVersionTexts();Items =[new("home", "nav.home", "Icon.Home", typeof(HomePageViewModel)),@@ -47,6 +58,7 @@ public sealed partial class MainWindowViewModel : ObservableObject{foreach (var item in Items)item.Refresh(loc);+ RefreshVersionTexts();CurrentPage = CreatePage(SelectedItem); // rebuild so code-generated labels update too};_selectedItem = Items[0];@@ -55,8 +67,23 @@ public sealed partial class MainWindowViewModel : ObservableObjectpublic IReadOnlyList<NavItem> Items { get; }+ /// <summary>Update state for the bottom of the navigation (version, "update available" button).</summary>+ public UpdateService Updates { get; }+[ObservableProperty] private NavItem _selectedItem;[ObservableProperty] private ObservableObject _currentPage;+ [ObservableProperty] private string _versionText = "";+ [ObservableProperty] private string _updateText = "";++ /// <summary>Opens the latest release page to download the new installer.</summary>+ [RelayCommand]+ private void DownloadUpdate() => Updates.OpenDownloadPage();++ private void RefreshVersionTexts()+ {+ VersionText = _loc.Format("about.version", UpdateService.CurrentVersion);+ UpdateText = Updates.LatestVersion is { } latest ? _loc.Format("update.sidebar", latest) : "";+ }public void Navigate(string key){diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.csindex 572c6c2c..d2797429 100644--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs@@ -32,7 +32,7 @@ public sealed partial class GeneralPageViewModel : ObservableObject_startWithSystem = store.Settings.StartWithSystem;_contextMenu = store.Settings.ContextMenuEnabled;_checkForUpdates = store.Settings.CheckForUpdates;- _updateStatus = updates.IsInstalled ? null : loc["general.update_dev"];+ ShowUpdateState(updates.LatestVersion);}public IReadOnlyList<Choice<string>> Languages { get; }@@ -62,17 +62,19 @@ public sealed partial class GeneralPageViewModel : ObservableObjectprivate 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);- }+ private async Task CheckNow() => ShowUpdateState(await _updates.CheckAsync(), afterCheck: true);+ /// <summary>Opens the latest release page; the new installer updates Filee in place.</summary>[RelayCommand]- private Task InstallUpdate() => _updates.ApplyAsync();+ private void DownloadUpdate() => _updates.OpenDownloadPage();++ private void ShowUpdateState(string? newer, bool afterCheck = false)+ {+ UpdateAvailable = newer is not null;+ UpdateStatus = newer is not null ? _loc.Format("general.update_available", newer)+ : afterCheck ? _loc.Format("general.update_none", UpdateService.CurrentVersion)+ : _loc.Format("about.version", UpdateService.CurrentVersion);+ }public void Export(string path){diff --git a/src/Filee.App/Views/MainWindow.axaml b/src/Filee.App/Views/MainWindow.axamlindex 91932eec..97aa7ec8 100644--- a/src/Filee.App/Views/MainWindow.axaml+++ b/src/Filee.App/Views/MainWindow.axaml@@ -19,6 +19,18 @@<TextBlock Classes="caption" Text="{DynamicResource app.tagline}" /></StackPanel></StackPanel>+ <!-- Bottom: the running version, and a download button when a newer release is out. -->+ <StackPanel DockPanel.Dock="Bottom" Spacing="8" Margin="4,12,4,0">+ <Button x:Name="UpdateButton" Classes="accent" HorizontalAlignment="Stretch" HorizontalContentAlignment="Left"+ Command="{Binding DownloadUpdateCommand}" IsVisible="{Binding Updates.IsUpdateAvailable}"+ ToolTip.Tip="{DynamicResource update.notice_text}">+ <StackPanel Orientation="Horizontal" Spacing="8">+ <PathIcon Width="14" Height="14" Data="{StaticResource Icon.Download}" />+ <TextBlock Text="{Binding UpdateText}" TextTrimming="CharacterEllipsis" />+ </StackPanel>+ </Button>+ <TextBlock x:Name="VersionLabel" Classes="caption" Margin="8,0,0,0" Text="{Binding VersionText}" />+ </StackPanel><ListBox Classes="nav" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}"><ListBox.ItemTemplate><DataTemplate x:DataType="vm:NavItem">diff --git a/src/Filee.App/Views/Pages/AboutPage.axaml b/src/Filee.App/Views/Pages/AboutPage.axamlindex a268fd0f..32bc2168 100644--- a/src/Filee.App/Views/Pages/AboutPage.axaml+++ b/src/Filee.App/Views/Pages/AboutPage.axaml@@ -1,6 +1,7 @@<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.AboutPage"x:DataType="vm:AboutPageViewModel"><StackPanel Spacing="18">@@ -24,7 +25,7 @@<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}" />+ <c:MarkdownView Markdown="{Binding Notices}" SkipTitle="True" /></StackPanel></Border></StackPanel>diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axamlindex 4cd68c44..d6298d56 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml@@ -22,7 +22,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}" />+ <Button Classes="accent" Command="{Binding DownloadUpdateCommand}" IsVisible="{Binding UpdateAvailable}">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Download}" />+ <TextBlock Text="{DynamicResource update.download}" />+ </StackPanel>+ </Button><TextBlock Classes="muted" VerticalAlignment="Center" Text="{Binding UpdateStatus}" /></StackPanel></StackPanel>diff --git a/src/Filee.App/Views/UpdateNoticeWindow.axaml b/src/Filee.App/Views/UpdateNoticeWindow.axamlnew file mode 100644index 00000000..801ff33d--- /dev/null+++ b/src/Filee.App/Views/UpdateNoticeWindow.axaml@@ -0,0 +1,39 @@+<!-- "A new version is out" card in the bottom-right corner, shown once per new version (UpdateService.UpdateFound). -->+<Window xmlns="https://github.com/avaloniaui"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ x:Class="Filee.App.Views.UpdateNoticeWindow"+ Title="Filee"+ Width="360"+ SizeToContent="Height"+ WindowDecorations="None"+ Background="Transparent"+ TransparencyLevelHint="Transparent"+ Topmost="True"+ ShowInTaskbar="False"+ ShowActivated="False"+ CanResize="False">+ <Border Classes="card" Margin="12" Padding="16,14">+ <DockPanel>+ <Image DockPanel.Dock="Left" Source="avares://Filee/Assets/Icons/filee.png" Width="36" Height="36"+ VerticalAlignment="Top" Margin="0,2,12,0" />+ <StackPanel Spacing="8">+ <DockPanel>+ <Button DockPanel.Dock="Right" Classes="icon" Padding="4" VerticalAlignment="Top" Click="OnClose">+ <PathIcon Width="12" Height="12" Data="{StaticResource Icon.Close}" />+ </Button>+ <TextBlock x:Name="TitleText" FontWeight="SemiBold" TextWrapping="Wrap" VerticalAlignment="Center" />+ </DockPanel>+ <TextBlock Classes="caption" Text="{DynamicResource update.notice_text}" TextWrapping="Wrap" />+ <StackPanel Orientation="Horizontal" Spacing="8" Margin="0,2,0,0">+ <Button Classes="accent" Click="OnDownload" Padding="12,5">+ <StackPanel Orientation="Horizontal" Spacing="6">+ <PathIcon Width="13" Height="13" Data="{StaticResource Icon.Download}" />+ <TextBlock Text="{DynamicResource update.download}" />+ </StackPanel>+ </Button>+ <Button Content="{DynamicResource update.later}" Click="OnClose" Padding="12,5" />+ </StackPanel>+ </StackPanel>+ </DockPanel>+ </Border>+</Window>diff --git a/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs b/src/Filee.App/Views/UpdateNoticeWindow.axaml.csnew file mode 100644index 00000000..2d5a2c3b--- /dev/null+++ b/src/Filee.App/Views/UpdateNoticeWindow.axaml.cs@@ -0,0 +1,45 @@+using Avalonia;+using Avalonia.Controls;+using Avalonia.Interactivity;+using Filee.App.Services;++namespace Filee.App.Views;++/// <summary>Bottom-right notice about a new version. "Download" opens the latest release page.</summary>+public partial class UpdateNoticeWindow : Window+{+ private const int ScreenMargin = 12;+ private readonly UpdateService? _updates;++ public UpdateNoticeWindow() => InitializeComponent();++ public UpdateNoticeWindow(UpdateService updates, string title) : this()+ {+ _updates = updates;+ TitleText.Text = title;+ Motion.Track(this);+ SizeChanged += (_, _) => PlaceBottomRight();+ }++ /// <summary>Extra distance from the bottom of the screen, e.g. to stay above the conversion toast.</summary>+ public int BottomOffset { get; set; }++ private void OnDownload(object? sender, RoutedEventArgs e)+ {+ _updates?.OpenDownloadPage();+ Close();+ }++ private void OnClose(object? sender, RoutedEventArgs e) => Close();++ private void PlaceBottomRight()+ {+ var screen = Screens.Primary;+ if (screen is null)+ return;+ var area = screen.WorkingArea;+ var width = (int)Math.Ceiling(Bounds.Width * screen.Scaling);+ var height = (int)Math.Ceiling(Bounds.Height * screen.Scaling);+ Position = new PixelPoint(area.Right - width - ScreenMargin, area.Bottom - height - ScreenMargin - BottomOffset);+ }+}diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex ea8e61fb..7cd5146a 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -172,7 +172,11 @@ public sealed class JobQueue : IAsyncDisposablevar stepIndex = s;var progress = new Progress<double>(p =>{- file.Progress = (stepIndex + Math.Clamp(p, 0, 1)) / route.Steps.Count;+ // Reports arrive on the thread pool, possibly out of order: progress only moves forward.+ var value = (stepIndex + Math.Clamp(p, 0, 1)) / route.Steps.Count;+ if (value <= file.Progress)+ return;+ file.Progress = value;Notify(job);});diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 8760d66f..c977d04d 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -88,10 +88,20 @@ public static class BuiltInDataExtensions = ["hwp", "hwpx"],PresetIds = ["to-pdf", "to-docx", "to-hwpx", "to-png", "to-txt", "to-md", "merge-pdf"],},+ TextProfile(),new(){Id = "mixed", NameKey = "profile.mixed", IsFallback = true,PresetIds = ["to-pdf", "merge-pdf", "to-png", "to-txt"],},];++ /// <summary>Markdown, plain text and HTML (added in settings schema 4, see SettingsMigrations).</summary>+ public static ToolbarProfile TextProfile() => new()+ {+ Id = "text",+ NameKey = "profile.text",+ Extensions = ["md", "markdown", "txt", "html", "htm"],+ PresetIds = ["to-pdf", "to-hwpx", "to-docx", "to-html", "to-txt"],+ };}diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex e6e023e0..12c48e54 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -48,7 +48,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 3;+ public const int CurrentSchemaVersion = 4;public int SchemaVersion { get; set; } = CurrentSchemaVersion;@@ -62,6 +62,9 @@ public sealed class AppSettingspublic bool CheckForUpdates { get; set; } = true;+ /// <summary>Newest version the user was already told about, so the update notice shows once per release.</summary>+ public string? NotifiedUpdateVersion { get; set; }+/// <summary>Temporarily disable all trigger gestures (tray "Pause").</summary>public bool Paused { get; set; }@@ -75,7 +78,7 @@ public sealed class AppSettingspublic 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"];+ public List<string> EnginePriority { get; set; } = ["magick", "pdfium", "pdfsharp", "rhwp", "unhwp", "markdown", "hwpx-writer", "word", "pandoc", "libreoffice"];/// <summary>User-provided executable paths per engine id, overriding auto-detection.</summary>public Dictionary<string, string> EnginePaths { get; set; } = [];diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex c7723e3f..a38365d6 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -60,8 +60,19 @@ public sealed class UserDataStoreProfiles = Read(ProfilesPath, FileeJsonContext.Default.ListToolbarProfile) ?? BuiltInData.CreateProfiles();History = Read(HistoryPath, FileeJsonContext.Default.ListHistoryEntry) ?? [];+ var schema = Settings.SchemaVersion;SettingsMigrations.Apply(Settings);+ var libraryChanged = File.Exists(ProfilesPath) && SettingsMigrations.ApplyToLibrary(schema, Presets, Profiles);EnsureConsistency();++ // Persist upgrades right away so they run once, even if the user never changes a setting.+ if (schema < AppSettings.CurrentSchemaVersion && File.Exists(SettingsPath))+ Write(SettingsPath, Settings, FileeJsonContext.Default.AppSettings);+ if (libraryChanged)+ {+ Write(PresetsPath, Presets, FileeJsonContext.Default.ListPreset);+ Write(ProfilesPath, Profiles, FileeJsonContext.Default.ListToolbarProfile);+ }}public void SaveSettings()@@ -215,12 +226,36 @@ internal static class SettingsMigrationssettings.EnginePriority[index] = "hwpx-writer";}+ // v4: built-in "markdown" engine (Markdig, no Pandoc needed); the "text" toolbar profile is added by+ // ApplyToLibrary.+ if (settings.SchemaVersion < 4)+ InsertBefore(settings.EnginePriority, "markdown", "hwpx-writer");+if (settings.Triggers.Count == 0)settings.Triggers = TriggerGesture.Defaults();settings.SchemaVersion = AppSettings.CurrentSchemaVersion;}+ /// <summary>Upgrades presets and profiles written with settings schema <paramref name="from"/>.</summary>+ /// <returns>True when something was added.</returns>+ public static bool ApplyToLibrary(int from, List<Preset> presets, List<ToolbarProfile> profiles)+ {+ var changed = false;+ // v4: Markdown / TXT / HTML files get their own donut instead of the "mixed files" fallback. Skipped when+ // the user already routes Markdown through a profile of their own.+ if (from < 4 && !profiles.Any(p => p.Id == "text" || p.Extensions.Contains("md", StringComparer.OrdinalIgnoreCase)))+ {+ var text = BuiltInData.TextProfile();+ var ids = presets.Select(p => p.Id).ToHashSet();+ text.PresetIds = text.PresetIds.Where(ids.Contains).ToList();+ var fallback = profiles.FindIndex(p => p.IsFallback);+ profiles.Insert(fallback < 0 ? profiles.Count : fallback, text);+ changed = true;+ }+ return changed;+ }+private static void InsertBefore(List<string> list, string id, string before){if (list.Contains(id))diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.csindex 113517fd..a0122fa1 100644--- a/src/Filee.Engines/EngineRegistry.cs+++ b/src/Filee.Engines/EngineRegistry.cs@@ -7,6 +7,7 @@ using Filee.Engines.Infrastructure;using Filee.Engines.Magick;using Filee.Engines.Office;using Filee.Engines.Pdf;+using Filee.Engines.Text;namespace Filee.Engines;@@ -24,6 +25,7 @@ public static class EngineRegistrynew PdfiumConverter(),new RhwpConverter(env),new UnhwpConverter(),+ new MarkdownConverter(),new HwpxConverter(env),new WordComConverter(),new PandocConverter(env),diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.csindex c9d7716e..186f3bba 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxConverter.cs@@ -2,7 +2,8 @@// 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).+// * Markdown is parsed with Markdig (MarkdownReader), no external engine needed.+// * HTML, ODT and RTF are parsed by Pandoc (optional engine) into its JSON AST (PandocAstReader).using System.Text;using System.Text.Json.Nodes;@@ -24,7 +25,6 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter["odt"] = "odt",["rtf"] = "rtf",["html"] = "html",- ["md"] = "markdown",};private string? _pandoc;@@ -39,8 +39,8 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter{_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})");+ ? "DOCX, TXT, Markdown → HWPX. 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)@@ -51,6 +51,8 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverter{"docx" => DocxReader.Read(step.InputPath, media),"txt" => TextDocument(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),+ "md" => MarkdownReader.Read(DecodeText(await File.ReadAllBytesAsync(step.InputPath, cancellationToken)),+ Path.GetDirectoryName(Path.GetFullPath(step.InputPath))!),_ => await ReadWithPandocAsync(step, media, cancellationToken),};progress?.Report(0.6);@@ -68,10 +70,10 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConvertervar 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.+ // Working directory = the input's folder, so relative image paths in HTML 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));+ Timeout, cancellationToken, workingDirectory: Path.GetDirectoryName(Path.GetFullPath(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))@@ -80,7 +82,7 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverterreturn 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>+ /// <summary>Images extracted by Pandoc have absolute paths; HTML may use paths relative to the input.</summary>private static string? ResolveImage(string target, string inputFolder){if (string.IsNullOrWhiteSpace(target) || target.Contains("://", StringComparison.Ordinal))@@ -133,7 +135,7 @@ public sealed class HwpxConverter(EngineEnvironment env) : IConverterprivate static List<ConversionEdge> BuildEdges(bool pandoc){- List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx")];+ List<ConversionEdge> edges = [new("txt", "hwpx"), new("docx", "hwpx"), new("md", "hwpx")];if (pandoc)edges.AddRange(PandocReaders.Keys.Select(from => new ConversionEdge(from, "hwpx")));return edges;diff --git a/src/Filee.Engines/Hwp/Hwpx/MarkdownReader.cs b/src/Filee.Engines/Hwp/Hwpx/MarkdownReader.csnew file mode 100644index 00000000..fe16bfb6--- /dev/null+++ b/src/Filee.Engines/Hwp/Hwpx/MarkdownReader.cs@@ -0,0 +1,401 @@+// Markdown → HDocument with Markdig (BSD-2-Clause), so Markdown → HWPX needs no external engine.+//+// Mirrors PandocAstReader: headings (with their ids as bookmarks), paragraphs, bold / italic / strike / sub- and+// superscript / inserted / marked text, code, lists (1. / a. / i. / A. / I. with the start number, nested levels),+// task lists, block quotes, pipe and grid tables with spans, definition lists, links, images, footnotes and math.+// The YAML front matter's "title" becomes the document title. Raw HTML is skipped, except <br>.++using Markdig;+using Markdig.Extensions.DefinitionLists;+using Markdig.Extensions.Footnotes;+using Markdig.Extensions.Mathematics;+using Markdig.Extensions.Tables;+using Markdig.Extensions.TaskLists;+using Markdig.Extensions.Yaml;+using Markdig.Renderers.Html;+using Markdig.Syntax;+using Markdig.Syntax.Inlines;++namespace Filee.Engines.Hwp.Hwpx;++internal sealed class MarkdownReader+{+ /// <summary>Indent per block quote level (same as PandocAstReader).</summary>+ private const int QuoteIndent = 2000;++ /// <summary>GitHub-style Markdown plus the common extensions (tables, footnotes, task lists, math, …).</summary>+ public static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder()+ .UseAdvancedExtensions()+ .UseYamlFrontMatter()+ .Build();++ private static readonly HCharFormat Plain = default;+ private static readonly HCharFormat CodeFormat = new(Shade: "#F1F0F5");+ private readonly string _baseFolder;++ private MarkdownReader(string baseFolder) => _baseFolder = baseFolder;++ /// <summary>Parses Markdown text.</summary>+ /// <param name="markdown">The document text.</param>+ /// <param name="baseFolder">Folder of the Markdown file: relative image paths are resolved against it.</param>+ public static HDocument Read(string markdown, string baseFolder)+ {+ var parsed = Markdown.Parse(markdown, Pipeline);+ var reader = new MarkdownReader(baseFolder);+ var section = new HSection();+ reader.Blocks(parsed, section.Blocks, new Context());+ var document = new HDocument { Title = Title(parsed) };+ 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(ContainerBlock container, List<HBlock> output, Context context)+ {+ foreach (var block in container)+ Block(block, output, context);+ }++ private void Block(Block block, List<HBlock> output, Context context)+ {+ switch (block)+ {+ // First: YAML front matter is a code block and HTML blocks are leaf blocks in Markdig's model.+ case HtmlBlock or YamlFrontMatterBlock or LinkReferenceDefinitionGroup or FootnoteGroup:+ break; // raw HTML, metadata and definitions carry no document text (footnotes are read at their links)+ case HeadingBlock heading:+ output.Add(Heading(heading, context));+ break;+ case ParagraphBlock paragraph:+ output.Add(Paragraph(paragraph.Inline, context));+ break;+ case ListBlock list:+ List(list, output, context);+ break;+ case QuoteBlock quote:+ Blocks(quote, output, context with { Indent = context.Indent + QuoteIndent });+ break;+ case MathBlock math:+ CodeLines(math, output, context, Plain with { Italic = true });+ break;+ case CodeBlock code:+ CodeLines(code, output, context, CodeFormat);+ break;+ case ThematicBreakBlock:+ output.Add(NewParagraph(context));+ break;+ case Table table:+ output.Add(TableBlock(table, context));+ break;+ case DefinitionList definitions:+ DefinitionListBlock(definitions, output, context);+ break;+ case ContainerBlock container:+ Blocks(container, output, context); // figures, custom containers, …+ break;+ case LeafBlock { Inline: { } inline }:+ output.Add(Paragraph(inline, context));+ break;+ }+ }++ private static HParagraph NewParagraph(Context context) =>+ new() { Format = context.Indent > 0 ? new HParaFormat(Left: context.Indent) : default };++ private HParagraph Paragraph(ContainerInline? inlines, Context context)+ {+ var paragraph = NewParagraph(context);+ Inlines(inlines, paragraph.Inlines, Plain);+ return paragraph;+ }++ private HParagraph Heading(HeadingBlock heading, Context context)+ {+ var paragraph = Paragraph(heading.Inline, context);+ paragraph.HeadingLevel = Math.Clamp(heading.Level, 1, 9);+ // Heading ids are link targets ("#id" links, e.g. a table of contents).+ if (heading.GetAttributes().Id is { Length: > 0 } id)+ paragraph.Inlines.Insert(0, new HBookmark(id));+ return paragraph;+ }++ private static void CodeLines(LeafBlock code, List<HBlock> output, Context context, HCharFormat format)+ {+ foreach (var line in code.Lines.ToString().Replace("\r\n", "\n").Split('\n'))+ {+ var paragraph = NewParagraph(context);+ if (line.Length > 0)+ paragraph.Inlines.Add(new HText(line, format));+ output.Add(paragraph);+ }+ }++ private static HNumbering Numbering(ListBlock list)+ {+ string[] bullets = ["●", "○", "■"];+ string[] defaultFormats = ["DIGIT", "LATIN_CAPITAL", "ROMAN_SMALL"];+ var numbering = new HNumbering();+ var start = int.TryParse(list.OrderedStart, out var value) ? Math.Max(1, value) : 1;+ for (var level = 1; level <= 7; level++)+ {+ if (!list.IsOrdered)+ {+ numbering.Levels.Add(new HNumberingLevel("DIGIT", bullets[(level - 1) % 3], 1, Bullet: true));+ continue;+ }+ // The first level follows the Markdown list; deeper levels use the usual 1. → A. → i. sequence.+ var format = level > 1 ? defaultFormats[(level - 1) % 3] : list.BulletType switch+ {+ 'a' => "LATIN_SMALL",+ 'A' => "LATIN_CAPITAL",+ 'i' => "ROMAN_SMALL",+ 'I' => "ROMAN_CAPITAL",+ _ => "DIGIT",+ };+ var text = list.OrderedDelimiter == ')' ? $"^{level})" : $"^{level}.";+ numbering.Levels.Add(new HNumberingLevel(format, text, level == 1 ? start : 1, Bullet: false));+ }+ return numbering;+ }++ private void List(ListBlock list, List<HBlock> output, Context context)+ {+ var numbering = Numbering(list);+ foreach (var item in list.OfType<ListItemBlock>())+ {+ // Only the first paragraph of an item carries the bullet or number.+ var first = true;+ foreach (var block in item)+ {+ switch (block)+ {+ case ParagraphBlock paragraphBlock:+ {+ var paragraph = Paragraph(paragraphBlock.Inline, context);+ paragraph.List = new HListRef(numbering, context.ListLevel, Numbered: first);+ output.Add(paragraph);+ first = false;+ break;+ }+ case ListBlock nested:+ List(nested, output, context with { ListLevel = context.ListLevel + 1 });+ break;+ default:+ Block(block, output, context);+ first = false;+ break;+ }+ }+ }+ }++ private HTable TableBlock(Table table, Context context)+ {+ var rows = table.OfType<TableRow>().ToList();+ var columns = Math.Max(table.ColumnDefinitions.Count, rows.Count == 0 ? 1 : rows.Max(r => r.OfType<TableCell>().Sum(c => Math.Max(1, c.ColumnSpan))));+ var widths = table.ColumnDefinitions.Select(d => (double)d.Width / 100).ToList();+ while (widths.Count < columns)+ widths.Add(0);+ var hTable = new HTable+ {+ ColumnCount = columns,+ RelativeWidths = widths.Take(columns).All(w => w <= 0) ? null : [.. widths.Take(columns)],+ Indent = context.Indent,+ };+ foreach (var row in rows)+ {+ var hRow = new HRow { Header = row.IsHeader };+ foreach (var cell in row.OfType<TableCell>())+ {+ var hCell = new HCell+ {+ RowSpan = Math.Max(1, cell.RowSpan),+ ColSpan = Math.Max(1, cell.ColumnSpan),+ };+ Blocks(cell, hCell.Blocks, new Context());+ if (row.IsHeader)+ BoldHeader(hCell.Blocks);+ hRow.Cells.Add(hCell);+ }+ hTable.Rows.Add(hRow);+ }+ return hTable;+ }++ /// <summary>Header cells are bold, as Markdown renderers show them.</summary>+ private static void BoldHeader(List<HBlock> blocks)+ {+ foreach (var paragraph in blocks.OfType<HParagraph>())+ for (var i = 0; i < paragraph.Inlines.Count; i++)+ if (paragraph.Inlines[i] is HText text && text.Format.Bold is null)+ paragraph.Inlines[i] = new HText(text.Text, text.Format with { Bold = true });+ }++ private void DefinitionListBlock(DefinitionList definitions, List<HBlock> output, Context context)+ {+ foreach (var item in definitions.OfType<DefinitionItem>())+ {+ foreach (var block in item)+ {+ if (block is DefinitionTerm term)+ {+ var paragraph = NewParagraph(context);+ Inlines(term.Inline, paragraph.Inlines, new HCharFormat(Bold: true));+ output.Add(paragraph);+ }+ else+ {+ Block(block, output, context with { Indent = context.Indent + QuoteIndent });+ }+ }+ }+ }++ // ───────────────────────── Inlines ─────────────────────────++ private void Inlines(ContainerInline? container, List<HInline> output, HCharFormat format)+ {+ if (container is null)+ return;+ foreach (var inline in container)+ {+ switch (inline)+ {+ case LiteralInline literal:+ output.Add(new HText(literal.Content.ToString(), format));+ break;+ case CodeInline code:+ output.Add(new HText(code.Content, format with { Shade = CodeFormat.Shade }));+ break;+ case LineBreakInline lineBreak:+ output.Add(lineBreak.IsHard ? new HLineBreak(format) : new HText(" ", format));+ break;+ case EmphasisInline emphasis:+ Inlines(emphasis, output, Emphasis(emphasis, format));+ break;+ case LinkInline { IsImage: true } image:+ if (Image(image) is { } picture)+ output.Add(picture);+ break;+ case LinkInline link:+ Link(link.Url, link, output, format);+ break;+ case AutolinkInline autolink:+ {+ var target = autolink.IsEmail && !autolink.Url.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)+ ? "mailto:" + autolink.Url+ : autolink.Url;+ var hLink = new HLink(target);+ hLink.Content.Add(new HText(autolink.Url, format));+ output.Add(hLink);+ break;+ }+ case HtmlEntityInline entity:+ output.Add(new HText(entity.Transcoded.ToString(), format));+ break;+ case HtmlInline html:+ if (html.Tag.StartsWith("<br", StringComparison.OrdinalIgnoreCase))+ output.Add(new HLineBreak(format));+ break; // other raw HTML carries no text of its own+ case TaskList task:+ output.Add(new HText(task.Checked ? "☑" : "☐", format)); // the following text starts with a space+ break;+ case MathInline math:+ output.Add(new HText(math.Content.ToString(), format with { Italic = true }));+ break;+ case FootnoteLink { IsBackLink: false } footnote:+ {+ var note = new HNote(endnote: false);+ Blocks(footnote.Footnote, note.Blocks, new Context());+ output.Add(note);+ break;+ }+ case FootnoteLink:+ break; // the "↩" back link inside a footnote+ case ContainerInline other:+ Inlines(other, output, format);+ break;+ }+ }+ }++ private static HCharFormat Emphasis(EmphasisInline emphasis, HCharFormat format) => emphasis.DelimiterChar switch+ {+ '*' or '_' when emphasis.DelimiterCount >= 3 => format with { Bold = true, Italic = true },+ '*' or '_' when emphasis.DelimiterCount == 2 => format with { Bold = true },+ '*' or '_' => format with { Italic = true },+ '~' when emphasis.DelimiterCount >= 2 => format with { Strike = true },+ '~' => format with { Subscript = true, Superscript = null },+ '^' => format with { Superscript = true, Subscript = null },+ '+' => format with { Underline = true },+ '=' => format with { Shade = "#FFF3A3" },+ _ => format,+ };++ private void Link(string? url, ContainerInline content, List<HInline> output, HCharFormat format)+ {+ if (string.IsNullOrWhiteSpace(url))+ {+ Inlines(content, output, format);+ return;+ }+ var link = new HLink(url);+ Inlines(content, link.Content, format);+ output.Add(link);+ }++ private HImage? Image(LinkInline image)+ {+ var path = ResolveImage(image.Url, _baseFolder);+ if (path is null)+ return null; // remote or missing image: skip rather than produce a broken reference++ // Sizes from the generic attributes extension: {width=50% height=3cm}+ var properties = image.GetAttributes().Properties ?? [];+ string? Attribute(string name) => properties.FirstOrDefault(p => string.Equals(p.Key, name, StringComparison.OrdinalIgnoreCase)).Value;+ return new HImage(path)+ {+ Width = HwpxUnits.ParseLength(Attribute("width")),+ Height = HwpxUnits.ParseLength(Attribute("height")),+ };+ }++ /// <summary>Local image path of a Markdown image target, or null for remote / missing images.</summary>+ internal static string? ResolveImage(string? target, string baseFolder)+ {+ if (string.IsNullOrWhiteSpace(target) || target.Contains("://", StringComparison.Ordinal) && !target.StartsWith("file:", StringComparison.OrdinalIgnoreCase))+ return null;+ try+ {+ var path = target.StartsWith("file:", StringComparison.OrdinalIgnoreCase)+ ? new Uri(target).LocalPath+ : Uri.UnescapeDataString(target);+ var candidate = Path.IsPathRooted(path) ? path : Path.Combine(baseFolder, path);+ return File.Exists(candidate) ? Path.GetFullPath(candidate) : null;+ }+ catch (Exception ex) when (ex is ArgumentException or UriFormatException or NotSupportedException)+ {+ return null;+ }+ }++ // ───────────────────────── Helpers ─────────────────────────++ /// <summary>"title:" from the YAML front matter, if any.</summary>+ private static string? Title(MarkdownDocument document)+ {+ if (document.Descendants<YamlFrontMatterBlock>().FirstOrDefault() is not { } yaml)+ return null;+ foreach (var line in yaml.Lines.ToString().Split('\n'))+ {+ var trimmed = line.Trim();+ if (trimmed.StartsWith("title:", StringComparison.OrdinalIgnoreCase))+ return trimmed["title:".Length..].Trim().Trim('"', '\'') is { Length: > 0 } title ? title : null;+ }+ return null;+ }+}diff --git a/src/Filee.Engines/Hwp/RhwpConverter.cs b/src/Filee.Engines/Hwp/RhwpConverter.csindex 091dddc3..96894b26 100644--- a/src/Filee.Engines/Hwp/RhwpConverter.cs+++ b/src/Filee.Engines/Hwp/RhwpConverter.cs@@ -44,7 +44,9 @@ public sealed class RhwpConverter(EngineEnvironment env) : IConverter};progress?.Report(0.1);- var result = await ProcessRunner.RunAsync(exe, arguments, Timeout, cancellationToken);+ ProcessResult result;+ using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(1.5)))+ 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()}");diff --git a/src/Filee.Engines/Hwp/UnhwpConverter.cs b/src/Filee.Engines/Hwp/UnhwpConverter.csindex 184f5da7..cdfada06 100644--- a/src/Filee.Engines/Hwp/UnhwpConverter.cs+++ b/src/Filee.Engines/Hwp/UnhwpConverter.cs@@ -1,6 +1,5 @@// 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;@@ -56,17 +55,5 @@ public sealed class UnhwpConverter : IConverter}, 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>- """;+ Text.MarkdownConverter.HtmlPage(title, Markdown.ToHtml(markdown, Pipeline));}diff --git a/src/Filee.Engines/Infrastructure/ProgressEstimate.cs b/src/Filee.Engines/Infrastructure/ProgressEstimate.csnew file mode 100644index 00000000..51e8715d--- /dev/null+++ b/src/Filee.Engines/Infrastructure/ProgressEstimate.cs@@ -0,0 +1,46 @@+// Estimated progress for engines that report nothing while they work (LibreOffice, Pandoc, rhwp, Word): the value+// rises quickly at first and ever slower towards an upper bound, so the progress ring never sits still at 0 %.++using System.Diagnostics;++namespace Filee.Engines.Infrastructure;++/// <summary>Reports a rising progress estimate until disposed. Does nothing without a progress sink.</summary>+public sealed class ProgressEstimate : IDisposable+{+ private static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(150);++ private readonly Timer? _timer;+ private int _disposed;++ private ProgressEstimate(IProgress<double>? progress, TimeSpan typical, double from, double to)+ {+ if (progress is null)+ return;+ var started = Stopwatch.GetTimestamp();+ var seconds = Math.Max(0.1, typical.TotalSeconds);+ _timer = new Timer(_ =>+ {+ if (Volatile.Read(ref _disposed) == 0)+ progress.Report(Value(Stopwatch.GetElapsedTime(started).TotalSeconds, seconds, from, to));+ }, null, Interval, Interval);+ }++ /// <summary>Starts reporting.</summary>+ /// <param name="progress">Progress sink of the conversion step (may be null).</param>+ /// <param name="typical">Usual duration of the work: after it the estimate has covered about 63 % of the way.</param>+ /// <param name="from">Value at the start (what the engine reported before starting the work).</param>+ /// <param name="to">Upper bound, reached only asymptotically; the engine reports 1 itself when done.</param>+ public static ProgressEstimate Start(IProgress<double>? progress, TimeSpan typical, double from = 0.1, double to = 0.9) =>+ new(progress, typical, from, to);++ /// <summary>The estimate after <paramref name="elapsed"/> seconds.</summary>+ internal static double Value(double elapsed, double typical, double from, double to) =>+ from + (to - from) * (1 - Math.Exp(-Math.Max(0, elapsed) / typical));++ public void Dispose()+ {+ Interlocked.Exchange(ref _disposed, 1);+ _timer?.Dispose();+ }+}diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.csindex e7f686a4..370d75e9 100644--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs@@ -7,8 +7,10 @@// * 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.+// * The first conversion with a new profile takes 2-3× longer (LibreOffice builds its caches), so WarmUpAsync+// converts a tiny file once per worker profile in the background. --terminate_after_init alone doesn't help.+// * soffice reports no progress: ProgressEstimate keeps the progress ring moving while it runs.-using System.Collections.Concurrent;using Filee.Core.Conversion;using Filee.Engines.Infrastructure;using Microsoft.Win32;@@ -21,12 +23,19 @@ public sealed class LibreOfficeConverter : IConverterprivate const int Workers = 2;private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(3);+ /// <summary>Usual time of one conversion with a prepared profile (drives the progress estimate).</summary>+ private static readonly TimeSpan TypicalDuration = TimeSpan.FromSeconds(4);+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));++ // A worker profile must never be used by two soffice processes at once: conversions and the warm-up take a+ // profile number from _freeProfiles (guarded by itself) after _capacity lets them in.+ private readonly SemaphoreSlim _capacity = new(Workers, Workers);+ private readonly Stack<int> _freeProfiles = new(Enumerable.Range(0, Workers).Reverse());private string? _soffice;private bool _hasHwpFilter;@@ -54,28 +63,16 @@ public sealed class LibreOfficeConverter : IConverterpublic 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-+ var slot = await TakeProfileAsync(cancellationToken);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);+ ProcessResult result;+ using (ProgressEstimate.Start(progress, TypicalDuration))+ result = await RunAsync(soffice, slot, FilterFor(step.From, step.To, step.Preset.Document.PdfA), outDir, step.InputPath, cancellationToken);var produced = Directory.EnumerateFiles(outDir).FirstOrDefault(f => new FileInfo(f).Length > 0);if (produced is null)throw new InvalidOperationException(@@ -90,8 +87,92 @@ public sealed class LibreOfficeConverter : IConverter}finally{- _freeProfiles.Add(slot);+ ReturnProfile(slot);+ }+ }++ /// <summary>+ /// Prepares the worker profiles that were never used, by converting a tiny file with each of them, so the user's+ /// first conversion doesn't pay for LibreOffice's first start. Quick no-op when LibreOffice is missing or the+ /// profiles are ready. A conversion that starts meanwhile gets the other profile or waits for this one.+ /// </summary>+ /// <returns>Number of profiles prepared.</returns>+ public async Task<int> WarmUpAsync(CancellationToken cancellationToken = default)+ {+ Locate();+ if (_soffice is not { } soffice || Enumerable.Range(0, Workers).All(IsPrepared))+ return 0;++ var prepared = 0;+ int? held = null;+ try+ {+ for (var i = 0; i < Workers; i++)+ {+ // Taken while the previous one is still held, so every round gets a different profile.+ var slot = await TakeProfileAsync(cancellationToken);+ if (held is { } previous)+ ReturnProfile(previous);+ held = slot;+ if (IsPrepared(slot))+ continue;++ var folder = Path.Combine(Path.GetTempPath(), "filee-warmup-" + Guid.NewGuid().ToString("N")[..8]);+ try+ {+ Directory.CreateDirectory(folder);+ var input = Path.Combine(folder, "warmup.txt");+ await File.WriteAllTextAsync(input, "Filee", cancellationToken);+ await RunAsync(soffice, slot, FilterFor("txt", "pdf", pdfA: false), folder, input, cancellationToken);+ prepared++;+ }+ finally+ {+ try { Directory.Delete(folder, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { }+ }+ }}+ finally+ {+ if (held is { } last)+ ReturnProfile(last);+ }+ return prepared;+ }++ private string ProfileDirectory(int slot) => Path.Combine(_env.DataDirectory, "libreoffice-profiles", $"worker-{slot}");++ /// <summary>LibreOffice has started with this profile before (it creates the "user" folder).</summary>+ private bool IsPrepared(int slot) => Directory.Exists(Path.Combine(ProfileDirectory(slot), "user"));++ private async Task<int> TakeProfileAsync(CancellationToken cancellationToken)+ {+ await _capacity.WaitAsync(cancellationToken);+ lock (_freeProfiles)+ return _freeProfiles.Pop();+ }++ private void ReturnProfile(int slot)+ {+ lock (_freeProfiles)+ _freeProfiles.Push(slot);+ _capacity.Release();+ }++ private async Task<ProcessResult> RunAsync(string soffice, int slot, string filter, string outDir, string input, CancellationToken cancellationToken)+ {+ var profileDir = ProfileDirectory(slot);+ Directory.CreateDirectory(profileDir);+ 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", filter, "--outdir", outDir, input]);+ return await ProcessRunner.RunAsync(soffice, args, Timeout, cancellationToken);}/// <summary>Maps a target format to a LibreOffice <c>--convert-to</c> filter specification.</summary>diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.csindex 6d83bd41..26421284 100644--- a/src/Filee.Engines/Office/PandocConverter.cs+++ b/src/Filee.Engines/Office/PandocConverter.cs@@ -66,8 +66,10 @@ public sealed class PandocConverter(EngineEnvironment env) : IConverterif (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)));+ ProcessResult result;+ using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(1.5)))+ 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);diff --git a/src/Filee.Engines/Office/WordComConverter.cs b/src/Filee.Engines/Office/WordComConverter.csindex 128265bf..fdd8508b 100644--- a/src/Filee.Engines/Office/WordComConverter.cs+++ b/src/Filee.Engines/Office/WordComConverter.cs@@ -61,7 +61,8 @@ public sealed class WordComConverter : IConverterprogress?.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);+ using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(4)))+ await new AutomationProcessGuard("WINWORD").RunAsync(() => Convert(step.InputPath, target, step.To), Timeout, cancellationToken);#pragma warning restore CA1416progress?.Report(1);return [target];diff --git a/src/Filee.Engines/Text/MarkdownConverter.cs b/src/Filee.Engines/Text/MarkdownConverter.csnew file mode 100644index 00000000..9e698700--- /dev/null+++ b/src/Filee.Engines/Text/MarkdownConverter.cs@@ -0,0 +1,85 @@+// Markdown → HTML and plain text with Markdig (BSD-2-Clause), in-process: Markdown works without any optional engine.+// The HTML also serves as an intermediate step (Markdown → HTML → PDF / DOCX through LibreOffice), so local images+// get absolute file URIs whenever the page is written away from the Markdown file.++using System.Net;+using System.Text;+using Filee.Core.Conversion;+using Filee.Engines.Hwp.Hwpx;+using Markdig;+using Markdig.Renderers;+using Markdig.Syntax;+using Markdig.Syntax.Inlines;++namespace Filee.Engines.Text;++/// <summary>Markdown to HTML and TXT without external programs.</summary>+public sealed class MarkdownConverter : IConverter+{+ public string Id => "markdown";+ public string DisplayName => "Markdown (built-in)";+ public int MaxParallelism => 0;++ // Cheaper than Pandoc's Markdown edges, so the built-in path wins for HTML and TXT.+ public IReadOnlyList<ConversionEdge> Edges { get; } = [new("md", "html", 4), new("md", "txt", 5)];++ public EngineStatus GetStatus() => EngineStatus.Available("Markdig");++ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var markdown = HwpxConverter.DecodeText(await File.ReadAllBytesAsync(step.InputPath, cancellationToken));+ progress?.Report(0.3);+ var output = step.Output.Allocate(step.To);+ if (output is null)+ return [];++ var content = step.To switch+ {+ "html" => ToHtml(markdown, Path.GetFullPath(step.InputPath), output),+ "txt" => Markdown.ToPlainText(markdown, MarkdownReader.Pipeline),+ _ => throw new NotSupportedException(step.To),+ };+ await File.WriteAllTextAsync(output, content, new UTF8Encoding(encoderShouldEmitUTF8Identifier: step.To == "txt"), cancellationToken);+ progress?.Report(1);+ return [output];+ }++ /// <summary>A complete HTML page for the Markdown file at <paramref name="inputPath"/>, written to <paramref name="outputPath"/>.</summary>+ internal static string ToHtml(string markdown, string inputPath, string outputPath)+ {+ var document = Markdown.Parse(markdown, MarkdownReader.Pipeline);+ var inputFolder = Path.GetDirectoryName(inputPath)!;+ if (!string.Equals(inputFolder, Path.GetDirectoryName(Path.GetFullPath(outputPath)), StringComparison.OrdinalIgnoreCase))+ {+ // Relative image paths would break away from the Markdown file: point them at the original files.+ foreach (var image in document.Descendants<LinkInline>().Where(l => l.IsImage))+ if (MarkdownReader.ResolveImage(image.Url, inputFolder) is { } path)+ image.Url = new Uri(path).AbsoluteUri;+ }++ using var writer = new StringWriter();+ var renderer = new HtmlRenderer(writer);+ MarkdownReader.Pipeline.Setup(renderer);+ renderer.Render(document);+ var title = document.Descendants<HeadingBlock>().FirstOrDefault() is { Inline: { } heading }+ ? string.Concat(heading.Descendants<LiteralInline>().Select(l => l.Content.ToString()))+ : Path.GetFileNameWithoutExtension(inputPath);+ return HtmlPage(title, writer.ToString());+ }++ /// <summary>Wraps an HTML fragment into a readable, self-contained page (UTF-8, Korean / Chinese fonts).</summary>+ internal static string HtmlPage(string title, string body) =>+ $$"""+ <!DOCTYPE html>+ <html>+ <head>+ <meta charset="utf-8">+ <title>{{WebUtility.HtmlEncode(title)}}</title>+ <style>body{font-family:'Noto Sans KR','Malgun Gothic','Microsoft YaHei',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}pre,code{background:#f4f3f8;border-radius:4px}pre{padding:.6rem .8rem;overflow:auto}img{max-width:100%}blockquote{margin-left:0;padding-left:1rem;border-left:3px solid #ccc;color:#555}</style>+ </head>+ <body>+ {{body}}+ </body>+ </html>+ """;+}diff --git a/tests/Filee.App.Tests/MarkdownViewTests.cs b/tests/Filee.App.Tests/MarkdownViewTests.csnew file mode 100644index 00000000..07b7bda6--- /dev/null+++ b/tests/Filee.App.Tests/MarkdownViewTests.cs@@ -0,0 +1,49 @@+using Avalonia.Controls;+using Avalonia.Headless.XUnit;+using Avalonia.Platform;+using Avalonia.VisualTree;+using Filee.App.Controls;++namespace Filee.App.Tests;++public class MarkdownViewTests+{+ private static MarkdownView Show(string markdown, bool skipTitle = true)+ {+ var view = new MarkdownView { Markdown = markdown, SkipTitle = skipTitle };+ new Window { Content = new ScrollViewer { Content = view }, Width = 800, Height = 600 }.Show();+ return view;+ }++ [AvaloniaFact]+ public void Third_party_notices_render_as_headings_tables_and_links()+ {+ TestServices.EnsureInitialized("en");+ using var reader = new StreamReader(AssetLoader.Open(new Uri("avares://Filee/Assets/THIRD-PARTY-NOTICES.md")));+ var markdown = reader.ReadToEnd();++ var view = Show(markdown);++ var texts = view.GetVisualDescendants().OfType<TextBlock>().Select(t => t.Inlines?.Text ?? t.Text ?? "").ToList();+ Assert.DoesNotContain(texts, t => t.StartsWith('#') || t.Contains("|---")); // no raw Markdown left+ Assert.DoesNotContain("Third-party notices", texts); // the title is the page's own+ Assert.Contains("Libraries (NuGet)", texts);+ Assert.True(view.GetVisualDescendants().OfType<Grid>().Count() >= 3); // one per table+ var links = view.GetVisualDescendants().OfType<HyperlinkButton>().ToList();+ Assert.Contains(links, l => l.NavigateUri?.AbsoluteUri == "https://github.com/AvaloniaUI/Avalonia");+ }++ [AvaloniaFact]+ public void Inline_code_emphasis_and_lists_keep_their_text()+ {+ TestServices.EnsureInitialized("en");++ var view = Show("# Title\n\nUse **bold** and `code`.\n\n- one\n- two\n", skipTitle: false);++ var texts = view.GetVisualDescendants().OfType<TextBlock>().Select(t => t.Inlines?.Text ?? t.Text ?? "").ToList();+ Assert.Contains("Title", texts);+ Assert.Contains("Use bold and code.", texts);+ Assert.Contains("•", texts);+ Assert.Contains("two", texts);+ }+}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex 2c78b06f..177028ac 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -26,7 +26,7 @@ public class RenderTestspublic void Main_window_pages_render(string page, string language){TestServices.EnsureInitialized(language);- var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>());+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());vm.Navigate(page);var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };window.Show();@@ -94,7 +94,7 @@ public class RenderTestsTestServices.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>());+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());vm.Navigate("toolbar");var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };window.Show();@@ -118,6 +118,43 @@ public class RenderTestswindow.Close();}+ [AvaloniaTheory]+ [InlineData("en")]+ [InlineData("ko")]+ public void Sidebar_shows_the_version_and_a_new_release(string language)+ {+ TestServices.EnsureInitialized(language);+ var updates = AppHost.Get<UpdateService>();+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), updates);+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };+ window.Show();+ Pump();+ var button = window.FindControl<Button>("UpdateButton")!;+ var version = window.FindControl<TextBlock>("VersionLabel")!;+ Assert.False(button.IsVisible);+ Assert.Contains(UpdateService.CurrentVersion, version.Text);++ try+ {+ updates.LatestVersion = "9.9.9";+ Pump();+ Assert.True(button.IsVisible);+ Assert.Contains("9.9.9", vm.UpdateText);+ Save(window, $"sidebar-update-{language}.png");++ var notice = new UpdateNoticeWindow(updates, AppHost.Get<Filee.Core.Localization.ILocalizer>().Format("update.notice_title", "9.9.9"));+ notice.Show();+ Pump();+ Save(notice, $"update-notice-{language}.png");+ notice.Close();+ }+ finally+ {+ updates.LatestVersion = null;+ window.Close();+ }+ }+private static void Pump(){// Let layout, bindings and a few animation frames run.diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.csnew file mode 100644index 00000000..1e662afd--- /dev/null+++ b/tests/Filee.App.Tests/UpdateServiceTests.cs@@ -0,0 +1,24 @@+using Filee.App.Services;++namespace Filee.App.Tests;++public class UpdateServiceTests+{+ [Theory]+ [InlineData("v1.0.2", "1.0.1", true)]+ [InlineData("1.1", "1.0.9", true)]+ [InlineData("v2.0.0-beta.1", "1.9.0", true)]+ [InlineData("v1.0.1", "1.0.1", false)]+ [InlineData("v1.0.0", "1.0.1", false)]+ [InlineData("nightly", "1.0.1", false)]+ [InlineData(null, "1.0.1", false)]+ public void Release_tags_compare_by_version(string? tag, string current, bool newer) =>+ Assert.Equal(newer, UpdateService.IsNewer(tag, current));++ [Fact]+ public void Download_page_is_the_latest_release()+ {+ Assert.EndsWith("/releases/latest", UpdateService.LatestReleaseUrl);+ Assert.StartsWith(UpdateService.RepositoryUrl.TrimEnd('/'), UpdateService.LatestReleaseUrl);+ }+}diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex ce2f520e..d428c4d8 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -39,10 +39,49 @@ public class UserDataStoreTestsvar store = new UserDataStore(dir.Path);store.Load();- Assert.Equal(["magick", "word", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);+ Assert.Equal(["magick", "word", "markdown", "hwpx-writer", "pandoc", "libreoffice"], store.Settings.EnginePriority);Assert.Equal(AppSettings.CurrentSchemaVersion, store.Settings.SchemaVersion);}+ [Fact]+ public void Version_3_libraries_get_the_text_profile_once()+ {+ using var dir = new TempDir();+ var old = new UserDataStore(dir.Path);+ old.Load();+ old.Profiles.RemoveAll(p => p.Id == "text"); // as written by 1.0.0+ old.Settings.SchemaVersion = 3;+ old.Settings.EnginePriority.Remove("markdown");+ old.SaveSettings();+ old.SaveLibrary();++ var store = new UserDataStore(dir.Path);+ store.Load();++ var ids = store.Profiles.Select(p => p.Id).ToList();+ Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("text")); // right before the fallback+ Assert.Contains("md", store.Profiles.Single(p => p.Id == "text").Extensions);+ Assert.Equal(store.Settings.EnginePriority.IndexOf("hwpx-writer") - 1, store.Settings.EnginePriority.IndexOf("markdown"));++ // Saved right away: the next start neither migrates again nor brings back a profile the user deleted.+ store.Profiles.RemoveAll(p => p.Id == "text");+ store.SaveLibrary();+ var next = new UserDataStore(dir.Path);+ next.Load();+ Assert.DoesNotContain(next.Profiles, p => p.Id == "text");+ Assert.Equal(AppSettings.CurrentSchemaVersion, next.Settings.SchemaVersion);+ }++ [Fact]+ public void Text_profile_is_not_added_when_a_profile_already_takes_markdown()+ {+ var profiles = BuiltInData.CreateProfiles().Where(p => p.Id != "text").ToList();+ profiles[0].Extensions.Add("md");++ Assert.False(SettingsMigrations.ApplyToLibrary(3, BuiltInData.CreatePresets(), profiles));+ Assert.DoesNotContain(profiles, p => p.Id == "text");+ }+[Fact]public void Enums_are_stored_as_strings(){diff --git a/tests/Filee.Engines.Tests/HwpxWriterTests.cs b/tests/Filee.Engines.Tests/HwpxWriterTests.csindex 77339fad..d53c41e2 100644--- a/tests/Filee.Engines.Tests/HwpxWriterTests.cs+++ b/tests/Filee.Engines.Tests/HwpxWriterTests.cs@@ -1,4 +1,4 @@-// HWPX from Markdown / HTML (Pandoc AST → OWPML) and plain text, plus the writer's small helpers.+// HWPX from Markdown (Markdig, built in), 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.@@ -65,7 +65,7 @@ public class HwpxWriterTests(EngineFixture fx) : IClassFixture<EngineFixture>[Fact]public async Task Markdown_becomes_a_valid_hwpx_that_other_readers_understand(){- SkipUnlessPandoc();+ // No Pandoc needed: Markdown is read with Markdig.var dir = fx.NewFolder();using (var logo = new MagickImage(MagickColors.MediumPurple, 240, 120))logo.Write(Path.Combine(dir, "logo.png"));diff --git a/tests/Filee.Engines.Tests/MarkdownTests.cs b/tests/Filee.Engines.Tests/MarkdownTests.csnew file mode 100644index 00000000..33ee3d10--- /dev/null+++ b/tests/Filee.Engines.Tests/MarkdownTests.cs@@ -0,0 +1,187 @@+// Markdown without optional engines (Markdig, in-process), the progress estimate of silent engines and the LibreOffice+// profile warm-up.++using Filee.Core.Conversion;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;+using Filee.Engines.Office;+using Filee.Engines.Text;+using ImageMagick;++namespace Filee.Engines.Tests;++public class MarkdownTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private const string Sample = """+ ---+ title: 회의록+ ---++ # 주간 회의++ 오늘 결정한 것: **배포**, *문서 정리*, `v1.0.1`.++ | 항목 | 담당 |+ |------|------|+ | 설치 | 민지 |++ ++ - [x] 끝낸 일+ - [ ] 남은 일+ """;++ /// <summary>Only engines that ship with the app (or run in-process): no Pandoc, LibreOffice or Word.</summary>+ private static readonly string[] OptionalEngines = ["pandoc", "libreoffice", "word"];++ private RoutePlanner BuiltInPlanner(params string[] assumeInstalled) =>+ new ConverterCatalog(fx.Converters.Where(c => !OptionalEngines.Contains(c.Id))) { Priority = fx.Catalog.Priority }+ .CreatePlanner(assumeInstalled);++ private async Task<string> WriteSampleAsync(string dir)+ {+ using (var chart = new MagickImage(MagickColors.Teal, 160, 90))+ chart.Write(Path.Combine(dir, "chart.png"));+ var md = Path.Combine(dir, "회의록.md");+ await File.WriteAllTextAsync(md, Sample, TestContext.Current.CancellationToken);+ return md;+ }++ private async Task<string> ConvertAsync(string input, string target)+ {+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ return job.Outputs.Single();+ }++ [Fact]+ public void Markdown_routes_need_no_optional_engine()+ {+ var planner = BuiltInPlanner();++ Assert.Equal("markdown", Assert.Single(planner.Plan("md", "html")!.Steps).Converter.Id);+ Assert.Equal("markdown", Assert.Single(planner.Plan("md", "txt")!.Steps).Converter.Id);+ Assert.Equal("hwpx-writer", Assert.Single(planner.Plan("md", "hwpx")!.Steps).Converter.Id);+ // PDF: the built-in HWPX writer, then rhwp (bundled with the installer).+ Assert.Equal(["hwpx-writer", "rhwp"], BuiltInPlanner("rhwp").Plan("md", "pdf")!.Steps.Select(s => s.Converter.Id));+ }++ [Fact]+ public void Built_in_markdown_wins_over_pandoc_for_html_and_text()+ {+ var planner = fx.Catalog.CreatePlanner(["pandoc"]);++ Assert.Equal("markdown", Assert.Single(planner.Plan("md", "html")!.Steps).Converter.Id);+ Assert.Equal("markdown", Assert.Single(planner.Plan("md", "txt")!.Steps).Converter.Id);+ }++ [Fact]+ public async Task Markdown_to_html_and_text()+ {+ var dir = fx.NewFolder();+ var md = await WriteSampleAsync(dir);++ var html = await File.ReadAllTextAsync(await ConvertAsync(md, "html"), TestContext.Current.CancellationToken);+ Assert.Contains("<h1", html);+ Assert.Contains("<table>", html);+ Assert.Contains("<strong>배포</strong>", html);+ Assert.Contains("src=\"chart.png\"", html); // next to the Markdown file the relative path still works+ Assert.DoesNotContain("title: 회의록", html);++ var text = await File.ReadAllTextAsync(await ConvertAsync(md, "txt"), TestContext.Current.CancellationToken);+ Assert.Contains("주간 회의", text);+ Assert.Contains("배포", text);+ Assert.DoesNotContain("**", text);+ }++ [Fact]+ public async Task Html_written_elsewhere_points_images_at_the_original_files()+ {+ var dir = fx.NewFolder();+ var md = await WriteSampleAsync(dir);++ var html = MarkdownConverter.ToHtml(Sample, md, Path.Combine(fx.NewFolder(), "step.html"));++ Assert.Contains($"src=\"{new Uri(Path.Combine(dir, "chart.png")).AbsoluteUri}\"", html);+ }++ [Fact]+ public async Task Markdown_to_hwpx_keeps_structure()+ {+ var dir = fx.NewFolder();+ var hwpx = await ConvertAsync(await WriteSampleAsync(dir), "hwpx");++ HwpxAssert.ValidPackage(hwpx, expectImages: 1);+ using var document = Unhwp.UnhwpDocument.ParseFile(hwpx);+ var text = document.ToText();+ foreach (var expected in new[] { "주간 회의", "배포", "v1.0.1", "설치", "민지", "☑ 끝낸 일", "☐ 남은 일" })+ Assert.Contains(expected, text);+ Assert.DoesNotContain("title:", text);+ Assert.Single(HwpxAssert.Xml(hwpx).Descendants(HwpxAssert.Hp + "tbl"));+ }++ [Fact]+ public async Task Markdown_to_pdf_with_built_in_engines()+ {+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");+ Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not found (pwsh build/fetch-engines.ps1 -Only rhwp)");+ var dir = fx.NewFolder();+ var md = await WriteSampleAsync(dir);++ var pdf = await ConvertAsync(md, "pdf");++ Assert.True(new FileInfo(pdf).Length > 1000);+ Assert.Equal("%PDF", System.Text.Encoding.ASCII.GetString((await File.ReadAllBytesAsync(pdf, TestContext.Current.CancellationToken))[..4]));+ }++ [Fact]+ public void Progress_estimate_rises_towards_the_bound_and_never_reaches_it()+ {+ var values = new[] { 0, 0.5, 1, 2, 4, 8, 30 }.Select(t => ProgressEstimate.Value(t, typical: 2, from: 0.1, to: 0.9)).ToList();++ Assert.Equal(0.1, values[0], 6);+ Assert.True(values.Zip(values.Skip(1)).All(p => p.Second > p.First));+ Assert.True(values[^1] < 0.9);+ Assert.InRange(ProgressEstimate.Value(2, typical: 2, from: 0.1, to: 0.9), 0.6, 0.62); // 1 - 1/e of the way+ }++ [Fact]+ public async Task Progress_estimate_reports_while_running_and_stops_when_disposed()+ {+ var reports = new List<double>();+ var sink = new SyncProgress(v => { lock (reports) reports.Add(v); });++ using (ProgressEstimate.Start(sink, TimeSpan.FromSeconds(1)))+ await Task.Delay(700, TestContext.Current.CancellationToken);+ int count;+ lock (reports)+ count = reports.Count;+ await Task.Delay(400, TestContext.Current.CancellationToken);++ Assert.True(count >= 2, $"only {count} reports");+ lock (reports)+ {+ Assert.Equal(count, reports.Count);+ Assert.All(reports, v => Assert.InRange(v, 0.1, 0.9));+ }+ }++ [Fact]+ public async Task LibreOffice_warm_up_prepares_every_profile_once()+ {+ var env = new EngineEnvironment(_ => null, Path.Combine(fx.NewFolder(), "data"));+ var libreOffice = new LibreOfficeConverter(env);+ Assert.SkipUnless(libreOffice.GetStatus().IsAvailable, "LibreOffice not found");++ Assert.Equal(2, await libreOffice.WarmUpAsync(TestContext.Current.CancellationToken));+ Assert.All(Directory.GetDirectories(Path.Combine(env.DataDirectory, "libreoffice-profiles")),+ profile => Assert.True(Directory.Exists(Path.Combine(profile, "user"))));+ Assert.Equal(0, await libreOffice.WarmUpAsync(TestContext.Current.CancellationToken));+ }++ /// <summary>IProgress that reports synchronously (Progress<T> posts to the thread pool).</summary>+ private sealed class SyncProgress(Action<double> report) : IProgress<double>+ {+ public void Report(double value) => report(value);+ }+}