Skip to content

armgit / Filee

Public Imported from GitHub
0

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

rhwp, unhwp and LibreOffice run without the Visual C++ Redistributable

KnifeLemon22ddfb5bcb13
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index a6b78c5b..0f0d4fdc 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -53,6 +53,7 @@ Bundled with the installer:
|---|---|---|
| rhwp | MIT | https://github.com/edwardkim/rhwp |
| 7-Zip (console: `7z.exe`, `7z.dll`) | GNU LGPL-2.1-or-later; parts of `7z.dll`: LGPL with the unRAR license restriction, BSD-3-Clause, BSD-2-Clause | https://www.7-zip.org |
+| Microsoft Visual C++ Redistributable (Windows: next to `Filee.exe` and `rhwp.exe`, conda-forge `vc14_runtime`) | Microsoft Visual C++ Redistributable license | https://github.com/conda-forge/vc-feedstock |
The Linux packages contain an rhwp built by Filee's CI from the unmodified source of the same release (tag `v0.8.7`,
commit `1a76570e833917d15817415a53c09ad61ab3203f`, `cargo build --release --locked --bin rhwp` on Ubuntu 22.04), so it
diff --git a/build/build-installer.ps1 b/build/build-installer.ps1
index 02d93753..8d316e15 100644
--- a/build/build-installer.ps1
+++ b/build/build-installer.ps1
@@ -5,8 +5,9 @@
.DESCRIPTION
Without -PublishDir the app is published first (Release, self-contained, -p:FileeRelease=true) into
- publish/win-x64, together with the Windows 11 Explorer menu extension (build-explorer-menu.ps1) and the bundled
- small engines rhwp and 7-Zip (fetch-engines.ps1); the large engines are downloaded by the app (engines.json).
+ publish/win-x64, together with the Windows 11 Explorer menu extension (build-explorer-menu.ps1), the bundled
+ small engines rhwp and 7-Zip and the Microsoft C++ runtime DLLs next to rhwp.exe and Filee.exe
+ (fetch-engines.ps1); the large engines are downloaded by the app (engines.json).
Inno Setup 7 is downloaded once into build/.cache (pinned, SHA-256 verified) and set up there in its own portable
mode: nothing is installed or registered on the build machine. The installer's engine page is generated from
@@ -110,11 +111,19 @@ elseif (-not $PublishDir) {
Set-Content (Join-Path $PublishDir 'cli\filee.cmd') "@`"%~dp0..\filee-cli.exe`" %*" -Encoding ascii
# Next to Filee.exe: the Explorer menu package's external location is the install folder.
& (Join-Path $PSScriptRoot 'build-explorer-menu.ps1') -Destination $PublishDir -Version $Version
- # Only the small rhwp and 7-Zip are bundled; the app downloads the others when the user picks them.
- & (Join-Path $PSScriptRoot 'fetch-engines.ps1') -Only rhwp, 7zip -Destination (Join-Path $PublishDir 'engines')
+ # Only the small rhwp and 7-Zip are bundled; the app downloads the others when the user picks them. The Microsoft
+ # C++ runtime goes next to rhwp.exe and next to Filee.exe (unhwp.dll imports VCRUNTIME140.dll), so neither needs
+ # the Visual C++ Redistributable (#248).
+ & (Join-Path $PSScriptRoot 'fetch-engines.ps1') -Only rhwp, 7zip -Destination (Join-Path $PublishDir 'engines') -RuntimeTo $PublishDir
}
$PublishDir = (Resolve-Path $PublishDir).Path
if (-not (Test-Path (Join-Path $PublishDir 'Filee.exe'))) { throw "Filee.exe is missing in $PublishDir" }
+if (-not $CheckOnly) {
+ # Without them rhwp and unhwp fail on PCs without the Visual C++ Redistributable (#248).
+ foreach ($dll in 'vcruntime140.dll', 'engines\rhwp\msvcp140.dll', 'engines\rhwp\vcruntime140.dll') {
+ if (-not (Test-Path (Join-Path $PublishDir $dll))) { throw "$dll is missing in $PublishDir (see fetch-engines.ps1 -RuntimeTo)" }
+ }
+}
$iscc = Get-Iscc
Push-Location $root
diff --git a/build/fetch-engines.ps1 b/build/fetch-engines.ps1
index b9f7f4ad..a8383acf 100644
--- a/build/fetch-engines.ps1
+++ b/build/fetch-engines.ps1
@@ -10,7 +10,7 @@
libreoffice/ LibreOffice (MPL-2.0), extracted from the official MSI via an administrative install
+ H2Orestart (GPL-3.0) unpacked into share/extensions for HWP/HWPX import
jre/ Eclipse Temurin JRE 21 (GPLv2 + Classpath Exception), used by H2Orestart
- rhwp/ rhwp command line (MIT), HWP/HWPX -> PDF
+ rhwp/ rhwp command line (MIT), HWP/HWPX -> PDF, with the Microsoft C++ runtime DLLs next to rhwp.exe
pandoc/ Pandoc (GPL-2.0-or-later, separate program), Markdown/HTML and MD/HTML/ODT/RTF -> HWPX
7zip/ 7-Zip console (7z.exe + 7z.dll, LGPL-2.1 + unRAR restriction, separate program), archives
ghostscript/ Ghostscript (AGPL-3.0, separate program) from conda-forge, EPS/PS <-> PDF, with the Microsoft
@@ -22,12 +22,20 @@
Every download is pinned to a version and verified with SHA-256 (src/Filee.Engines/Infrastructure/engines.json,
shared with the app). Downloads are cached in build/.cache.
+ The Microsoft C++ runtime (the "vcruntime" component: MSVCP140.dll, VCRUNTIME140.dll, ...) is copied next to the
+ programs built with Visual C++ that do not ship it themselves (rhwp.exe, gswin64c.exe; LibreOffice's own copy goes
+ into its program folder), so they also run on PCs without the Visual C++ Redistributable. -RuntimeTo copies it into
+ more folders (build-installer.ps1: next to Filee.exe, for unhwp.dll).
+
.PARAMETER Destination
Target "engines" folder. Default: <repo>/engines (picked up automatically by debug builds).
.PARAMETER Only
Restrict to some engines, e.g. -Only rhwp,pandoc (LibreOffice is large: ~356 MB download).
+.PARAMETER RuntimeTo
+ More folders that get the Microsoft C++ runtime DLLs, e.g. the published app folder.
+
.EXAMPLE
pwsh build/fetch-engines.ps1
pwsh build/fetch-engines.ps1 -Only rhwp
@@ -37,7 +45,8 @@
param(
[string]$Destination = (Join-Path $PSScriptRoot '..\engines'),
# Accepts an array (-Only rhwp,jre from PowerShell) or one comma-separated string (pwsh -File ... -Only rhwp,jre).
- [string[]]$Only
+ [string[]]$Only,
+ [string[]]$RuntimeTo
)
$ErrorActionPreference = 'Stop'
@@ -104,6 +113,21 @@ function Expand-Conda([string]$conda, [string]$target) {
Remove-Item $tmp -Recurse -Force
}
+# Copies the Microsoft C++ runtime DLLs (the "vcruntime" component, unpacked once per run into build/.cache) into
+# $target, next to a program built with Visual C++: Windows looks for its DLLs in the program's folder first, so it
+# runs on PCs without the Visual C++ Redistributable. Same as EngineInstaller does for Ghostscript.
+$script:vcRuntime = $null
+function Copy-VcRuntime([string]$target) {
+ if (-not $script:vcRuntime) {
+ $script:vcRuntime = Join-Path $cache 'vcruntime'
+ Expand-Conda (Get-Engine 'vcruntime') $script:vcRuntime
+ }
+ Copy-Item (Join-Path $script:vcRuntime '*.dll') $target -Force
+ foreach ($dll in 'msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll') {
+ if (-not (Test-Path (Join-Path $target $dll))) { throw "$dll is missing in $target after copying the C++ runtime." }
+ }
+}
+
# Removes parts of LibreOffice that headless conversion never uses (~500 MB):
# help, readmes, the MSI stub copied by the admin install, the gallery, and spell-check dictionaries except
# English and Korean (their hyphenation patterns can affect page layout when exporting PDFs).
@@ -113,6 +137,15 @@ function Optimize-LibreOffice([string]$root) {
$remove += Get-ChildItem (Join-Path $root 'share\extensions') -Directory -Filter 'dict-*' |
Where-Object { $_.Name -notin @('dict-en', 'dict-ko') } | ForEach-Object FullName
foreach ($path in $remove) { Remove-Item $path -Recurse -Force -ErrorAction SilentlyContinue }
+ # The MSI installs LibreOffice's C++ runtime into the system folder; the administrative install leaves it in
+ # System64, where soffice.exe never looks. Same as AppLocalRuntime.CopyLibreOfficeRuntime.
+ $system64 = Join-Path $root 'System64'
+ if (Test-Path $system64) {
+ foreach ($dll in Get-ChildItem $system64 -Filter '*.dll') {
+ $target = Join-Path $root "program\$($dll.Name)"
+ if (-not (Test-Path $target)) { Copy-Item $dll.FullName $target }
+ }
+ }
}
$selected = if ($Only) { @($Only -split ',' | ForEach-Object { $_.Trim().ToLowerInvariant() } | Where-Object { $_ }) } else { @($engines.Keys) }
@@ -129,6 +162,8 @@ if ('rhwp' -in $selected) {
if ($exe.DirectoryName -ne (Join-Path $Destination 'rhwp')) {
Get-ChildItem $exe.DirectoryName -Force | Move-Item -Destination (Join-Path $Destination 'rhwp') -Force
}
+ # rhwp.exe imports MSVCP140.dll and VCRUNTIME140.dll; without them Windows does not start it (#248).
+ Copy-VcRuntime (Join-Path $Destination 'rhwp')
}
if ('pandoc' -in $selected) {
@@ -215,7 +250,7 @@ if ('ghostscript' -in $selected) {
Expand-Conda (Get-Engine 'ghostscript') $target
if (-not (Test-Path (Join-Path $target 'gswin64c.exe'))) { throw 'gswin64c.exe not found in the Ghostscript package.' }
# App-local Microsoft C++ runtime next to gswin64c.exe, as EngineInstaller does.
- Copy-Item (Join-Path $Destination 'vcruntime\*.dll') $target -Force
+ Copy-VcRuntime $target
}
if ('calibre' -in $selected) {
@@ -234,4 +269,9 @@ if ('calibre' -in $selected) {
Remove-Item $tmp -Recurse -Force
}
+foreach ($folder in $RuntimeTo) {
+ if (-not (Test-Path $folder -PathType Container)) { throw "-RuntimeTo: $folder is not a folder." }
+ Copy-VcRuntime $folder
+}
+
Write-Host "Engines ready in $Destination"
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index bbcdeb0a..7e3b82a7 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -26,7 +26,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF |
| **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |
| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX → each of them; → PNG, JPG, … (an isometric preview) |
-| rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
+| rhwp | bundled with the installer (`engines/rhwp`, with the Microsoft C++ runtime, see below) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** |
| Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files |
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT), Markdown and markup → PPTX slides |
@@ -89,6 +89,30 @@ they can be installed or removed later in Settings → *Engines*. A conversion t
Its fonts and resources are compiled into `gsdll64.dll`. The Microsoft C++ runtime it was built against
(`vcruntime` component) is copied next to `gswin64c.exe`, so it runs on PCs without the VC++ Redistributable.
+### Microsoft C++ runtime (Windows)
+
+Programs built with Visual C++ import `MSVCP140.dll` / `VCRUNTIME140.dll`, which a fresh Windows does not have (they
+come with the Visual C++ Redistributable). Windows looks for a program's DLLs in its own folder first, so Filee puts
+the runtime next to every program that needs it and does not ship it (`Infrastructure/AppLocalRuntime.cs`):
+
+| Binary | Runtime |
+|---|---|
+| `engines/rhwp/rhwp.exe` (bundled) | `vcruntime` component copied next to it by `fetch-engines.ps1` (#248) |
+| `unhwp.dll` (NuGet, loaded into Filee.exe and filee-cli.exe) | `vcruntime` component copied next to `Filee.exe` (`build-installer.ps1` → `fetch-engines.ps1 -RuntimeTo`) |
+| Ghostscript (download) | `vcruntime` component copied next to `gswin64c.exe` (`EngineInstaller`, `fetch-engines.ps1`) |
+| LibreOffice (download) | its own copy, which the administrative install leaves in `System64`, copied into `program/` (`EngineInstaller`, `fetch-engines.ps1`; `LibreOfficeConverter` also repairs a copy installed by an earlier Filee) |
+| calibre, Java (downloads) | ship their own next to their programs (`app/bin`, `bin`) |
+| 7-Zip, FFmpeg (GyanD), Pandoc, PDFium, SkiaSharp / HarfBuzz, Magick.Native, the Explorer menu DLL, .NET | import neither (static runtime or MinGW / GHC builds) |
+
+The installer and the portable zip are made from the same publish folder, so both have the DLLs. Filee installed in
+Program Files cannot repair its own bundled files, so an older installation gets them by installing the new version.
+When a DLL is still missing, Windows does not start the program and reports `0xC0000135` (STATUS_DLL_NOT_FOUND;
+`0xC0000139` for an outdated one) as its exit code: `ProcessRunner` and `FfmpegRunner` turn that into
+`error.runtime_missing` ("A Microsoft Visual C++ runtime file this engine needs is missing or outdated …", with the
+program and the code in brackets) instead of the raw exit code, and `UnhwpConverter` does the same when `unhwp.dll`
+cannot be loaded. To check binaries after an engine update, list the DLLs each `.exe` / `.dll` imports (its PE import
+table, e.g. `dumpbin /dependents`) and look for `MSVCP140*.dll`, `VCRUNTIME140*.dll` or `CONCRT140.dll`.
+
To bump a version, change `url`, `sha256` and `size` in engines.json together, run
`pwsh build/fetch-engines.ps1`, test, and update `THIRD-PARTY-NOTICES.md`. For rhwp, also update `RHWP_VERSION`,
`RHWP_COMMIT` and `RUST_TOOLCHAIN` in `build/build-linux-native.py` (see below); CI fails until they match. When the
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 869314ca..51014c3a 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -79,6 +79,7 @@
"error.rhwp_timeout": "rhwp couldn't finish this long document in time",
"error.rhwp_timeout_calibre": "rhwp couldn't finish this long document in time. For an e-book, move Calibre above the HWPX writer in Settings → Engines, and Calibre makes the PDF much faster",
"error.needs_shaping": "This script needs LibreOffice to convert correctly. Install it in Settings → Engines",
+ "error.runtime_missing": "A Microsoft Visual C++ runtime file this engine needs is missing or outdated. Update or reinstall Filee, or install the Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "The engine reported an error",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 6b38985f..11d7d7c7 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -73,6 +73,7 @@
"error.rhwp_timeout": "rhwp no pudo terminar este documento largo a tiempo",
"error.rhwp_timeout_calibre": "rhwp no pudo terminar este documento largo a tiempo. Para un libro electrónico, mueve Calibre por encima del escritor HWPX en Ajustes → Motores; Calibre genera el PDF mucho más rápido",
"error.needs_shaping": "Este sistema de escritura necesita LibreOffice para convertirse bien. Instálalo en Ajustes → Motores",
+ "error.runtime_missing": "Falta un archivo del runtime de Microsoft Visual C++ que necesita este motor, o está desactualizado. Actualiza o reinstala Filee, o instala Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "El motor devolvió un error",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
"engine.reason.not_installed": "No instalado",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index 0abd34cc..88eae8f3 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -73,6 +73,7 @@
"error.rhwp_timeout": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका",
"error.rhwp_timeout_calibre": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका। ई-बुक के लिए, सेटिंग्स → इंजन में Calibre को HWPX writer के ऊपर ले जाएँ, तब Calibre PDF बहुत तेज़ी से बनाएगा",
"error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें",
+ "error.runtime_missing": "इस इंजन के लिए ज़रूरी Microsoft Visual C++ रनटाइम फ़ाइल नहीं मिली या पुरानी है। Filee को अपडेट करें या फिर से इंस्टॉल करें, या Microsoft Visual C++ Redistributable (x64) इंस्टॉल करें",
"error.conversion_failed": "इंजन ने एक त्रुटि बताई",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
"engine.reason.not_installed": "इंस्टॉल नहीं है",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 347f7134..240616c3 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -79,6 +79,7 @@
"error.rhwp_timeout": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요",
"error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요",
"error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요",
+ "error.runtime_missing": "이 엔진에 필요한 Microsoft Visual C++ 런타임 파일이 없거나 오래됐어요. Filee를 업데이트하거나 다시 설치하거나, Microsoft Visual C++ 재배포 가능 패키지(x64)를 설치해 주세요",
"error.conversion_failed": "엔진에서 오류가 발생했어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 20e0b333..81bede6f 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -79,6 +79,7 @@
"error.rhwp_timeout": "rhwp nie zdążył przetworzyć tego długiego dokumentu",
"error.rhwp_timeout_calibre": "rhwp nie zdążył przetworzyć tego długiego dokumentu. Dla e-booka przenieś Calibre nad HWPX writer w Ustawienia → Silniki, a Calibre zrobi PDF znacznie szybciej",
"error.needs_shaping": "To pismo wymaga LibreOffice do poprawnej konwersji. Zainstaluj go w Ustawienia → Silniki",
+ "error.runtime_missing": "Brakuje pliku środowiska Microsoft Visual C++ potrzebnego temu silnikowi albo jest on nieaktualny. Zaktualizuj lub zainstaluj ponownie Filee albo zainstaluj Microsoft Visual C++ Redistributable (x64)",
"error.conversion_failed": "Silnik zgłosił błąd",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 22abca6d..35e5f560 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -79,6 +79,7 @@
"error.rhwp_timeout": "文档太长,rhwp 未能在时限内完成",
"error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多",
"error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装",
+ "error.runtime_missing": "此引擎所需的 Microsoft Visual C++ 运行库文件缺失或版本过旧。请更新或重新安装 Filee,或安装 Microsoft Visual C++ 可再发行程序包 (x64)",
"error.conversion_failed": "转换引擎出错",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
diff --git a/src/Filee.Engines/Hwp/UnhwpConverter.cs b/src/Filee.Engines/Hwp/UnhwpConverter.cs
index 86fcd067..494b7ca7 100644
--- a/src/Filee.Engines/Hwp/UnhwpConverter.cs
+++ b/src/Filee.Engines/Hwp/UnhwpConverter.cs
@@ -48,7 +48,7 @@ public sealed class UnhwpConverter : IConverter
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
Task.Run<IReadOnlyList<string>>(() =>
{
- using var document = UnhwpDocument.ParseFile(step.InputPath);
+ using var document = Parse(step.InputPath);
cancellationToken.ThrowIfCancellationRequested();
progress?.Report(0.5);
@@ -68,6 +68,22 @@ public sealed class UnhwpConverter : IConverter
return [path];
}, cancellationToken);
+ /// <summary>
+ /// Opens the document. unhwp.dll needs VCRUNTIME140.dll, which the Windows packages put next to it (see
+ /// <see cref="AppLocalRuntime"/>); without it Windows cannot load the library.
+ /// </summary>
+ private static UnhwpDocument Parse(string path)
+ {
+ try
+ {
+ return UnhwpDocument.ParseFile(path);
+ }
+ catch (DllNotFoundException ex) when (OperatingSystem.IsWindows())
+ {
+ throw new ConversionRefusedException(AppLocalRuntime.ErrorKey, ex.Message);
+ }
+ }
+
private static string WriteMarkdown(UnhwpDocument document, ConversionStep step, string output)
{
var markdown = document.ToMarkdown(new MarkdownOptions { IncludeFrontmatter = false });
diff --git a/src/Filee.Engines/Infrastructure/AppLocalRuntime.cs b/src/Filee.Engines/Infrastructure/AppLocalRuntime.cs
new file mode 100644
index 00000000..f4ee6b3f
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/AppLocalRuntime.cs
@@ -0,0 +1,61 @@
+// The Microsoft C++ runtime (MSVCP140.dll, VCRUNTIME140.dll, ...) that engines built with Visual C++ need.
+//
+// Windows has no copy of its own: a PC gets one from the Visual C++ Redistributable, which many programs install but a
+// fresh Windows lacks. Filee therefore puts the runtime next to the programs that need it (app-local deployment,
+// Windows looks in a program's folder first): the "vcruntime" download (conda-forge) next to rhwp.exe, Filee.exe
+// (for unhwp.dll) and gswin64c.exe, LibreOffice's own copy next to soffice.exe (see CopyLibreOfficeRuntime).
+// When a DLL is still missing, Windows does not start the program at all and reports STATUS_DLL_NOT_FOUND as its
+// exit code; ThrowIfMissing turns that into a message the user can act on.
+
+using Filee.Core.Conversion;
+
+namespace Filee.Engines.Infrastructure;
+
+public static class AppLocalRuntime
+{
+ /// <summary>Exit code of a program Windows could not start because a DLL it imports is missing (0xC0000135).</summary>
+ public const int DllNotFound = unchecked((int)0xC0000135);
+
+ /// <summary>Exit code of a program whose DLL is too old to have a function it imports (0xC0000139).</summary>
+ public const int EntryPointNotFound = unchecked((int)0xC0000139);
+
+ /// <summary>Localization key of the message for <see cref="DllNotFound"/> and <see cref="EntryPointNotFound"/>.</summary>
+ public const string ErrorKey = "error.runtime_missing";
+
+ /// <summary>True when Windows refused to start a program because of a missing or outdated DLL.</summary>
+ public static bool IsMissingDll(int exitCode) => exitCode is DllNotFound or EntryPointNotFound;
+
+ /// <summary>
+ /// Throws a <see cref="ConversionRefusedException"/> saying that a runtime file is missing (with the program and
+ /// the exit code as detail) when <paramref name="exitCode"/> is <see cref="DllNotFound"/> or
+ /// <see cref="EntryPointNotFound"/>, instead of the raw exit code each engine would report.
+ /// </summary>
+ public static void ThrowIfMissing(string executable, int exitCode)
+ {
+ if (IsMissingDll(exitCode))
+ throw new ConversionRefusedException(ErrorKey, $"{Path.GetFileName(executable)}, 0x{exitCode:X8}");
+ }
+
+ /// <summary>
+ /// LibreOffice's MSI installs the C++ runtime into the system folder; unpacked with an administrative install
+ /// (msiexec /a) it lands in System64 next to program/ instead, where soffice.exe never looks. Copies those DLLs
+ /// into program/ (never replacing one that is there). Returns the number of files copied; 0 for any other layout.
+ /// </summary>
+ public static int CopyLibreOfficeRuntime(string root)
+ {
+ var system64 = Path.Combine(root, "System64");
+ var program = Path.Combine(root, "program");
+ if (!Directory.Exists(system64) || !Directory.Exists(program))
+ return 0;
+ var copied = 0;
+ foreach (var dll in Directory.EnumerateFiles(system64, "*.dll"))
+ {
+ var target = Path.Combine(program, Path.GetFileName(dll));
+ if (File.Exists(target))
+ continue;
+ File.Copy(dll, target);
+ copied++;
+ }
+ return copied;
+ }
+}
diff --git a/src/Filee.Engines/Infrastructure/EngineInstaller.cs b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
index b09f6543..12fe5fac 100644
--- a/src/Filee.Engines/Infrastructure/EngineInstaller.cs
+++ b/src/Filee.Engines/Infrastructure/EngineInstaller.cs
@@ -304,7 +304,8 @@ public sealed class EngineInstaller
/// <summary>
/// The folder to keep from an administratively installed MSI, which lays files out as they would be installed
- /// (PFiles64\...): LibreOffice's folder with program/ and share/ (trimmed), calibre's folder with ebook-convert.
+ /// (PFiles64\...): LibreOffice's folder with program/ and share/ (trimmed, with its C++ runtime copied into
+ /// program/), calibre's folder with ebook-convert (it keeps its own C++ runtime in app/bin).
/// </summary>
private static string MsiProgramFolder(string id, string staging)
{
@@ -318,6 +319,7 @@ public sealed class EngineInstaller
?? throw new InvalidDataException("soffice.exe not found in the LibreOffice package.");
var libreOffice = Path.GetDirectoryName(Path.GetDirectoryName(soffice)!)!; // folder with program/, share/
TrimLibreOffice(libreOffice);
+ AppLocalRuntime.CopyLibreOfficeRuntime(libreOffice);
return libreOffice;
}
diff --git a/src/Filee.Engines/Infrastructure/ProcessRunner.cs b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
index 521b4a34..d3671a80 100644
--- a/src/Filee.Engines/Infrastructure/ProcessRunner.cs
+++ b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
@@ -15,6 +15,9 @@ public static class ProcessRunner
/// Starts <paramref name="executable"/> with the given arguments (no shell, arguments are escaped),
/// waits for it to exit and kills the whole process tree on timeout or cancellation.
/// </summary>
+ /// <exception cref="Filee.Core.Conversion.ConversionRefusedException">
+ /// Windows could not start the program because a DLL is missing (see <see cref="AppLocalRuntime"/>).
+ /// </exception>
/// <param name="onOutput">Called with every line of standard output and error as it arrives (e.g. to parse progress).</param>
public static async Task<ProcessResult> RunAsync(
string executable,
@@ -67,6 +70,7 @@ public static class ProcessRunner
// Make sure the async output readers have drained.
process.WaitForExit();
+ AppLocalRuntime.ThrowIfMissing(executable, process.ExitCode);
return new ProcessResult(process.ExitCode, stdout.ToString(), stderr.ToString());
}
diff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.cs
index c4497197..b049b9bc 100644
--- a/src/Filee.Engines/Media/FfmpegRunner.cs
+++ b/src/Filee.Engines/Media/FfmpegRunner.cs
@@ -102,6 +102,7 @@ internal static class FfmpegRunner
// Make sure the asynchronous readers have delivered the last lines.
process.WaitForExit();
+ AppLocalRuntime.ThrowIfMissing(ffmpeg, process.ExitCode);
string stderr;
lock (errors)
stderr = string.Join(Environment.NewLine, errors);
diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.cs
index ae85f781..68aa84d1 100644
--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs
+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs
@@ -386,11 +386,33 @@ public sealed class LibreOfficeConverter : IConverter
private void Locate()
{
_soffice = EngineEnvironment.OwnProgram("libreoffice", "soffice.exe")
- ?? EngineEnvironment.BundledProgram("libreoffice", "soffice.exe")
+ ?? WithRuntime(EngineEnvironment.BundledProgram("libreoffice", "soffice.exe"))
?? EngineEnvironment.SystemProgram("libreoffice", "soffice.exe");
_hasHwpFilter = _soffice is not null && HasH2Orestart(_soffice);
}
+ /// <summary>
+ /// Filee's copy as earlier versions installed it has LibreOffice's C++ runtime only in System64, where soffice.exe
+ /// does not look (see <see cref="AppLocalRuntime.CopyLibreOfficeRuntime"/>): copied next to it once, so LibreOffice
+ /// also starts on PCs without the Visual C++ Redistributable.
+ /// </summary>
+ private string? WithRuntime(string? soffice)
+ {
+ if (soffice is null || !OperatingSystem.IsWindows())
+ return soffice;
+ try
+ {
+ var copied = AppLocalRuntime.CopyLibreOfficeRuntime(Directory.GetParent(Path.GetDirectoryName(soffice)!)!.FullName);
+ if (copied > 0)
+ _logger.LogInformation("Copied {Count} C++ runtime files next to {Program}", copied, soffice);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ _logger.LogWarning(ex, "Could not copy the C++ runtime next to {Program}", soffice);
+ }
+ return soffice;
+ }
+
/// <summary>Detects the H2Orestart extension in the installation (shared) extension folders.</summary>
private static bool HasH2Orestart(string soffice)
{
diff --git a/tests/Filee.Engines.Tests/AppLocalRuntimeTests.cs b/tests/Filee.Engines.Tests/AppLocalRuntimeTests.cs
new file mode 100644
index 00000000..b7f37537
--- /dev/null
+++ b/tests/Filee.Engines.Tests/AppLocalRuntimeTests.cs
@@ -0,0 +1,79 @@
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+
+namespace Filee.Engines.Tests;
+
+public sealed class AppLocalRuntimeTests : IDisposable
+{
+ private readonly string _root = Directory.CreateTempSubdirectory("filee-runtime-").FullName;
+
+ public void Dispose() => Directory.Delete(_root, recursive: true);
+
+ [Theory]
+ [InlineData(-1073741515)] // 0xC0000135 STATUS_DLL_NOT_FOUND, as reported in #248
+ [InlineData(-1073741511)] // 0xC0000139 STATUS_ENTRYPOINT_NOT_FOUND
+ public void A_program_Windows_could_not_load_is_refused_with_the_runtime_message(int exitCode)
+ {
+ var refused = Assert.Throws<ConversionRefusedException>(() => AppLocalRuntime.ThrowIfMissing(@"C:\Filee\engines\rhwp\rhwp.exe", exitCode));
+
+ Assert.Equal("error.runtime_missing", refused.ErrorKey);
+ Assert.Equal($"rhwp.exe, 0x{unchecked((uint)exitCode):X8}", refused.Detail);
+ Assert.StartsWith("rhwp.exe, 0xC000013", refused.Detail);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(-1)]
+ [InlineData(-1073741819)] // 0xC0000005 access violation: the program ran and crashed
+ public void Other_exit_codes_are_left_to_the_engine(int exitCode)
+ {
+ AppLocalRuntime.ThrowIfMissing("rhwp.exe", exitCode);
+ Assert.False(AppLocalRuntime.IsMissingDll(exitCode));
+ }
+
+ [Fact]
+ public async Task ProcessRunner_reports_a_missing_DLL_instead_of_the_exit_code()
+ {
+ Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows exit status.");
+ var cmd = Path.Combine(Environment.SystemDirectory, "cmd.exe");
+
+ var refused = await Assert.ThrowsAsync<ConversionRefusedException>(() =>
+ ProcessRunner.RunAsync(cmd, ["/c", "exit -1073741515"], TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken));
+
+ Assert.Equal(AppLocalRuntime.ErrorKey, refused.ErrorKey);
+ Assert.Equal("cmd.exe, 0xC0000135", refused.Detail);
+ var ordinary = await ProcessRunner.RunAsync(cmd, ["/c", "exit 3"], TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken);
+ Assert.Equal(3, ordinary.ExitCode);
+ }
+
+ [Fact]
+ public void LibreOffice_gets_its_own_runtime_next_to_soffice()
+ {
+ var lo = Path.Combine(_root, "libreoffice");
+ Directory.CreateDirectory(Path.Combine(lo, "program"));
+ Directory.CreateDirectory(Path.Combine(lo, "System64"));
+ Directory.CreateDirectory(Path.Combine(lo, "System"));
+ File.WriteAllText(Path.Combine(lo, "System64", "msvcp140.dll"), "x64 c++");
+ File.WriteAllText(Path.Combine(lo, "System64", "vcruntime140.dll"), "x64 runtime");
+ File.WriteAllText(Path.Combine(lo, "System", "vcruntime140.dll"), "x86 runtime");
+ File.WriteAllText(Path.Combine(lo, "program", "vcruntime140.dll"), "newer runtime");
+
+ Assert.Equal(1, AppLocalRuntime.CopyLibreOfficeRuntime(lo));
+
+ Assert.Equal("x64 c++", File.ReadAllText(Path.Combine(lo, "program", "msvcp140.dll")));
+ Assert.Equal("newer runtime", File.ReadAllText(Path.Combine(lo, "program", "vcruntime140.dll")));
+ Assert.Equal(0, AppLocalRuntime.CopyLibreOfficeRuntime(lo)); // already repaired
+ }
+
+ [Fact]
+ public void Other_LibreOffice_layouts_are_left_alone()
+ {
+ var installed = Path.Combine(_root, "LibreOffice");
+ Directory.CreateDirectory(Path.Combine(installed, "program"));
+
+ Assert.Equal(0, AppLocalRuntime.CopyLibreOfficeRuntime(installed));
+ Assert.Equal(0, AppLocalRuntime.CopyLibreOfficeRuntime(Path.Combine(_root, "missing")));
+ Assert.Empty(Directory.GetFiles(Path.Combine(installed, "program")));
+ }
+}