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
WIP: Linux and macOS support (backup, not finished)
KnifeLemon98093657a9b8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2da2c4e6..338e864c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -18,6 +18,9 @@ concurrency:cancel-in-progress: truejobs:+ portable:+ uses: ./.github/workflows/portable.yml+build:runs-on: windows-lateststeps:diff --git a/.github/workflows/portable.yml b/.github/workflows/portable.ymlnew file mode 100644index 00000000..7056a72f--- /dev/null+++ b/.github/workflows/portable.yml@@ -0,0 +1,174 @@+name: Linux and macOS packages++on:+ workflow_call:+ inputs:+ version:+ type: string+ default: ''+ required: false+ workflow_dispatch:+ inputs:+ version:+ description: 'Package version (empty uses Directory.Build.props)'+ type: string+ required: false++permissions:+ contents: read++jobs:+ portable:+ strategy:+ fail-fast: false+ matrix:+ include:+ - runner: ubuntu-24.04+ rid: linux-x64+ - runner: ubuntu-24.04-arm+ rid: linux-arm64+ - runner: macos-15+ rid: osx-arm64+ - runner: macos-15-intel+ rid: osx-x64+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 40+ defaults:+ run:+ shell: pwsh+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-dotnet@v4+ with:+ global-json-file: global.json++ - name: Linux desktop dependencies+ if: runner.os == 'Linux'+ shell: bash+ run: |+ sudo apt-get update+ sudo apt-get install -y ca-certificates libc6 libgcc-s1 libgssapi-krb5-2 libicu74 libssl3t64 libstdc++6 tzdata zlib1g \+ libfontconfig1 libfreetype6 libx11-6 libice6 libsm6 libxrandr2 libxkbcommon0 libxi6 libxtst6 xvfb fonts-noto-cjk++ - name: Fonts+ run: ./build/fetch-fonts.ps1++ - name: Restore engine downloads+ uses: actions/cache@v4+ with:+ path: build/.cache/portable-downloads+ key: portable-engines-${{ matrix.rid }}-${{ hashFiles('src/Filee.Engines/Infrastructure/engines.json') }}++ - name: Build and test native projects+ run: |+ ./build/fetch-portable-engines.ps1 -Runtime '${{ matrix.rid }}' -Destination engines+ dotnet build Filee.slnx -c Release+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+ $projects = @('Filee.Core.Tests', 'Filee.Platform.Tests', 'Filee.Engines.Tests', 'Filee.Cli.Tests', 'Filee.App.Tests')+ foreach ($project in $projects) {+ $testArguments = @('test', "tests/$project/$project.csproj", '--no-build', '-c', 'Release', '--logger', 'trx', '--results-directory', "TestResults/${{ matrix.rid }}",+ '--filter', 'FullyQualifiedName!=Filee.App.Tests.ExplorerMenuTests.Every_native_import_exists_in_the_dll_it_names&FullyQualifiedName!=Filee.App.Tests.ExplorerMenuTests.Reading_the_registered_package_never_throws')+ if ($IsLinux) {+ xvfb-run -a env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 dotnet @testArguments+ } else {+ dotnet @testArguments+ }+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }+ }++ - name: Build portable package+ env:+ PACKAGE_VERSION: ${{ inputs.version }}+ run: ./build/build-portable.ps1 -Runtime '${{ matrix.rid }}' -Version $env:PACKAGE_VERSION -SkipFonts++ - name: Check archive and run native converters+ run: |+ $archives = @(Get-ChildItem Releases -Filter '*-${{ matrix.rid }}.tar.gz')+ if ($archives.Count -ne 1) { throw 'Expected one portable archive.' }+ $archive = $archives[0]+ $expected = (Get-Content (Join-Path Releases ($archive.Name.Replace('.tar.gz', '-SHA256SUMS.txt')))).Split(' ')[0]+ if ((Get-FileHash $archive.FullName -Algorithm SHA256).Hash -ne $expected) { throw 'Archive checksum mismatch.' }+ $smoke = Join-Path $env:RUNNER_TEMP 'filee-smoke'+ New-Item -ItemType Directory -Path $smoke | Out-Null+ tar -xzf $archive.FullName -C $smoke+ if ($LASTEXITCODE -ne 0) { throw 'Archive extraction failed.' }+ $package = Join-Path $smoke ($archive.Name.Replace('.tar.gz', ''))+ if ($IsMacOS) {+ codesign --verify --deep --strict (Join-Path $package 'Filee.app')+ if ($LASTEXITCODE -ne 0) { throw 'Extracted app signature did not verify.' }+ }+ $bin = if ($IsMacOS) { Join-Path $package 'Filee.app/Contents/MacOS' } else { $package }+ $cli = Join-Path $bin 'filee-cli'+ & $cli version+ if ($LASTEXITCODE -ne 0) { throw 'CLI did not start.' }+ & (Join-Path $bin 'engines/rhwp/rhwp') --version+ if ($LASTEXITCODE -ne 0) { throw 'rhwp did not start.' }+ & (Join-Path $bin 'engines/7zip/7zz') i | Out-Null+ if ($LASTEXITCODE -ne 0) { throw '7-Zip did not start.' }+ $inputFile = Join-Path $smoke 'sample.txt'+ 'Filee 한글 conversion smoke test' | Set-Content $inputFile -Encoding utf8NoBOM+ & $cli convert $inputFile --to hwpx -o (Join-Path $smoke 'converted') --json+ if ($LASTEXITCODE -ne 0 -or -not (Test-Path (Join-Path $smoke 'converted/sample.hwpx'))) { throw 'Published CLI conversion failed.' }+ "FILEE_SMOKE_APP=$(Join-Path $bin 'Filee')" >> $env:GITHUB_ENV++ - name: Launch native desktop app+ shell: bash+ run: |+ set -euo pipefail+ python3 - <<'PY'+ import os+ import pathlib+ import signal+ import subprocess+ import sys+ import time++ app = os.environ['FILEE_SMOKE_APP']+ command = [app, '--settings', '--install-engines=', '--context-menu=off', '--start-with-system=off']+ if os.environ['RUNNER_OS'] == 'Linux':+ command = ['xvfb-run', '-a', 'env', '-u', 'WAYLAND_DISPLAY', 'XDG_SESSION_TYPE=x11', *command]+ log_path = pathlib.Path(os.environ['RUNNER_TEMP']) / 'filee-startup.log'+ with log_path.open('w') as log:+ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ try:+ time.sleep(8)+ if process.poll() is not None:+ raise RuntimeError('The desktop app exited before the startup check.')+ quit_code = 'import os, sys; os.setsid(); os.execv(sys.argv[1], [sys.argv[1], "--quit"])'+ subprocess.run([sys.executable, '-c', quit_code, app], check=True, timeout=30)+ if process.wait(timeout=15) != 0:+ raise RuntimeError('The desktop app did not exit cleanly.')+ except BaseException:+ log.flush()+ print(log_path.read_text(errors='replace'), file=sys.stderr)+ raise+ finally:+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout=10)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait()+ PY++ - name: Upload packages+ uses: actions/upload-artifact@v4+ with:+ name: portable-${{ matrix.rid }}+ path: |+ Releases/*-${{ matrix.rid }}.tar.gz+ Releases/*-${{ matrix.rid }}-SHA256SUMS.txt+ if-no-files-found: error++ - name: Upload test diagnostics+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: unix-test-results-${{ matrix.rid }}+ path: |+ TestResults/${{ matrix.rid }}/+ tests/Filee.App.Tests/bin/Release/net10.0/screenshots/+ ${{ runner.temp }}/filee-startup.log+ if-no-files-found: ignorediff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex aff3eb6d..cdff7566 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -18,7 +18,13 @@ permissions:contents: writejobs:+ portable:+ uses: ./.github/workflows/portable.yml+ with:+ version: ${{ github.ref_name }}+windows:+ needs: portableruns-on: windows-lateststeps:- uses: actions/checkout@v4@@ -64,6 +70,13 @@ jobs:shell: pwshrun: ./build/build-installer.ps1 -Version ${{ steps.version.outputs.value }} -Portable+ - name: Download Linux and macOS packages+ uses: actions/download-artifact@v4+ with:+ pattern: portable-*+ merge-multiple: true+ path: Releases+- name: Publish the GitHub releaseshell: pwshenv:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 615952d0..de9d21c2 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -11,11 +11,51 @@ Thanks for helping! Filee is built to be easy to extend: most contributions toucDOCX. XLSX ↔ CSV and anything → HWPX work without either). Without `-Only` it also downloads LibreOffice withH2Orestart and Java (~420 MB), which only older formats such as DOC, XLS and PPT need. Engines in therepository's `engines/` folder are picked up by debug builds; users download the large ones from the app.- Filee never uses programs installed on the system (Microsoft Office, a system LibreOffice, tools on `PATH`).+ Filee can also discover supported engines on `PATH` and in their standard installation folders. Settings >+ Engines lets you choose a specific copy. Microsoft Office is not used.4. `dotnet run --project src/Filee.App`, `dotnet test`.Any IDE works (Visual Studio 2022+, Rider, VS Code with C# Dev Kit).+## Linux and macOS development++These ports are development builds until native desktop tests are complete. Install .NET 10 and PowerShell 7,+then build on the target OS. Supported package targets are `linux-x64`, `linux-arm64`, `osx-x64` and `osx-arm64`.++```sh+pwsh build/fetch-fonts.ps1+pwsh build/fetch-portable-engines.ps1 -Runtime linux-x64 -Destination engines+dotnet test Filee.slnx -c Release+pwsh build/build-portable.ps1 -Runtime linux-x64+```++Use the matching runtime on a Mac or ARM64 Linux machine. Packaging runs on Linux/macOS so archives retain+executable permissions. Each archive contains the app, CLI, rhwp, 7-Zip, installation instructions and per-user+install/uninstall scripts. `Filee-<version>-<rid>-SHA256SUMS.txt` verifies the archive. macOS bundles use+`com.filee.app` and a development ad-hoc signature by default; public distribution still needs Developer ID signing+and notarization. `-SigningIdentity` can supply a signing identity, but does not perform notarization.++- **Linux:** drag gestures require X11. Install the Avalonia desktop dependencies (fontconfig, FreeType, X11,+ Xrandr, Xi, Xtst, XkbCommon, ICE and SM) and CJK fonts for document comparisons. File actions are installed for+ Thunar, Nautilus, Nemo and Dolphin. The first enabled keyboard shortcut uses Thunar's native custom action;+ close Thunar before changing or pausing that shortcut and reopen it afterwards. Global selected-file queries+ and hold gestures are not supported. Wayland can use file actions, the drop zone, watch folders and CLI.+- **macOS:** grant Filee Accessibility permission for gestures and Finder Automation permission for selection.+ Keep the development `.app` at a stable path while testing these permissions. Finder integration is a Quick+ Action under Services; auto-start uses a per-user LaunchAgent.+- **Engines:** packages are selected by OS and architecture. Linux LibreOffice/Ghostscript and macOS+ FFmpeg/Ghostscript currently use system or user-selected installations. Linux ARM64 has no Unhwp native binary.+ The macOS LibreOffice package does not include H2Orestart; native rhwp/Unhwp provide the supported HWP routes.+ Use Settings > Engines to inspect actual availability before comparing formats.++The reusable `portable.yml` workflow builds and tests all four targets. Native platform tests skip on other OSes.+Before calling a port ready, verify the installed package, CLI conversion, Finder/Thunar selection with Unicode+and spaced paths, drag and keyboard gestures, permissions denied/granted, Retina/scaling, tray, login startup,+engine downloads, watch folders, and uninstall. CI GUI startup alone does not validate these interactions.++The website lives in the adjacent `../filee-web` repository. Its downloads must match real release assets and+keep development status visible until native validation is complete.+## Where things liveRead [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short:diff --git a/Directory.Packages.props b/Directory.Packages.propsindex 5ca2f58e..5ba27f9c 100644--- a/Directory.Packages.props+++ b/Directory.Packages.props@@ -35,6 +35,8 @@<PackageVersion Include="ExcelNumberFormat" Version="1.1.0" /><!-- 5.2+ requires SkiaSharp 4 (see PDFtoImage above); 5.1.1 uses SkiaSharp 3.119 and HarfBuzzSharp 8.3 like Avalonia. --><PackageVersion Include="Svg.Skia" Version="5.1.1" />+ <PackageVersion Include="SkiaSharp" Version="3.119.4" />+ <PackageVersion Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.4" /><!-- Managed zstd / bzip2 for unpacking downloaded engines (conda packages). --><PackageVersion Include="SharpCompress" Version="1.0.0" /><PackageVersion Include="ExcelDataReader" Version="3.9.0" />diff --git a/Filee.slnx b/Filee.slnxindex 8cd8f7f8..01b89402 100644--- a/Filee.slnx+++ b/Filee.slnx@@ -3,6 +3,8 @@<Project Path="src/Filee.Core/Filee.Core.csproj" /><Project Path="src/Filee.Engines/Filee.Engines.csproj" /><Project Path="src/Filee.Platform.Windows/Filee.Platform.Windows.csproj" />+ <Project Path="src/Filee.Platform.Linux/Filee.Platform.Linux.csproj" />+ <Project Path="src/Filee.Platform.MacOS/Filee.Platform.MacOS.csproj" /><Project Path="src/Filee.App/Filee.App.csproj" /><Project Path="src/Filee.Cli/Filee.Cli.csproj" /></Folder>@@ -11,6 +13,7 @@<Project Path="tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj" /><Project Path="tests/Filee.App.Tests/Filee.App.Tests.csproj" /><Project Path="tests/Filee.Cli.Tests/Filee.Cli.Tests.csproj" />+ <Project Path="tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj" /></Folder><Folder Name="/Solution Items/"><File Path="Directory.Build.props" />diff --git a/README.ko.md b/README.ko.mdindex 5f2ece1a..64088dd2 100644--- a/README.ko.md+++ b/README.ko.md@@ -57,7 +57,8 @@업데이트한 다음 다시 켜 주고, 설정과 엔진은 그대로 남아요. 휴대용 버전은 대신 릴리스 페이지가 열려요. 사용자별로설치된 Filee 1.1 이하도 새 설치 파일이 넘겨받아요.-macOS 지원을 계획 중이고, Linux 지원도 검토하고 있어요.+Linux와 macOS 버전을 개발 중이며 실제 데스크톱 검증을 진행하고 있어요. 현재 안정 버전 다운로드는 Windows용이에요.+개발 빌드는 [Unix 빌드 안내](CONTRIBUTING.md#linux-and-macos-development)를 참고해 주세요.## 기능diff --git a/README.md b/README.mdindex 585241a5..08c1b233 100644--- a/README.md+++ b/README.md@@ -60,7 +60,8 @@ administrator rights once and installs Filee for all users in Program Files. Prestarts it again. The portable copy opens the release page instead. Filee 1.1 and earlier (installed per user) aretaken over by the new installer too.-macOS support is planned, and Linux is being considered.+Linux and macOS ports are in development. Native desktop validation is still in progress; the Windows release+remains the stable download. See [the Unix build instructions](CONTRIBUTING.md#linux-and-macos-development).## Featuresdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex a85368be..3743c861 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -55,7 +55,8 @@ Program Files。不想安装?把 `Filee-<版本>-win-Portable.zip` 解压到用发布页的 SHA-256 校验文件核对,再经过一次管理员确认后运行。安装程序会关闭 Filee、完成更新并重新启动它,设置和引擎都会保留。便携版则会打开发布页面。按用户安装的 Filee 1.1 及更早版本也会由新的安装程序接管。-macOS 版本正在计划中,也在考虑支持 Linux。+Linux 和 macOS 版本正在开发,实际桌面验证尚未完成。当前稳定版下载仍为 Windows 版。+开发构建请参阅 [Unix 构建说明](CONTRIBUTING.md#linux-and-macos-development)。## 功能diff --git a/build/build-portable.ps1 b/build/build-portable.ps1new file mode 100644index 00000000..f82317a5--- /dev/null+++ b/build/build-portable.ps1@@ -0,0 +1,120 @@+[CmdletBinding()]+param(+ [ValidateSet('linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64')][string]$Runtime,+ [string]$Version,+ [string]$OutputDir = (Join-Path $PSScriptRoot '../Releases'),+ [string]$SigningIdentity = '-',+ [switch]$SkipFonts+)++$ErrorActionPreference = 'Stop'+$root = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path+if ($IsWindows) { throw 'Create Unix packages on Linux or macOS to preserve executable permissions and sign macOS binaries.' }+if (-not $Runtime) {+ $cpu = [Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString().ToLowerInvariant()+ $Runtime = $(if ($IsMacOS) { 'osx' } else { 'linux' }) + "-$cpu"+}+if (($Runtime.StartsWith('osx-') -and -not $IsMacOS) -or ($Runtime.StartsWith('linux-') -and -not $IsLinux)) {+ throw "Build $Runtime on its native operating system."+}+if (-not $Version) {+ $Version = ([xml](Get-Content -LiteralPath (Join-Path $root 'Directory.Build.props') -Raw)).Project.PropertyGroup.Version |+ Where-Object { $_ } | Select-Object -First 1+}+$Version = $Version.TrimStart('v')+if ($Version -notmatch '^\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?$') {+ throw 'Version must be a three-part version with an optional prerelease suffix.'+}+$bundleVersion = ($Version -split '-')[0]+$packageName = "Filee-$Version-$Runtime"+New-Item -ItemType Directory -Force -Path $OutputDir | Out-Null+$OutputDir = (Resolve-Path -LiteralPath $OutputDir).Path+$archive = Join-Path $OutputDir "$packageName.tar.gz"+$sums = Join-Path $OutputDir "$packageName-SHA256SUMS.txt"+if ((Test-Path -LiteralPath $archive) -or (Test-Path -LiteralPath $sums)) {+ throw "Package $packageName already exists. Use another output folder or version."+}+$stage = Join-Path $root ('build/.cache/portable/' + [Guid]::NewGuid().ToString('N'))+$package = Join-Path $stage $packageName+$appBundle = Join-Path $package 'Filee.app'+$publish = if ($Runtime.StartsWith('osx-')) { Join-Path $appBundle 'Contents/MacOS' } else { $package }+New-Item -ItemType Directory -Force -Path $publish | Out-Null++function Invoke-Checked([string]$name, [scriptblock]$command) {+ & $command+ if ($LASTEXITCODE -ne 0) { throw "$name failed with exit code $LASTEXITCODE" }+}++if (-not $SkipFonts) { & (Join-Path $PSScriptRoot 'fetch-fonts.ps1') }+foreach ($project in @('Filee.App', 'Filee.Cli')) {+ Invoke-Checked "Publish $project" {+ dotnet publish (Join-Path $root "src/$project/$project.csproj") -c Release -r $Runtime --self-contained true `+ "-p:Version=$Version" -p:FileeRelease=true -p:PublishReadyToRun=false -o $publish+ }+}+& (Join-Path $PSScriptRoot 'fetch-portable-engines.ps1') -Runtime $Runtime -Destination (Join-Path $publish 'engines')+foreach ($name in @('Filee', 'filee-cli')) {+ $executable = Join-Path $publish $name+ if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Publish did not produce $name" }+ Invoke-Checked 'Executable permissions' { chmod +x $executable }+}+foreach ($notice in @('LICENSE', 'THIRD-PARTY-NOTICES.md')) {+ if (Test-Path -LiteralPath (Join-Path $root $notice)) {+ Copy-Item -LiteralPath (Join-Path $root $notice) -Destination $package+ }+}++if ($Runtime.StartsWith('osx-')) {+ $contents = Join-Path $appBundle 'Contents'+ $resources = Join-Path $contents 'Resources'+ New-Item -ItemType Directory -Path $resources | Out-Null+ $info = Get-Content -LiteralPath (Join-Path $root 'installer/macos/Info.plist') -Raw+ $info.Replace('__VERSION__', $bundleVersion).Replace('__BUNDLE_VERSION__', $bundleVersion) |+ Set-Content -LiteralPath (Join-Path $contents 'Info.plist') -Encoding utf8NoBOM+ Invoke-Checked 'Validate Info.plist' { plutil -lint (Join-Path $contents 'Info.plist') }+ $iconset = Join-Path $stage 'filee.iconset'+ New-Item -ItemType Directory -Path $iconset | Out-Null+ $sourceIcon = Join-Path $root 'src/Filee.App/Assets/Icons/filee.png'+ foreach ($size in @(16, 32, 128, 256, 512)) {+ foreach ($scale in @(1, 2)) {+ $pixels = $size * $scale+ $suffix = if ($scale -eq 2) { '@2x' } else { '' }+ $target = Join-Path $iconset "icon_${size}x${size}$suffix.png"+ Invoke-Checked 'Render app icon' { sips -z $pixels $pixels $sourceIcon --out $target | Out-Null }+ }+ }+ Invoke-Checked 'Create app icon' { iconutil -c icns $iconset -o (Join-Path $resources 'filee.icns') }+ $entitlements = Join-Path $root 'installer/macos/entitlements.plist'+ $signOptions = @('--force', '--sign', $SigningIdentity)+ if ($SigningIdentity -ne '-') { $signOptions += @('--timestamp', '--options', 'runtime') }+ foreach ($file in Get-ChildItem -LiteralPath $publish -Recurse -File | Sort-Object { $_.FullName.Length } -Descending) {+ $format = & /usr/bin/file --brief $file.FullName+ if ($LASTEXITCODE -ne 0) { throw "Cannot inspect $($file.FullName) before signing." }+ if ($format -match 'Mach-O') {+ Invoke-Checked 'Sign native binary' { codesign @signOptions --entitlements $entitlements $file.FullName }+ }+ }+ Invoke-Checked 'Sign app bundle' { codesign @signOptions --entitlements $entitlements $appBundle }+ Invoke-Checked 'Verify app signature' { codesign --verify --deep --strict $appBundle }+ Copy-Item -LiteralPath (Join-Path $root 'installer/macos/install.sh') -Destination $package+ Copy-Item -LiteralPath (Join-Path $root 'installer/macos/uninstall.sh') -Destination $package+ Copy-Item -LiteralPath (Join-Path $root 'installer/macos/INSTALL.txt') -Destination $package+}+else {+ Copy-Item -LiteralPath (Join-Path $root 'src/Filee.App/Assets/Icons/filee.png') -Destination $package+ Copy-Item -LiteralPath (Join-Path $root 'installer/linux/install.sh') -Destination $package+ Copy-Item -LiteralPath (Join-Path $root 'installer/linux/uninstall.sh') -Destination $package+ Copy-Item -LiteralPath (Join-Path $root 'installer/linux/INSTALL.txt') -Destination $package+}+Invoke-Checked 'Installer permissions' { chmod +x (Join-Path $package 'install.sh') (Join-Path $package 'uninstall.sh') }+$temporaryArchive = "$archive.$([Guid]::NewGuid().ToString('N')).partial"+Invoke-Checked 'Create tar.gz' { tar -czf $temporaryArchive -C $stage $packageName }+Move-Item -LiteralPath $temporaryArchive -Destination $archive+"$((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant()) $packageName.tar.gz" |+ Set-Content -LiteralPath $sums -Encoding ascii+Write-Host "Package: $archive"+Write-Host "Checksums: $sums"+Write-Host "Unpacked build retained for testing: $package"+if ($Runtime.StartsWith('osx-') -and $SigningIdentity -eq '-') {+ Write-Host 'This macOS build is ad-hoc signed for testing; it is not notarized for public distribution.'+}diff --git a/build/fetch-portable-engines.ps1 b/build/fetch-portable-engines.ps1new file mode 100644index 00000000..479f385f--- /dev/null+++ b/build/fetch-portable-engines.ps1@@ -0,0 +1,73 @@+[CmdletBinding()]+param(+ [Parameter(Mandatory)][ValidateSet('linux-x64', 'linux-arm64', 'osx-x64', 'osx-arm64')][string]$Runtime,+ [Parameter(Mandatory)][string]$Destination,+ [ValidateSet('rhwp', '7zip')][string[]]$Only = @('rhwp', '7zip')+)++$ErrorActionPreference = 'Stop'+$ProgressPreference = 'SilentlyContinue'+$manifestPath = Join-Path $PSScriptRoot '../src/Filee.Engines/Infrastructure/engines.json'+$manifest = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json -AsHashtable+$components = $manifest.platforms[$Runtime].components+$cache = Join-Path $PSScriptRoot '.cache/portable-downloads'+New-Item -ItemType Directory -Force -Path $cache, $Destination | Out-Null+$Destination = (Resolve-Path -LiteralPath $Destination).Path++foreach ($name in $Only) {+ $component = $components[$name]+ if (-not $component -or $component.sha256 -notmatch '^[0-9a-fA-F]{64}$') {+ throw "A pinned $name download is missing for $Runtime."+ }+ $target = Join-Path $Destination $name+ if (Test-Path -LiteralPath $target) {+ throw "Engine destination already exists: $target. Use a fresh publish folder."+ }+ $archive = Join-Path $cache "$($component.sha256).$($component.kind)"+ if (-not (Test-Path -LiteralPath $archive)) {+ $download = "$archive.$([Guid]::NewGuid().ToString('N')).partial"+ Invoke-WebRequest -Uri $component.url -OutFile $download+ if ((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash -ne $component.sha256) {+ Remove-Item -LiteralPath $download+ throw "Checksum mismatch for $name ($Runtime)."+ }+ Move-Item -LiteralPath $download -Destination $archive+ }+ if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $component.sha256) {+ throw "Cached engine checksum mismatch: $archive"+ }+ $members = @(& tar -tf $archive)+ if ($LASTEXITCODE -ne 0) { throw "Cannot read $archive" }+ foreach ($member in $members) {+ if ($member -match '^[/\\]' -or $member -match '(^|[/\\])\.\.([/\\]|$)' -or $member.Contains(':')) {+ throw "Unsafe archive member: $member"+ }+ }+ # These two bundles contain only files and directories; reject links before tar can create them.+ $details = @(& tar -tvf $archive)+ if ($LASTEXITCODE -ne 0) { throw "Cannot inspect entry types in $archive" }+ foreach ($entry in $details) {+ if ($entry -notmatch '^[-d]') {+ throw "Unsupported archive entry (links and special files are not allowed): $entry"+ }+ }+ $stage = Join-Path $cache ('extract-' + [Guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Path $stage | Out-Null+ & tar -xf $archive -C $stage+ if ($LASTEXITCODE -ne 0) { throw "Cannot extract $archive" }+ $children = @(Get-ChildItem -LiteralPath $stage -Force)+ $payload = if ($children.Count -eq 1 -and $children[0].PSIsContainer) { $children[0].FullName } else { $stage }+ $executable = if ($name -eq 'rhwp') { 'rhwp' } else { '7zz' }+ if (-not (Test-Path -LiteralPath (Join-Path $payload $executable) -PathType Leaf)) {+ throw "$executable was not found at the expected location in $archive"+ }+ Move-Item -LiteralPath $payload -Destination $target+ if (-not $IsWindows) {+ & chmod +x (Join-Path $target $executable)+ if ($LASTEXITCODE -ne 0) { throw "Could not make $executable executable." }+ }+ if (Test-Path -LiteralPath $stage) {+ Remove-Item -LiteralPath $stage+ }+ Write-Host "$name ready for $Runtime"+}diff --git a/installer/linux/INSTALL.txt b/installer/linux/INSTALL.txtnew file mode 100644index 00000000..6f854bff--- /dev/null+++ b/installer/linux/INSTALL.txt@@ -0,0 +1,29 @@+Run ./Filee to test the extracted app, or ./filee-cli help for the command line.++Run ./install.sh to install for the current user. It requires Python 3, creates+an application launcher and ~/.local/bin/filee, and does not require root.+Run ./uninstall.sh to remove this installation and Filee-downloaded engines.+Your settings and converted files are kept. If integration cleanup fails, the+installation is kept so you can fix the error and run the uninstaller again.+An existing installation is never overwritten; uninstall it before replacing it.++The .NET runtime is bundled; its native system libraries are still required.+On Ubuntu 24.04, install the desktop and runtime dependencies with:++sudo apt-get install ca-certificates libc6 libgcc-s1 libgssapi-krb5-2 libicu74 libssl3t64 libstdc++6 tzdata zlib1g libfontconfig1 libfreetype6 libx11-6 libice6 libsm6 libxrandr2 libxkbcommon0 libxi6 libxtst6 fonts-noto-cjk python3++Other distributions use different package names. The desktop needs an X11+server (or XWayland), fontconfig, FreeType and the X11 libraries above.+X11 supports the global gesture toolbar. A native Wayland session has additional+input restrictions; use the drop window and file-manager actions if needed.+Ubuntu 24.04 is the automated build and smoke-test baseline.++rhwp and 7-Zip are bundled. Other engines are installed from Filee settings or+discovered in the system. Format support depends on available native engines.+Optional engines can require additional system libraries. In particular, calibre+may require libxcb-cursor0, libxcb-xinerama0 and other Qt/XCB dependencies.++Dependency references:+https://learn.microsoft.com/en-us/dotnet/core/install/linux-ubuntu-install#ubuntu-2404+https://docs.avaloniaui.net/docs/deployment/linux+https://calibre-ebook.com/download_linuxdiff --git a/installer/linux/install.sh b/installer/linux/install.shnew file mode 100644index 00000000..2a3cec01--- /dev/null+++ b/installer/linux/install.sh@@ -0,0 +1,52 @@+#!/bin/sh+set -eu++source_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+data_dir=${XDG_DATA_HOME:-"$HOME/.local/share"}+install_dir="$data_dir/filee/application"+bin_dir="$HOME/.local/bin"+desktop_file="$data_dir/applications/com.filee.app.desktop"+if [ -e "$install_dir" ] || [ -L "$install_dir" ]; then+ printf '%s\n' "An installation already exists at $install_dir. Run its uninstall.sh first."+ exit 1+fi+if [ -e "$bin_dir/filee" ] || [ -L "$bin_dir/filee" ]; then+ printf '%s\n' "$bin_dir/filee already exists. Remove or rename it before installing Filee."+ exit 1+fi+if [ -e "$desktop_file" ] || [ -L "$desktop_file" ]; then+ printf '%s\n' "$desktop_file already exists. Remove or rename it before installing Filee."+ exit 1+fi+command -v python3 >/dev/null+test -x "$source_dir/Filee"+test -x "$source_dir/filee-cli"+mkdir -p "$data_dir/filee" "$bin_dir" "$data_dir/applications"+cp -R "$source_dir" "$install_dir"+printf '%s\n' 'com.filee.app' > "$install_dir/.filee-package"+ln -s "$install_dir/filee-cli" "$bin_dir/filee"+python3 - "$install_dir" "$desktop_file" <<'PY'+import pathlib+import sys++app, desktop = map(pathlib.Path, sys.argv[1:])+def quoted_exec(value):+ value = value.replace('%', '%%')+ for character in ('\\', '"', '`', '$'):+ value = value.replace(character, '\\' + character)+ return '"' + value.replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '\\r') + '"'++def desktop_value(value):+ return str(value).replace('\\', '\\\\').replace('\n', '\\n').replace('\r', '\\r')++desktop.write_text(+ '[Desktop Entry]\nType=Application\nName=Filee\n'+ 'Comment=Convert files with Filee\n'+ f'Exec={quoted_exec(str(app / "Filee"))} --convert %F\n'+ f'Icon={desktop_value(app / "filee.png")}\n'+ 'Terminal=false\nCategories=Utility;\nX-Filee-Managed=true\n', encoding='utf-8')+PY+if command -v update-desktop-database >/dev/null 2>&1; then+ update-desktop-database "$data_dir/applications"+fi+printf '%s\n' "Installed Filee at $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."diff --git a/installer/linux/uninstall.sh b/installer/linux/uninstall.shnew file mode 100644index 00000000..bccb5593--- /dev/null+++ b/installer/linux/uninstall.sh@@ -0,0 +1,26 @@+#!/bin/sh+set -eu++data_dir=${XDG_DATA_HOME:-"$HOME/.local/share"}+install_dir="$data_dir/filee/application"+desktop_file="$data_dir/applications/com.filee.app.desktop"+python3 - "$data_dir" "$install_dir" <<'PY'+import pathlib+import sys++root, target = map(pathlib.Path, sys.argv[1:])+expected = root.resolve() / 'filee' / 'application'+if target.is_symlink() or target.resolve() != expected:+ raise SystemExit('Refusing to remove an installation outside its expected directory.')+if (target / '.filee-package').read_text(encoding='utf-8').strip() != 'com.filee.app':+ raise SystemExit('The directory is not an installation created by Filee.')+PY+"$install_dir/Filee" --uninstall-cleanup+if [ -L "$HOME/.local/bin/filee" ] && [ "$(readlink "$HOME/.local/bin/filee")" = "$install_dir/filee-cli" ]; then+ rm -- "$HOME/.local/bin/filee"+fi+if [ -f "$desktop_file" ] && grep -q '^X-Filee-Managed=true$' "$desktop_file"; then+ rm -- "$desktop_file"+fi+rm -rf -- "$install_dir"+printf '%s\n' 'Filee was removed. Your settings and conversion results were kept.'diff --git a/installer/macos/INSTALL.txt b/installer/macos/INSTALL.txtnew file mode 100644index 00000000..90352be9--- /dev/null+++ b/installer/macos/INSTALL.txt@@ -0,0 +1,25 @@+This package requires macOS 14 or later and contains a separate build for+Apple Silicon or Intel Macs. The .NET runtime is included.+Run ./install.sh to copy Filee.app to ~/Applications and add ~/.local/bin/filee.+You can also move Filee.app into Applications manually. Keep its location stable+so Accessibility and Finder Automation permissions continue to identify it.++Test packages are ad-hoc signed and are not notarized. For a downloaded test+build, use System Settings > Privacy & Security > Open Anyway when macOS blocks+the first launch. Only open a build whose source and checksum you trust.++Allow Filee in System Settings > Privacy & Security > Accessibility for global+gestures. Allow Finder under Automation when using a selection shortcut.+Enable the Finder Quick Action in Filee settings. Services can also be managed+under System Settings > Keyboard > Keyboard Shortcuts > Services.++Run ./uninstall.sh to remove the ~/Applications installation, integration and+Filee-downloaded engines. Your settings and conversion results are kept.+If integration cleanup fails, the installation is kept so you can fix the error+and run the uninstaller again. A manually placed app in+/Applications can be removed after running its Filee executable with+--uninstall-cleanup.++rhwp and 7-Zip are bundled. Other engines can be installed in Filee settings or+discovered in the system. Public distribution requires Developer ID signing+and notarization; neither is supplied by this test package.diff --git a/installer/macos/Info.plist b/installer/macos/Info.plistnew file mode 100644index 00000000..49eca65a--- /dev/null+++ b/installer/macos/Info.plist@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key><string>en</string>+ <key>CFBundleIdentifier</key><string>com.filee.app</string>+ <key>CFBundleName</key><string>Filee</string>+ <key>CFBundleDisplayName</key><string>Filee</string>+ <key>CFBundleExecutable</key><string>Filee</string>+ <key>CFBundlePackageType</key><string>APPL</string>+ <key>CFBundleShortVersionString</key><string>__VERSION__</string>+ <key>CFBundleVersion</key><string>__BUNDLE_VERSION__</string>+ <key>CFBundleIconFile</key><string>filee.icns</string>+ <key>LSMinimumSystemVersion</key><string>14.0</string>+ <key>NSHighResolutionCapable</key><true/>+ <key>NSAppleEventsUsageDescription</key><string>Filee reads selected Finder files when you use a conversion shortcut.</string>+ <key>NSInputMonitoringUsageDescription</key><string>Filee detects your conversion shortcut and drag gesture to show the conversion menu.</string>+</dict>+</plist>diff --git a/installer/macos/entitlements.plist b/installer/macos/entitlements.plistnew file mode 100644index 00000000..e7df6a9a--- /dev/null+++ b/installer/macos/entitlements.plist@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.cs.allow-jit</key><true/>+ <key>com.apple.security.automation.apple-events</key><true/>+</dict>+</plist>diff --git a/installer/macos/install.sh b/installer/macos/install.shnew file mode 100644index 00000000..e7c7fda8--- /dev/null+++ b/installer/macos/install.sh@@ -0,0 +1,20 @@+#!/bin/sh+set -eu++source_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+install_dir="$HOME/Applications/Filee.app"+bin_dir="$HOME/.local/bin"+if [ -e "$install_dir" ] || [ -L "$install_dir" ]; then+ printf '%s\n' "An installation already exists at $install_dir. Run uninstall.sh first."+ exit 1+fi+if [ -e "$bin_dir/filee" ] || [ -L "$bin_dir/filee" ]; then+ printf '%s\n' "$bin_dir/filee already exists. Remove or rename it before installing Filee."+ exit 1+fi+test -x "$source_dir/Filee.app/Contents/MacOS/Filee"+mkdir -p "$HOME/Applications" "$bin_dir"+/usr/bin/ditto "$source_dir/Filee.app" "$install_dir"+ln -s "$install_dir/Contents/MacOS/filee-cli" "$bin_dir/filee"+printf '%s\n' "Installed $install_dir" "CLI: $bin_dir/filee (add $bin_dir to PATH if needed)."+printf '%s\n' 'Open Filee from Applications. Grant Accessibility and Finder Automation access when requested.'diff --git a/installer/macos/uninstall.sh b/installer/macos/uninstall.shnew file mode 100644index 00000000..7998bba0--- /dev/null+++ b/installer/macos/uninstall.sh@@ -0,0 +1,25 @@+#!/bin/sh+set -eu++install_dir="$HOME/Applications/Filee.app"+if [ -L "$install_dir" ] || [ ! -d "$install_dir" ]; then+ printf '%s\n' "No ordinary Filee app bundle was found at $install_dir."+ exit 1+fi+resolved_parent=$(CDPATH= cd -- "$HOME/Applications" && pwd -P)+resolved_app=$(CDPATH= cd -- "$install_dir" && pwd -P)+if [ "$resolved_app" != "$resolved_parent/Filee.app" ]; then+ printf '%s\n' 'Refusing to remove an app outside the expected Applications directory.'+ exit 1+fi+bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$install_dir/Contents/Info.plist")+if [ "$bundle_id" != 'com.filee.app' ]; then+ printf '%s\n' 'The bundle is not Filee.'+ exit 1+fi+"$install_dir/Contents/MacOS/Filee" --uninstall-cleanup+if [ -L "$HOME/.local/bin/filee" ] && [ "$(readlink "$HOME/.local/bin/filee")" = "$install_dir/Contents/MacOS/filee-cli" ]; then+ rm -- "$HOME/.local/bin/filee"+fi+rm -rf -- "$install_dir"+printf '%s\n' 'Filee was removed. Your settings and conversion results were kept.'diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex 70387e44..8d290037 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -20,6 +20,7 @@ public partial class App : Application{private readonly List<string> _pendingConvertFiles = [];private IDisposable? _convertDebounce;+ private bool _selectionPending;public override void Initialize() => AvaloniaXamlLoader.Load(this);@@ -49,11 +50,29 @@ public partial class App : Applicationvar platform = AppHost.Get<IPlatformServices>();triggers.DragStarted += (_, e) => radial.ShowForDrag(e.X, e.Y);triggers.DragEnded += (_, _) => radial.OnDragGestureEnded();- triggers.SelectionGesture += (_, e) =>+ triggers.SelectionGesture += async (_, e) =>{- var files = platform.GetFileManagerSelection();- if (files.Count > 0)- radial.ShowForFiles(e.X, e.Y, files);+ if (_selectionPending || store.Settings.Paused)+ return;+ _selectionPending = true;+ try+ {+ var files = OperatingSystem.IsMacOS()+ ? await Task.Run(platform.GetFileManagerSelection) : platform.GetFileManagerSelection();+ if (files.Count > 0 && !store.Settings.Paused)+ radial.ShowForFiles(e.X, e.Y, files);+ }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ log.LogWarning(ex, "Could not read the file manager selection");+ AppHost.Get<WindowService>().ShowMain("triggers");+ if (AppHost.Get<WindowService>().Main is { } window)+ _ = AppHost.Get<WindowService>().MessageAsync(window, ex.Message);+ }+ finally+ {+ _selectionPending = false;+ }};triggers.Start();log.LogInformation("Filee {Version} started", UpdateService.CurrentVersion);@@ -124,28 +143,7 @@ public partial class App : ApplicationAppHost.Get<ConverterCatalog>().Refresh();AppHost.Get<EngineDownloadService>().RefreshStatus();}- ApplySystemIntegration(settings, loc);- }-- /// <summary>Keeps registry entries in sync with settings (idempotent; paths follow updates).</summary>- private static void ApplySystemIntegration(AppSettings settings, ILocalizer loc)- {- var exe = Environment.ProcessPath;- if (exe is null || !OperatingSystem.IsWindows())- return;- // When running from the IDE (bin\Debug) don't touch the user's Explorer / startup settings.- if (!UpdateService.IsReleaseBuild)- return;- try- {- var platform = AppHost.Get<IPlatformServices>();- platform.SetStartWithSystem(settings.StartWithSystem, exe);- platform.SetContextMenu(settings.ContextMenuEnabled, exe, loc["general.context_menu_label"]);- }- catch (Exception ex)- {- AppHost.Get<ILogger<App>>().LogWarning(ex, "Could not update system integration");- }+ AppHost.Get<SystemIntegrationService>().Apply(settings);}private void HandleCommandLine(CommandLine options, bool firstLaunch = false)@@ -193,7 +191,7 @@ public partial class App : Application}/// <summary>- /// Options ticked on the installer's task page. Saving applies them (registry entries, see ApplySystemIntegration)+ /// Options ticked on the installer's task page. Saving applies them through SystemIntegrationService/// as if they had been switched on the General page./// </summary>private static void ApplyInstallerChoices(CommandLine options, UserDataStore store)@@ -209,7 +207,7 @@ public partial class App : Applicationprivate void OpenPendingFiles(){- var files = _pendingConvertFiles.Distinct(StringComparer.OrdinalIgnoreCase).ToList();+ var files = _pendingConvertFiles.Distinct(FileSystemPaths.Comparer).ToList();_pendingConvertFiles.Clear();var (x, y) = AppHost.Get<TriggerService>().LastCursor;if (x == 0 && y == 0 && AppHost.Get<WindowService>().Main is { } main)diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex bec646af..d3120c0a 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -125,6 +125,11 @@"general.start_with_system": "Start Filee when I sign in","general.context_menu": "Show “Convert with Filee” in the Explorer context menu","general.context_menu_label": "Convert with Filee",+ "general.context_menu_macos": "Add “Convert with Filee” to Finder Quick Actions",+ "general.context_menu_linux": "Add “Convert with Filee” to the file manager",+ "general.integration_macos": "Finder shows the action under Quick Actions or Services. Enable it in System Settings > Keyboard > Keyboard Shortcuts > Services if it is hidden.",+ "general.integration_linux": "File actions are installed for Thunar, Nautilus, Nemo and Dolphin. Close Thunar before changing or pausing its shortcut, then reopen it to load the change.",+ "general.integration_failed": "Could not apply system integration: {0}","general.modern_menu_hint": "On Windows 11 this entry is under “Show more options”. Filee can also add it to the main menu; Windows asks for administrator permission once.","general.modern_menu_on": "“Convert with Filee” is in the main Windows 11 menu.","general.modern_menu_outdated": "The main-menu entry belongs to an older or moved copy of Filee. Add it again to update it.",@@ -171,6 +176,14 @@"triggers.title": "Shortcuts","triggers.description": "Choose how the donut toolbar opens. You can add as many gestures as you like.",+ "triggers.macos_permissions": "Allow Filee in System Settings > Privacy & Security > Accessibility, then retry gestures. Finder also asks for Automation permission when you first use a selection shortcut.",+ "triggers.linux_x11": "Drag gestures use X11. The first enabled keyboard shortcut is assigned to the Thunar Filee action when file manager integration is on. Close Thunar before changing it, then reopen Thunar. Hold gestures and global selection shortcuts in other file managers are unavailable; use their Filee menu action or the drop zone.",+ "triggers.linux_wayland": "Cursor-following gestures are unavailable in this Wayland session. Use an X11 session for drag gestures, or convert through file manager actions and the drop zone. Thunar can use the first enabled keyboard shortcut after it restarts.",+ "triggers.open_accessibility": "Open Accessibility settings",+ "triggers.retry_hook": "Retry gestures",+ "triggers.hook_running": "Global input detection is running.",+ "triggers.hook_stopped": "Global input detection is stopped. File manager actions and the drop zone remain available.",+ "triggers.hook_failed": "Global input detection failed: {0}","triggers.add": "Add gesture","triggers.remove": "Remove","triggers.enabled": "On",@@ -359,6 +372,8 @@"engines.package.calibre.name": "Calibre (Kindle and rare e-book formats)","engines.package.calibre.description": "Saves as MOBI and AZW3 for Kindle, and converts rare e-book formats: LIT, LRF, PDB, PML, RB, SNB and TCR, plus CHM and OEB input. EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) are read without it.","engines.package.size": "Download {0} · {1} on disk",+ "engines.package.system_required": "Use a copy installed on this computer.",+ "engines.use_own_app_folder": "Choose the folder containing {0}.app","engines.progress_detail": "{0} of {1} · {2}/s · {3}","engines.eta.estimating": "estimating time left…","engines.eta.seconds": "{0} s left",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 4fdf561e..35a4d58a 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -125,6 +125,11 @@"general.start_with_system": "로그인할 때 Filee 시작","general.context_menu": "탐색기 우클릭 메뉴에 “Filee로 변환” 표시","general.context_menu_label": "Filee로 변환",+ "general.context_menu_macos": "Finder 빠른 동작에 “Filee로 변환” 추가",+ "general.context_menu_linux": "파일 관리자 메뉴에 “Filee로 변환” 추가",+ "general.integration_macos": "Finder의 빠른 동작 또는 서비스에서 사용할 수 있어요. 보이지 않으면 시스템 설정 > 키보드 > 키보드 단축키 > 서비스에서 켜 주세요.",+ "general.integration_linux": "Thunar, Nautilus, Nemo, Dolphin에 파일 동작을 추가해요. Thunar 단축키를 변경하거나 일시정지할 때는 Thunar를 닫은 상태에서 적용한 뒤 다시 열어 주세요.",+ "general.integration_failed": "시스템 연동을 적용하지 못했어요: {0}","general.modern_menu_hint": "Windows 11에서는 이 항목이 “추가 옵션 표시” 안에 있어요. 기본 메뉴에도 추가할 수 있고, 이때 Windows가 관리자 권한을 한 번 요청해요.","general.modern_menu_on": "“Filee로 변환”이 Windows 11 기본 메뉴에 있어요.","general.modern_menu_outdated": "기본 메뉴 항목이 이전 버전이나 다른 위치의 Filee를 가리키고 있어요. 다시 추가하면 업데이트돼요.",@@ -171,6 +176,14 @@"triggers.title": "단축키","triggers.description": "원형 툴바를 여는 방법을 정하세요. 제스처는 원하는 만큼 추가할 수 있어요.",+ "triggers.macos_permissions": "시스템 설정 > 개인정보 보호 및 보안 > 손쉬운 사용에서 Filee를 허용한 뒤 제스처를 다시 시도해 주세요. 선택 파일 단축키를 처음 사용하면 Finder 자동화 권한도 요청해요.",+ "triggers.linux_x11": "드래그 제스처는 X11에서 작동해요. 파일 관리자 연동을 켜면 첫 번째 활성 키보드 단축키를 Thunar의 Filee 동작에 연결해요. 변경할 때는 Thunar를 닫고 변경 후 다시 열어 주세요. 길게 누르기와 다른 파일 관리자의 전역 선택 단축키는 사용할 수 없어요. Filee 메뉴나 드롭 영역을 사용해 주세요.",+ "triggers.linux_wayland": "이 Wayland 세션에서는 커서를 따라가는 제스처를 사용할 수 없어요. 드래그 제스처는 X11 세션에서 사용하거나, 파일 관리자 메뉴와 드롭 영역으로 변환해 주세요. Thunar는 다시 시작한 뒤 첫 번째 활성 키보드 단축키를 사용할 수 있어요.",+ "triggers.open_accessibility": "손쉬운 사용 설정 열기",+ "triggers.retry_hook": "제스처 다시 시도",+ "triggers.hook_running": "전역 입력을 감지하고 있어요.",+ "triggers.hook_stopped": "전역 입력 감지가 멈춰 있어요. 파일 관리자 메뉴와 드롭 영역은 사용할 수 있어요.",+ "triggers.hook_failed": "전역 입력을 감지하지 못했어요: {0}","triggers.add": "제스처 추가","triggers.remove": "삭제","triggers.enabled": "사용",@@ -359,6 +372,8 @@"engines.package.calibre.name": "Calibre (킨들과 드문 전자책 형식)","engines.package.calibre.description": "킨들용 MOBI·AZW3로 저장하고, 드문 전자책 형식(LIT·LRF·PDB·PML·RB·SNB·TCR, CHM·OEB 읽기)을 변환해요. EPUB·MOBI·AZW3·FB2와 만화책(CBZ·CBR)은 없어도 읽을 수 있어요.","engines.package.size": "다운로드 {0} · 설치 후 {1}",+ "engines.package.system_required": "이 컴퓨터에 설치된 엔진을 연결해 주세요.",+ "engines.use_own_app_folder": "{0}.app이 들어 있는 폴더 선택","engines.progress_detail": "{0} / {1} · {2}/s · {3}","engines.eta.estimating": "남은 시간 계산 중…","engines.eta.seconds": "{0}초 남음",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 02a768c0..91edad89 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -125,6 +125,11 @@"general.start_with_system": "登录时启动 Filee","general.context_menu": "在资源管理器右键菜单中显示“用 Filee 转换”","general.context_menu_label": "用 Filee 转换",+ "general.context_menu_macos": "在 Finder 快速操作中添加“用 Filee 转换”",+ "general.context_menu_linux": "在文件管理器菜单中添加“用 Filee 转换”",+ "general.integration_macos": "可在 Finder 的快速操作或服务中找到此操作。若未显示,请在系统设置 > 键盘 > 键盘快捷键 > 服务中启用。",+ "general.integration_linux": "为 Thunar、Nautilus、Nemo 和 Dolphin 安装文件操作。修改或暂停 Thunar 快捷键前请关闭 Thunar,然后重新打开以加载更改。",+ "general.integration_failed": "无法应用系统集成:{0}","general.modern_menu_hint": "在 Windows 11 中,此项位于“显示更多选项”里。Filee 也可以把它添加到主菜单,Windows 会请求一次管理员权限。","general.modern_menu_on": "“用 Filee 转换”已在 Windows 11 主菜单中。","general.modern_menu_outdated": "主菜单中的此项属于旧版本或其他位置的 Filee。重新添加即可更新。",@@ -171,6 +176,14 @@"triggers.title": "快捷操作","triggers.description": "选择打开环形工具栏的方式。可以添加任意多个手势。",+ "triggers.macos_permissions": "请在系统设置 > 隐私与安全性 > 辅助功能中允许 Filee,然后重试手势。首次使用选择文件的快捷键时,Finder 还会请求自动化权限。",+ "triggers.linux_x11": "拖动手势需要 X11。启用文件管理器集成后,第一个已启用的键盘快捷键会分配给 Thunar 的 Filee 操作。修改前请关闭 Thunar,修改后重新打开。不支持长按手势及其他文件管理器的全局选择快捷键,请使用 Filee 菜单或拖放区域。",+ "triggers.linux_wayland": "当前 Wayland 会话不支持跟随光标的手势。请使用 X11 会话进行拖动,或通过文件管理器操作和拖放区域转换。重启 Thunar 后可使用第一个已启用的键盘快捷键。",+ "triggers.open_accessibility": "打开辅助功能设置",+ "triggers.retry_hook": "重试手势",+ "triggers.hook_running": "正在检测全局输入。",+ "triggers.hook_stopped": "全局输入检测已停止。仍可使用文件管理器操作和拖放区域。",+ "triggers.hook_failed": "全局输入检测失败:{0}","triggers.add": "添加手势","triggers.remove": "删除","triggers.enabled": "启用",@@ -359,6 +372,8 @@"engines.package.calibre.name": "Calibre(Kindle 与少见电子书格式)","engines.package.calibre.description": "可保存为 Kindle 使用的 MOBI 和 AZW3,并转换少见的电子书格式:LIT、LRF、PDB、PML、RB、SNB、TCR,以及读取 CHM 和 OEB。EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)无需它即可读取。","engines.package.size": "下载 {0} · 占用 {1}",+ "engines.package.system_required": "请使用此电脑上已安装的引擎。",+ "engines.use_own_app_folder": "选择包含 {0}.app 的文件夹","engines.progress_detail": "{0} / {1} · {2}/s · {3}","engines.eta.estimating": "正在估算剩余时间…","engines.eta.seconds": "剩余 {0} 秒",diff --git a/src/Filee.App/Filee.App.csproj b/src/Filee.App/Filee.App.csprojindex d7dd4f3a..b08ead4f 100644--- a/src/Filee.App/Filee.App.csproj+++ b/src/Filee.App/Filee.App.csproj@@ -16,6 +16,8 @@<ProjectReference Include="..\Filee.Core\Filee.Core.csproj" /><ProjectReference Include="..\Filee.Engines\Filee.Engines.csproj" /><ProjectReference Include="..\Filee.Platform.Windows\Filee.Platform.Windows.csproj" />+ <ProjectReference Include="..\Filee.Platform.Linux\Filee.Platform.Linux.csproj" />+ <ProjectReference Include="..\Filee.Platform.MacOS\Filee.Platform.MacOS.csproj" /></ItemGroup><ItemGroup>diff --git a/src/Filee.App/Program.cs b/src/Filee.App/Program.csindex 2972ae2a..06872003 100644--- a/src/Filee.App/Program.cs+++ b/src/Filee.App/Program.cs@@ -67,7 +67,7 @@ internal static class Programif (!WaitForOtherProcessesOfThisExe(deadline))return 1;if (Options.UninstallCleanup)- UninstallCleanup.Run();+ return UninstallCleanup.Run() ? 0 : 1;return 0;}}@@ -83,7 +83,7 @@ internal static class Programtry{if (process.Id == Environment.ProcessId- || !string.Equals(process.MainModule?.FileName, exe, StringComparison.OrdinalIgnoreCase))+ || !string.Equals(process.MainModule?.FileName, exe, Filee.Core.Platform.FileSystemPaths.Comparison))continue;var left = deadline - DateTime.UtcNow;if (left <= TimeSpan.Zero || !process.WaitForExit(left))diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.csindex 1349291c..5b03168f 100644--- a/src/Filee.App/Services/AppHost.cs+++ b/src/Filee.App/Services/AppHost.cs@@ -8,6 +8,8 @@ using Filee.Core.Platform;using Filee.Core.Settings;using Filee.Engines;using Filee.Engines.Infrastructure;+using Filee.Platform.Linux;+using Filee.Platform.MacOS;using Filee.Platform.Windows;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;@@ -33,11 +35,15 @@ public static class AppHostservices.AddSingleton(sp => new UserDataStore(dataDir, sp.GetRequiredService<ILogger<UserDataStore>>()));services.AddSingleton<IPlatformServices>(_ =>- OperatingSystem.IsWindows() ? new WindowsPlatformServices() : new NullPlatformServices());+ OperatingSystem.IsWindows() ? new WindowsPlatformServices()+ : OperatingSystem.IsMacOS() ? new MacOSPlatformServices()+ : OperatingSystem.IsLinux() ? new LinuxPlatformServices()+ : new NullPlatformServices());services.AddSingleton<LocalizationService>();services.AddSingleton<ILocalizer>(sp => sp.GetRequiredService<LocalizationService>());services.AddSingleton<ThemeService>();+ services.AddSingleton<SystemIntegrationService>();// Conversion enginesservices.AddSingleton(_ => new EngineEnvironment(dataDir));diff --git a/src/Filee.App/Services/CommandLine.cs b/src/Filee.App/Services/CommandLine.csindex 4bd77760..d9a9c6f5 100644--- a/src/Filee.App/Services/CommandLine.cs+++ b/src/Filee.App/Services/CommandLine.cs@@ -66,7 +66,7 @@ public sealed record CommandLine(engines = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(id => id.ToLowerInvariant()).Distinct().ToList();break;- case "--start-with-windows" when OnOff(value) is { } on:+ case "--start-with-windows" or "--start-with-system" when OnOff(value) is { } on:startWithWindows = on;break;case "--context-menu" when OnOff(value) is { } on:@@ -139,7 +139,7 @@ public sealed record CommandLine(return Path.GetFileName(full).StartsWith(ListFilePrefix, StringComparison.OrdinalIgnoreCase)&& full.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)&& string.Equals(Path.TrimEndingDirectorySeparator(Path.GetDirectoryName(full) ?? ""),- Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())), StringComparison.OrdinalIgnoreCase);+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())), Filee.Core.Platform.FileSystemPaths.Comparison);}catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException){diff --git a/src/Filee.App/Services/EngineDownloadService.cs b/src/Filee.App/Services/EngineDownloadService.csindex a2b85e07..c094abd0 100644--- a/src/Filee.App/Services/EngineDownloadService.cs+++ b/src/Filee.App/Services/EngineDownloadService.cs@@ -39,8 +39,11 @@ public sealed partial class EnginePackageState : ObservableObjectpublic string Name => _loc[$"engines.package.{Package.Id}.name"];public string Description => _loc[$"engines.package.{Package.Id}.description"];- public string Sizes => _loc.Format("engines.package.size",- FormatBytes(EngineDownloads.DownloadSize(Package)), FormatBytes(Package.InstalledSize));+ public string Sizes => EngineDownloads.CanDownload(Package)+ ? _loc.Format("engines.package.size", FormatBytes(EngineDownloads.DownloadSize(Package)), FormatBytes(Package.InstalledSize))+ : _loc["engines.package.system_required"];++ public string? InstallGuidance => EngineDownloads.UnavailableReason(Package);[ObservableProperty][NotifyPropertyChangedFor(nameof(StatusText), nameof(IsInstalled), nameof(IsBusy), nameof(CanInstall), nameof(CanRemove),@@ -87,8 +90,8 @@ public sealed partial class EnginePackageState : ObservableObject|| (Status == EnginePackageStatus.OwnCopy && FromSystem);public bool IsBusy => Status is EnginePackageStatus.Queued or EnginePackageStatus.Downloading or EnginePackageStatus.Unpacking;/// <summary>Also when a copy on the PC is used: Filee's download is the tested version and wins once installed.</summary>- public bool CanInstall => Status is EnginePackageStatus.NotInstalled or EnginePackageStatus.Failed- || (Status == EnginePackageStatus.OwnCopy && FromSystem);+ public bool CanInstall => EngineDownloads.CanDownload(Package) && (Status is EnginePackageStatus.NotInstalled or EnginePackageStatus.Failed+ || (Status == EnginePackageStatus.OwnCopy && FromSystem));public string StatusText => Status switch{@@ -204,7 +207,7 @@ public sealed class EngineDownloadService/// <summary>Downloads and installs a package; packages queue up and install one after another.</summary>public async Task InstallAsync(EnginePackageState state){- if (state.IsBusy || state.IsInstalled)+ if (!state.CanInstall)return;using var cancellation = new CancellationTokenSource();state.Cancellation = cancellation;diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.csindex 8a51c98e..25dbcdd1 100644--- a/src/Filee.App/Services/RadialController.cs+++ b/src/Filee.App/Services/RadialController.cs@@ -279,7 +279,7 @@ public sealed class RadialController({var cursor = new PixelPoint(x, y);var screen = window.Screens.ScreenFromPoint(cursor) ?? window.Screens.Primary;- var scaling = screen?.Scaling ?? 1;+ var scaling = OperatingSystem.IsMacOS() ? 1 : screen?.Scaling ?? 1;// Window size follows the donut size (SizeToContent); compute it up front to centre on the cursor.var side = 2 * (viewModel.OuterRadius + 7 + 14);@@ -308,5 +308,5 @@ public sealed class RadialController(}private static bool SameFiles(IReadOnlyList<string> a, IReadOnlyList<string> b) =>- a.Count == b.Count && a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase);+ a.Count == b.Count && a.SequenceEqual(b, FileSystemPaths.Comparer);}diff --git a/src/Filee.App/Services/SingleInstance.cs b/src/Filee.App/Services/SingleInstance.csindex e98f34ac..c3e45f2e 100644--- a/src/Filee.App/Services/SingleInstance.cs+++ b/src/Filee.App/Services/SingleInstance.cs@@ -1,5 +1,5 @@-// Makes sure only one Filee runs per user session. Later launches send their command line to the first-// instance through a named pipe (e.g. Explorer starts one process per selected file for the context menu).+// Keeps one Filee per Windows session, or per user across Unix launcher/terminal sessions.+// Later launches forward arguments through a named pipe.using System.IO.Pipes;using System.Text.Json;@@ -28,7 +28,11 @@ public sealed class SingleInstance : IDisposablepublic static SingleInstance Acquire(){- var mutex = new Mutex(initiallyOwned: true, @"Local\" + Name, out var createdNew);+ bool createdNew;+ var mutex = OperatingSystem.IsWindows()+ ? new Mutex(initiallyOwned: true, @"Local\" + Name, out createdNew)+ : new Mutex(initiallyOwned: true, Name,+ new NamedWaitHandleOptions { CurrentUserOnly = true, CurrentSessionOnly = false }, out createdNew);return new SingleInstance(mutex, createdNew);}diff --git a/src/Filee.App/Services/SystemIntegrationService.cs b/src/Filee.App/Services/SystemIntegrationService.csnew file mode 100644index 00000000..569da464--- /dev/null+++ b/src/Filee.App/Services/SystemIntegrationService.cs@@ -0,0 +1,64 @@+using Filee.Core.Localization;+using Filee.Core.Platform;+using Filee.Core.Settings;+using Filee.Platform.Linux;+using Microsoft.Extensions.Logging;++namespace Filee.App.Services;++public sealed class SystemIntegrationService(IPlatformServices platform, ILocalizer loc, ILogger<SystemIntegrationService> log)+{+ private (bool Enabled, string Executable)? _startup;+ private (bool Enabled, string Executable, string Label)? _menu;+ private bool _shortcutApplied;+ private string? _shortcut;++ public string? Error { get; private set; }+ internal bool RegistrationEnabled { get; init; } = UpdateService.IsReleaseBuild;+ internal string? ExecutablePath { get; init; } = Environment.ProcessPath;++ public void Apply(AppSettings settings)+ {+ Error = null;+ if (!RegistrationEnabled || ExecutablePath is not { } executable)+ return;+ var errors = new List<string>();+ var startup = (settings.StartWithSystem, executable);+ if (_startup != startup && ApplyOne(() => platform.SetStartWithSystem(startup.StartWithSystem, executable)))+ _startup = startup;+ var menu = (settings.ContextMenuEnabled, executable, Label: loc["general.context_menu_label"]);+ if (_menu != menu && ApplyOne(() => platform.SetContextMenu(menu.ContextMenuEnabled, executable, menu.Label)))+ {+ _menu = menu;+ _shortcutApplied = false;+ }+ if (OperatingSystem.IsLinux() && platform is LinuxPlatformServices linux)+ {+ ApplyOne(() =>+ {+ var shortcut = settings.ContextMenuEnabled && !settings.Paused+ ? settings.Triggers.FirstOrDefault(g => g.Enabled && g.Kind == TriggerKind.KeyChord) : null;+ var accelerator = shortcut is null ? null : LinuxPlatformServices.ToThunarAccelerator(shortcut);+ if (!_shortcutApplied || _shortcut != accelerator)+ {+ linux.SetThunarShortcut(accelerator);+ _shortcut = accelerator;+ _shortcutApplied = true;+ }+ });+ }+ if (errors.Count > 0)+ Error = loc.Format("general.integration_failed", string.Join(Environment.NewLine, errors));++ bool ApplyOne(Action action)+ {+ try { action(); return true; }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ log.LogWarning(ex, "Could not update system integration");+ errors.Add(ex.Message);+ return false;+ }+ }+ }+}diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.csindex da632dbc..24eb0bf3 100644--- a/src/Filee.App/Services/Triggers/TriggerService.cs+++ b/src/Filee.App/Services/Triggers/TriggerService.cs@@ -50,10 +50,14 @@ public sealed class TriggerService : IDisposablepublic (int X, int Y) LastCursor { get; private set; }public bool IsRunning => _hook?.IsRunning == true;+ public string? Error { get; private set; }+ public event EventHandler? StatusChanged;++ private void NotifyStatus() => Post(() => StatusChanged?.Invoke(this, EventArgs.Empty));public void Apply(AppSettings settings){- _detector.Configure(settings.Triggers);+ _detector.Configure(settings.Triggers.Where(g => _platform.SupportsSelectionShortcut || g.Kind == TriggerKind.Drag).ToList());_detector.Paused = settings.Paused;_excluded = new HashSet<string>(settings.ExcludedProcesses.Select(p => p.Trim().Replace(".exe", "", StringComparison.OrdinalIgnoreCase)),StringComparer.OrdinalIgnoreCase);@@ -63,11 +67,14 @@ public sealed class TriggerService : IDisposable{if (_hook is not null)return;+ if (!_platform.SupportsGlobalPointerGestures)+ return;+ Error = null;try{_hook = new EventLoopGlobalHook();- _hook.HookEnabled += (_, _) => _log.LogInformation("Global input hook started");- _hook.HookDisabled += (_, _) => _log.LogInformation("Global input hook stopped");+ _hook.HookEnabled += (_, _) => { _log.LogInformation("Global input hook started"); NotifyStatus(); };+ _hook.HookDisabled += (_, _) => { _log.LogInformation("Global input hook stopped"); NotifyStatus(); };_hook.MousePressed += (_, e) => _detector.MouseDown(Map(e.Data.Button), e.Data.X, e.Data.Y, Map(e.RawEvent.Mask));_hook.MouseReleased += (_, e) => _detector.MouseUp(Map(e.Data.Button), e.Data.X, e.Data.Y);_hook.MouseDragged += (_, e) => OnMove(e);@@ -77,14 +84,21 @@ public sealed class TriggerService : IDisposable{// e.g. macOS without Accessibility permission. Drop zone and context menu keep working.if (t.Exception is not null)+ {+ Error = t.Exception.GetBaseException().Message;_log.LogError(t.Exception, "Global input hook failed; gestures are unavailable");+ NotifyStatus();+ }}, TaskScheduler.Default);}catch (Exception ex){// e.g. macOS without Accessibility permission. The app keeps working via the drop zone / context menu._log.LogError(ex, "Could not start the global input hook");+ Error = ex.Message;+ _hook?.Dispose();_hook = null;+ NotifyStatus();}}diff --git a/src/Filee.App/Services/UninstallCleanup.cs b/src/Filee.App/Services/UninstallCleanup.csindex e2b98ac2..4d5cef3a 100644--- a/src/Filee.App/Services/UninstallCleanup.cs+++ b/src/Filee.App/Services/UninstallCleanup.cs@@ -1,33 +1,54 @@-// Runs as "Filee.exe --uninstall-cleanup" from the uninstaller (installer/Filee.iss), after the running Filee exited:-// removes registry entries, the Windows 11 Explorer menu package, downloaded engines and other integration Filee-// created for the current user. Settings in %APPDATA%\Filee stay, so reinstalling brings them back.+// Removes per-user integration and downloaded engines after Filee exits. User settings remain for reinstalling.+using Filee.Core.Platform;+using Filee.Platform.Linux;+using Filee.Platform.MacOS;using Filee.Platform.Windows;namespace Filee.App.Services;internal static class UninstallCleanup{- public static void Run()+ public static bool Run(){- if (!OperatingSystem.IsWindows())- return;- try+ IPlatformServices platform = OperatingSystem.IsWindows() ? new WindowsPlatformServices()+ : OperatingSystem.IsMacOS() ? new MacOSPlatformServices()+ : OperatingSystem.IsLinux() ? new LinuxPlatformServices() : new NullPlatformServices();+ var succeeded = true;+ Clean(() => platform.SetContextMenu(false, "", ""));+ Clean(() => platform.SetStartWithSystem(false, ""));+ if (OperatingSystem.IsLinux() && platform is LinuxPlatformServices linux)+ Clean(() => linux.SetThunarShortcut(null));+ if (OperatingSystem.IsWindows() && ExplorerMenuRegistration.IsSupportedOs){- var platform = new WindowsPlatformServices();- // Deletes the classic verb, Send To and the title file (which already hides the top-level entry).- platform.SetContextMenu(false, "", "");- platform.SetStartWithSystem(false, "");- // The uninstaller runs with administrator rights already, so no UAC prompt can appear here.- if (ExplorerMenuRegistration.IsSupportedOs)- ExplorerMenuRegistration.RemoveAsync(allowElevation: false).Wait(TimeSpan.FromSeconds(40));- // Engines downloaded later live outside the app folder (see EngineEnvironment.DownloadRoot).- if (Directory.Exists(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot))- Directory.Delete(Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot, recursive: true);+ Clean(() =>+ {+ var task = ExplorerMenuRegistration.RemoveAsync(allowElevation: false);+ if (!task.Wait(TimeSpan.FromSeconds(40)))+ throw new TimeoutException("Timed out removing the Explorer menu.");+ if (!task.Result.Succeeded)+ throw new IOException(task.Result.Error ?? "Could not remove the Explorer menu.");+ });}- catch (Exception)+ if (succeeded){- // Uninstall must never fail because of cleanup.+ Clean(() =>+ {+ var engines = Filee.Engines.Infrastructure.EngineEnvironment.DownloadRoot;+ if (Directory.Exists(engines))+ Directory.Delete(engines, recursive: true);+ });+ }+ return succeeded;++ void Clean(Action action)+ {+ try { action(); }+ catch (Exception ex) when (ex is not OutOfMemoryException)+ {+ succeeded = false;+ Console.Error.WriteLine(ex.Message);+ }}}}diff --git a/src/Filee.App/ViewModels/EngineSetupViewModel.cs b/src/Filee.App/ViewModels/EngineSetupViewModel.csindex da4fcecf..bb8c9e67 100644--- a/src/Filee.App/ViewModels/EngineSetupViewModel.cs+++ b/src/Filee.App/ViewModels/EngineSetupViewModel.cs@@ -20,7 +20,7 @@ public sealed partial class EngineSetupViewModel : ObservableObject_loc = loc;foreach (var package in Packages){- package.Selected = !package.IsInstalled && Filee.Engines.Infrastructure.EngineDownloads.IsSuggested(package.Package);+ package.Selected = package.CanInstall && Filee.Engines.Infrastructure.EngineDownloads.IsSuggested(package.Package);package.PropertyChanged += OnPackageChanged;}}diff --git a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.csindex 10a720bf..60592c0a 100644--- a/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/GeneralPageViewModel.cs@@ -16,13 +16,16 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposableprivate readonly ILocalizer _loc;private readonly IPlatformServices _platform;private readonly UpdateService _updates;+ private readonly SystemIntegrationService? _integration;- public GeneralPageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices platform, UpdateService updates)+ public GeneralPageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices platform, UpdateService updates,+ SystemIntegrationService? integration = null){_store = store;_loc = loc;_platform = platform;_updates = updates;+ _integration = integration;Languages =[@@ -62,6 +65,11 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposablepublic IReadOnlyList<Choice<string>> Languages { get; }public string DataFolder => _store.Directory;public bool IsWindows => OperatingSystem.IsWindows();+ public bool HasSystemIntegration => _platform is not NullPlatformServices;+ public string ContextMenuText => _loc[OperatingSystem.IsMacOS() ? "general.context_menu_macos"+ : OperatingSystem.IsLinux() ? "general.context_menu_linux" : "general.context_menu"];+ public string? IntegrationMessage => _integration?.Error ?? (OperatingSystem.IsMacOS()+ ? _loc["general.integration_macos"] : OperatingSystem.IsLinux() ? _loc["general.integration_linux"] : null);/// <summary>Choices for the default save location (everything but "Default" itself).</summary>public IReadOnlyList<Choice<OutputLocation>> OutputLocations { get; }@@ -193,6 +201,7 @@ public sealed partial class GeneralPageViewModel : ObservableObject, IDisposable{change(_store.Settings);_store.SaveSettings();+ OnPropertyChanged(nameof(IntegrationMessage));}[RelayCommand]diff --git a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.csindex 0e312436..1d5d4598 100644--- a/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs+++ b/src/Filee.App/ViewModels/Pages/TriggersPageViewModel.cs@@ -6,8 +6,12 @@ using Avalonia.Input;using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;using Filee.App.Services;+using Filee.App.Services.Triggers;using Filee.Core.Localization;+using Filee.Core.Platform;using Filee.Core.Settings;+using Filee.Platform.Linux;+using Filee.Platform.MacOS;using ModifierKeys = Filee.Core.Settings.ModifierKeys;namespace Filee.App.ViewModels.Pages;@@ -127,15 +131,26 @@ public sealed partial class TriggerGestureViewModel : ObservableObject}}-public sealed partial class TriggersPageViewModel : ObservableObject+public sealed partial class TriggersPageViewModel : ObservableObject, IDisposable{private readonly UserDataStore _store;private readonly ILocalizer _loc;+ private readonly IPlatformServices? _platform;+ private readonly TriggerService? _triggers;+ private readonly SystemIntegrationService? _integration;+ private string? _accessibilityError;- public TriggersPageViewModel(UserDataStore store, ILocalizer loc)+ public TriggersPageViewModel(UserDataStore store, ILocalizer loc, IPlatformServices? platform = null, TriggerService? triggers = null,+ SystemIntegrationService? integration = null){_store = store;_loc = loc;+ _platform = platform;+ _triggers = triggers;+ _integration = integration;+ store.SettingsChanged += OnTriggerSettingsChanged;+ if (triggers is not null)+ triggers.StatusChanged += OnTriggerStatusChanged;foreach (var gesture in store.Settings.Triggers)Gestures.Add(new TriggerGestureViewModel(gesture, loc, Save));_excluded = string.Join(", ", store.Settings.ExcludedProcesses);@@ -143,6 +158,53 @@ public sealed partial class TriggersPageViewModel : ObservableObjectpublic ObservableCollection<TriggerGestureViewModel> Gestures { get; } = [];+ public bool IsMacOS => _platform is MacOSPlatformServices;+ public bool CanRetryHook => _triggers is not null && (_platform?.SupportsGlobalPointerGestures == true || IsMacOS);+ public string? IntegrationError => _accessibilityError ?? _integration?.Error;+ public string? PlatformNotice => _platform switch+ {+ MacOSPlatformServices => _loc["triggers.macos_permissions"],+ LinuxPlatformServices when OperatingSystem.IsLinux() && LinuxPlatformServices.IsWaylandSession => _loc["triggers.linux_wayland"],+ LinuxPlatformServices => _loc["triggers.linux_x11"],+ _ => null,+ };+ public string? HookStatus => _triggers?.Error is { } error ? _loc.Format("triggers.hook_failed", error)+ : _triggers is null ? null : _loc[_triggers.IsRunning ? "triggers.hook_running" : "triggers.hook_stopped"];++ private void OnTriggerStatusChanged(object? sender, EventArgs e) => OnPropertyChanged(nameof(HookStatus));+ private void OnTriggerSettingsChanged(object? sender, EventArgs e) => OnPropertyChanged(nameof(IntegrationError));++ [RelayCommand]+ private void OpenAccessibility()+ {+ try+ {+ _accessibilityError = null;+ if (OperatingSystem.IsMacOS() && _platform is MacOSPlatformServices mac)+ mac.OpenAccessibilitySettings();+ }+ catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException)+ {+ _accessibilityError = ex.Message;+ }+ OnPropertyChanged(nameof(IntegrationError));+ }++ [RelayCommand]+ private void RetryHook()+ {+ _triggers?.Dispose();+ _triggers?.Start();+ OnPropertyChanged(nameof(HookStatus));+ }++ public void Dispose()+ {+ _store.SettingsChanged -= OnTriggerSettingsChanged;+ if (_triggers is not null)+ _triggers.StatusChanged -= OnTriggerStatusChanged;+ }+[ObservableProperty] private string _excluded;partial void OnExcludedChanged(string value)diff --git a/src/Filee.App/Views/EngineSetupWindow.axaml b/src/Filee.App/Views/EngineSetupWindow.axamlindex 1e831328..8c2e1072 100644--- a/src/Filee.App/Views/EngineSetupWindow.axaml+++ b/src/Filee.App/Views/EngineSetupWindow.axaml@@ -39,6 +39,8 @@</StackPanel><TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Description}" /><TextBlock Classes="caption" Text="{Binding Sizes}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding InstallGuidance}"+ IsVisible="{Binding InstallGuidance, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" /><ProgressBar Classes="soft" Maximum="100" Value="{Binding Progress}" IsVisible="{Binding IsBusy}" Margin="0,4,0,0" /><TextBlock Classes="caption" Text="{Binding ProgressDetail}" IsVisible="{Binding ProgressDetail, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" /></StackPanel>diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml b/src/Filee.App/Views/Pages/EnginesPage.axamlindex 461bca92..d17e9d73 100644--- a/src/Filee.App/Views/Pages/EnginesPage.axaml+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml@@ -53,6 +53,8 @@</StackPanel><TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Description}" /><TextBlock Classes="caption" Text="{Binding Sizes}" IsVisible="{Binding !UsesOwnCopy}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding InstallGuidance}"+ IsVisible="{Binding InstallGuidance, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" /><TextBlock Classes="caption" Text="{Binding OwnCopyFolder}" IsVisible="{Binding ShowsCopyFolder}" TextTrimming="CharacterEllipsis" /><TextBlock Classes="caption" Foreground="{DynamicResource WarningBrush}" TextWrapping="Wrap" Text="{Binding UpdateNote}"IsVisible="{Binding UpdateNote, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />diff --git a/src/Filee.App/Views/Pages/EnginesPage.axaml.cs b/src/Filee.App/Views/Pages/EnginesPage.axaml.csindex da6d247c..91510ba9 100644--- a/src/Filee.App/Views/Pages/EnginesPage.axaml.cs+++ b/src/Filee.App/Views/Pages/EnginesPage.axaml.cs@@ -19,13 +19,27 @@ public partial class EnginesPage : UserControlreturn;var loc = AppHost.Get<ILocalizer>();var programs = Filee.Engines.Infrastructure.EngineEnvironment.OwnCopyPrograms[package.Package.Id];- var files = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions+ string? path;+ if (OperatingSystem.IsMacOS() && package.Package.Id is "libreoffice" or "calibre"){- Title = loc.Format("engines.use_own_title", package.Name),- AllowMultiple = false,- FileTypeFilter = [new FilePickerFileType(programs[0]) { Patterns = [programs[0]] }, FilePickerFileTypes.All],- });- if (files.FirstOrDefault()?.TryGetLocalPath() is not { } path)+ var folders = await window.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions+ {+ Title = loc.Format("engines.use_own_app_folder", package.Name),+ AllowMultiple = false,+ });+ path = folders.FirstOrDefault()?.TryGetLocalPath();+ }+ else+ {+ var files = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions+ {+ Title = loc.Format("engines.use_own_title", package.Name),+ AllowMultiple = false,+ FileTypeFilter = [new FilePickerFileType(programs[0]) { Patterns = [programs[0]] }, FilePickerFileTypes.All],+ });+ path = files.FirstOrDefault()?.TryGetLocalPath();+ }+ if (path is null)return;if (!vm.UseOwnCopy(package, path))await AppHost.Get<WindowService>().MessageAsync(window, loc.Format("engines.use_own_missing", string.Join(", ", programs)));diff --git a/src/Filee.App/Views/Pages/GeneralPage.axaml b/src/Filee.App/Views/Pages/GeneralPage.axamlindex 737dfa4b..6317b9a0 100644--- a/src/Filee.App/Views/Pages/GeneralPage.axaml+++ b/src/Filee.App/Views/Pages/GeneralPage.axaml@@ -13,7 +13,9 @@<ComboBox ItemsSource="{Binding Languages}" SelectedItem="{Binding Language}" MinWidth="240" /></StackPanel><ToggleSwitch Content="{DynamicResource general.start_with_system}" IsChecked="{Binding StartWithSystem}" />- <ToggleSwitch Content="{DynamicResource general.context_menu}" IsChecked="{Binding ContextMenu}" IsVisible="{Binding IsWindows}" />+ <ToggleSwitch Content="{Binding ContextMenuText}" IsChecked="{Binding ContextMenu}" IsVisible="{Binding HasSystemIntegration}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding IntegrationMessage}"+ IsVisible="{Binding IntegrationMessage, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" /><!-- Windows 11: optional top-level entry (needs one administrator prompt), see ExplorerMenuRegistration. --><StackPanel Spacing="8" IsVisible="{Binding ShowModernMenu}"><TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding ModernMenuStatus}" />diff --git a/src/Filee.App/Views/Pages/TriggersPage.axaml b/src/Filee.App/Views/Pages/TriggersPage.axamlindex feb93161..70001b8e 100644--- a/src/Filee.App/Views/Pages/TriggersPage.axaml+++ b/src/Filee.App/Views/Pages/TriggersPage.axaml@@ -17,6 +17,19 @@</StackPanel></DockPanel>+ <StackPanel Spacing="8">+ <TextBlock Classes="muted" TextWrapping="Wrap" Text="{Binding PlatformNotice}"+ IsVisible="{Binding PlatformNotice, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding HookStatus}" />+ <TextBlock Classes="caption" Foreground="{DynamicResource WarningBrush}" TextWrapping="Wrap" Text="{Binding IntegrationError}"+ IsVisible="{Binding IntegrationError, Converter={x:Static StringConverters.IsNotNullOrEmpty}}" />+ <WrapPanel>+ <Button Content="{DynamicResource triggers.open_accessibility}" Command="{Binding OpenAccessibilityCommand}"+ IsVisible="{Binding IsMacOS}" Margin="0,0,8,0" />+ <Button Content="{DynamicResource triggers.retry_hook}" Command="{Binding RetryHookCommand}" IsVisible="{Binding CanRetryHook}" />+ </WrapPanel>+ </StackPanel>+<ItemsControl ItemsSource="{Binding Gestures}"><ItemsControl.ItemsPanel><ItemsPanelTemplate>diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.csindex 58543c97..45727f35 100644--- a/src/Filee.Cli/Cli.cs+++ b/src/Filee.Cli/Cli.cs@@ -6,6 +6,7 @@ using System.Text.Json;using Filee.Core.Conversion;using Filee.Core.Formats;using Filee.Core.Localization;+using Filee.Core.Platform;using Filee.Core.Presets;using Filee.Core.Watching;@@ -281,7 +282,7 @@ internal static class Clielsemissing.Add(input);}- return files.Select(Path.GetFullPath).Distinct(StringComparer.OrdinalIgnoreCase).ToList();+ return files.Select(Path.GetFullPath).Distinct(FileSystemPaths.Comparer).ToList();}private static int ListFormats(CliOptions options, CliHost host, TextWriter output, TextWriter errors)diff --git a/src/Filee.Core/Platform/FileSystemPaths.cs b/src/Filee.Core/Platform/FileSystemPaths.csnew file mode 100644index 00000000..93ef4e94--- /dev/null+++ b/src/Filee.Core/Platform/FileSystemPaths.cs@@ -0,0 +1,11 @@+namespace Filee.Core.Platform;++public static class FileSystemPaths+{+ // Unix volumes can be case-sensitive, including APFS formatted with that option.+ public static StringComparer Comparer { get; } = OperatingSystem.IsWindows()+ ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;++ public static StringComparison Comparison { get; } = OperatingSystem.IsWindows()+ ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;+}diff --git a/src/Filee.Core/Platform/IPlatformServices.cs b/src/Filee.Core/Platform/IPlatformServices.csindex c68b5311..21bd05ff 100644--- a/src/Filee.Core/Platform/IPlatformServices.cs+++ b/src/Filee.Core/Platform/IPlatformServices.cs@@ -1,12 +1,12 @@-// OS integration points. Windows implementation: Filee.Platform.Windows. macOS: planned.-// Code that needs the OS goes through this interface so the rest of the app stays portable.-namespace Filee.Core.Platform;/// <summary>Operating-system specific services.</summary>public interface IPlatformServices{- /// <summary>True if the window under the given screen point (physical pixels) belongs to the file manager or desktop.</summary>+ bool SupportsGlobalPointerGestures => true;+ bool SupportsSelectionShortcut => true;++ /// <summary>True if the window at the screen point belongs to the file manager or desktop. Coordinates are pixels on Windows/Linux and desktop points on macOS.</summary>bool IsFileManagerAt(int x, int y);/// <summary>Process name (without extension) owning the window under the point, or <c>null</c>.</summary>@@ -15,7 +15,7 @@ public interface IPlatformServices/// <summary>Files currently selected in the foreground file manager window (empty if none).</summary>IReadOnlyList<string> GetFileManagerSelection();- /// <summary>System drag threshold in physical pixels.</summary>+ /// <summary>System drag threshold in the same units as screen coordinates.</summary>int SystemDragThreshold { get; }/// <summary>True if the user asked the OS to reduce animations.</summary>@@ -71,7 +71,9 @@ public sealed record ModernContextMenuResult(bool Succeeded, bool Cancelled = fa/// <summary>Fallback used on platforms without an implementation yet. Everything is a no-op.</summary>public sealed class NullPlatformServices : IPlatformServices{- public bool IsFileManagerAt(int x, int y) => true;+ public bool SupportsGlobalPointerGestures => false;+ public bool SupportsSelectionShortcut => false;+ public bool IsFileManagerAt(int x, int y) => false;public string? ProcessNameAt(int x, int y) => null;public IReadOnlyList<string> GetFileManagerSelection() => [];public int SystemDragThreshold => 4;@@ -91,6 +93,8 @@ public sealed class NullPlatformServices : IPlatformServicesif (target is null)return;var opener = OperatingSystem.IsMacOS() ? "open" : "xdg-open";- System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(opener, $"\"{target}\"") { UseShellExecute = false });+ var start = new System.Diagnostics.ProcessStartInfo(opener) { UseShellExecute = false };+ start.ArgumentList.Add(target);+ System.Diagnostics.Process.Start(start)?.Dispose();}}diff --git a/src/Filee.Core/Presets/OutputPathResolver.cs b/src/Filee.Core/Presets/OutputPathResolver.csindex dc74a49a..6741efdc 100644--- a/src/Filee.Core/Presets/OutputPathResolver.cs+++ b/src/Filee.Core/Presets/OutputPathResolver.cs@@ -84,8 +84,7 @@ public static class OutputPathResolver}private static bool PathsEqual(string a, string b) =>+ // A Unix mount may still be case-insensitive. Prefer a numbered output to risking the source.string.Equals(Path.GetFullPath(a), Path.GetFullPath(b),- OperatingSystem.IsWindows() || OperatingSystem.IsMacOS()- ? StringComparison.OrdinalIgnoreCase- : StringComparison.Ordinal);+ StringComparison.OrdinalIgnoreCase);}diff --git a/src/Filee.Core/Watching/FolderWatcher.cs b/src/Filee.Core/Watching/FolderWatcher.csindex 5d3143b5..6d6c420e 100644--- a/src/Filee.Core/Watching/FolderWatcher.cs+++ b/src/Filee.Core/Watching/FolderWatcher.cs@@ -6,6 +6,7 @@using System.Collections.Concurrent;using Filee.Core.Conversion;using Filee.Core.Formats;+using Filee.Core.Platform;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Logging.Abstractions;@@ -31,8 +32,8 @@ public sealed class FolderWatcher : IAsyncDisposableprivate readonly ILogger _log;private readonly TimeSpan _settleTime;private readonly TimeProvider _time;- private readonly ConcurrentDictionary<string, Candidate> _pending = new(StringComparer.OrdinalIgnoreCase);- private readonly HashSet<string> _handled = new(StringComparer.OrdinalIgnoreCase);+ private readonly ConcurrentDictionary<string, Candidate> _pending = new(FileSystemPaths.Comparer);+ private readonly HashSet<string> _handled = new(FileSystemPaths.Comparer);private readonly SemaphoreSlim _busy = new(1, 1);private readonly CancellationTokenSource _stop = new();private FileSystemWatcher? _watcher;@@ -143,7 +144,7 @@ public sealed class FolderWatcher : IAsyncDisposableif (ready.Count == 0 || _stop.IsCancellationRequested)return 0;- ready.Sort(StringComparer.OrdinalIgnoreCase);+ ready.Sort(FileSystemPaths.Comparer);_log.LogInformation("Watch folder {Folder}: converting {Count} file(s)", Rule.Folder, ready.Count);var job = await _convert(ready, _stop.Token);if (job is not null)@@ -242,12 +243,12 @@ public sealed class FolderWatcher : IAsyncDisposableif (string.IsNullOrWhiteSpace(folder))return false;var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)) + Path.DirectorySeparatorChar;- return Path.GetFullPath(path).StartsWith(root, StringComparison.OrdinalIgnoreCase);+ return Path.GetFullPath(path).StartsWith(root, FileSystemPaths.Comparison);}private static bool SameFolder(string? a, string b) =>a is not null && string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)),- Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), StringComparison.OrdinalIgnoreCase);+ Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), FileSystemPaths.Comparison);public async ValueTask DisposeAsync(){diff --git a/src/Filee.Engines/Ebooks/CalibreConverter.cs b/src/Filee.Engines/Ebooks/CalibreConverter.csindex 2afb5e94..7e204609 100644--- a/src/Filee.Engines/Ebooks/CalibreConverter.cs+++ b/src/Filee.Engines/Ebooks/CalibreConverter.cs@@ -108,7 +108,5 @@ public sealed partial class CalibreConverter : IConverter?? EngineEnvironment.SystemProgram("calibre", "ebook-convert.exe");private static string? LocateBundled() =>- OperatingSystem.IsWindows() && EngineEnvironment.FindBundled("calibre") is { } folder- ? EngineEnvironment.FirstExisting(Path.Combine(folder, "ebook-convert.exe"))- : null;+ EngineEnvironment.BundledProgram("calibre", "ebook-convert.exe");}diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csprojindex 16dd1af1..9dea9c5f 100644--- a/src/Filee.Engines/Filee.Engines.csproj+++ b/src/Filee.Engines/Filee.Engines.csproj@@ -19,6 +19,8 @@<PackageReference Include="Markdig" /><PackageReference Include="ExcelNumberFormat" /><PackageReference Include="Svg.Skia" />+ <PackageReference Include="SkiaSharp" />+ <PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" /><PackageReference Include="SharpCompress" /><PackageReference Include="ExcelDataReader" /><PackageReference Include="PdfPig" />diff --git a/src/Filee.Engines/Infrastructure/CopyVersions.cs b/src/Filee.Engines/Infrastructure/CopyVersions.csindex 0b211c60..dc4e6610 100644--- a/src/Filee.Engines/Infrastructure/CopyVersions.cs+++ b/src/Filee.Engines/Infrastructure/CopyVersions.cs@@ -23,7 +23,7 @@ public static partial class CopyVersions{var program = id switch{- "libreoffice" => Path.Combine(folder, "version.ini"),+ "libreoffice" when OperatingSystem.IsWindows() => Path.Combine(folder, "version.ini"),_ when EngineEnvironment.OwnCopyPrograms.TryGetValue(id, out var programs) => Path.Combine(folder, programs[0]),_ => null,};@@ -58,7 +58,7 @@ public static partial class CopyVersionsprivate static string Read(string id, string program){- if (id == "libreoffice")+ if (id == "libreoffice" && OperatingSystem.IsWindows())return File.ReadAllText(program);var arguments = id == "ffmpeg" ? "-hide_banner -version" : "--version";try@@ -96,7 +96,7 @@ public static partial class CopyVersions[GeneratedRegex(@"calibre (\d+)\.(\d+)")]private static partial Regex CalibreVersion();- [GeneratedRegex(@"MsiProductVersion=(\d+)\.(\d+)")]+ [GeneratedRegex(@"(?:MsiProductVersion=|LibreOffice\s+)(\d+)\.(\d+)")]private static partial Regex LibreOfficeVersion();[GeneratedRegex(@"^\s*(\d+)\.(\d+)", RegexOptions.Multiline)]diff --git a/src/Filee.Engines/Infrastructure/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.csindex 35bdca91..7dc3916e 100644--- a/src/Filee.Engines/Infrastructure/EngineDownloads.cs+++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs@@ -1,14 +1,14 @@// Engines that are downloaded on demand instead of being bundled with the installer (they are large), and the// pinned download list they come from (engines.json, shared with build/fetch-engines.ps1).+using System.Runtime.InteropServices;using System.Text.Json;namespace Filee.Engines.Infrastructure;/// <summary>One download from engines.json.</summary>/// <param name="Kind">-/// "zip" (extracted), "msi" (administrative install, no system changes; LibreOffice, calibre), "oxt" (LibreOffice-/// extension) or "conda" (conda-forge package: its Windows binaries are extracted).+/// Archive format: zip, tar.gz, tar.xz, dmg, msi, oxt or conda./// </param>/// <param name="Size">Download size in bytes.</param>public sealed record EngineComponent(string Id, string Version, string Url, string Sha256, long Size, string Kind);@@ -21,24 +21,51 @@ public sealed record EnginePackage(string Id, IReadOnlyList<string> Components,public static class EngineDownloads{- /// <summary>Every component of engines.json by id.</summary>- public static IReadOnlyDictionary<string, EngineComponent> Components { get; } = Load();+ /// <summary>The operating system and architecture of the running process.</summary>+ public static string RuntimeIdentifier { get; } =+ (OperatingSystem.IsWindows() ? "win" : OperatingSystem.IsMacOS() ? "osx" : OperatingSystem.IsLinux() ? "linux" : "unknown")+ + "-" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant();++ public static IReadOnlyDictionary<string, EngineComponent> Components { get; } = ComponentsForRuntime(RuntimeIdentifier);/// <summary>/// Packages offered in Settings → Engines and on first run. rhwp and 7-Zip are not listed: they are small and bundled./// </summary>public static IReadOnlyList<EnginePackage> Packages { get; } =[- new("libreoffice", ["libreoffice", "h2orestart", "jre"], 1_265_000_000, ["libreoffice"]),+ new("libreoffice", OperatingSystem.IsWindows() ? ["libreoffice", "h2orestart", "jre"] : ["libreoffice"], 1_265_000_000, ["libreoffice"]),new("pandoc", ["pandoc"], 236_000_000, ["pandoc"]),// Ghostscript from conda-forge plus the Microsoft C++ runtime it was built against (copied next to it).- new("ghostscript", ["ghostscript", "vcruntime"], 31_000_000, ["ghostscript"]),+ new("ghostscript", OperatingSystem.IsWindows() ? ["ghostscript", "vcruntime"] : ["ghostscript"], 31_000_000, ["ghostscript"]),new("ffmpeg", ["ffmpeg"], 272_000_000, ["ffmpeg"]),new("calibre", ["calibre"], 663_000_000, ["calibre"]),];/// <summary>Total download size of a package in bytes.</summary>- public static long DownloadSize(EnginePackage package) => package.Components.Sum(c => Components[c].Size);+ public static long DownloadSize(EnginePackage package) => package.Components.Sum(c => Components.GetValueOrDefault(c)?.Size ?? 0);++ public static bool CanDownload(EnginePackage package) => package.Components.Count > 0 && package.Components.All(Components.ContainsKey);++ public static string? UnavailableReason(EnginePackage package)+ {+ if (CanDownload(package))+ return null;+ if (OperatingSystem.IsMacOS())+ return package.Id switch+ {+ "ffmpeg" => "Install FFmpeg with Homebrew (brew install ffmpeg), then check again or select its bin folder.",+ "ghostscript" => "Install Ghostscript with Homebrew (brew install ghostscript), then check again or select its bin folder.",+ _ => $"No Filee download is available for {RuntimeIdentifier}. Install {package.Id} for this Mac and select its program or .app folder.",+ };+ if (OperatingSystem.IsLinux())+ return package.Id switch+ {+ "libreoffice" => "Install LibreOffice using your distribution's package manager (Ubuntu/Debian: sudo apt install libreoffice), then check again. HWP import through LibreOffice also needs Java and the H2Orestart extension.",+ "ghostscript" => "Install Ghostscript using your distribution's package manager (Ubuntu/Debian: sudo apt install ghostscript), then check again.",+ _ => $"No Filee download is available for {RuntimeIdentifier}. Install {package.Id} using your distribution's package manager and select its program folder.",+ };+ return $"No Filee download is available for {RuntimeIdentifier}. Select a compatible installed copy.";+ }/// <summary>Packages whose download is smaller than this (bytes) are suggested, see <see cref="IsSuggested"/>.</summary>public const long SuggestLimit = 60_000_000;@@ -49,14 +76,22 @@ public static class EngineDownloads/// audio, calibre (~230 MB) only for rare e-book formats and Kindle output. Ghostscript is small but only needed for/// EPS / PostScript./// </summary>- public static bool IsSuggested(EnginePackage package) => DownloadSize(package) < SuggestLimit && package.Id != "ghostscript";+ public static bool IsSuggested(EnginePackage package) => CanDownload(package) && DownloadSize(package) < SuggestLimit && package.Id != "ghostscript";- private static Dictionary<string, EngineComponent> Load()+ public static IReadOnlyDictionary<string, EngineComponent> ComponentsForRuntime(string runtimeIdentifier){using var stream = typeof(EngineDownloads).Assembly.GetManifestResourceStream("Filee.Engines.engines.json")?? throw new InvalidOperationException("Embedded engines.json is missing.");using var json = JsonDocument.Parse(stream);- return json.RootElement.GetProperty("components").EnumerateObject().ToDictionary(+ JsonElement components;+ if (runtimeIdentifier == "win-x64")+ components = json.RootElement.GetProperty("components");+ else if (json.RootElement.TryGetProperty("platforms", out var platforms)+ && platforms.TryGetProperty(runtimeIdentifier, out var platform))+ components = platform.GetProperty("components");+ else+ return new Dictionary<string, EngineComponent>();+ return components.EnumerateObject().ToDictionary(p => p.Name,p => new EngineComponent(p.Name,diff --git a/src/Filee.Engines/Infrastructure/EngineEnvironment.cs b/src/Filee.Engines/Infrastructure/EngineEnvironment.csindex 1ed4ada6..4a33e4fb 100644--- a/src/Filee.Engines/Infrastructure/EngineEnvironment.cs+++ b/src/Filee.Engines/Infrastructure/EngineEnvironment.cs@@ -54,43 +54,62 @@ public sealed class EngineEnvironment(string dataDirectory)/// </summary>public static IReadOnlyDictionary<string, string> OwnCopies { get; set; } = new Dictionary<string, string>();- /// <summary>Programs that must be in the folder of an own copy, per package (Windows names).</summary>- public static IReadOnlyDictionary<string, string[]> OwnCopyPrograms { get; } = new Dictionary<string, string[]>+ /// <summary>Programs required by each engine package on the current operating system.</summary>+ public static IReadOnlyDictionary<string, string[]> OwnCopyPrograms { get; } = Programs(OperatingSystem.IsWindows());++ private static IReadOnlyDictionary<string, string[]> Programs(bool windows) => new Dictionary<string, string[]>{- ["libreoffice"] = ["soffice.exe"],- ["pandoc"] = ["pandoc.exe"],- ["ghostscript"] = ["gswin64c.exe"],- ["ffmpeg"] = ["ffmpeg.exe", "ffprobe.exe"],- ["calibre"] = ["ebook-convert.exe"],+ ["libreoffice"] = [windows ? "soffice.exe" : "soffice"],+ ["pandoc"] = [windows ? "pandoc.exe" : "pandoc"],+ ["ghostscript"] = [windows ? "gswin64c.exe" : "gs"],+ ["ffmpeg"] = windows ? ["ffmpeg.exe", "ffprobe.exe"] : ["ffmpeg", "ffprobe"],+ ["calibre"] = [windows ? "ebook-convert.exe" : "ebook-convert"],+ ["rhwp"] = [windows ? "rhwp.exe" : "rhwp"],+ ["7zip"] = [windows ? "7z.exe" : "7zz"],};+ public static string ProgramName(string name) => OperatingSystem.IsWindows() ? name+ : name == "gswin64c.exe" ? "gs" : name.EndsWith(".exe", StringComparison.Ordinal) ? name[..^4] : name;+/// <summary>The folder of the user's own copy of package <paramref name="id"/>, when it has every program.</summary>public static string? OwnCopyFolder(string id) =>OwnCopies.TryGetValue(id, out var path) ? FolderWithPrograms(id, path) : null;/// <summary>A program of the user's own copy of package <paramref name="id"/>, or null.</summary>public static string? OwnProgram(string id, string program) =>- OwnCopyFolder(id) is { } folder ? Path.Combine(folder, program) : null;+ OwnCopyFolder(id) is { } folder ? Path.Combine(folder, ProgramName(program)) : null;++ public static string? BundledProgram(string id, string program) =>+ FindBundled(id) is { } root && FolderWithPrograms(id, root) is { } folder+ ? Path.Combine(folder, ProgramName(program)) : null;/// <summary>/// The folder with all programs of package <paramref name="id"/>, given a program the user picked or a folder:/// that folder itself, or its bin\ or program\ sub folder (FFmpeg builds, LibreOffice). Null when they are missing./// </summary>- public static string? FolderWithPrograms(string id, string path)+ public static string? FolderWithPrograms(string id, string path) =>+ FolderWithPrograms(id, path, OperatingSystem.IsWindows());++ internal static string? FolderWithPrograms(string id, string path, bool windows){- if (!OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(path) || !OwnCopyPrograms.TryGetValue(id, out var programs))+ if (string.IsNullOrWhiteSpace(path) || !Programs(windows).TryGetValue(id, out var programs))return null;var start = File.Exists(path) ? Path.GetDirectoryName(path) : Directory.Exists(path) ? path : null;if (start is null)return null;- foreach (var folder in new[] { start, Path.Combine(start, "bin"), Path.Combine(start, "program") })+ var app = id == "libreoffice" ? "LibreOffice.app" : id == "calibre" ? "calibre.app" : null;+ var candidates = new List<string> { start, Path.Combine(start, "bin"), Path.Combine(start, "program"), Path.Combine(start, "Contents", "MacOS") };+ if (app is not null)+ candidates.Add(Path.Combine(start, app, "Contents", "MacOS"));+ foreach (var folder in candidates)if (programs.All(p => File.Exists(Path.Combine(folder, p))))return folder;return null;}/// <summary>True when package <paramref name="id"/> runs from Filee's own copy (not the user's or the PC's).</summary>- public static bool UsesFileesCopy(string id) => OwnCopyFolder(id) is null && FindBundled(id) is not null;+ public static bool UsesFileesCopy(string id) => OwnCopyFolder(id) is null+ && FindBundled(id) is { } folder && FolderWithPrograms(id, folder) is not null;/// <summary>Searching the PC for engines; tests turn it off so the machine's tools don't change results.</summary>public static bool SearchSystem { get; set; } = true;@@ -104,11 +123,11 @@ public sealed class EngineEnvironment(string dataDirectory)/// <see cref="ForgetSystemCopies"/>./// </summary>public static string? SystemCopyFolder(string id) =>- SearchSystem && OperatingSystem.IsWindows() ? SystemCopies.GetOrAdd(id, FindOnSystem) : null;+ SearchSystem ? SystemCopies.GetOrAdd(id, FindOnSystem) : null;/// <summary>A program of the copy of package <paramref name="id"/> on the PC, or null.</summary>public static string? SystemProgram(string id, string program) =>- SystemCopyFolder(id) is { } folder ? Path.Combine(folder, program) : null;+ SystemCopyFolder(id) is { } folder ? Path.Combine(folder, ProgramName(program)) : null;/// <summary>Searches the PC again (Settings → Engines → Check again, settings changes).</summary>public static void ForgetSystemCopies() => SystemCopies.Clear();@@ -118,14 +137,34 @@ public sealed class EngineEnvironment(string dataDirectory)private static IEnumerable<string> SystemFolders(string id){- var path = string.Join(';',+ var path = OperatingSystem.IsWindows() ? string.Join(Path.PathSeparator,Environment.GetEnvironmentVariable("PATH"),Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User),- Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine));- var folders = path.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)+ Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine))+ : Environment.GetEnvironmentVariable("PATH") ?? "";+ var folders = path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(entry => Environment.ExpandEnvironmentVariables(entry.Trim('"'))).ToList();- foreach (var root in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }+ if (!OperatingSystem.IsWindows())+ {+ folders.AddRange(["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/opt/local/bin"]);+ if (id == "libreoffice")+ {+ folders.AddRange(["/Applications/LibreOffice.app", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Applications", "LibreOffice.app"), "/usr/lib/libreoffice/program", "/usr/lib64/libreoffice/program"]);+ try+ {+ if (Directory.Exists("/opt"))+ folders.AddRange(Directory.EnumerateDirectories("/opt", "libreoffice*")+ .OrderDescending(StringComparer.Ordinal).Select(p => Path.Combine(p, "program")));+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }+ }+ if (id == "calibre")+ folders.AddRange(["/Applications/calibre.app", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Applications", "calibre.app"), "/opt/calibre"]);+ }+ foreach (var root in (OperatingSystem.IsWindows()+ ? new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }+ : []).Select(Environment.GetFolderPath).Where(r => r.Length > 0)){switch (id)@@ -152,11 +191,15 @@ public sealed class EngineEnvironment(string dataDirectory)}}// Never Filee's own folders: those are its own copy, found before.- return folders.Distinct(StringComparer.OrdinalIgnoreCase)- .Where(f => !f.StartsWith(DownloadRoot, StringComparison.OrdinalIgnoreCase)- && !f.StartsWith(AppContext.BaseDirectory, StringComparison.OrdinalIgnoreCase));+ var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;+ return folders.Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal)+ .Where(f => !IsWithin(f, DownloadRoot, comparison) && !IsWithin(f, AppContext.BaseDirectory, comparison));}+ private static bool IsWithin(string path, string root, StringComparison comparison) =>+ string.Equals(Path.TrimEndingDirectorySeparator(path), Path.TrimEndingDirectorySeparator(root), comparison)+ || path.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, comparison);+/// <summary>Returns the first path that exists as a file.</summary>public static string? FirstExisting(params string?[] candidates) =>candidates.FirstOrDefault(c => !string.IsNullOrWhiteSpace(c) && File.Exists(c));diff --git a/src/Filee.Engines/Infrastructure/EngineInstaller.cs b/src/Filee.Engines/Infrastructure/EngineInstaller.csindex 8a177419..b09f6543 100644--- a/src/Filee.Engines/Infrastructure/EngineInstaller.cs+++ b/src/Filee.Engines/Infrastructure/EngineInstaller.cs@@ -15,6 +15,7 @@ using System.IO.Compression;using System.Security.Cryptography;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Logging.Abstractions;+using SharpCompress.Compressors.Xz;using SharpCompress.Compressors.ZStandard;namespace Filee.Engines.Infrastructure;@@ -52,15 +53,19 @@ public sealed class EngineInstaller}/// <summary>True when every component is installed (any version).</summary>- public bool IsInstalled(EnginePackage package) => package.Components.All(c => Marker(c) is not null);+ public bool IsInstalled(EnginePackage package) => package.Components.All(c => _components.ContainsKey(c) && Marker(c) is not null);/// <summary>True when every component is installed in the version engines.json pins.</summary>public bool IsUpToDate(EnginePackage package) =>- package.Components.All(c => string.Equals(Marker(c), _components[c].Sha256, StringComparison.OrdinalIgnoreCase));+ package.Components.All(c => _components.TryGetValue(c, out var component)+ && string.Equals(Marker(c), component.Sha256, StringComparison.OrdinalIgnoreCase));/// <summary>Downloads and unpacks the components that are missing or outdated.</summary>public async Task InstallAsync(EnginePackage package, IProgress<EngineInstallProgress>? progress, CancellationToken cancellationToken){+ if (package.Components.Any(c => !_components.ContainsKey(c)))+ throw new PlatformNotSupportedException(EngineDownloads.UnavailableReason(package)+ ?? $"The {package.Id} package is unavailable on this platform.");var pending = package.Components.Where(c => !string.Equals(Marker(c), _components[c].Sha256, StringComparison.OrdinalIgnoreCase)).Select(c => _components[c])@@ -179,8 +184,19 @@ public sealed class EngineInstaller{case "zip":ZipFile.ExtractToDirectory(file, staging);+ EnsureExecutablePrograms(component.Id, SingleRoot(staging));Replace(component.Id, SingleRoot(staging));break;+ case "tar.gz":+ case "tar.xz":+ await UnpackTarAsync(file, staging, component.Kind, cancellationToken);+ EnsureExecutablePrograms(component.Id, SingleRoot(staging));+ Replace(component.Id, SingleRoot(staging));+ break;+ case "dmg":+ await UnpackDiskImageAsync(component.Id, file, staging, cancellationToken);+ Replace(component.Id, staging);+ break;case "msi":await UnpackMsiAsync(component.Id, file, staging, Path.Combine(Path.GetTempPath(), "filee-msiexec.log"), cancellationToken);Replace(component.Id, MsiProgramFolder(component.Id, staging));@@ -212,6 +228,80 @@ public sealed class EngineInstaller}}+ internal static async Task UnpackTarAsync(string file, string target, string kind, CancellationToken cancellationToken)+ {+ Directory.CreateDirectory(target);+ await using var input = File.OpenRead(file);+ await using Stream content = kind switch+ {+ "tar.gz" => new GZipStream(input, CompressionMode.Decompress),+ "tar.xz" => new XZStream(input),+ _ => throw new NotSupportedException(kind),+ };+ await TarFile.ExtractToDirectoryAsync(content, target, overwriteFiles: false, cancellationToken);+ }++ internal static void EnsureExecutablePrograms(string id, string root)+ {+ var folder = RequiredProgramFolder(id, root, OperatingSystem.IsWindows());+ if (OperatingSystem.IsWindows() || folder is null)+ return;+ foreach (var program in EngineEnvironment.OwnCopyPrograms[id])+ {+ var path = Path.Combine(folder, program);+ File.SetUnixFileMode(path, File.GetUnixFileMode(path)+ | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);+ }+ }++ internal static string? RequiredProgramFolder(string id, string root, bool windows)+ {+ if (!EngineEnvironment.OwnCopyPrograms.ContainsKey(id))+ return null;+ return EngineEnvironment.FolderWithPrograms(id, root, windows)+ ?? throw new InvalidDataException($"The {id} package is missing required executable programs in its expected folders.");+ }++ private async Task UnpackDiskImageAsync(string id, string file, string target, CancellationToken cancellationToken)+ {+ if (!OperatingSystem.IsMacOS())+ throw new PlatformNotSupportedException("Disk image packages can only be installed on macOS.");+ var appName = id switch+ {+ "libreoffice" => "LibreOffice.app",+ "calibre" => "calibre.app",+ _ => throw new NotSupportedException($"No application bundle is specified for {id}."),+ };+ // Keep the mount outside staging so failed unmounts cannot be removed by staging cleanup.+ var mount = Path.Combine(_root, ".mount-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(mount);+ var attached = false;+ try+ {+ var attach = await ProcessRunner.RunAsync("/usr/bin/hdiutil",+ ["attach", "-readonly", "-nobrowse", "-mountpoint", mount, file], TimeSpan.FromMinutes(3), cancellationToken);+ if (attach.ExitCode != 0)+ throw new InvalidOperationException($"Could not open {id} disk image: {attach.StandardError.Trim()}");+ attached = true;+ var app = Path.Combine(mount, appName);+ if (!Directory.Exists(app) || new DirectoryInfo(app).LinkTarget is not null)+ throw new InvalidDataException($"{appName} is missing from the disk image.");+ Directory.CreateDirectory(target);+ var copy = await ProcessRunner.RunAsync("/usr/bin/ditto", [app, Path.Combine(target, appName)],+ TimeSpan.FromMinutes(10), cancellationToken);+ if (copy.ExitCode != 0)+ throw new InvalidOperationException($"Could not copy {appName}: {copy.StandardError.Trim()}");+ }+ finally+ {+ var detach = await ProcessRunner.RunAsync("/usr/bin/hdiutil", ["detach", mount],+ TimeSpan.FromSeconds(30), CancellationToken.None);+ if (detach.ExitCode != 0 && attached)+ throw new IOException($"Could not unmount the engine disk image at {mount}: {detach.StandardError.Trim()}");+ Directory.Delete(mount);+ }+ }+/// <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.@@ -351,6 +441,7 @@ public sealed class EngineInstaller/// <summary>Makes <paramref name="source"/> the engine folder, replacing a previous version.</summary>private void Replace(string id, string source){+ RequiredProgramFolder(id, source, _components[id].Kind is "msi" or "conda" || OperatingSystem.IsWindows());var target = FolderOf(id);if (Directory.Exists(target))Directory.Delete(target, recursive: true);diff --git a/src/Filee.Engines/Infrastructure/engines.json b/src/Filee.Engines/Infrastructure/engines.jsonindex 3dfc93ba..1501176b 100644--- a/src/Filee.Engines/Infrastructure/engines.json+++ b/src/Filee.Engines/Infrastructure/engines.json@@ -71,5 +71,163 @@"size": 226549760,"kind": "msi"}+ },+ "platforms": {+ "linux-x64": {+ "components": {+ "rhwp": {+ "version": "0.8.6",+ "url": "https://github.com/edwardkim/rhwp/releases/download/v0.8.6/rhwp-v0.8.6-linux-x86_64.tar.gz",+ "sha256": "458DE22A6B9B86088DFDCD59552D4E8FAB5362A64578C64761FA28DF9BE45E9A",+ "size": 10092553,+ "kind": "tar.gz"+ },+ "7zip": {+ "version": "26.03",+ "url": "https://github.com/ip7z/7zip/releases/download/26.03/7z2603-linux-x64.tar.xz",+ "sha256": "DC99EFF5008F1AB79BD7084C68513701547A808A89502BF4133683535AB3C695",+ "size": 1575072,+ "kind": "tar.xz"+ },+ "pandoc": {+ "version": "3.12",+ "url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-linux-amd64.tar.gz",+ "sha256": "67D7D011FED8C8543306022B985B9B2499AB9B74818DF91D8727C7E9EBC5BA06",+ "size": 35326100,+ "kind": "tar.gz"+ },+ "ffmpeg": {+ "version": "9.0.2",+ "url": "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-09-30-13-08/ffmpeg-n9.0.2-17-g2a571b6068-linux64-gpl-9.0.tar.xz",+ "sha256": "68EE646831ADAAE2495618346F3BBA94FF207FF83BBD34D643E7004730D66269",+ "size": 151017172,+ "kind": "tar.xz"+ },+ "calibre": {+ "version": "9.15.0",+ "url": "https://github.com/kovidgoyal/calibre/releases/download/v9.15.0/calibre-9.15.0-x86_64.txz",+ "sha256": "3F5301C0AA51E5FB2D5F6DCD04024BA4E86501AB328CE5D9D6760EFCCB887990",+ "size": 194998300,+ "kind": "tar.xz"+ }+ }+ },+ "linux-arm64": {+ "components": {+ "rhwp": {+ "version": "0.8.6",+ "url": "https://github.com/edwardkim/rhwp/releases/download/v0.8.6/rhwp-v0.8.6-linux-aarch64.tar.gz",+ "sha256": "1288AA5609A67574A6B1372397BEF9A8941FDA9AD16B1224342512F915AE016E",+ "size": 9330223,+ "kind": "tar.gz"+ },+ "7zip": {+ "version": "26.03",+ "url": "https://github.com/ip7z/7zip/releases/download/26.03/7z2603-linux-arm64.tar.xz",+ "sha256": "2389BA20E4D8295E8709C20B6263B69BD1EC4972FE38A04AD7A1BADBF595B996",+ "size": 1328620,+ "kind": "tar.xz"+ },+ "pandoc": {+ "version": "3.12",+ "url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-linux-arm64.tar.gz",+ "sha256": "6CEFCF7100E23A99447C26F89D1FF5B253F3407FCEF99A9E27AE06F3ED16CB82",+ "size": 37857559,+ "kind": "tar.gz"+ },+ "ffmpeg": {+ "version": "9.0.2",+ "url": "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-09-30-13-08/ffmpeg-n9.0.2-17-g2a571b6068-linuxarm64-gpl-9.0.tar.xz",+ "sha256": "91AFCD7695D4BBBB9E0057AA10BAAF9875EC4E1A97303F9059EC971336A2AB46",+ "size": 127445692,+ "kind": "tar.xz"+ },+ "calibre": {+ "version": "9.15.0",+ "url": "https://github.com/kovidgoyal/calibre/releases/download/v9.15.0/calibre-9.15.0-arm64.txz",+ "sha256": "15AB887F9D787809BC834CA0EA6408E981B409F0B23046C41C18DE948EB50A38",+ "size": 182488416,+ "kind": "tar.xz"+ }+ }+ },+ "osx-x64": {+ "components": {+ "rhwp": {+ "version": "0.8.6",+ "url": "https://github.com/edwardkim/rhwp/releases/download/v0.8.6/rhwp-v0.8.6-macos-x86_64.tar.gz",+ "sha256": "A9581617E7CCAB75481B9D36069D28C46E30A543A1FB0AA9FF581567A25321B8",+ "size": 9776200,+ "kind": "tar.gz"+ },+ "7zip": {+ "version": "26.03",+ "url": "https://github.com/ip7z/7zip/releases/download/26.03/7z2603-mac.tar.xz",+ "sha256": "5CA87677072C59F5602E5C49BAA27D4694BACD2259B4E507F0094249D4281480",+ "size": 1863192,+ "kind": "tar.xz"+ },+ "pandoc": {+ "version": "3.12",+ "url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-x86_64-macOS.zip",+ "sha256": "18577F9460C3DC5D2651AD3BAB37D513BC2034A5A777FBE18FA0A5ACF2E936EA",+ "size": 26442035,+ "kind": "zip"+ },+ "calibre": {+ "version": "9.15.0",+ "url": "https://github.com/kovidgoyal/calibre/releases/download/v9.15.0/calibre-9.15.0.dmg",+ "sha256": "1B3A7451175B73AE2BAA28FE1BC1C53EE34D65B489881E7EC02C20F9E0FF6019",+ "size": 350293492,+ "kind": "dmg"+ },+ "libreoffice": {+ "version": "26.2.6",+ "url": "https://download.documentfoundation.org/libreoffice/stable/26.2.6/mac/x86_64/LibreOffice_26.2.6_MacOS_x86-64.dmg",+ "sha256": "135B8A95B8133396D54BF8E726DBC0066145EFA0D785963FC3D4592ACBFCFE5B",+ "size": 308308875,+ "kind": "dmg"+ }+ }+ },+ "osx-arm64": {+ "components": {+ "rhwp": {+ "version": "0.8.6",+ "url": "https://github.com/edwardkim/rhwp/releases/download/v0.8.6/rhwp-v0.8.6-macos-aarch64.tar.gz",+ "sha256": "7D8928FAEB03F00C35C8028F0B562F08F3DA22BEF86F750E0D7E0CD19344EAA3",+ "size": 8972945,+ "kind": "tar.gz"+ },+ "7zip": {+ "version": "26.03",+ "url": "https://github.com/ip7z/7zip/releases/download/26.03/7z2603-mac.tar.xz",+ "sha256": "5CA87677072C59F5602E5C49BAA27D4694BACD2259B4E507F0094249D4281480",+ "size": 1863192,+ "kind": "tar.xz"+ },+ "pandoc": {+ "version": "3.12",+ "url": "https://github.com/jgm/pandoc/releases/download/3.12/pandoc-3.12-arm64-macOS.zip",+ "sha256": "F148CA09C9F36594DB527A9FC988AD736290CE428F79594C50208CD1EC58B3C0",+ "size": 42267373,+ "kind": "zip"+ },+ "calibre": {+ "version": "9.15.0",+ "url": "https://github.com/kovidgoyal/calibre/releases/download/v9.15.0/calibre-9.15.0.dmg",+ "sha256": "1B3A7451175B73AE2BAA28FE1BC1C53EE34D65B489881E7EC02C20F9E0FF6019",+ "size": 350293492,+ "kind": "dmg"+ },+ "libreoffice": {+ "version": "26.2.6",+ "url": "https://download.documentfoundation.org/libreoffice/stable/26.2.6/mac/aarch64/LibreOffice_26.2.6_MacOS_aarch64.dmg",+ "sha256": "94BB3248DF074C225490A8A6D1D9DC87C7D6783DBB7A8E9F0D0C3D94348552AF",+ "size": 297798926,+ "kind": "dmg"+ }+ }+ }}}diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex a9c88925..c8cfa980 100644--- a/src/Filee.Engines/Media/FfmpegConverter.cs+++ b/src/Filee.Engines/Media/FfmpegConverter.cs@@ -126,23 +126,14 @@ public sealed partial class FfmpegConverter : IConverter}}- /// <summary>- /// Filee's own FFmpeg (engines/ffmpeg, downloaded on demand; the programs are in its bin folder), never one- /// found elsewhere on the system.- /// </summary>+ /// <summary>Both tools must come from the same installation.</summary>internal static (string Ffmpeg, string Ffprobe)? Locate(){- // The user's own FFmpeg (Settings → Engines) comes first.- if (EngineEnvironment.OwnCopyFolder("ffmpeg") is { } own)- return (Path.Combine(own, "ffmpeg.exe"), Path.Combine(own, "ffprobe.exe"));- if (EngineEnvironment.FindBundled("ffmpeg") is not { } folder)- return EngineEnvironment.SystemCopyFolder("ffmpeg") is { } system- ? (Path.Combine(system, "ffmpeg.exe"), Path.Combine(system, "ffprobe.exe"))- : null;- var suffix = OperatingSystem.IsWindows() ? ".exe" : "";- var ffmpeg = EngineEnvironment.FirstExisting(Path.Combine(folder, "bin", "ffmpeg" + suffix), Path.Combine(folder, "ffmpeg" + suffix));- var ffprobe = EngineEnvironment.FirstExisting(Path.Combine(folder, "bin", "ffprobe" + suffix), Path.Combine(folder, "ffprobe" + suffix));- return ffmpeg is null || ffprobe is null ? null : (ffmpeg, ffprobe);+ var folder = EngineEnvironment.OwnCopyFolder("ffmpeg")+ ?? (EngineEnvironment.FindBundled("ffmpeg") is { } bundled ? EngineEnvironment.FolderWithPrograms("ffmpeg", bundled) : null)+ ?? EngineEnvironment.SystemCopyFolder("ffmpeg");+ return folder is null ? null : (Path.Combine(folder, EngineEnvironment.ProgramName("ffmpeg.exe")),+ Path.Combine(folder, EngineEnvironment.ProgramName("ffprobe.exe")));}/// <summary>"9.0.2" from <c>ffmpeg -version</c>; cached per executable so re-checking the engines stays cheap.</summary>diff --git a/src/Filee.Engines/Office/LibreOfficeConverter.cs b/src/Filee.Engines/Office/LibreOfficeConverter.csindex 581bf282..fc65860c 100644--- a/src/Filee.Engines/Office/LibreOfficeConverter.cs+++ b/src/Filee.Engines/Office/LibreOfficeConverter.cs@@ -1,7 +1,7 @@// Office documents via LibreOffice in headless mode (MPL-2.0): the optional fallback for formats the built-in engines// don't handle (DOC, XLS, PPT, OpenDocument, ...) and the only reader of rarer ones: Works / WPS, WordPerfect, Lotus// Word Pro, AbiWord, Apple Pages / Numbers / Keynote, StarOffice, WPS Office, Publisher, CorelDRAW, Visio, CGM.-// Filee downloads its own copy on request (engines/libreoffice); a LibreOffice installed on the system is never used.+// Uses a selected installation, Filee's downloaded copy, or the system installation.//// Gotchas handled here:// * Each concurrent soffice process needs its own user profile (-env:UserInstallation), otherwise@@ -42,7 +42,7 @@ public sealed class LibreOfficeConverter : IConverter/// <summary>CGM opens in Impress but is a drawing: exported like one (PDF, ODG, SVG, PNG).</summary>private static readonly string[] ImpressGraphics = ["cgm"];- private static readonly string[] Draw = ["pub", "cdr", "vsd", "odg"];+ private static readonly string[] Draw = ["pub", "cdr", "vsd", "odg", "emf", "wmf"];private readonly EngineEnvironment _env;@@ -187,7 +187,11 @@ public sealed class LibreOfficeConverter : IConverter};// The HWP import filter (H2Orestart) is written in Java: point LibreOffice at the bundled JRE.if (EngineEnvironment.FindBundled("jre") is { } jre)+ {+ if (Directory.Exists(Path.Combine(jre, "Contents", "Home")))+ jre = Path.Combine(jre, "Contents", "Home");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);}@@ -271,10 +275,8 @@ public sealed class LibreOfficeConverter : IConverter/// </summary>private void Locate(){- var bundled = EngineEnvironment.FindBundled("libreoffice");- _soffice = EngineEnvironment.OwnProgram("libreoffice", "soffice.exe") ?? (bundled is null ? null : EngineEnvironment.FirstExisting(- Path.Combine(bundled, "program", OperatingSystem.IsWindows() ? "soffice.exe" : "soffice"),- Path.Combine(bundled, "Contents", "MacOS", "soffice")))+ _soffice = EngineEnvironment.OwnProgram("libreoffice", "soffice.exe")+ ?? EngineEnvironment.BundledProgram("libreoffice", "soffice.exe")?? EngineEnvironment.SystemProgram("libreoffice", "soffice.exe");_hasHwpFilter = _soffice is not null && HasH2Orestart(_soffice);}@@ -284,6 +286,7 @@ public sealed class LibreOfficeConverter : IConverter{try{+ soffice = File.ResolveLinkTarget(soffice, returnFinalTarget: true)?.FullName ?? soffice;var root = Directory.GetParent(Path.GetDirectoryName(soffice)!)!.FullName;foreach (var sub in new[] { "share/uno_packages", "share/extensions", "Resources/uno_packages", "Resources/extensions" }){diff --git a/src/Filee.Engines/Office/PandocConverter.cs b/src/Filee.Engines/Office/PandocConverter.csindex cc191eea..61c8cf64 100644--- a/src/Filee.Engines/Office/PandocConverter.cs+++ b/src/Filee.Engines/Office/PandocConverter.cs@@ -93,12 +93,10 @@ public sealed class PandocConverter : IConverterreturn [output];}- /// <summary>Filee's own pandoc (engines/pandoc, downloaded on demand), never one found elsewhere on the system.</summary>+ /// <summary>Uses the selected copy, a bundled copy, then the system installation.</summary>internal static string? Locate() =>EngineEnvironment.OwnProgram("pandoc", "pandoc.exe") ?? LocateBundled() ?? EngineEnvironment.SystemProgram("pandoc", "pandoc.exe");private static string? LocateBundled() =>- EngineEnvironment.FindBundled("pandoc") is { } bundled- ? EngineEnvironment.FirstExisting(Path.Combine(bundled, OperatingSystem.IsWindows() ? "pandoc.exe" : "pandoc"))- : null;+ EngineEnvironment.BundledProgram("pandoc", "pandoc.exe");}diff --git a/src/Filee.Engines/Vector/GhostscriptConverter.cs b/src/Filee.Engines/Vector/GhostscriptConverter.csindex fd936109..4ec4f1fa 100644--- a/src/Filee.Engines/Vector/GhostscriptConverter.cs+++ b/src/Filee.Engines/Vector/GhostscriptConverter.cs@@ -65,9 +65,7 @@ public sealed class GhostscriptConverter : IConverter?? EngineEnvironment.SystemProgram("ghostscript", "gswin64c.exe");private static string? LocateBundled() =>- EngineEnvironment.FindBundled("ghostscript") is { } folder- ? EngineEnvironment.FirstExisting(Path.Combine(folder, OperatingSystem.IsWindows() ? "gswin64c.exe" : "gs"))- : null;+ EngineEnvironment.BundledProgram("ghostscript", "gswin64c.exe");/// <summary>/// Converts PostScript (PS, EPS, PostScript-based Illustrator files) to PDF. EPS pages are cropped to thediff --git a/src/Filee.Platform.Linux/Filee.Platform.Linux.csproj b/src/Filee.Platform.Linux/Filee.Platform.Linux.csprojnew file mode 100644index 00000000..4c528cfa--- /dev/null+++ b/src/Filee.Platform.Linux/Filee.Platform.Linux.csproj@@ -0,0 +1,9 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Filee.Platform.Linux</RootNamespace>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />+ <InternalsVisibleTo Include="Filee.Platform.Tests" />+ </ItemGroup>+</Project>diff --git a/src/Filee.Platform.Linux/LinuxDesktopIntegration.cs b/src/Filee.Platform.Linux/LinuxDesktopIntegration.csnew file mode 100644index 00000000..73e555c4--- /dev/null+++ b/src/Filee.Platform.Linux/LinuxDesktopIntegration.cs@@ -0,0 +1,226 @@+using System.Text;+using System.Text.RegularExpressions;+using System.Xml.Linq;+using Filee.Core.Settings;++namespace Filee.Platform.Linux;++internal sealed class LinuxDesktopIntegration(string configHome, string dataHome)+{+ internal const string ThunarActionId = "filee-convert";+ internal const string ThunarAcceleratorPath = "<Actions>/ThunarActions/uca-action-" + ThunarActionId;++ internal static string? ToThunarAccelerator(TriggerGesture gesture)+ {+ if (!gesture.Enabled || gesture.Kind != TriggerKind.KeyChord || string.IsNullOrEmpty(gesture.Key))+ return null;+ var key = gesture.Key switch+ {+ "Space" => "space",+ "Enter" => "Return",+ "Backspace" => "BackSpace",+ "PageUp" => "Page_Up",+ "PageDown" => "Page_Down",+ "Semicolon" => "semicolon",+ "Equals" => "equal",+ "Comma" => "comma",+ "Minus" => "minus",+ "Period" => "period",+ "Slash" => "slash",+ "BackQuote" => "grave",+ "OpenBracket" => "bracketleft",+ "Backslash" or "BackSlash" => "backslash",+ "CloseBracket" => "bracketright",+ "Quote" => "apostrophe",+ "PrintScreen" => "Print",+ "Pause" => "Pause",+ "Tab" or "Escape" or "Delete" or "Insert" or "Home" or "End" or "Left" or "Right" or "Up" or "Down" => gesture.Key,+ { Length: 1 } single when char.IsAsciiLetterOrDigit(single[0]) => single.ToLowerInvariant(),+ { Length: 7 } numberPad when numberPad.StartsWith("NumPad", StringComparison.Ordinal) && char.IsAsciiDigit(numberPad[6]) => "KP_" + numberPad[6],+ var function when function.StartsWith('F') && int.TryParse(function.AsSpan(1), out var number) && number is >= 1 and <= 24 => function,+ _ => throw new NotSupportedException($"The key '{gesture.Key}' has no Thunar shortcut mapping."),+ };+ return (gesture.Modifiers.HasFlag(ModifierKeys.Ctrl) ? "<Control>" : "")+ + (gesture.Modifiers.HasFlag(ModifierKeys.Alt) ? "<Alt>" : "")+ + (gesture.Modifiers.HasFlag(ModifierKeys.Shift) ? "<Shift>" : "")+ + (gesture.Modifiers.HasFlag(ModifierKeys.Meta) ? "<Super>" : "") + key;+ }++ public bool SetThunarShortcut(string? accelerator)+ {+ var path = Path.Combine(configHome, "Thunar", "accels.scm");+ var contents = File.Exists(path) ? File.ReadAllText(path) : "";+ var updated = UpdateThunarShortcut(contents, accelerator);+ if (contents == updated)+ return false;+ Write(path, updated);+ return true;+ }++ internal static string UpdateThunarShortcut(string contents, string? accelerator)+ {+ if (accelerator is not null && !Regex.IsMatch(accelerator,+ @"\A(?:<(?:Control|Primary|Alt|Shift|Super|Meta)>)*[A-Za-z0-9_]+\z", RegexOptions.CultureInvariant))+ throw new ArgumentException("Use a GTK shortcut such as <Control><Alt>space.", nameof(accelerator));+ var bindingPattern = @"(?m)^[ \t]*(?<disabled>;[ \t]*)?\(gtk_accel_path ""(?<path>[^""\r\n]+)"" ""(?<key>[^""\r\n]*)""\)[ \t]*\r?$";+ foreach (Match match in Regex.Matches(contents, bindingPattern, RegexOptions.CultureInvariant))+ {+ if (accelerator is not null && !match.Groups["disabled"].Success+ && match.Groups["path"].Value != ThunarAcceleratorPath+ && string.Equals(NormalizeAccelerator(match.Groups["key"].Value), NormalizeAccelerator(accelerator), StringComparison.Ordinal))+ throw new InvalidOperationException($"Thunar already uses {accelerator} for {match.Groups["path"].Value}.");+ }+ var ownPattern = @"(?m)^[ \t]*;?[ \t]*\(gtk_accel_path """ + Regex.Escape(ThunarAcceleratorPath)+ + @""" ""[^""\r\n]*""\)[ \t]*(?:\r?\n|$)";+ var updated = Regex.Replace(contents, ownPattern, "", RegexOptions.CultureInvariant);+ if (accelerator is not null)+ {+ if (updated.Length > 0 && !updated.EndsWith('\n'))+ updated += "\n";+ updated += $"(gtk_accel_path \"{ThunarAcceleratorPath}\" \"{accelerator}\")\n";+ }+ return updated;+ }++ private static string NormalizeAccelerator(string value)+ {+ var pieces = value.Replace("<Primary>", "<Control>", StringComparison.OrdinalIgnoreCase).ToLowerInvariant().Split('>');+ return string.Join('>', pieces[..^1].Order(StringComparer.Ordinal)) + ">" + pieces[^1];+ }++ public void SetAutostart(bool enabled, string executablePath)+ {+ var path = Path.Combine(configHome, "autostart", "filee.desktop");+ if (!enabled)+ {+ File.Delete(path);+ return;+ }+ Write(path, $"[Desktop Entry]\nType=Application\nName=Filee\nExec={DesktopArgument(executablePath)} --background\nTerminal=false\nX-GNOME-Autostart-enabled=true\n");+ }++ public void SetContextMenu(bool enabled, string executablePath, string label)+ {+ var thunarPath = Path.Combine(configHome, "Thunar", "uca.xml");+ var menuPaths = new[]+ {+ Path.Combine(dataHome, "Thunar", "sendto", "filee.desktop"),+ Path.Combine(dataHome, "nautilus", "scripts", "Filee"),+ Path.Combine(dataHome, "nemo", "actions", "filee.nemo_action"),+ Path.Combine(dataHome, "kio", "servicemenus", "filee.desktop"),+ };+ var thunar = LoadThunarActions(thunarPath);+ UpdateThunarAction(thunar, enabled, executablePath, label);+ if (!enabled)+ {+ if (File.Exists(thunarPath))+ Write(thunarPath, thunar.ToString());+ foreach (var path in menuPaths)+ File.Delete(path);+ return;+ }++ var command = $"{DesktopArgument(executablePath)} --convert %F";+ var name = DesktopValue(label);+ Write(thunarPath, thunar.ToString());+ Write(menuPaths[0], $"[Desktop Entry]\nType=Application\nName={name}\nExec={command}\nIcon=document-save-as\nTerminal=false\n");+ Write(menuPaths[1], $"#!/bin/sh\n[ \"$#\" -gt 0 ] || exit 0\nfor file do\n case \"$file\" in\n /*) set -- \"$@\" \"$file\" ;;\n *) set -- \"$@\" \"$PWD/$file\" ;;\n esac\n shift\ndone\nexec {ShellArgument(executablePath)} --convert \"$@\"\n", executable: true);+ Write(menuPaths[2], $"[Nemo Action]\nName={name.Replace("%", "%%", StringComparison.Ordinal)}\nExec={command}\nSelection=notnone\nExtensions=nodirs;\nUriScheme=file\nIcon-Name=document-save-as\n");+ Write(menuPaths[3], $"[Desktop Entry]\nType=Service\nMimeType=application/octet-stream;\nActions=convert;\nX-KDE-Protocols=file\n\n[Desktop Action convert]\nName={name}\nIcon=document-save-as\nExec={command}\n", executable: true);+ }++ internal static void UpdateThunarAction(XDocument document, bool enabled, string executablePath, string label)+ {+ if (document.Root?.Name != "actions")+ throw new InvalidDataException("Thunar's custom actions file has an unexpected root element.");+ document.Root.Elements("action")+ .Where(action => (string?)action.Element("unique-id") == ThunarActionId).Remove();+ if (!enabled)+ return;+ var command = ShellArgument(executablePath).Replace("%", "%%", StringComparison.Ordinal) + " --convert %F";+ document.Root.Add(new XElement("action",+ new XElement("icon", "document-save-as"),+ new XElement("name", label),+ new XElement("unique-id", ThunarActionId),+ new XElement("command", command),+ new XElement("description", label),+ new XElement("patterns", "*"),+ new XElement("audio-files"),+ new XElement("image-files"),+ new XElement("other-files"),+ new XElement("text-files"),+ new XElement("video-files")));+ }++ private static XDocument LoadThunarActions(string path)+ {+ if (File.Exists(path))+ return XDocument.Load(path, LoadOptions.PreserveWhitespace);+ var systemDirectories = (Environment.GetEnvironmentVariable("XDG_CONFIG_DIRS") ?? "/etc/xdg")+ .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries);+ foreach (var directory in systemDirectories.Where(Path.IsPathFullyQualified))+ {+ var defaults = Path.Combine(directory, "Thunar", "uca.xml");+ if (File.Exists(defaults))+ return XDocument.Load(defaults, LoadOptions.PreserveWhitespace);+ }+ return new XDocument(new XElement("actions"));+ }++ internal static string DesktopArgument(string value)+ {+ ValidateCommandValue(value);+ if (value.Contains('='))+ throw new ArgumentException("Desktop launchers do not support '=' in an executable path.", nameof(value));+ var argument = new StringBuilder("\"");+ foreach (var character in value)+ {+ if (character is '"' or '`' or '$' or '\\')+ argument.Append('\\');+ argument.Append(character);+ }+ argument.Append('"');+ return DesktopValue(argument.ToString()).Replace("%", "%%", StringComparison.Ordinal);+ }++ internal static string ShellArgument(string value)+ {+ ValidateCommandValue(value);+ return "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'";+ }++ internal static string DesktopValue(string value) => value+ .Replace("\\", "\\\\", StringComparison.Ordinal)+ .Replace("\r", "\\r", StringComparison.Ordinal)+ .Replace("\n", "\\n", StringComparison.Ordinal)+ .Replace("\t", "\\t", StringComparison.Ordinal);++ private static void ValidateCommandValue(string value)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(value);+ if (value.IndexOfAny(['\0', '\r', '\n']) >= 0)+ throw new ArgumentException("The executable path cannot contain a null character or line break.", nameof(value));+ }++ private static void Write(string path, string contents, bool executable = false)+ {+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";+ try+ {+ File.WriteAllText(temporary, contents.ReplaceLineEndings("\n"), new UTF8Encoding(false));+ if (!OperatingSystem.IsWindows())+ {+ var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead;+ if (executable)+ mode |= UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute;+ File.SetUnixFileMode(temporary, mode);+ }+ File.Move(temporary, path, overwrite: true);+ }+ finally+ {+ File.Delete(temporary);+ }+ }+}diff --git a/src/Filee.Platform.Linux/LinuxPlatformServices.cs b/src/Filee.Platform.Linux/LinuxPlatformServices.csnew file mode 100644index 00000000..7ee2d013--- /dev/null+++ b/src/Filee.Platform.Linux/LinuxPlatformServices.cs@@ -0,0 +1,111 @@+using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.Versioning;+using Filee.Core.Platform;+using Filee.Core.Settings;++namespace Filee.Platform.Linux;++[SupportedOSPlatform("linux")]+public sealed class LinuxPlatformServices : IPlatformServices+{+ private readonly LinuxDesktopIntegration _integration = new(+ XdgDirectory("XDG_CONFIG_HOME", ".config"), XdgDirectory("XDG_DATA_HOME", ".local/share"));++ private static readonly HashSet<string> FileManagers = new(StringComparer.OrdinalIgnoreCase)+ {+ "thunar", "nautilus", "org.gnome.nautilus", "nemo", "dolphin", "caja", "pcmanfm", "pcmanfm-qt", "xfdesktop",+ };++ public static bool IsWaylandSession =>+ string.Equals(Environment.GetEnvironmentVariable("XDG_SESSION_TYPE"), "wayland", StringComparison.OrdinalIgnoreCase)+ || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY"));++ public bool SupportsGlobalPointerGestures => X11WindowSystem.IsAvailable;+ public bool SupportsSelectionShortcut => false;+ public string SelectionShortcutUnavailableReason =>+ "Linux file managers do not expose a shared selected-file API. Use the Filee context action or its Thunar shortcut.";+ public string? GlobalPointerGesturesUnavailableReason => SupportsGlobalPointerGestures ? null : IsWaylandSession+ ? "The cursor-following gesture requires an X11 desktop session. File actions and the drop zone remain available on Wayland."+ : "The cursor-following gesture requires an X11 display.";+ public string ThunarShortcutRestartRequired =>+ "Close Thunar before changing its shortcut, then reopen it to load the Filee action and shortcut.";++ public bool IsFileManagerAt(int x, int y) => ProcessNameAt(x, y) is { } name && FileManagers.Contains(name);+ public string? ProcessNameAt(int x, int y) => X11WindowSystem.ProcessNameAt(x, y);+ public IReadOnlyList<string> GetFileManagerSelection() => throw new NotSupportedException(SelectionShortcutUnavailableReason);+ public int SystemDragThreshold => 8;++ public bool PrefersReducedMotion+ {+ get+ {+ var result = Run("gsettings", ["get", "org.gnome.desktop.interface", "enable-animations"], allowFailure: true);+ return result?.Trim() == "false";+ }+ }++ public void SetStartWithSystem(bool enabled, string executablePath) => _integration.SetAutostart(enabled, executablePath);+ public void SetContextMenu(bool enabled, string executablePath, string label) => _integration.SetContextMenu(enabled, executablePath, label);+ public bool SetThunarShortcut(string? accelerator) => _integration.SetThunarShortcut(accelerator);+ public static string? ToThunarAccelerator(TriggerGesture gesture) => LinuxDesktopIntegration.ToThunarAccelerator(gesture);+ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;+ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>+ Task.FromResult(new ModernContextMenuResult(false, Error: "Use the Linux file manager context action."));++ public void RevealInFileManager(string path)+ {+ var fullPath = Path.GetFullPath(path);+ if (File.Exists(fullPath))+ {+ var uri = new Uri(fullPath).AbsoluteUri;+ var result = Run("gdbus", ["call", "--session", "--dest", "org.freedesktop.FileManager1", "--object-path",+ "/org/freedesktop/FileManager1", "--method", "org.freedesktop.FileManager1.ShowItems",+ "['" + uri.Replace("'", "\\'", StringComparison.Ordinal) + "']", ""], allowFailure: true);+ if (result is not null)+ return;+ }+ var directory = Directory.Exists(fullPath) ? fullPath : Path.GetDirectoryName(fullPath);+ if (directory is null || !Directory.Exists(directory))+ throw new DirectoryNotFoundException($"Cannot find the folder containing '{path}'.");+ var opener = new ProcessStartInfo("xdg-open") { UseShellExecute = false };+ opener.ArgumentList.Add(directory);+ using var process = Process.Start(opener) ?? throw new InvalidOperationException("Could not start xdg-open.");+ }++ public void RaiseTopmost(nint windowHandle) => X11WindowSystem.RaiseTopmost(windowHandle);++ private static string XdgDirectory(string variable, string fallback)+ {+ var configured = Environment.GetEnvironmentVariable(variable);+ return !string.IsNullOrEmpty(configured) && Path.IsPathFullyQualified(configured)+ ? configured+ : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), fallback);+ }++ private static string? Run(string executable, IEnumerable<string> arguments, bool allowFailure = false)+ {+ try+ {+ var info = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };+ foreach (var argument in arguments)+ info.ArgumentList.Add(argument);+ using var process = Process.Start(info) ?? throw new InvalidOperationException($"Could not start {executable}.");+ var output = process.StandardOutput.ReadToEndAsync();+ var error = process.StandardError.ReadToEndAsync();+ if (!process.WaitForExit(3000))+ {+ process.Kill(entireProcessTree: true);+ throw new TimeoutException($"{executable} did not respond within 3 seconds.");+ }+ if (process.ExitCode != 0)+ throw new InvalidOperationException($"{executable}: {error.GetAwaiter().GetResult().Trim()}");+ return output.GetAwaiter().GetResult();+ }+ catch (Exception exception) when (allowFailure && exception is Win32Exception or InvalidOperationException or TimeoutException)+ {+ Trace.TraceInformation($"Optional Linux integration command failed: {exception.Message}");+ return null;+ }+ }+}diff --git a/src/Filee.Platform.Linux/X11WindowSystem.cs b/src/Filee.Platform.Linux/X11WindowSystem.csnew file mode 100644index 00000000..96cfaac3--- /dev/null+++ b/src/Filee.Platform.Linux/X11WindowSystem.cs@@ -0,0 +1,179 @@+using System.ComponentModel;+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Text;++namespace Filee.Platform.Linux;++internal static class X11WindowSystem+{+ private const string Library = "libX11.so.6";++ internal static bool IsAvailable => OperatingSystem.IsLinux()+ && !LinuxPlatformServices.IsWaylandSession+ && !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY"));++ internal static string? ProcessNameAt(int x, int y)+ {+ if (!IsAvailable)+ return null;+ var display = OpenDisplay();+ if (display == 0)+ return null;+ try+ {+ // Keep windows alive between hit testing and reading their properties.+ XGrabServer(display);+ var root = XDefaultRootWindow(display);+ var window = root;+ string? name = null;+ for (var depth = 0; depth < 32; depth++)+ {+ name = ReadProcessName(display, window) ?? name;+ if (XTranslateCoordinates(display, root, window, x, y, out _, out _, out var child) == 0 || child == 0)+ break;+ window = child;+ }+ return name;+ }+ finally+ {+ XUngrabServer(display);+ XCloseDisplay(display);+ }+ }++ internal static void RaiseTopmost(nint window)+ {+ if (window == 0 || !IsAvailable)+ return;+ var display = OpenDisplay();+ if (display == 0)+ return;+ try+ {+ var above = XInternAtom(display, "_NET_WM_STATE_ABOVE", 0);+ SendClientMessage(display, window, "_NET_WM_STATE", 1, (nint)above, 0, 1);+ SendClientMessage(display, window, "_NET_RESTACK_WINDOW", 1, 0, 0, 0);+ XFlush(display);+ }+ finally+ {+ XCloseDisplay(display);+ }+ }++ private static nint OpenDisplay()+ {+ try { return XOpenDisplay(0); }+ catch (DllNotFoundException exception)+ {+ Trace.TraceWarning($"X11 integration is unavailable: {exception.Message}");+ return 0;+ }+ catch (EntryPointNotFoundException exception)+ {+ Trace.TraceWarning($"X11 integration is unavailable: {exception.Message}");+ return 0;+ }+ }++ private static string? ReadProcessName(nint display, nuint window)+ {+ var property = XInternAtom(display, "_NET_WM_PID", 1);+ if (property != 0 && XGetWindowProperty(display, window, property, 0, 1, 0, 0,+ out _, out var format, out var count, out _, out var data) == 0)+ {+ try+ {+ if (format == 32 && count > 0 && data != 0)+ {+ var pid = unchecked((int)Marshal.ReadIntPtr(data));+ try+ {+ using var process = Process.GetProcessById(pid);+ return process.ProcessName;+ }+ catch (ArgumentException) { }+ catch (InvalidOperationException) { }+ catch (Win32Exception) { }+ }+ }+ finally+ {+ if (data != 0)+ XFree(data);+ }+ }+ var windowClass = XInternAtom(display, "WM_CLASS", 1);+ if (windowClass == 0 || XGetWindowProperty(display, window, windowClass, 0, 256, 0, 0,+ out _, out var classFormat, out var classCount, out _, out var classData) != 0)+ return null;+ try+ {+ if (classData == 0 || classFormat != 8 || classCount == 0)+ return null;+ var bytes = new byte[Math.Min((int)classCount, 1024)];+ Marshal.Copy(classData, bytes, 0, bytes.Length);+ return Encoding.UTF8.GetString(bytes).Split('\0', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();+ }+ finally+ {+ if (classData != 0)+ XFree(classData);+ }+ }++ private static void SendClientMessage(nint display, nint window, string message, nint a, nint b, nint c, nint d)+ {+ var clientEvent = new XClientMessageEvent+ {+ Type = 33,+ SendEvent = 1,+ Display = display,+ Window = (nuint)window,+ MessageType = XInternAtom(display, message, 0),+ Format = 32,+ Data0 = a,+ Data1 = b,+ Data2 = c,+ Data3 = d,+ };+ XSendEvent(display, XDefaultRootWindow(display), 0, (1L << 20) | (1L << 19), ref clientEvent);+ }++ // XEvent is a union of 24 native longs on supported 64-bit Linux targets.+ [StructLayout(LayoutKind.Sequential, Size = 192)]+ private struct XClientMessageEvent+ {+ public int Type;+ public nuint Serial;+ public int SendEvent;+ public nint Display;+ public nuint Window;+ public nuint MessageType;+ public int Format;+ public nint Data0;+ public nint Data1;+ public nint Data2;+ public nint Data3;+ public nint Data4;+ }++ [DllImport(Library)] private static extern nint XOpenDisplay(nint displayName);+ [DllImport(Library)] private static extern int XCloseDisplay(nint display);+ [DllImport(Library)] private static extern nuint XDefaultRootWindow(nint display);+ [DllImport(Library)] private static extern int XGrabServer(nint display);+ [DllImport(Library)] private static extern int XUngrabServer(nint display);+ [DllImport(Library)]+ private static extern int XTranslateCoordinates(nint display, nuint source, nuint destination,+ int x, int y, out int destinationX, out int destinationY, out nuint child);+ [DllImport(Library)] private static extern nuint XInternAtom(nint display, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int onlyIfExists);+ [DllImport(Library)]+ private static extern int XGetWindowProperty(nint display, nuint window, nuint property,+ nint offset, nint length, int delete, nuint requestedType, out nuint actualType, out int actualFormat,+ out nuint itemCount, out nuint bytesAfter, out nint propertyData);+ [DllImport(Library)] private static extern int XFree(nint data);+ [DllImport(Library)] private static extern int XSendEvent(nint display, nuint window, int propagate, long mask, ref XClientMessageEvent clientEvent);+ [DllImport(Library)] private static extern int XFlush(nint display);+}diff --git a/src/Filee.Platform.MacOS/Filee.Platform.MacOS.csproj b/src/Filee.Platform.MacOS/Filee.Platform.MacOS.csprojnew file mode 100644index 00000000..5056b1d2--- /dev/null+++ b/src/Filee.Platform.MacOS/Filee.Platform.MacOS.csproj@@ -0,0 +1,9 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <RootNamespace>Filee.Platform.MacOS</RootNamespace>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Filee.Core\Filee.Core.csproj" />+ <InternalsVisibleTo Include="Filee.Platform.Tests" />+ </ItemGroup>+</Project>diff --git a/src/Filee.Platform.MacOS/MacOSIntegrationFiles.cs b/src/Filee.Platform.MacOS/MacOSIntegrationFiles.csnew file mode 100644index 00000000..de5673d0--- /dev/null+++ b/src/Filee.Platform.MacOS/MacOSIntegrationFiles.cs@@ -0,0 +1,89 @@+using System.Xml.Linq;++namespace Filee.Platform.MacOS;++internal static class MacOSIntegrationFiles+{+ internal static string LaunchAgent(string executablePath) => Plist(Dict(+ ("Label", "com.filee.app"),+ ("AssociatedBundleIdentifiers", Array("com.filee.app")),+ ("ProgramArguments", Array(executablePath, "--background")),+ ("LimitLoadToSessionType", "Aqua"),+ ("RunAtLoad", true),+ ("KeepAlive", false)));++ internal static string ServiceInfo(string label) => Plist(Dict(+ ("CFBundleName", label),+ ("CFBundleIdentifier", "com.filee.app.convert-service"),+ ("NSServices", Array(Dict(+ ("NSMenuItem", Dict(("default", label))),+ ("NSMessage", "runWorkflowAsService"),+ ("NSRequiredContext", Dict(("NSApplicationIdentifier", "com.apple.finder"))),+ ("NSSendFileTypes", Array("public.item")))))));++ internal static string Workflow(string executablePath) => Plist(Dict(+ ("AMDocumentVersion", "2"),+ ("actions", Array(Dict(("action", Dict(+ ("AMAccepts", Dict(("Container", "List"), ("Optional", false), ("Types", Array("com.apple.cocoa.path")))),+ ("AMProvides", Dict(("Container", "List"), ("Types", Array("com.apple.cocoa.string")))),+ ("AMApplication", Array("Automator")),+ ("AMActionVersion", "2.0.3"),+ ("AMParameterProperties", Dict(("COMMAND_STRING", Dict()), ("inputMethod", Dict()), ("shell", Dict()), ("source", Dict()))),+ ("ActionBundlePath", "/System/Library/Automator/Run Shell Script.action"),+ ("ActionName", "Run Shell Script"),+ ("ActionParameters", Dict(+ ("COMMAND_STRING", ConversionCommand(executablePath)),+ ("CheckedForUserDefaultShell", true),+ ("inputMethod", 1),+ ("shell", "/bin/sh"),+ ("source", ""))),+ ("BundleIdentifier", "com.apple.RunShellScript"),+ ("Class Name", "RunShellScriptAction"),+ ("CanShowWhenRun", false),+ ("InputUUID", "E79B8709-D276-4DB2-A0D9-07FDF599774E"),+ ("OutputUUID", "09A1D308-CB6C-4EC8-9545-68272C47BA52"),+ ("UUID", "ED186538-5D03-4A64-88BD-52FC9A905E4F"),+ ("arguments", Dict())))))),+ ("connectors", Dict()),+ ("workflowMetaData", Dict(+ ("serviceApplicationBundleID", "com.apple.finder"),+ ("serviceApplicationPath", "/System/Library/CoreServices/Finder.app"),+ ("serviceInputTypeIdentifier", "com.apple.Automator.fileSystemObject"),+ ("serviceOutputTypeIdentifier", "com.apple.Automator.nothing"),+ ("serviceProcessesInput", true),+ ("workflowTypeIdentifier", "com.apple.Automator.servicesMenu")))));++ internal static string ConversionCommand(string executablePath)+ {+ const string contents = "/Contents/MacOS/";+ var index = executablePath.LastIndexOf(contents, StringComparison.Ordinal);+ if (index > 0 && executablePath[..index].EndsWith(".app", StringComparison.OrdinalIgnoreCase))+ {+ // A fresh process forwards arguments to Filee's running instance; open otherwise discards them.+ return $"exec /usr/bin/open -n -a {ShellQuote(executablePath[..index])} --args --convert \"$@\"";+ }+ return $"exec {ShellQuote(executablePath)} --convert \"$@\"";+ }++ private static string ShellQuote(string value) => "'" + value.Replace("'", "'\"'\"'", StringComparison.Ordinal) + "'";++ private static string Plist(XElement dictionary) =>+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ++ new XDocument(+ new XDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null),+ new XElement("plist", new XAttribute("version", "1.0"), dictionary));++ private static XElement Dict(params (string Key, object Value)[] entries) => new("dict",+ entries.SelectMany(entry => new[] { new XElement("key", entry.Key), Value(entry.Value) }));++ private static XElement Array(params object[] values) => new("array", values.Select(Value));++ private static XElement Value(object value) => value switch+ {+ XElement element => element,+ bool flag => new XElement(flag ? "true" : "false"),+ int number => new XElement("integer", number),+ string text => new XElement("string", text),+ _ => throw new ArgumentException("Unsupported property-list value.", nameof(value)),+ };+}diff --git a/src/Filee.Platform.MacOS/MacOSPlatformServices.cs b/src/Filee.Platform.MacOS/MacOSPlatformServices.csnew file mode 100644index 00000000..9b5963ac--- /dev/null+++ b/src/Filee.Platform.MacOS/MacOSPlatformServices.cs@@ -0,0 +1,149 @@+using System.Diagnostics;+using System.Runtime.Versioning;+using System.Text;+using System.Text.Json;+using Filee.Core.Platform;++namespace Filee.Platform.MacOS;++[SupportedOSPlatform("macos")]+public sealed class MacOSPlatformServices : IPlatformServices+{+ private const string FinderSelectionScript = """+ ObjC.import('Foundation');+ const finder = Application('com.apple.finder');+ JSON.stringify(finder.selection().map(item => ObjC.unwrap($.NSURL.URLWithString(item.url()).path)));+ """;++ public bool HasAccessibilityPermission => NativeMethods.AXIsProcessTrusted();++ public bool SupportsGlobalPointerGestures => HasAccessibilityPermission;++ public bool SupportsSelectionShortcut => true;++ public string? LastSelectionError { get; private set; }++ public bool IsFileManagerAt(int x, int y) =>+ string.Equals(ProcessNameAt(x, y), "Finder", StringComparison.OrdinalIgnoreCase);++ public string? ProcessNameAt(int x, int y) => NativeMethods.ProcessNameAt(x, y);++ public IReadOnlyList<string> GetFileManagerSelection()+ {+ LastSelectionError = null;+ if (!NativeMethods.IsFinderFrontmost())+ return [];++ try+ {+ var output = Run("/usr/bin/osascript", ["-l", "JavaScript", "-e", FinderSelectionScript], 30_000);+ return ParseSelection(output).Where(path => File.Exists(path) || Directory.Exists(path)).ToArray();+ }+ catch (Exception ex) when (ex is IOException or TimeoutException or InvalidOperationException or JsonException)+ {+ LastSelectionError = ex.Message;+ Trace.TraceWarning($"Reading Finder selection failed: {ex.Message}");+ throw new InvalidOperationException($"Could not read Finder selection. Allow Filee to control Finder in System Settings > Privacy & Security > Automation. {ex.Message}", ex);+ }+ }++ // AppKit exposes no public system drag-distance preference; match its usual four-point threshold.+ public int SystemDragThreshold => 4;++ public bool PrefersReducedMotion => NativeMethods.PrefersReducedMotion();++ public void SetStartWithSystem(bool enabled, string executablePath)+ {+ var path = Path.Combine(UserLibrary, "LaunchAgents", "com.filee.app.plist");+ if (!enabled)+ {+ File.Delete(path);+ return;+ }++ RequireExecutable(executablePath);+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ File.WriteAllText(path, MacOSIntegrationFiles.LaunchAgent(executablePath), new UTF8Encoding(false));+ }++ public void SetContextMenu(bool enabled, string executablePath, string label)+ {+ var workflow = Path.Combine(UserLibrary, "Services", "Filee.workflow");+ var contents = Path.Combine(workflow, "Contents");+ if (enabled)+ {+ RequireExecutable(executablePath);+ Directory.CreateDirectory(contents);+ File.WriteAllText(Path.Combine(contents, "Info.plist"), MacOSIntegrationFiles.ServiceInfo(label), new UTF8Encoding(false));+ File.WriteAllText(Path.Combine(contents, "document.wflow"), MacOSIntegrationFiles.Workflow(executablePath), new UTF8Encoding(false));+ }+ else if (Directory.Exists(contents))+ {+ File.Delete(Path.Combine(contents, "Info.plist"));+ File.Delete(Path.Combine(contents, "document.wflow"));+ if (!Directory.EnumerateFileSystemEntries(contents).Any())+ Directory.Delete(contents);+ if (!Directory.EnumerateFileSystemEntries(workflow).Any())+ Directory.Delete(workflow);+ }++ Run("/System/Library/CoreServices/pbs", ["-update"], 10_000);+ }++ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;++ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>+ Task.FromResult(new ModernContextMenuResult(false, Error: "The Windows Explorer extension is unavailable on macOS. Use the Finder Quick Action."));++ public void RevealInFileManager(string path)+ {+ var fullPath = Path.GetFullPath(path);+ Run("/usr/bin/open", File.Exists(fullPath) ? ["-R", fullPath] : [fullPath], 10_000);+ }++ public void OpenAccessibilitySettings() =>+ Run("/usr/bin/open", ["x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"], 10_000);++ public void RaiseTopmost(nint windowHandle)+ {+ if (windowHandle != 0)+ NativeMethods.RaiseTopmost(windowHandle);+ }++ internal static IReadOnlyList<string> ParseSelection(string json) =>+ JsonSerializer.Deserialize<string[]>(json) ?? [];++ private static string UserLibrary => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library");++ private static void RequireExecutable(string path)+ {+ if (!Path.IsPathFullyQualified(path) || !File.Exists(path))+ throw new FileNotFoundException("Filee's executable must have an existing absolute path.", path);+ }++ private static string Run(string executable, IReadOnlyList<string> arguments, int timeoutMs)+ {+ var start = new ProcessStartInfo(executable)+ {+ UseShellExecute = false,+ RedirectStandardOutput = true,+ RedirectStandardError = true,+ StandardOutputEncoding = Encoding.UTF8,+ StandardErrorEncoding = Encoding.UTF8,+ };+ foreach (var argument in arguments)+ start.ArgumentList.Add(argument);+ using var process = Process.Start(start) ?? throw new IOException($"Could not start {executable}.");+ var output = process.StandardOutput.ReadToEndAsync();+ var error = process.StandardError.ReadToEndAsync();+ if (!process.WaitForExit(timeoutMs))+ {+ try { process.Kill(entireProcessTree: true); }+ catch (InvalidOperationException) { }+ throw new TimeoutException($"{Path.GetFileName(executable)} did not respond within {timeoutMs / 1000} seconds.");+ }+ if (process.ExitCode != 0)+ throw new IOException($"{Path.GetFileName(executable)} failed ({process.ExitCode}): {error.GetAwaiter().GetResult().Trim()}");+ return output.GetAwaiter().GetResult();+ }+}diff --git a/src/Filee.Platform.MacOS/NativeMethods.cs b/src/Filee.Platform.MacOS/NativeMethods.csnew file mode 100644index 00000000..e5247b31--- /dev/null+++ b/src/Filee.Platform.MacOS/NativeMethods.cs@@ -0,0 +1,158 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;++namespace Filee.Platform.MacOS;++[SupportedOSPlatform("macos")]+internal static class NativeMethods+{+ private const string CoreGraphics = "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics";+ private const string CoreFoundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";+ private const string ApplicationServices = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices";+ private const string ObjC = "/usr/lib/libobjc.A.dylib";+ private static readonly nint AppKit = NativeLibrary.Load("/System/Library/Frameworks/AppKit.framework/AppKit");+ private static readonly nint BoundsKey = CFStringCreateWithCString(0, "kCGWindowBounds", 0x08000100);+ private static readonly nint PidKey = CFStringCreateWithCString(0, "kCGWindowOwnerPID", 0x08000100);+ private static readonly nint AlphaKey = CFStringCreateWithCString(0, "kCGWindowAlpha", 0x08000100);++ internal static string? ProcessNameAt(int x, int y)+ {+ var windows = CGWindowListCopyWindowInfo(1, 0);+ if (windows == 0)+ return null;+ try+ {+ for (nint index = 0; index < CFArrayGetCount(windows); index++)+ {+ var window = CFArrayGetValueAtIndex(windows, index);+ var boundsValue = CFDictionaryGetValue(window, BoundsKey);+ if (boundsValue == 0 || !CGRectMakeWithDictionaryRepresentation(boundsValue, out var bounds))+ continue;+ // Quartz and Avalonia's macOS desktop coordinates use top-left points, including on Retina displays.+ if (x < bounds.X || y < bounds.Y || x >= bounds.X + bounds.Width || y >= bounds.Y + bounds.Height)+ continue;+ var alphaValue = CFDictionaryGetValue(window, AlphaKey);+ if (alphaValue != 0 && CFNumberGetDouble(alphaValue, 6, out var alpha) && alpha <= 0)+ continue;+ var pidValue = CFDictionaryGetValue(window, PidKey);+ if (pidValue == 0 || !CFNumberGetInt(pidValue, 3, out var pid))+ continue;+ try+ {+ using var process = Process.GetProcessById(pid);+ var name = process.ProcessName;+ if (!string.Equals(name, "WindowServer", StringComparison.OrdinalIgnoreCase))+ return name;+ }+ catch (ArgumentException) { }+ catch (InvalidOperationException) { }+ catch (System.ComponentModel.Win32Exception) { }+ }+ return null;+ }+ finally+ {+ CFRelease(windows);+ }+ }++ internal static bool IsFinderFrontmost()+ {+ using var pool = new AutoreleasePool();+ var workspace = Send(objc_getClass("NSWorkspace"), sel_registerName("sharedWorkspace"));+ var application = Send(workspace, sel_registerName("frontmostApplication"));+ var bundle = Send(application, sel_registerName("bundleIdentifier"));+ return Marshal.PtrToStringUTF8(Send(bundle, sel_registerName("UTF8String"))) == "com.apple.finder";+ }++ internal static bool PrefersReducedMotion()+ {+ using var pool = new AutoreleasePool();+ var workspace = Send(objc_getClass("NSWorkspace"), sel_registerName("sharedWorkspace"));+ return SendBool(workspace, sel_registerName("accessibilityDisplayShouldReduceMotion"));+ }++ internal static void RaiseTopmost(nint window)+ {+ const nint canJoinAllSpaces = 1, moveToActiveSpace = 1 << 1;+ const nint fullScreenPrimary = 1 << 7, fullScreenAuxiliary = 1 << 8, fullScreenNone = 1 << 9;+ var behavior = Send(window, sel_registerName("collectionBehavior"));+ behavior = (behavior & ~(moveToActiveSpace | fullScreenPrimary | fullScreenNone)) | canJoinAllSpaces | fullScreenAuxiliary;+ if (OperatingSystem.IsMacOSVersionAtLeast(13))+ {+ const nint primary = 1 << 16, auxiliary = 1 << 17, canJoinAllApplications = 1 << 18;+ behavior = (behavior & ~(primary | auxiliary)) | canJoinAllApplications;+ }+ // Finder can occupy a full-screen Space that would otherwise hide another app's toolbar.+ SendInteger(window, sel_registerName("setCollectionBehavior:"), behavior);+ SendInteger(window, sel_registerName("setLevel:"), 3);+ SendVoid(window, sel_registerName("orderFrontRegardless"));+ }++ private readonly struct AutoreleasePool : IDisposable+ {+ private readonly nint _pool = Send(Send(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")), sel_registerName("init"));+ public AutoreleasePool() { }+ public void Dispose() => SendVoid(_pool, sel_registerName("drain"));+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct CGRect+ {+ public double X, Y, Width, Height;+ }++ [DllImport(ApplicationServices)]+ [return: MarshalAs(UnmanagedType.I1)]+ internal static extern bool AXIsProcessTrusted();++ [DllImport(CoreGraphics)]+ private static extern nint CGWindowListCopyWindowInfo(uint option, uint relativeToWindow);++ [DllImport(CoreGraphics)]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool CGRectMakeWithDictionaryRepresentation(nint dictionary, out CGRect rect);++ [DllImport(CoreFoundation)]+ private static extern void CFRelease(nint value);++ [DllImport(CoreFoundation)]+ private static extern nint CFArrayGetCount(nint array);++ [DllImport(CoreFoundation)]+ private static extern nint CFArrayGetValueAtIndex(nint array, nint index);++ [DllImport(CoreFoundation)]+ private static extern nint CFDictionaryGetValue(nint dictionary, nint key);++ [DllImport(CoreFoundation)]+ private static extern nint CFStringCreateWithCString(nint allocator, [MarshalAs(UnmanagedType.LPUTF8Str)] string value, uint encoding);++ [DllImport(CoreFoundation, EntryPoint = "CFNumberGetValue")]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool CFNumberGetInt(nint number, nint type, out int value);++ [DllImport(CoreFoundation, EntryPoint = "CFNumberGetValue")]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool CFNumberGetDouble(nint number, nint type, out double value);++ [DllImport(ObjC)]+ private static extern nint objc_getClass([MarshalAs(UnmanagedType.LPUTF8Str)] string name);++ [DllImport(ObjC)]+ private static extern nint sel_registerName([MarshalAs(UnmanagedType.LPUTF8Str)] string name);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern nint Send(nint receiver, nint selector);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ [return: MarshalAs(UnmanagedType.I1)]+ private static extern bool SendBool(nint receiver, nint selector);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern void SendVoid(nint receiver, nint selector);++ [DllImport(ObjC, EntryPoint = "objc_msgSend")]+ private static extern void SendInteger(nint receiver, nint selector, nint value);+}diff --git a/tests/Filee.App.Tests/InstallerTests.cs b/tests/Filee.App.Tests/InstallerTests.csindex 591e7e08..b3ca636a 100644--- a/tests/Filee.App.Tests/InstallerTests.cs+++ b/tests/Filee.App.Tests/InstallerTests.cs@@ -50,6 +50,7 @@ public class InstallerTestsAssert.Null(CommandLine.Parse(["--background"]).InstallEngines);Assert.Null(CommandLine.Parse(["--start-with-windows=maybe"]).StartWithWindows);Assert.Null(CommandLine.Parse([]).ContextMenu);+ Assert.True(CommandLine.Parse(["--start-with-system=on"]).StartWithWindows);}[Fact]diff --git a/tests/Filee.App.Tests/SystemIntegrationTests.cs b/tests/Filee.App.Tests/SystemIntegrationTests.csnew file mode 100644index 00000000..6490f63f--- /dev/null+++ b/tests/Filee.App.Tests/SystemIntegrationTests.cs@@ -0,0 +1,94 @@+using Filee.App.Services;+using Filee.Core.Localization;+using Filee.Core.Platform;+using Filee.Core.Settings;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.App.Tests;++public sealed class SystemIntegrationTests+{+ [Fact]+ public void Unrelated_settings_do_not_reregister_the_file_manager()+ {+ var platform = new RecordingPlatform();+ var service = Create(platform);+ var settings = new AppSettings();+ service.Apply(settings);+ settings.Donut.OuterRadius = 170;+ service.Apply(settings);+ Assert.Equal(1, platform.StartupCalls);+ Assert.Equal(1, platform.MenuCalls);+ settings.ContextMenuEnabled = false;+ service.Apply(settings);+ Assert.Equal(1, platform.StartupCalls);+ Assert.Equal(2, platform.MenuCalls);+ }++ [Fact]+ public void Failed_registration_is_reported_and_can_be_retried_without_repeating_successful_work()+ {+ var platform = new RecordingPlatform { FailMenu = true };+ var service = Create(platform);+ var settings = new AppSettings();+ service.Apply(settings);+ Assert.Contains("denied", service.Error);+ platform.FailMenu = false;+ service.Apply(settings);+ Assert.Null(service.Error);+ Assert.Equal(1, platform.StartupCalls);+ Assert.Equal(2, platform.MenuCalls);+ }++ [Fact]+ public void Source_builds_do_not_register_os_integration()+ {+ var platform = new RecordingPlatform();+ var service = new SystemIntegrationService(platform, new Texts(), NullLogger<SystemIntegrationService>.Instance)+ {+ RegistrationEnabled = false,+ };+ service.Apply(new AppSettings());+ Assert.Equal(0, platform.StartupCalls);+ Assert.Equal(0, platform.MenuCalls);+ }++ private static SystemIntegrationService Create(RecordingPlatform platform) =>+ new(platform, new Texts(), NullLogger<SystemIntegrationService>.Instance)+ {+ RegistrationEnabled = true,+ ExecutablePath = Path.Combine(Path.GetTempPath(), "Filee test", "Filee"),+ };++ private sealed class Texts : ILocalizer+ {+ public string Language => "en";+ public string this[string key] => key;+ public string Format(string key, params object[] args) => key + ": " + string.Join(", ", args);+ public event EventHandler? LanguageChanged { add { } remove { } }+ }++ private sealed class RecordingPlatform : IPlatformServices+ {+ public int StartupCalls { get; private set; }+ public int MenuCalls { get; private set; }+ public bool FailMenu { get; set; }+ public void SetStartWithSystem(bool enabled, string executablePath) => StartupCalls++;+ public void SetContextMenu(bool enabled, string executablePath, string label)+ {+ MenuCalls++;+ if (FailMenu)+ throw new IOException("denied");+ }+ public bool IsFileManagerAt(int x, int y) => false;+ public string? ProcessNameAt(int x, int y) => null;+ public IReadOnlyList<string> GetFileManagerSelection() => [];+ public int SystemDragThreshold => 4;+ public bool PrefersReducedMotion => false;+ public ModernContextMenuState GetModernContextMenuState(string executablePath) => ModernContextMenuState.Unsupported;+ public Task<ModernContextMenuResult> SetModernContextMenuAsync(bool enabled, string executablePath) =>+ Task.FromResult(new ModernContextMenuResult(false));+ public void RevealInFileManager(string path) { }+ public void RaiseTopmost(nint windowHandle) { }+ }+}diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.csindex d0225cfa..fdf3af16 100644--- a/tests/Filee.Cli.Tests/CliTests.cs+++ b/tests/Filee.Cli.Tests/CliTests.cs@@ -179,4 +179,50 @@ public sealed class CliTests : IDisposableAssert.Equal(Cli.Success, code);Assert.StartsWith("filee ", output);}++ [Fact]+ public async Task Case_distinct_inputs_are_both_converted_and_exact_duplicates_are_removed()+ {+ var lower = Png("photo.png");+ if (File.Exists(Path.Combine(_folder, "PHOTO.png")))+ {+ Assert.Skip("The temporary volume is case-insensitive.");+ return;+ }+ var upper = Png("PHOTO.png");+ var outputFolder = Path.Combine(_folder, "out");++ var (code, output, errors) = await Run("convert", lower, upper, lower, "--to", "jpg", "-o", outputFolder, "--json");++ Assert.Equal(Cli.Success, code);+ Assert.Equal("", errors);+ using var json = JsonDocument.Parse(output);+ Assert.Equal(2, json.RootElement.GetProperty("converted").GetInt32());+ Assert.Equal(2, json.RootElement.GetProperty("files").GetArrayLength());+ var outputPaths = json.RootElement.GetProperty("files").EnumerateArray()+ .Select(file => file.GetProperty("outputs")[0].GetString()!).ToArray();+ Assert.Equal(2, outputPaths.Distinct(StringComparer.OrdinalIgnoreCase).Count());+ Assert.All(outputPaths, path => Assert.True(File.Exists(path)));+ }++ [Fact]+ public async Task Unicode_spaces_and_quotes_stay_in_a_single_input_argument()+ {+ var name = OperatingSystem.IsWindows() ? "한글 report's 100%.png" : "한글 report's \"quoted\" 100%.png";+ var source = Png(name);+ var outputFolder = Path.Combine(_folder, "결과 output's");++ var (code, output, errors) = await Run("convert", source, "--to", "jpg", "-o", outputFolder, "--json");++ Assert.Equal(Cli.Success, code);+ Assert.Equal("", errors);+ using var json = JsonDocument.Parse(output);+ Assert.Equal(1, json.RootElement.GetProperty("converted").GetInt32());+ var result = json.RootElement.GetProperty("files")[0].GetProperty("outputs")[0].GetString();+ Assert.NotNull(result);+ Assert.Equal(outputFolder, Path.GetDirectoryName(result));+ Assert.Contains("한글 report's", Path.GetFileName(result));+ Assert.True(File.Exists(result));+ Assert.True(File.Exists(source));+ }}diff --git a/tests/Filee.Core.Tests/FolderWatcherTests.cs b/tests/Filee.Core.Tests/FolderWatcherTests.csindex a12af786..3854b28b 100644--- a/tests/Filee.Core.Tests/FolderWatcherTests.cs+++ b/tests/Filee.Core.Tests/FolderWatcherTests.cs@@ -157,4 +157,64 @@ public class FolderWatcherTestsAssert.False(watcher.Start());Assert.NotNull(watcher.Error);}++ [Fact]+ public async Task Case_distinct_files_with_identical_metadata_are_both_converted()+ {+ using var dir = new TempDir();+ var lower = dir.File("photo.jpg", "one");+ var upper = Path.Combine(dir.Path, "PHOTO.jpg");+ if (File.Exists(upper))+ {+ Assert.Skip("The temporary volume is case-insensitive.");+ return;+ }+ File.WriteAllText(upper, "two");+ File.SetLastWriteTimeUtc(upper, File.GetLastWriteTimeUtc(lower));+ var (watcher, time, jobs, queue) = Create(new WatchRule { Folder = dir.Path });+ await using var queueLifetime = queue;+ await using var watcherLifetime = watcher;++ watcher.Notice(lower);+ watcher.Notice(upper);+ time.Advance(3);++ Assert.Equal(2, await watcher.ProcessPendingAsync());+ var job = Assert.Single(jobs);+ Assert.Equal(2, job.Files.Count);+ Assert.Equal(2, job.Outputs.Distinct(StringComparer.OrdinalIgnoreCase).Count());+ foreach (var result in job.Files)+ {+ Assert.Equal(FileState.Done, result.State);+ Assert.Contains(Path.GetFileName(result.SourcePath), File.ReadAllText(Assert.Single(result.Outputs)));+ }++ watcher.Notice(lower);+ watcher.Notice(upper);+ time.Advance(3);+ Assert.Equal(0, await watcher.ProcessPendingAsync());+ Assert.Single(jobs);+ }++ [Fact]+ public void A_case_distinct_folder_is_not_mistaken_for_the_output_folder()+ {+ using var dir = new TempDir();+ var rule = new WatchRule { Folder = dir.Path, IncludeSubfolders = true };+ Directory.CreateDirectory(rule.ResolvedOutputFolder);+ var alternate = Path.Combine(dir.Path, "Converted");+ if (Directory.Exists(alternate))+ {+ Assert.Skip("The temporary volume is case-insensitive.");+ return;+ }+ Directory.CreateDirectory(alternate);+ var input = Path.Combine(alternate, "photo.jpg");+ var output = Path.Combine(rule.ResolvedOutputFolder, "photo.jpg");+ File.WriteAllText(input, "input");+ File.WriteAllText(output, "output");++ Assert.False(FolderWatcher.ShouldIgnore(input, rule));+ Assert.True(FolderWatcher.ShouldIgnore(output, rule));+ }}diff --git a/tests/Filee.Core.Tests/OutputPathResolverTests.cs b/tests/Filee.Core.Tests/OutputPathResolverTests.csindex 5003156e..a4d98d4e 100644--- a/tests/Filee.Core.Tests/OutputPathResolverTests.cs+++ b/tests/Filee.Core.Tests/OutputPathResolverTests.cs@@ -116,4 +116,21 @@ public class OutputPathResolverTestsAssert.Equal(Path.Combine("D:", "out", "a.png"), path);}++ [Theory]+ [InlineData(ConflictPolicy.Overwrite)]+ [InlineData(ConflictPolicy.Skip)]+ [InlineData(ConflictPolicy.Rename)]+ public void A_case_alias_of_the_source_is_never_overwritten(ConflictPolicy policy)+ {+ using var dir = new TempDir();+ var source = dir.File("photo.jpg", "original");+ var rule = new OutputRule { FileNamePattern = "PHOTO", Conflict = policy };++ var path = OutputPathResolver.Resolve(rule, Tokens(source), "jpg", File.Exists);++ Assert.Equal(Path.Combine(dir.Path, "PHOTO (2).jpg"), path);+ Assert.Equal("original", File.ReadAllText(source));+ }+}diff --git a/tests/Filee.Engines.Tests/EngineInstallerTests.cs b/tests/Filee.Engines.Tests/EngineInstallerTests.csindex 08afdee7..0d52a7f1 100644--- a/tests/Filee.Engines.Tests/EngineInstallerTests.cs+++ b/tests/Filee.Engines.Tests/EngineInstallerTests.cs@@ -52,6 +52,18 @@ public sealed class EngineInstallerTests : IDisposablereturn buffer.ToArray();}+ private static byte[] TarGzip(params (string Path, string Text)[] files)+ {+ using var buffer = new MemoryStream();+ using (var gzip = new GZipStream(buffer, CompressionLevel.Fastest, leaveOpen: true))+ using (var tar = new TarWriter(gzip, TarEntryFormat.Pax, leaveOpen: true))+ {+ foreach (var (path, text) in files)+ tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, path) { DataStream = new MemoryStream(Encoding.UTF8.GetBytes(text)) });+ }+ return buffer.ToArray();+ }+/// <summary>A conda package: a zip with metadata and the files as a zstd-compressed tarball.</summary>private static byte[] Conda(params (string Path, string Text)[] files){@@ -150,6 +162,53 @@ public sealed class EngineInstallerTests : IDisposableAssert.Empty(Directory.GetFiles(Path.Combine(_root, ".downloads")));}+ [Theory]+ [InlineData("zip")]+ [InlineData("tar.gz")]+ public async Task An_incomplete_engine_update_preserves_the_working_install_and_its_marker(string kind)+ {+ var programs = EngineEnvironment.OwnCopyPrograms["ffmpeg"];+ byte[] Archive(params (string Path, string Text)[] files) => kind == "zip" ? Zip(files) : TarGzip(files);+ var previousArchive = Archive(($"ffmpeg-1.0/bin/{programs[0]}", "working encoder"),+ ($"ffmpeg-1.0/bin/{programs[1]}", "working probe"));+ var previousComponent = Component("ffmpeg", kind, previousArchive);+ var package = new EnginePackage("ffmpeg", ["ffmpeg"], 1, ["ffmpeg"]);+ var previousInstaller = Installer(new FakeServer(new() { [previousComponent.Url] = previousArchive }), previousComponent);+ await previousInstaller.InstallAsync(package, null, TestContext.Current.CancellationToken);++ var incompleteArchive = Archive(($"ffmpeg-2.0/bin/{programs[0]}", "new encoder without probe"));+ var incompleteComponent = Component("ffmpeg", kind, incompleteArchive) with { Version = "2.0" };+ var installer = Installer(new FakeServer(new() { [incompleteComponent.Url] = incompleteArchive }), incompleteComponent);+ var error = await Assert.ThrowsAsync<InvalidDataException>(() =>+ installer.InstallAsync(package, null, TestContext.Current.CancellationToken));++ Assert.Contains("ffmpeg", error.Message);+ var folder = Path.Combine(_root, "ffmpeg");+ Assert.Equal("working encoder", File.ReadAllText(Path.Combine(folder, "bin", programs[0])));+ Assert.Equal("working probe", File.ReadAllText(Path.Combine(folder, "bin", programs[1])));+ Assert.Equal(previousComponent.Sha256, File.ReadAllText(Path.Combine(folder, ".filee-component")));+ Assert.True(previousInstaller.IsUpToDate(package));+ Assert.True(installer.IsInstalled(package));+ Assert.False(installer.IsUpToDate(package));+ Assert.Empty(Directory.GetDirectories(_root, "~*"));+ Assert.Empty(Directory.GetFiles(Path.Combine(_root, ".downloads")));+ }++ [Theory]+ [InlineData("libreoffice", "LibreOffice.app", "soffice")]+ [InlineData("calibre", "calibre.app", "ebook-convert")]+ public void A_Mac_application_bundle_requires_its_conversion_program(string id, string app, string program)+ {+ var folder = Path.Combine(_root, app, "Contents", "MacOS");+ Directory.CreateDirectory(folder);+ File.WriteAllText(Path.Combine(folder, "README"), "not an executable");++ Assert.Throws<InvalidDataException>(() => EngineInstaller.RequiredProgramFolder(id, _root, windows: false));++ File.WriteAllText(Path.Combine(folder, program), "binary");+ Assert.Equal(folder, EngineInstaller.RequiredProgramFolder(id, _root, windows: false));+ }+[Fact]public async Task Redirects_to_plain_http_mirrors_are_followed_because_the_hash_is_checked(){@@ -235,7 +294,7 @@ public sealed class EngineInstallerTests : IDisposable[Fact]public void Every_package_component_is_pinned_in_the_manifest(){- foreach (var package in EngineDownloads.Packages)+ foreach (var package in EngineDownloads.Packages.Where(EngineDownloads.CanDownload)){foreach (var id in package.Components){diff --git a/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs b/tests/Filee.Engines.Tests/LibreOfficeFormatTests.csindex c2c39ba7..fec1e6d2 100644--- a/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs+++ b/tests/Filee.Engines.Tests/LibreOfficeFormatTests.cs@@ -37,13 +37,15 @@ public class LibreOfficeFormatTests(EngineFixture fx) : IClassFixture<EngineFixt[InlineData("odg", "odg", null, "odg:draw8")][InlineData("cgm", "odg", null, "odg:impress8_draw")][InlineData("cgm", "svg", null, "svg:impress_svg_Export")]+ [InlineData("emf", "pdf", null, "pdf:draw_pdf_Export")]+ [InlineData("wmf", "png", null, "png:draw_png_Export")]public void Filters_follow_the_application_that_opens_the_file(string from, string to, string? extension, string expected) =>Assert.Equal(expected, LibreOfficeConverter.FilterFor(from, to, pdfA: false, extension));[Fact]public void Every_edge_has_a_filter_of_its_application(){- string[] draw = ["pub", "cdr", "vsd", "odg"];+ string[] draw = ["pub", "cdr", "vsd", "odg", "emf", "wmf"];string[] impress = ["pptx", "ppt", "odp", "key", "dps", "sda", "cgm"];string[] calc = ["xlsx", "xls", "ods", "csv", "et", "numbers", "sdc"];foreach (var edge in LibreOffice.Edges)diff --git a/tests/Filee.Engines.Tests/OwnCopyTests.cs b/tests/Filee.Engines.Tests/OwnCopyTests.csindex 0d8afdaf..64486f27 100644--- a/tests/Filee.Engines.Tests/OwnCopyTests.cs+++ b/tests/Filee.Engines.Tests/OwnCopyTests.cs@@ -30,13 +30,11 @@ public sealed class OwnCopyTests : IDisposable[Fact]public void The_users_own_copy_wins_over_filees_download(){- if (!OperatingSystem.IsWindows())- return;- var ffmpeg = Program(@"ffmpeg\bin\ffmpeg.exe");- var ffprobe = Program(@"ffmpeg\bin\ffprobe.exe");- var pandoc = Program(@"pandoc\pandoc.exe");- var calibre = Program(@"Calibre2\calibre.exe");- var convert = Program(@"Calibre2\ebook-convert.exe");+ var ffmpeg = Program(Path.Combine("ffmpeg", "bin", EngineEnvironment.ProgramName("ffmpeg.exe")));+ var ffprobe = Program(Path.Combine("ffmpeg", "bin", EngineEnvironment.ProgramName("ffprobe.exe")));+ var pandoc = Program(Path.Combine("pandoc", EngineEnvironment.ProgramName("pandoc.exe")));+ var calibre = Program(Path.Combine("Calibre2", EngineEnvironment.ProgramName("calibre.exe")));+ var convert = Program(Path.Combine("Calibre2", EngineEnvironment.ProgramName("ebook-convert.exe")));EngineEnvironment.OwnCopies = new Dictionary<string, string>{@@ -53,9 +51,7 @@ public sealed class OwnCopyTests : IDisposable[Fact]public void A_folder_without_every_program_is_not_used(){- if (!OperatingSystem.IsWindows())- return;- var ffmpeg = Program(@"tools\ffmpeg.exe"); // no ffprobe.exe next to it+ var ffmpeg = Program(Path.Combine("tools", EngineEnvironment.ProgramName("ffmpeg.exe")));Assert.Null(EngineEnvironment.FolderWithPrograms("ffmpeg", ffmpeg));EngineEnvironment.OwnCopies = new Dictionary<string, string> { ["ffmpeg"] = ffmpeg };@@ -84,16 +80,13 @@ public sealed class SystemCopyTests : IDisposable[Fact]public void A_tool_on_the_path_is_found_when_filee_has_no_copy(){- if (!OperatingSystem.IsWindows())- return;- // Like Scoop's shims folder: ffmpeg.exe and ffprobe.exe side by side, on the PATH.- File.WriteAllBytes(Path.Combine(_folder, "ffmpeg.exe"), [0x4D, 0x5A]);- File.WriteAllBytes(Path.Combine(_folder, "ffprobe.exe"), [0x4D, 0x5A]);- Environment.SetEnvironmentVariable("PATH", _folder + ";" + _path);+ File.WriteAllBytes(Path.Combine(_folder, EngineEnvironment.ProgramName("ffmpeg.exe")), [0x4D, 0x5A]);+ File.WriteAllBytes(Path.Combine(_folder, EngineEnvironment.ProgramName("ffprobe.exe")), [0x4D, 0x5A]);+ Environment.SetEnvironmentVariable("PATH", _folder + Path.PathSeparator + _path);EngineEnvironment.ForgetSystemCopies();Assert.Equal(_folder, EngineEnvironment.SystemCopyFolder("ffmpeg"));- Assert.Equal(Path.Combine(_folder, "ffmpeg.exe"), EngineEnvironment.SystemProgram("ffmpeg", "ffmpeg.exe"));+ Assert.Equal(Path.Combine(_folder, EngineEnvironment.ProgramName("ffmpeg.exe")), EngineEnvironment.SystemProgram("ffmpeg", "ffmpeg.exe"));}[Theory]@@ -104,6 +97,7 @@ public sealed class SystemCopyTests : IDisposable[InlineData("calibre", "ebook-convert.exe (calibre 8.5.0)\nCreated by: Kovid Goyal", "8.5")][InlineData("ghostscript", "10.04.0\r\n", "10.4")][InlineData("libreoffice", "[Version]\nAllLanguages=en-US\nMsiProductVersion=25.2.4.3\n", "25.2")]+ [InlineData("libreoffice", "LibreOffice 26.2.6.2 98d5f8\n", "26.2")]public void Versions_are_read_from_each_program(string id, string output, string? expected) =>Assert.Equal(expected is null ? null : Version.Parse(expected), CopyVersions.ParseVersion(id, output));diff --git a/tests/Filee.Engines.Tests/PortableEngineTests.cs b/tests/Filee.Engines.Tests/PortableEngineTests.csnew file mode 100644index 00000000..b6e90cdf--- /dev/null+++ b/tests/Filee.Engines.Tests/PortableEngineTests.cs@@ -0,0 +1,136 @@+using System.Formats.Tar;+using System.IO.Compression;+using System.Text;+using Filee.Engines.Infrastructure;++namespace Filee.Engines.Tests;++public sealed class PortableEngineTests : IDisposable+{+ private readonly string _root = Directory.CreateTempSubdirectory("filee-portable-").FullName;++ public void Dispose() => Directory.Delete(_root, recursive: true);++ [Theory]+ [InlineData("linux-x64")]+ [InlineData("linux-arm64")]+ [InlineData("osx-x64")]+ [InlineData("osx-arm64")]+ public void Unix_downloads_are_pinned_for_the_requested_runtime(string runtime)+ {+ var components = EngineDownloads.ComponentsForRuntime(runtime);+ Assert.Contains("rhwp", components.Keys);+ Assert.Contains("7zip", components.Keys);+ Assert.Contains("pandoc", components.Keys);+ Assert.Contains("calibre", components.Keys);+ Assert.DoesNotContain("vcruntime", components.Keys);+ Assert.DoesNotContain("ghostscript", components.Keys);+ foreach (var component in components.Values)+ {+ Assert.StartsWith("https://", component.Url);+ Assert.DoesNotContain("windows", component.Url, StringComparison.OrdinalIgnoreCase);+ Assert.DoesNotContain(component.Kind, new[] { "msi", "conda" });+ Assert.Matches("^[0-9A-F]{64}$", component.Sha256);+ Assert.True(component.Size > 0);+ }+ var arch = runtime.EndsWith("arm64", StringComparison.Ordinal) ? "aarch64" : "x86_64";+ Assert.Contains(arch, components["rhwp"].Url);+ }++ [Fact]+ public void Unknown_platforms_cannot_fall_back_to_Windows_downloads() =>+ Assert.Empty(EngineDownloads.ComponentsForRuntime("linux-riscv64"));++ [Theory]+ [InlineData("libreoffice", "LibreOffice.app/Contents/MacOS", "soffice")]+ [InlineData("calibre", "calibre.app/Contents/MacOS", "ebook-convert")]+ [InlineData("pandoc", "bin", "pandoc")]+ [InlineData("ghostscript", "bin", "gs")]+ public void Unix_programs_are_found_inside_archives_and_Mac_application_bundles(string id, string relative, string program)+ {+ var folder = Path.Combine(_root, relative.Replace('/', Path.DirectorySeparatorChar));+ Directory.CreateDirectory(folder);+ File.WriteAllText(Path.Combine(folder, program), "binary");+ Assert.Equal(folder, EngineEnvironment.FolderWithPrograms(id, _root, windows: false));+ Assert.Equal(folder, EngineEnvironment.FolderWithPrograms(id, Path.Combine(folder, program), windows: false));+ Assert.Null(EngineEnvironment.FolderWithPrograms(id, _root, windows: true));+ }++ [Fact]+ public void Unix_FFmpeg_requires_both_tools_in_the_same_folder()+ {+ File.WriteAllText(Path.Combine(_root, "ffmpeg"), "binary");+ Assert.Null(EngineEnvironment.FolderWithPrograms("ffmpeg", _root, windows: false));+ File.WriteAllText(Path.Combine(_root, "ffprobe"), "binary");+ Assert.Equal(_root, EngineEnvironment.FolderWithPrograms("ffmpeg", _root, windows: false));+ }++ [Fact]+ public async Task Tar_archives_preserve_program_layout_contents_and_Unix_executable_mode()+ {+ var file = TarGzip(new PaxTarEntry(TarEntryType.RegularFile, "tool/bin/tool")+ {+ DataStream = new MemoryStream(Encoding.UTF8.GetBytes("#!/bin/sh\necho ready\n")),+ Mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute,+ });+ var target = Path.Combine(_root, "extract");+ await EngineInstaller.UnpackTarAsync(file, target, "tar.gz", TestContext.Current.CancellationToken);+ var program = Path.Combine(target, "tool", "bin", "tool");+ Assert.Contains("echo ready", File.ReadAllText(program));+ if (!OperatingSystem.IsWindows())+ Assert.True(File.GetUnixFileMode(program).HasFlag(UnixFileMode.UserExecute));+ }++ [Fact]+ public async Task Tar_entries_cannot_escape_the_staging_folder()+ {+ var file = TarGzip(new PaxTarEntry(TarEntryType.RegularFile, "../escaped")+ {+ DataStream = new MemoryStream([1]),+ });+ await Assert.ThrowsAsync<IOException>(() => EngineInstaller.UnpackTarAsync(file,+ Path.Combine(_root, "extract"), "tar.gz", TestContext.Current.CancellationToken));+ Assert.False(File.Exists(Path.Combine(_root, "escaped")));+ }++ [Fact]+ public async Task Tar_symbolic_links_cannot_write_outside_staging()+ {+ var outside = Path.Combine(_root, "outside");+ Directory.CreateDirectory(outside);+ var file = TarGzip(+ new PaxTarEntry(TarEntryType.SymbolicLink, "link") { LinkName = "../outside" },+ new PaxTarEntry(TarEntryType.RegularFile, "link/escaped") { DataStream = new MemoryStream([1]) });+ var exception = await Record.ExceptionAsync(() => EngineInstaller.UnpackTarAsync(file,+ Path.Combine(_root, "extract"), "tar.gz", TestContext.Current.CancellationToken));+ Assert.NotNull(exception);+ Assert.False(File.Exists(Path.Combine(outside, "escaped")));+ }++ [Fact]+ public void Downloaded_Unix_programs_get_execute_permission_without_changing_data_files()+ {+ if (OperatingSystem.IsWindows())+ return;+ var program = Path.Combine(_root, "pandoc");+ var readme = Path.Combine(_root, "README");+ File.WriteAllText(program, "binary");+ File.WriteAllText(readme, "data");+ File.SetUnixFileMode(program, UnixFileMode.UserRead | UnixFileMode.UserWrite);+ var dataMode = File.GetUnixFileMode(readme);+ EngineInstaller.EnsureExecutablePrograms("pandoc", _root);+ Assert.True(File.GetUnixFileMode(program).HasFlag(UnixFileMode.UserExecute));+ Assert.Equal(dataMode, File.GetUnixFileMode(readme));+ }++ private string TarGzip(params TarEntry[] entries)+ {+ var file = Path.Combine(_root, Guid.NewGuid().ToString("N") + ".tar.gz");+ using var output = File.Create(file);+ using var gzip = new GZipStream(output, CompressionLevel.Fastest);+ using var writer = new TarWriter(gzip);+ foreach (var entry in entries)+ writer.WriteEntry(entry);+ return file;+ }+}diff --git a/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj b/tests/Filee.Platform.Tests/Filee.Platform.Tests.csprojnew file mode 100644index 00000000..f6ccad1d--- /dev/null+++ b/tests/Filee.Platform.Tests/Filee.Platform.Tests.csproj@@ -0,0 +1,15 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <IsPackable>false</IsPackable>+ <IsTestProject>true</IsTestProject>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\..\src\Filee.Platform.Linux\Filee.Platform.Linux.csproj" />+ <ProjectReference Include="..\..\src\Filee.Platform.MacOS\Filee.Platform.MacOS.csproj" />+ <PackageReference Include="Microsoft.NET.Test.Sdk" />+ <PackageReference Include="xunit.v3" />+ <PackageReference Include="xunit.runner.visualstudio" />+ <Using Include="Xunit" />+ </ItemGroup>+</Project>diff --git a/tests/Filee.Platform.Tests/LinuxDesktopIntegrationTests.cs b/tests/Filee.Platform.Tests/LinuxDesktopIntegrationTests.csnew file mode 100644index 00000000..19e3e86d--- /dev/null+++ b/tests/Filee.Platform.Tests/LinuxDesktopIntegrationTests.cs@@ -0,0 +1,122 @@+using System.Xml.Linq;+using Filee.Core.Settings;+using Filee.Platform.Linux;++namespace Filee.Platform.Tests;++public sealed class LinuxDesktopIntegrationTests : IDisposable+{+ private readonly string _root = Path.Combine(Path.GetTempPath(), "Filee.Platform.Tests", Guid.NewGuid().ToString("N"));++ [Fact]+ public void ContextMenuRoundTripPreservesOtherThunarActions()+ {+ var configuration = Path.Combine(_root, "config");+ var data = Path.Combine(_root, "data");+ var path = Path.Combine(configuration, "Thunar", "uca.xml");+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ const string existing = "<action><name>Keep me</name><unique-id>other</unique-id><command>echo unchanged</command><other-files /></action>";+ File.WriteAllText(path, "<actions>" + existing + "</actions>");+ var integration = new LinuxDesktopIntegration(configuration, data);++ integration.SetContextMenu(true, "/opt/Filee's app/Filee.App", "Filee로 변환 & test");+ integration.SetContextMenu(true, "/opt/new/Filee.App", "Updated");++ var document = XDocument.Load(path);+ Assert.Equal(2, document.Root!.Elements("action").Count());+ Assert.Equal("echo unchanged", document.Root.Elements("action")+ .Single(action => (string?)action.Element("unique-id") == "other").Element("command")!.Value);+ Assert.Equal("'/opt/new/Filee.App' --convert %F", document.Root.Elements("action")+ .Single(action => (string?)action.Element("unique-id") == LinuxDesktopIntegration.ThunarActionId).Element("command")!.Value);+ Assert.Contains("exec '/opt/new/Filee.App' --convert \"$@\"", File.ReadAllText(Path.Combine(data, "nautilus", "scripts", "Filee")));++ integration.SetContextMenu(false, "", "");++ document = XDocument.Load(path);+ Assert.Single(document.Root!.Elements("action"));+ Assert.Equal("other", document.Root.Element("action")!.Element("unique-id")!.Value);+ Assert.False(File.Exists(Path.Combine(data, "kio", "servicemenus", "filee.desktop")));+ }++ [Fact]+ public void MalformedThunarConfigurationIsNotOverwritten()+ {+ var configuration = Path.Combine(_root, "config");+ var path = Path.Combine(configuration, "Thunar", "uca.xml");+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);+ File.WriteAllText(path, "<actions><action>");++ Assert.Throws<System.Xml.XmlException>(() =>+ new LinuxDesktopIntegration(configuration, Path.Combine(_root, "data"))+ .SetContextMenu(true, "/opt/Filee.App", "Convert"));+ Assert.Equal("<actions><action>", File.ReadAllText(path));+ Assert.False(Directory.Exists(Path.Combine(_root, "data")));+ }++ [Fact]+ public void AutostartEscapesLineBreaksAndKeepsTheExecutableAsOneArgument()+ {+ var integration = new LinuxDesktopIntegration(_root, Path.Combine(_root, "data"));+ integration.SetAutostart(true, "/opt/Filee test/Filee.App");+ var path = Path.Combine(_root, "autostart", "filee.desktop");+ Assert.Contains("Exec=\"/opt/Filee test/Filee.App\" --background\n", File.ReadAllText(path));+ Assert.Throws<ArgumentException>(() => integration.SetAutostart(true, "/opt/Filee\nExec=bad"));+ Assert.Contains("Exec=\"/opt/Filee test/Filee.App\" --background\n", File.ReadAllText(path));+ integration.SetAutostart(false, "");+ Assert.False(File.Exists(path));+ }++ [Fact]+ public void DesktopArgumentsEscapeBothDesktopParsingLayers()+ {+ Assert.Equal("\"/tmp/a\\\\\"b\\\\$c\\\\`d\\\\\\\\e%%f\"",+ LinuxDesktopIntegration.DesktopArgument("/tmp/a\"b$c`d\\e%f"));+ Assert.Equal("'/tmp/a'\\''b $c'", LinuxDesktopIntegration.ShellArgument("/tmp/a'b $c"));+ Assert.Equal("label\\nExec=bad", LinuxDesktopIntegration.DesktopValue("label\nExec=bad"));+ }++ [Fact]+ public void ShortcutUpdatePreservesOthersAndIsIdempotent()+ {+ const string original = "; other comment\n(gtk_accel_path \"<Actions>/ThunarWindow/open\" \"<Control>o\")\n";+ var updated = LinuxDesktopIntegration.UpdateThunarShortcut(original, "<Control><Alt>space");+ Assert.StartsWith(original, updated);+ Assert.Contains("\"<Control><Alt>space\")\n", updated);+ Assert.Equal(updated, LinuxDesktopIntegration.UpdateThunarShortcut(updated, "<Control><Alt>space"));+ Assert.Equal(original, LinuxDesktopIntegration.UpdateThunarShortcut(updated, null));+ Assert.Throws<InvalidOperationException>(() => LinuxDesktopIntegration.UpdateThunarShortcut(original, "<Primary>o"));+ Assert.Throws<InvalidOperationException>(() => LinuxDesktopIntegration.UpdateThunarShortcut(+ original.Replace("<Control>o", "<Alt><Control>space", StringComparison.Ordinal), "<Control><Alt>space"));+ Assert.Throws<ArgumentException>(() => LinuxDesktopIntegration.UpdateThunarShortcut(original, "space\")\n(bad)"));+ }++ [Theory]+ [InlineData("Backslash", "backslash")]+ [InlineData("BackSlash", "backslash")]+ [InlineData("NumPad0", "KP_0")]+ [InlineData("NumPad7", "KP_7")]+ [InlineData("NumPad9", "KP_9")]+ [InlineData("PrintScreen", "Print")]+ [InlineData("Pause", "Pause")]+ [InlineData("PageDown", "Page_Down")]+ [InlineData("Space", "space")]+ public void RecordedKeysHaveGtkAccelerators(string recorded, string expected)+ {+ var gesture = new TriggerGesture+ {+ Kind = TriggerKind.KeyChord,+ Modifiers = ModifierKeys.Ctrl | ModifierKeys.Alt,+ Key = recorded,+ };+ var accelerator = LinuxDesktopIntegration.ToThunarAccelerator(gesture);+ Assert.Equal("<Control><Alt>" + expected, accelerator);+ var contents = LinuxDesktopIntegration.UpdateThunarShortcut("", accelerator);+ Assert.Contains("\"" + accelerator + "\"", contents);+ }++ public void Dispose()+ {+ if (Directory.Exists(_root))+ Directory.Delete(_root, recursive: true);+ }+}diff --git a/tests/Filee.Platform.Tests/LinuxNativeIntegrationTests.cs b/tests/Filee.Platform.Tests/LinuxNativeIntegrationTests.csnew file mode 100644index 00000000..b7ba567b--- /dev/null+++ b/tests/Filee.Platform.Tests/LinuxNativeIntegrationTests.cs@@ -0,0 +1,121 @@+using System.Diagnostics;+using System.Runtime.InteropServices;+using Filee.Platform.Linux;++namespace Filee.Platform.Tests;++public sealed class LinuxNativeIntegrationTests+{+ [Fact]+ public void NautilusScriptPreservesDistinctPathsAndShellCharacters()+ {+ if (!OperatingSystem.IsLinux())+ {+ Assert.Skip("Requires the Linux POSIX shell.");+ return;+ }+ var root = Path.Combine(Path.GetTempPath(), "filee-linux-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(root);+ try+ {+ var capture = Path.Combine(root, "arguments");+ var target = Path.Combine(root, "Filee's app");+ File.WriteAllText(target, "#!/bin/sh\nprintf '%s\\0' \"$@\" > " + LinuxDesktopIntegration.ShellArgument(capture) + "\n");+ File.SetUnixFileMode(target, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);+ var first = Path.Combine(root, "a", "한글 ' $(touch BAD) %F.txt");+ var second = Path.Combine(root, "b", Path.GetFileName(first));+ foreach (var file in new[] { first, second })+ {+ Directory.CreateDirectory(Path.GetDirectoryName(file)!);+ File.WriteAllText(file, "sample");+ }+ var data = Path.Combine(root, "data");+ new LinuxDesktopIntegration(Path.Combine(root, "config"), data).SetContextMenu(true, target, "Convert");+ var processInfo = new ProcessStartInfo(Path.Combine(data, "nautilus", "scripts", "Filee"))+ {+ UseShellExecute = false,+ WorkingDirectory = root,+ };+ processInfo.ArgumentList.Add(Path.GetRelativePath(root, first));+ processInfo.ArgumentList.Add(second);+ using var process = Process.Start(processInfo)!;+ Assert.True(process.WaitForExit(5000));+ Assert.Equal(0, process.ExitCode);+ Assert.Equal(new[] { "--convert", first, second }, File.ReadAllText(capture).Split('\0', StringSplitOptions.RemoveEmptyEntries));+ Assert.False(File.Exists(Path.Combine(root, "BAD")));+ }+ finally+ {+ Directory.Delete(root, recursive: true);+ }+ }++ [Fact]+ public void X11CanIdentifyAnOwnedWindowAndRequestRestackingWithoutChangingFocus()+ {+ if (!OperatingSystem.IsLinux() || !X11WindowSystem.IsAvailable)+ {+ Assert.Skip("Requires a Linux X11 desktop session.");+ return;+ }+ var display = XOpenDisplay(0);+ Assert.NotEqual(0, display);+ var window = XCreateSimpleWindow(display, XDefaultRootWindow(display), 40, 40, 80, 80, 0, 0, 0);+ var pid = Marshal.AllocHGlobal(nint.Size);+ try+ {+ var attributes = new XSetWindowAttributes { OverrideRedirect = 1 };+ XChangeWindowAttributes(display, window, 1 << 9, ref attributes);+ Marshal.WriteIntPtr(pid, Environment.ProcessId);+ XChangeProperty(display, window, XInternAtom(display, "_NET_WM_PID", 0), 6, 32, 0, pid, 1);+ XMapRaised(display, window);+ XSync(display, 0);+ XTranslateCoordinates(display, window, XDefaultRootWindow(display), 20, 20, out var x, out var y, out _);+ Assert.Equal(Process.GetCurrentProcess().ProcessName, X11WindowSystem.ProcessNameAt(x, y));+ XGetInputFocus(display, out var previousFocus, out _);+ X11WindowSystem.RaiseTopmost((nint)window);+ XSync(display, 0);+ XGetInputFocus(display, out var currentFocus, out _);+ Assert.Equal(previousFocus, currentFocus);+ }+ finally+ {+ Marshal.FreeHGlobal(pid);+ XDestroyWindow(display, window);+ XCloseDisplay(display);+ }+ }++ [DllImport("libX11.so.6")] private static extern nint XOpenDisplay(nint name);+ [DllImport("libX11.so.6")] private static extern int XCloseDisplay(nint display);+ [DllImport("libX11.so.6")] private static extern nuint XDefaultRootWindow(nint display);+ [DllImport("libX11.so.6")] private static extern nuint XCreateSimpleWindow(nint display, nuint parent, int x, int y, uint width, uint height, uint borderWidth, nuint border, nuint background);+ [DllImport("libX11.so.6")] private static extern int XDestroyWindow(nint display, nuint window);+ [DllImport("libX11.so.6")] private static extern nuint XInternAtom(nint display, [MarshalAs(UnmanagedType.LPUTF8Str)] string name, int onlyIfExists);+ [DllImport("libX11.so.6")] private static extern int XChangeProperty(nint display, nuint window, nuint property, nuint type, int format, int mode, nint data, int count);+ [DllImport("libX11.so.6")] private static extern int XMapRaised(nint display, nuint window);+ [DllImport("libX11.so.6")] private static extern int XSync(nint display, int discard);+ [DllImport("libX11.so.6")] private static extern int XGetInputFocus(nint display, out nuint focus, out int revertTo);+ [DllImport("libX11.so.6")] private static extern int XTranslateCoordinates(nint display, nuint source, nuint destination, int x, int y, out int destinationX, out int destinationY, out nuint child);+ [DllImport("libX11.so.6")] private static extern int XChangeWindowAttributes(nint display, nuint window, nuint mask, ref XSetWindowAttributes attributes);++ [StructLayout(LayoutKind.Sequential)]+ private struct XSetWindowAttributes+ {+ public nuint BackgroundPixmap;+ public nuint BackgroundPixel;+ public nuint BorderPixmap;+ public nuint BorderPixel;+ public int BitGravity;+ public int WinGravity;+ public int BackingStore;+ public nuint BackingPlanes;+ public nuint BackingPixel;+ public int SaveUnder;+ public nint EventMask;+ public nint DoNotPropagateMask;+ public int OverrideRedirect;+ public nuint Colormap;+ public nuint Cursor;+ }+}diff --git a/tests/Filee.Platform.Tests/MacOSIntegrationTests.cs b/tests/Filee.Platform.Tests/MacOSIntegrationTests.csnew file mode 100644index 00000000..00df686f--- /dev/null+++ b/tests/Filee.Platform.Tests/MacOSIntegrationTests.cs@@ -0,0 +1,73 @@+using System.Xml.Linq;+using Filee.Platform.MacOS;++namespace Filee.Platform.Tests;++public sealed class MacOSIntegrationTests+{+ [Fact]+ public void LaunchAgentKeepsExecutableAndArgumentsSeparate()+ {+ const string executable = "/Users/a & b/도구 '$(touch nope)'/Filee.app/Contents/MacOS/Filee";+ var root = ReadPlist(MacOSIntegrationFiles.LaunchAgent(executable));+ Assert.Equal([executable, "--background"], Property(root, "ProgramArguments").Elements().Select(x => x.Value));+ Assert.Equal("true", Property(root, "RunAtLoad").Name.LocalName);+ Assert.Equal("false", Property(root, "KeepAlive").Name.LocalName);+ Assert.Equal("Aqua", Property(root, "LimitLoadToSessionType").Value);+ }++ [Fact]+ public void ServiceMenuEscapesLocalizedLabelAndOnlyAcceptsFinderFiles()+ {+ const string label = "Filee로 변환 <빠르게> & 'convert'";+ var root = ReadPlist(MacOSIntegrationFiles.ServiceInfo(label));+ var service = Property(root, "NSServices").Element("dict")!;+ Assert.Equal(label, Property(Property(service, "NSMenuItem"), "default").Value);+ Assert.Equal(label, Property(root, "CFBundleName").Value);+ Assert.Equal("com.apple.finder", Property(Property(service, "NSRequiredContext"), "NSApplicationIdentifier").Value);+ Assert.Equal("public.item", Property(service, "NSSendFileTypes").Element("string")!.Value);+ }++ [Fact]+ public void QuickActionLaunchesFreshBundleInstanceToForwardArguments()+ {+ const string executable = "/Applications/O'Brien & Friends/Filee.app/Contents/MacOS/Filee";+ var workflow = ReadPlist(MacOSIntegrationFiles.Workflow(executable));+ var action = Property(Property(workflow, "actions").Element("dict")!, "action");+ var parameters = Property(action, "ActionParameters");+ Assert.Equal("1", Property(parameters, "inputMethod").Value);+ Assert.Equal("/bin/sh", Property(parameters, "shell").Value);+ Assert.Equal("exec /usr/bin/open -n -a '/Applications/O'\"'\"'Brien & Friends/Filee.app' --args --convert \"$@\"",+ Property(parameters, "COMMAND_STRING").Value);+ var metadata = Property(workflow, "workflowMetaData");+ Assert.Equal("com.apple.Automator.fileSystemObject", Property(metadata, "serviceInputTypeIdentifier").Value);+ Assert.Equal("com.apple.finder", Property(metadata, "serviceApplicationBundleID").Value);+ }++ [Fact]+ public void RawExecutableIsQuotedWithoutEvaluatingShellMetacharacters()+ {+ Assert.Equal("exec '/tmp/$(touch nope) `echo bad` \"quote\"' --convert \"$@\"",+ MacOSIntegrationFiles.ConversionCommand("/tmp/$(touch nope) `echo bad` \"quote\""));+ }++ [Fact]+ public void SelectionJsonPreservesWhitespaceUnicodeAndNewlines()+ {+#pragma warning disable CA1416 // Pure JSON parsing does not access the operating system.+ var paths = MacOSPlatformServices.ParseSelection("[\"/tmp/ 한글 .txt\",\"/tmp/line\\nbreak.txt\",\"/tmp/quote\\\".txt\"]");+#pragma warning restore CA1416+ Assert.Equal(["/tmp/ 한글 .txt", "/tmp/line\nbreak.txt", "/tmp/quote\".txt"], paths);+ }++ private static XElement ReadPlist(string text)+ {+ var document = XDocument.Parse(text);+ Assert.Equal("plist", document.Root!.Name.LocalName);+ Assert.Equal("1.0", document.Root.Attribute("version")!.Value);+ return document.Root.Element("dict")!;+ }++ private static XElement Property(XElement dictionary, string key) =>+ dictionary.Elements("key").Single(x => x.Value == key).ElementsAfterSelf().First();+}diff --git a/tests/Filee.Platform.Tests/MacOSNativeTests.cs b/tests/Filee.Platform.Tests/MacOSNativeTests.csnew file mode 100644index 00000000..523a8aa2--- /dev/null+++ b/tests/Filee.Platform.Tests/MacOSNativeTests.cs@@ -0,0 +1,22 @@+using Filee.Platform.MacOS;++namespace Filee.Platform.Tests;++public sealed class MacOSNativeTests+{+ [Fact]+ public void NativeFrameworksAndPermissionProbeLoadOnMacOS()+ {+ if (!OperatingSystem.IsMacOS())+ {+ Assert.Skip("Requires macOS frameworks.");+ return;+ }++ var platform = new MacOSPlatformServices();+ _ = platform.HasAccessibilityPermission;+ _ = platform.PrefersReducedMotion;+ _ = platform.ProcessNameAt(0, 0);+ Assert.Equal(4, platform.SystemDragThreshold);+ }+}