From d5aa6960a27ea07bc94f5de910a220407e7b4c0f Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Tue, 10 Nov 2026 16:45:36 +0900 Subject: [PATCH 01/95] build(release): ship the Windows ARM64 Setup and Portable The release workflow builds and tests win-arm64 on windows-11-arm and keeps it unsigned as windows-arm64-unsigned; the draft waits for both Windows builds. sign-release.ps1 signs and packs it next to the x64 build, writes and signs Filee--win-arm64-SHA256SUMS.txt (one passphrase prompt) and mirrors it to dl.filee.sh. It also removes its worktree when git trips over long paths. make-setup takes --runtime, so an ARM64 Setup packed on an x64 PC offers what the ARM64 app downloads. The updater of an ARM64 build takes the ARM64 Setup and checksums, without falling back to x64; the x64 target skips -win-arm64- files. Refs #236 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 112 +++++++++++++++++- CONTRIBUTING.md | 19 +-- README.md | 1 + build/build-installer.ps1 | 5 +- build/sign-release.ps1 | 106 ++++++++++++----- build/tools/make-setup.cs | 17 ++- docs/ENGINES.md | 8 +- docs/readme/README.ar.md | 1 + docs/readme/README.bn-BD.md | 1 + docs/readme/README.es.md | 1 + docs/readme/README.fa.md | 1 + docs/readme/README.fr.md | 1 + docs/readme/README.hi.md | 1 + docs/readme/README.id.md | 1 + docs/readme/README.it.md | 1 + docs/readme/README.ja.md | 1 + docs/readme/README.ko.md | 1 + docs/readme/README.pl.md | 1 + docs/readme/README.pt-BR.md | 1 + docs/readme/README.pt-PT.md | 1 + docs/readme/README.ru.md | 1 + docs/readme/README.th.md | 1 + docs/readme/README.tr.md | 1 + docs/readme/README.zh-CN.md | 1 + docs/readme/README.zh-TW.md | 1 + src/Filee.App/Services/UpdateService.cs | 35 ++++-- .../Infrastructure/EngineDownloads.cs | 10 +- tests/Filee.App.Tests/UpdateServiceTests.cs | 75 ++++++++++++ .../PortableEngineTests.cs | 21 ++++ 29 files changed, 367 insertions(+), 60 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d13d7f19a..20d0676b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,10 +2,13 @@ # Trigger: push a tag like v1.0.0 (git tag v1.0.0 && git push origin v1.0.0) # # Output (build/build-installer.ps1): Filee--win-Setup.exe (Filee's own installer, src/Filee.Setup), -# Filee--win-Portable.zip and Filee--SHA256SUMS.txt. +# Filee--win-Portable.zip and Filee--SHA256SUMS.txt for x64, and the same for Windows on ARM64 +# (#236), built and tested on an ARM64 runner: Filee--win-arm64-Setup.exe, -win-arm64-Portable.zip and +# -win-arm64-SHA256SUMS.txt. # The release is a draft with the Linux and macOS packages: the Windows files are signed on a PC signed in to Certum's -# SimplySign cloud (its key needs a phone token), so this run keeps the tested, unsigned build as the artifact -# windows-unsigned, and build/sign-release.ps1 signs it, packs Setup again, uploads the Windows files and publishes. +# SimplySign cloud (its key needs a phone token), so this run keeps the tested, unsigned builds as the artifacts +# windows-unsigned and windows-arm64-unsigned, and build/sign-release.ps1 signs them, packs both Setups again, uploads +# the Windows files and publishes. The draft waits for both Windows builds, so a release never lacks one of them. # The SHA256SUMS files are signed there too, with the update key that never leaves that PC: it uploads a .sig next to # every SHA256SUMS file of the release (the Linux and macOS ones drafted here as well), and official builds refuse an # update without one. @@ -109,6 +112,106 @@ jobs: if-no-files-found: error retention-days: 30 + # Windows on ARM64, built and tested natively like CI's build (win-arm64) job: the app, Setup, the Explorer menu DLL, + # 7-Zip, rhwp and Unhwp's library are ARM64 builds (rhwp and Unhwp from the pins in build/fetch-engines.ps1). + windows-arm64: + needs: portable + runs-on: windows-11-arm + timeout-minutes: 120 + defaults: + run: + shell: pwsh + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - name: Version from tag + id: version + run: | + $version = '${{ github.ref_name }}'.TrimStart('v') + "value=$version" >> $env:GITHUB_OUTPUT + + # CI builds without them (and skips their tests); a release doesn't. + - name: ARM64 pins + run: | + $missing = @(./build/fetch-engines.ps1 -Runtime win-arm64 -MissingPins) + if ($missing) { throw "Not pinned for win-arm64: $($missing -join ', ') (build/fetch-engines.ps1)." } + + - name: Fonts + run: ./build/fetch-fonts.ps1 + + # Unhwp's library goes next to the test programs through the build. + - name: Fetch engines for engine tests + run: ./build/fetch-engines.ps1 -Runtime win-arm64 -Only pandoc,7zip,rhwp,unhwp + + - name: Build + run: | + dotnet build Filee.slnx -c Release "-p:UnhwpNativeLibrary=$((Resolve-Path engines/unhwp/unhwp.dll).Path)" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + # The x64 Zig toolchain CI's build job saves; it cross-compiles the ARM64 DLL under x64 emulation. + - name: Restore Zig toolchain + uses: actions/cache/restore@v5 + with: + path: build/.cache/zig-x86_64-windows-0.16.0 + key: zig-0.16.0-x86_64-windows + + - name: Build Explorer menu extension + timeout-minutes: 30 + run: ./build/build-explorer-menu.ps1 -Architecture arm64 -Version ${{ steps.version.outputs.value }} + + - name: Test UI on its own + run: dotnet test tests/Filee.App.Tests --no-build -c Release --blame-crash --blame-hang-timeout 5m --logger "console;verbosity=normal" --results-directory TestResults/app + + - name: Test + run: dotnet test Filee.slnx --no-build -c Release --filter "FullyQualifiedName!~Filee.App.Tests" --logger "trx" --results-directory TestResults + + # Setup around a stub app, installed, updated and uninstalled in a sandbox: the PC that signs the release is + # x64 and can't run the ARM64 Setup. + - name: Check the installer + run: ./build/build-installer.ps1 -CheckOnly -Runtime win-arm64 + + - name: Upload test results + if: failure() + uses: actions/upload-artifact@v7 + with: + name: test-results-windows-arm64 + path: TestResults/ + if-no-files-found: ignore + + - name: Build installer and portable zip + run: ./build/build-installer.ps1 -Version ${{ steps.version.outputs.value }} -Runtime win-arm64 -Portable + + # Laid out like windows-unsigned, for build/sign-release.ps1. + - name: Keep the unsigned Windows ARM64 build + run: | + New-Item -ItemType Directory -Force -Path unsigned | Out-Null + Move-Item publish/win-arm64 unsigned/app + Copy-Item build/.cache/setup/Filee.Setup.exe unsigned/ + + - uses: actions/upload-artifact@v7 + with: + name: windows-arm64-unsigned + path: unsigned/ + if-no-files-found: error + retention-days: 30 + + draft: + needs: [portable, windows, windows-arm64] + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + + - name: Version from tag + id: version + shell: pwsh + run: | + $version = '${{ github.ref_name }}'.TrimStart('v') + "value=$version" >> $env:GITHUB_OUTPUT + - name: Download Linux and macOS packages uses: actions/download-artifact@v8 with: @@ -123,7 +226,8 @@ jobs: run: | $version = '${{ steps.version.outputs.value }}' # Linux and macOS only: build/sign-release.ps1 adds the signed Windows files. - $windows = "Filee-$version-win-Setup.exe", "Filee-$version-win-Portable.zip", "Filee-$version-SHA256SUMS.txt" + $windows = "Filee-$version-win-Setup.exe", "Filee-$version-win-Portable.zip", "Filee-$version-SHA256SUMS.txt", + "Filee-$version-win-arm64-Setup.exe", "Filee-$version-win-arm64-Portable.zip", "Filee-$version-win-arm64-SHA256SUMS.txt" $files = Get-ChildItem Releases -File -Filter "Filee-$version-*" | Where-Object Name -notin $windows | ForEach-Object FullName # "## 1.4.0" up to the next "## " heading of CHANGELOG.md, without the heading itself. $changes = '' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ed606c8eb..71f160153 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -117,9 +117,10 @@ Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short: Bump `` in `Directory.Build.props`, merge, then push a tag `vX.Y.Z`. `.github/workflows/release.yml` runs the tests and `build/build-installer.ps1 -Portable`: it publishes the app (`-p:FileeRelease=true`, which lets it register Explorer and startup entries), adds the Explorer menu extension and the bundled rhwp and 7-Zip, compiles -`src/Filee.Setup` (Filee's own installer) and appends the app to it. It drafts the release with the Linux and macOS -packages and release notes generated from the merged pull requests, and keeps the tested Windows build unsigned (the -artifact `windows-unsigned`). +`src/Filee.Setup` (Filee's own installer) and appends the app to it, for x64 and, on a Windows 11 ARM64 runner, for +Windows on ARM64 (`-Runtime win-arm64`). It keeps both tested Windows builds unsigned (the artifacts +`windows-unsigned` and `windows-arm64-unsigned`) and then drafts the release with the Linux and macOS packages and +release notes generated from the merged pull requests. Then, on a PC signed in to SimplySign Desktop (Certum's cloud certificate; its key needs the phone app's token), sign the Windows files and add them to the draft: @@ -128,12 +129,14 @@ the Windows files and add them to the draft: pwsh build/sign-release.ps1 -Version X.Y.Z -CertificateThumbprint -UpdateKey ``` -It signs every unsigned program in the build and the Setup program, packs and signs `Filee-X.Y.Z-win-Setup.exe`, zips -the portable copy, checks the signed Setup in a sandbox install and uploads the files with their SHA-256 sums. It signs +It signs every unsigned program in both builds and their Setup programs, packs and signs `Filee-X.Y.Z-win-Setup.exe` +and `Filee-X.Y.Z-win-arm64-Setup.exe`, zips the portable copies, checks the signed x64 Setup in a sandbox install (and +the ARM64 one too on an ARM64 PC; on an x64 PC it checks the ARM64 signatures without running it) and uploads the +files with their SHA-256 sums (`Filee-X.Y.Z-SHA256SUMS.txt`, `Filee-X.Y.Z-win-arm64-SHA256SUMS.txt`). It signs every `SHA256SUMS` file of the release (Windows, Linux and macOS) with Filee's update key and uploads the `.sig` files -next to them (`build/sign-checksums.ps1`; it asks for the key's passphrase). It also copies the Windows files to the -download mirror `https://dl.filee.sh/X.Y.Z/` (Cloudflare R2; needs `npx wrangler login` once), which the Microsoft -Store listing points at because GitHub's download links redirect. Look over the draft and publish it (or pass +next to them (`build/sign-checksums.ps1`; it asks for the key's passphrase once). It also copies the Windows files to +the download mirror `https://dl.filee.sh/X.Y.Z/` (Cloudflare R2; needs `npx wrangler login` once), which the +Microsoft Store listing points at because GitHub's download links redirect. Look over the draft and publish it (or pass `-Publish`). `build/sign-windows.ps1` signs any folder or file on its own. The update key is made once with `pwsh build/new-update-key.ps1 -PrivateKeyPath `. Its diff --git a/README.md b/README.md index 54a4b0e87..551046780 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: run `Filee--win-Setup.exe`, or unzip the `win-Portable.zip` and run `Filee.exe`. + - On a Windows on ARM PC (Settings → System → About says "ARM-based processor"), take `win-arm64-Setup.exe` or `win-arm64-Portable.zip` instead: it runs natively, not under x64 emulation. - Setup is Filee's own installer, in Filee's languages, and needs nothing else on the PC. - It can add the Explorer menu, start at sign-in, the `filee` command and optional engines. - Silent installs take Inno Setup's switches (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/build/build-installer.ps1 b/build/build-installer.ps1 index aeb6240cf..5f0d5ec96 100644 --- a/build/build-installer.ps1 +++ b/build/build-installer.ps1 @@ -18,7 +18,8 @@ win-x64 (default) or win-arm64. The ARM64 build (Filee--win-arm64-Setup.exe and -Portable.zip) has an ARM64 Setup, Explorer menu DLL, rhwp, 7-Zip and Unhwp library (fetch-engines.ps1 -Runtime win-arm64, which fails while the ARM64 rhwp and Unhwp builds are not pinned yet). They link the C runtime statically: no Microsoft C++ runtime - DLLs are copied. + DLLs are copied. With -PublishDir and -SetupProgram from an ARM64 build it signs and packs on an x64 PC too + (build/sign-release.ps1); -CheckOnly runs the ARM64 Setup, so it needs Windows on ARM. .PARAMETER CertificateThumbprint Signs the release (build/sign-windows.ps1): the programs in the publish folder that come unsigned, the Setup @@ -152,7 +153,7 @@ Write-Host "pack installer $Version" $fast = @(if ($CheckOnly) { '--fast' }) Push-Location $root try { - Invoke-Checked 'make-setup' { dotnet run --no-cache build/tools/make-setup.cs -- $SetupProgram $PublishDir $Version $setupExe @fast } + Invoke-Checked 'make-setup' { dotnet run --no-cache build/tools/make-setup.cs -- $SetupProgram $PublishDir $Version $setupExe "--runtime=$Runtime" @fast } } finally { Pop-Location diff --git a/build/sign-release.ps1 b/build/sign-release.ps1 index 2ce8350fe..5834cd5de 100644 --- a/build/sign-release.ps1 +++ b/build/sign-release.ps1 @@ -4,24 +4,29 @@ once the release workflow of the tag has finished. .DESCRIPTION - The release workflow tests and builds the tag, keeps the unsigned Windows build (artifact windows-unsigned: the - publish folder and the Setup program) and drafts the release with the Linux and macOS packages. This script: - - 1. downloads that build, exactly as it was tested; - 2. checks out the tag in a worktree and runs its build-installer.ps1 with -CertificateThumbprint, which signs the - unsigned programs and the Setup program, packs Setup.exe, signs it, zips the portable copy and writes the - SHA-256 sums; + The release workflow tests and builds the tag, keeps the unsigned Windows builds (artifacts windows-unsigned and + windows-arm64-unsigned: the publish folder and the Setup program of each) and drafts the release with the Linux and + macOS packages. This script: + + 1. downloads those builds, exactly as they were tested; + 2. checks out the tag in a worktree and runs its build-installer.ps1 with -CertificateThumbprint for each, which + signs the unsigned programs and the Setup program, packs Setup.exe, signs it, zips the portable copy and writes + the SHA-256 sums (x64: Filee--win-Setup.exe, -win-Portable.zip and Filee--SHA256SUMS.txt; + ARM64: Filee--win-arm64-Setup.exe, -win-arm64-Portable.zip and -win-arm64-SHA256SUMS.txt); 3. installs the signed Setup into a sandbox (nothing on the PC is touched) and checks that Filee.exe and - uninstall.exe come out signed, then uninstalls it; - 4. signs every SHA256SUMS file of the release (Windows, and the Linux and macOS ones from the draft) with Filee's - update key (build/sign-checksums.ps1, -UpdateKey), which writes a .sig file next to each; - 5. uploads Filee--win-Setup.exe, the portable zip, Filee--SHA256SUMS.txt and the .sig files to - the draft; - 6. copies the Windows files and their checksum signature to the download mirror, Cloudflare R2 behind + uninstall.exe come out signed, then uninstalls it. An x64 PC can't run the ARM64 Setup: there it checks the + signatures of the ARM64 Setup.exe and of the signed files that went into it instead (the release workflow ran + the ARM64 Setup program in a sandbox on Windows on ARM, around a stub app); + 4. signs every SHA256SUMS file of the release (both Windows ones, and the Linux and macOS ones from the draft) with + Filee's update key (build/sign-checksums.ps1, -UpdateKey), which writes a .sig file next to each; + 5. uploads the Windows files and the .sig files to the draft; + 6. copies the Windows files and their checksum signatures to the download mirror, Cloudflare R2 behind https://dl.filee.sh//, and checks that each one is served there as is (no redirect, the same size). The - Microsoft Store takes Setup.exe from that address, because GitHub's download links redirect; + Microsoft Store takes the Setup programs from that address, because GitHub's download links redirect; 7. with -Publish, publishes the release. + A tag whose release workflow keeps no ARM64 build (2.4.0 and earlier) gets the x64 files only. + When the tag's Directory.Build.props carries an update key (FileeUpdatePublicKey), its builds refuse an update without signed checksums: the script then stops early without -UpdateKey, checks that the private key belongs to that public key, and doesn't publish while a SHA256SUMS file on the draft has no .sig next to it. @@ -77,12 +82,26 @@ if ($UpdateKey -and -not (Test-Path -LiteralPath $UpdateKey -PathType Leaf)) { t $work = Join-Path $PSScriptRoot ".cache\release-$Version" $source = Join-Path $work 'source' -if (Test-Path $source) { Invoke-Checked 'git worktree remove' { git -C $root worktree remove --force $source } } +# git can't delete paths longer than 260 characters, and the worktree has some once make-setup.cs has built its +# projects in it: PowerShell deletes what is left, and git forgets the worktree. +function Remove-Source { + if (Test-Path -LiteralPath $source) { + git -C $root worktree remove --force $source + if (Test-Path -LiteralPath $source) { Remove-Item -LiteralPath $source -Recurse -Force } + } + git -C $root worktree prune +} +Remove-Source Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $work | Out-Null -Write-Host "download the unsigned build of run $($run.databaseId)" +# The release workflow keeps an ARM64 build after 2.4.0 (#236); older tags have only the x64 one. +$arm64 = (git -C $root show "${tag}:.github/workflows/release.yml" | Out-String) -match 'windows-arm64-unsigned' +Write-Host "download the unsigned Windows build$(if ($arm64) { 's (x64, ARM64)' }) of run $($run.databaseId)" Invoke-Checked 'gh run download' { gh run download $run.databaseId --name windows-unsigned --dir (Join-Path $work 'unsigned') } +if ($arm64) { + Invoke-Checked 'gh run download' { gh run download $run.databaseId --name windows-arm64-unsigned --dir (Join-Path $work 'unsigned-arm64') } +} Invoke-Checked 'git worktree add' { git -C $root worktree add --detach $source $tag } try { @@ -90,13 +109,22 @@ try { & (Join-Path $source 'build\build-installer.ps1') -Version $Version -Portable -OutputDir $out ` -PublishDir (Join-Path $work 'unsigned\app') -SetupProgram (Join-Path $work 'unsigned\Filee.Setup.exe') ` -CertificateThumbprint $CertificateThumbprint + if ($arm64) { + & (Join-Path $source 'build\build-installer.ps1') -Version $Version -Portable -OutputDir $out -Runtime win-arm64 ` + -PublishDir (Join-Path $work 'unsigned-arm64\app') -SetupProgram (Join-Path $work 'unsigned-arm64\Filee.Setup.exe') ` + -CertificateThumbprint $CertificateThumbprint + } } finally { - git -C $root worktree remove --force $source + Remove-Source } $setup = Join-Path $out "Filee-$Version-win-Setup.exe" $files = @($setup, (Join-Path $out "Filee-$Version-win-Portable.zip"), (Join-Path $out "Filee-$Version-SHA256SUMS.txt")) +$setupArm64 = Join-Path $out "Filee-$Version-win-arm64-Setup.exe" +if ($arm64) { + $files += @($setupArm64, (Join-Path $out "Filee-$Version-win-arm64-Portable.zip"), (Join-Path $out "Filee-$Version-win-arm64-SHA256SUMS.txt")) +} foreach ($file in $files) { if (-not (Test-Path $file)) { throw "$file was not written." } } # The signed Setup still finds its payload, and what it installs is signed, the uninstaller too. @@ -105,24 +133,43 @@ function Invoke-Setup([string]$exe) { $process = Start-Process -FilePath $exe -ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', "/SANDBOX=`"$sandbox`"") -Wait -PassThru if ($process.ExitCode -ne 0) { throw "$(Split-Path $exe -Leaf) failed in the sandbox with exit code $($process.ExitCode) (logs: $sandbox\Temp)" } } -Write-Host 'install the signed Setup into a sandbox' -Invoke-Setup $setup -$installed = Join-Path $sandbox 'Program Files\Filee' -foreach ($file in 'Filee.exe', 'filee-cli.exe', 'uninstall.exe', 'engines\rhwp\rhwp.exe') { - $signature = Get-AuthenticodeSignature (Join-Path $installed $file) - if ($signature.Status -ne 'Valid') { throw "$file is not signed after installing ($($signature.Status))." } +# Programs Setup installs that must come out signed: the app's own, and rhwp, which comes unsigned. +$programs = 'Filee.exe', 'filee-cli.exe', 'engines\rhwp\rhwp.exe' +function Assert-Signed([string]$folder, [string[]]$names, [string]$where) { + foreach ($file in $names) { + $signature = Get-AuthenticodeSignature (Join-Path $folder $file) + if ($signature.Status -ne 'Valid') { throw "$file is not signed $where ($($signature.Status))." } + } +} +function Test-Setup([string]$exe) { + Write-Host "install the signed $(Split-Path $exe -Leaf) into a sandbox" + Invoke-Setup $exe + $installed = Join-Path $sandbox 'Program Files\Filee' + Assert-Signed $installed ($programs + 'uninstall.exe') 'after installing' + Invoke-Setup (Join-Path $installed 'uninstall.exe') + Remove-Item $sandbox -Recurse -Force -ErrorAction SilentlyContinue +} +Test-Setup $setup +if ($arm64 -and [Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq 'Arm64') { + Test-Setup $setupArm64 +} +elseif ($arm64) { + # What its payload was packed from, signed in place by build-installer.ps1, and the Setup program, which Setup + # writes out as uninstall.exe. The release workflow ran the ARM64 Setup program in a sandbox (around a stub app). + Write-Host 'check the signatures of the ARM64 build (an x64 PC cannot run its Setup)' + Assert-Signed (Join-Path $work 'unsigned-arm64\app') $programs 'in the ARM64 build' + Assert-Signed (Join-Path $work 'unsigned-arm64') 'Filee.Setup.exe' 'in the ARM64 build' + Assert-Signed $out (Split-Path $setupArm64 -Leaf) 'after packing' } -Invoke-Setup (Join-Path $installed 'uninstall.exe') -Remove-Item $sandbox -Recurse -Force -ErrorAction SilentlyContinue -# Every SHA256SUMS file of the release, signed: the Linux and macOS ones the workflow put on the draft, and the new -# Windows one. +# Every SHA256SUMS file of the release, signed in one go (one passphrase): the Linux and macOS ones the workflow put +# on the draft, and the new Windows ones. $signatures = @() if ($UpdateKey) { $sums = Join-Path $work 'sums' New-Item -ItemType Directory -Force -Path $sums | Out-Null Invoke-Checked 'gh release download' { gh release download $tag --pattern '*SHA256SUMS.txt' --dir $sums --clobber } - Copy-Item (Join-Path $out "Filee-$Version-SHA256SUMS.txt") $sums -Force + Copy-Item @($files | Where-Object { $_ -like '*SHA256SUMS.txt' }) $sums -Force $signatures = @(& (Join-Path $PSScriptRoot 'sign-checksums.ps1') -Folder $sums -PrivateKeyPath $UpdateKey -PublicKey $publicKey) } @@ -135,7 +182,8 @@ if (-not $NoMirror) { $mirror = "https://dl.filee.sh/$Version" $types = @{ '.exe' = 'application/vnd.microsoft.portable-executable'; '.zip' = 'application/zip'; '.txt' = 'text/plain; charset=utf-8' '.sig' = 'text/plain; charset=utf-8' } - $mirrored = $files + @($signatures | Where-Object { (Split-Path $_ -Leaf) -eq "Filee-$Version-SHA256SUMS.txt.sig" }) + $windowsSignatures = @($files | Where-Object { $_ -like '*SHA256SUMS.txt' } | ForEach-Object { "$(Split-Path $_ -Leaf).sig" }) + $mirrored = $files + @($signatures | Where-Object { (Split-Path $_ -Leaf) -in $windowsSignatures }) foreach ($file in $mirrored) { $name = Split-Path $file -Leaf Write-Host "copy $name to $mirror" diff --git a/build/tools/make-setup.cs b/build/tools/make-setup.cs index f0730bdf2..0fd1d6241 100644 --- a/build/tools/make-setup.cs +++ b/build/tools/make-setup.cs @@ -2,22 +2,27 @@ // src/Filee.Setup/Payload/SetupPayload.cs) to the published Setup program. The engines Setup offers on a fresh install // come from EngineDownloads (engines.json), so Setup offers exactly what Settings → Engines offers. // Run by build/build-installer.ps1: -// dotnet run build/tools/make-setup.cs -- [--fast] +// dotnet run build/tools/make-setup.cs -- [--fast] [--runtime=win-arm64] // LZMA with a 48 MB dictionary, programs through the x86 branch filter; --fast uses a small dictionary, for checks. +// --runtime is the build the payload is (win-x64 by default): build/sign-release.ps1 packs the ARM64 Setup on an x64 PC, +// and it offers the engines of the ARM64 app. Both download the win-x64 engines on Windows 11 (EngineDownloads), so +// only the package list differs. #:project ../../src/Filee.Setup/Filee.Setup.csproj #:project ../../src/Filee.Engines/Filee.Engines.csproj #:property PublishAot=false using System.Diagnostics; using System.Reflection; +using System.Runtime.InteropServices; using Filee.Engines.Infrastructure; using Filee.Setup.Payload; var fast = args.Contains("--fast"); -var positional = args.Where(a => a != "--fast").ToArray(); -if (positional.Length != 4) +var runtime = args.FirstOrDefault(a => a.StartsWith("--runtime=", StringComparison.Ordinal))?["--runtime=".Length..] ?? "win-x64"; +var positional = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray(); +if (positional.Length != 4 || runtime is not ("win-x64" or "win-arm64")) { - Console.Error.WriteLine("usage: dotnet run build/tools/make-setup.cs -- [--fast]"); + Console.Error.WriteLine("usage: dotnet run build/tools/make-setup.cs -- [--fast] [--runtime=win-x64|win-arm64]"); return 2; } var (program, app, version, output) = (positional[0], positional[1], positional[2], positional[3]); @@ -31,7 +36,7 @@ // LibreOffice and come with it, so they have no folder of their own. var marker = (string?)typeof(EngineInstaller).GetField("MarkerName", BindingFlags.NonPublic | BindingFlags.Static)?.GetRawConstantValue() ?? throw new InvalidOperationException("EngineInstaller.MarkerName not found"); -var engines = EngineDownloads.Packages +var engines = EngineDownloads.PackagesFor(runtime == "win-arm64" ? Architecture.Arm64 : Architecture.X64) .Where(EngineDownloads.CanDownload) .Select(p => new EngineOffer( p.Id, @@ -45,5 +50,5 @@ var manifest = SetupPayload.Write(program, app, Path.GetFullPath(output), version, engines, marker, fast, Console.WriteLine); var size = new FileInfo(output).Length; Console.WriteLine($"{manifest.Files.Count} files, {manifest.TotalSize / 1_000_000} MB -> {output} ({size / 1_000_000} MB) in {watch.Elapsed.TotalSeconds:0} s; " + - $"engines offered: {string.Join(", ", engines.Select(e => e.Suggested ? e.Id + "*" : e.Id))}"); + $"engines offered ({runtime}): {string.Join(", ", engines.Select(e => e.Suggested ? e.Id + "*" : e.Id))}"); return 0; diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 67ce7bd9d..bac07963c 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -179,7 +179,8 @@ app, the command line and Setup for win-arm64, the Explorer menu DLL for ARM64 ( -Architecture arm64`, packaged as `arm64`), and ARM64 builds of the bundled engines (`fetch-engines.ps1 -Runtime win-arm64`). The engines the app downloads stay x64: on Windows 11 on ARM, which runs them under emulation, the app offers the win-x64 downloads (`EngineDownloads.DownloadRuntime`); Windows 10 on ARM can't run them and gets none. -Setup's engine list is made when it is packed (`build/tools/make-setup.cs`), so the ARM64 Setup offers the x64 one. +Setup's engine list is made when it is packed (`build/tools/make-setup.cs --runtime=win-arm64`, also on the x64 PC +that signs the release): the x64 downloads, without the packages the ARM64 app has none of (the upscaler). - **7-Zip**: the official ARM64 installer of the version engines.json pins, a 7z self-extracting archive unpacked by the x64 7-Zip (Windows' `tar.exe` can't undo its ARM64 executable filter). @@ -192,7 +193,10 @@ Setup's engine list is made when it is packed (`build/tools/make-setup.cs`), so `UnhwpConverter` reports Unhwp as available where its library loads, so a build without it shows the engine as not available on this platform. CI's `build (win-arm64)` job builds and tests on Windows 11 ARM64; once both pins are filled -in it also builds the package (artifact `windows-arm64-package`). +in it also builds the package (artifact `windows-arm64-package`). Releases ship it next to the x64 files: the release +workflow's `windows-arm64` job builds and tests it the same way and keeps it unsigned for `build/sign-release.ps1` +(see [Releasing](../CONTRIBUTING.md#releasing-maintainers)), and the in-app updater of an ARM64 build takes +`-win-arm64-Setup.exe` and `-win-arm64-SHA256SUMS.txt` (an x64 build keeps to the x64 files, also on Windows on ARM). ## Images and vector graphics diff --git a/docs/readme/README.ar.md b/docs/readme/README.ar.md index c4b19043e..0c94c94e6 100644 --- a/docs/readme/README.ar.md +++ b/docs/readme/README.ar.md @@ -95,6 +95,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: شغّل `Filee--win-Setup.exe`، أو فكّ ضغط `win-Portable.zip` وشغّل `Filee.exe`. + - على حاسوب Windows on ARM (تظهر عبارة «معالج يستند إلى ARM» في الإعدادات ← النظام ← حول)، استخدم `win-arm64-Setup.exe` أو `win-arm64-Portable.zip` بدلًا من ذلك: فهو يعمل أصليًا، لا عبر محاكاة x64. - برنامج الإعداد خاص بـ Filee، ويعمل بلغات Filee، ولا يحتاج إلى أي شيء آخر على الكمبيوتر. - يمكنه إضافة قائمة مستكشف الملفات، والتشغيل عند تسجيل الدخول، والأمر `filee`، والمحركات الاختيارية. - وتقبل عمليات التثبيت الصامت مفاتيح Inno Setup نفسها (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.bn-BD.md b/docs/readme/README.bn-BD.md index f1f6ec395..d92c74bd2 100644 --- a/docs/readme/README.bn-BD.md +++ b/docs/readme/README.bn-BD.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: `Filee--win-Setup.exe` চালান, অথবা `win-Portable.zip` আনজিপ করে `Filee.exe` চালান। + - Windows on ARM পিসিতে (Settings → System → About-এ "ARM-based processor" লেখা থাকে) এর বদলে `win-arm64-Setup.exe` বা `win-arm64-Portable.zip` নিন: এটি x64 ইমুলেশনে নয়, সরাসরি নেটিভভাবে চলে। - Setup হলো Filee-র নিজস্ব ইনস্টলার, Filee-র বিভিন্ন ভাষায় উপলব্ধ, এবং কম্পিউটারে অন্য কিছুর প্রয়োজন পড়ে না। - এটি Explorer মেনু, সাইন-ইনের সময় স্বয়ংক্রিয় চালু, `filee` কমান্ড এবং ঐচ্ছিক ইঞ্জিনগুলো যোগ করতে পারে। - সাইলেন্ট ইনস্টলেশন Inno Setup-এর সুইচগুলো সমর্থন করে (`/VERYSILENT /SUPPRESSMSGBOXES`)। diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index 04f213fac..c2120b0d7 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: ejecuta `Filee--win-Setup.exe`, o descomprime `win-Portable.zip` y ejecuta `Filee.exe`. + - En un PC con Windows on ARM (Configuración → Sistema → Información indica «procesador basado en ARM»), usa `win-arm64-Setup.exe` o `win-arm64-Portable.zip`: se ejecuta de forma nativa, sin emulación x64. - El instalador es el propio de Filee, está en los idiomas de Filee y no necesita nada más en el equipo. - Puede añadir el menú del Explorador, el inicio al iniciar sesión, el comando `filee` y motores opcionales. - Las instalaciones silenciosas aceptan las opciones de Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.fa.md b/docs/readme/README.fa.md index 1b1a0730f..557ee387c 100644 --- a/docs/readme/README.fa.md +++ b/docs/readme/README.fa.md @@ -95,6 +95,7 @@ winget install KnifeLemon.Filee ``` - **ویندوز ۱۰ و ۱۱**: فایل `Filee--win-Setup.exe` را اجرا کنید، یا نسخه پرتابل `win-Portable.zip` را از حالت فشرده خارج کرده و `Filee.exe` را اجرا نمایید. + - روی رایانه‌های Windows on ARM (در Settings → System → About عبارت «ARM-based processor» دیده می‌شود)، به‌جای آن `win-arm64-Setup.exe` یا `win-arm64-Portable.zip` را بگیرید: به‌صورت بومی اجرا می‌شود، نه با شبیه‌سازی x64. - نصاب Filee نرم‌افزار اختصاصی خود آن است، به زبان‌های مختلف برنامه ارائه می‌شود و به برنامه دیگری نیاز ندارد. - می‌تواند منوی راست‌کلیک Explorer، اجرا در هنگام ورود به سیستم، دستور `filee` و موتورهای اختیاری را اضافه کند. - برای نصب بی‌صدا از سوئیچ‌های Inno Setup استفاده کنید (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.fr.md b/docs/readme/README.fr.md index d1273f2b8..7470e65b1 100644 --- a/docs/readme/README.fr.md +++ b/docs/readme/README.fr.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11** : exécutez `Filee--win-Setup.exe`, ou décompressez `win-Portable.zip` et lancez `Filee.exe`. + - Sur un PC Windows on ARM (Paramètres → Système → Informations système indique « processeur ARM »), prenez plutôt `win-arm64-Setup.exe` ou `win-arm64-Portable.zip` : il s'exécute en natif, sans émulation x64. - Le programme d'installation est celui de Filee, dans les langues de Filee, et ne demande rien d'autre sur le PC. - Il peut ajouter le menu de l'Explorateur, le démarrage à l'ouverture de session, la commande `filee` et des moteurs facultatifs. - Les installations silencieuses acceptent les options d'Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.hi.md b/docs/readme/README.hi.md index 684bd7618..565aa1df9 100644 --- a/docs/readme/README.hi.md +++ b/docs/readme/README.hi.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: `Filee--win-Setup.exe` चलाएँ, या `win-Portable.zip` को अनज़िप करके `Filee.exe` चलाएँ। + - Windows on ARM पीसी पर (Settings → System → About में "ARM-based processor" लिखा होता है) इसकी जगह `win-arm64-Setup.exe` या `win-arm64-Portable.zip` लें: यह x64 एमुलेशन के बिना, सीधे नेटिव रूप से चलता है। - सेटअप Filee का अपना इंस्टॉलर है, Filee की ही भाषाओं में, और PC पर इसके लिए कुछ और नहीं चाहिए। - यह Explorer मेनू, साइन इन पर Filee शुरू करना, `filee` कमांड और वैकल्पिक इंजन जोड़ सकता है। - साइलेंट इंस्टॉल Inno Setup के स्विच (`/VERYSILENT /SUPPRESSMSGBOXES`) लेते हैं। diff --git a/docs/readme/README.id.md b/docs/readme/README.id.md index c5063de73..ba8352ffa 100644 --- a/docs/readme/README.id.md +++ b/docs/readme/README.id.md @@ -91,6 +91,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: Jalankan `Filee--win-Setup.exe`, atau ekstrak `win-Portable.zip` lalu jalankan `Filee.exe`. + - Di PC Windows on ARM (Settings → System → About menampilkan "ARM-based processor"), gunakan `win-arm64-Setup.exe` atau `win-arm64-Portable.zip`: berjalan secara native, bukan lewat emulasi x64. - Installer bawaan Filee mendukung berbagai bahasa dan tidak memerlukan dependensi tambahan di PC. - Opsi instalasi mencakup: integrasi menu klik kanan Explorer, jalan otomatis saat login (*start at sign-in*), perintah CLI `filee`, serta engine opsional. - Untuk instalasi senyap (*silent install*), gunakan opsi bawaan Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.it.md b/docs/readme/README.it.md index 9bae4a10c..d6959767d 100644 --- a/docs/readme/README.it.md +++ b/docs/readme/README.it.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: esegui `Filee--win-Setup.exe`, oppure decomprimi `win-Portable.zip` ed esegui `Filee.exe`. + - Su un PC Windows on ARM (Impostazioni → Sistema → Informazioni riporta «processore basato su ARM»), usa invece `win-arm64-Setup.exe` o `win-arm64-Portable.zip`: funziona in modo nativo, senza emulazione x64. - Setup è l'installer proprio di Filee, nelle lingue di Filee, e non richiede altro sul PC. - Può aggiungere la voce nel menu di Esplora risorse, l'avvio all'accesso, il comando `filee` ed engine opzionali. - Le installazioni silenziose accettano gli switch di Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index 2a0d386cd..d6711b644 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**:`Filee--win-Setup.exe`を実行するか、`win-Portable.zip`を展開して`Filee.exe`を実行します。 + - Windows on ARMのPC(設定 → システム → バージョン情報に「ARMベースプロセッサ」と表示)では、代わりに`win-arm64-Setup.exe`または`win-arm64-Portable.zip`を使ってください。x64エミュレーションではなくネイティブで動きます。 - セットアップはFilee独自のインストーラーで、Fileeと同じ言語で表示され、PCにほかのソフトは必要ありません。 - エクスプローラーのメニュー、サインイン時の起動、`filee`コマンド、追加の変換エンジンを選べます。 - サイレントインストールにはInno Setupと同じスイッチ(`/VERYSILENT /SUPPRESSMSGBOXES`)が使えます。 diff --git a/docs/readme/README.ko.md b/docs/readme/README.ko.md index 9709a3358..ee2246981 100644 --- a/docs/readme/README.ko.md +++ b/docs/readme/README.ko.md @@ -94,6 +94,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: `Filee--win-Setup.exe`를 실행하거나, `win-Portable.zip`을 풀고 `Filee.exe`를 실행해요. + - Windows on ARM PC(설정 → 시스템 → 정보에 "ARM 기반 프로세서"로 표시)에서는 대신 `win-arm64-Setup.exe`나 `win-arm64-Portable.zip`을 받으세요. x64 에뮬레이션 없이 네이티브로 실행돼요. - 설치 프로그램은 Filee가 직접 만든 것이라 Filee와 같은 언어로 안내하고, PC에 따로 설치할 것이 없어요. - 설치할 때 탐색기 메뉴, 로그인 시 자동 실행, `filee` 명령, 추가 엔진을 고를 수 있어요. - 무인 설치에는 Inno Setup의 스위치(`/VERYSILENT /SUPPRESSMSGBOXES`)를 그대로 쓸 수 있어요. diff --git a/docs/readme/README.pl.md b/docs/readme/README.pl.md index 669e65c64..c8f95a115 100644 --- a/docs/readme/README.pl.md +++ b/docs/readme/README.pl.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: uruchom `Filee--win-Setup.exe` albo rozpakuj `win-Portable.zip` i uruchom `Filee.exe`. + - Na komputerze z Windows on ARM (Ustawienia → System → Informacje pokazuje „procesor oparty na architekturze ARM”) pobierz zamiast tego `win-arm64-Setup.exe` lub `win-arm64-Portable.zip`: działa natywnie, bez emulacji x64. - Setup to własny instalator Filee, mówi w językach Filee i nie potrzebuje na komputerze niczego więcej. - Może dodać menu Eksploratora, uruchamianie po zalogowaniu, polecenie `filee` i opcjonalne silniki. - Instalacja cicha przyjmuje przełączniki Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.pt-BR.md b/docs/readme/README.pt-BR.md index c7ccc49a9..c5ac4e9f0 100644 --- a/docs/readme/README.pt-BR.md +++ b/docs/readme/README.pt-BR.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: execute `Filee--win-Setup.exe`, ou descompacte o `win-Portable.zip` e execute `Filee.exe`. + - Em um PC com Windows on ARM (Configurações → Sistema → Sobre mostra "processador baseado em ARM"), use `win-arm64-Setup.exe` ou `win-arm64-Portable.zip`: ele roda nativamente, sem emulação x64. - A instalação é o instalador do próprio Filee, nos idiomas do Filee, e não precisa de mais nada no PC. - Ela pode adicionar o menu do Explorador, iniciar com o Windows, o comando `filee` e motores opcionais. - Instalações silenciosas usam as opções do Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.pt-PT.md b/docs/readme/README.pt-PT.md index 14bbf2e48..c5beee1a5 100644 --- a/docs/readme/README.pt-PT.md +++ b/docs/readme/README.pt-PT.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: executa `Filee--win-Setup.exe` ou extrai o `win-Portable.zip` e executa `Filee.exe`. + - Num PC com Windows on ARM (Definições → Sistema → Acerca de indica "processador baseado em ARM"), usa `win-arm64-Setup.exe` ou `win-arm64-Portable.zip`: corre de forma nativa, sem emulação x64. - O Filee tem um instalador próprio, disponível nos idiomas da aplicação, que não precisa de mais nada no computador. - Permite adicionar o menu do Explorador, o arranque ao iniciar sessão, o comando `filee` e motores opcionais. - As instalações silenciosas aceitam as opções do Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index cffedeafc..216e684f7 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: запустите `Filee--win-Setup.exe` или распакуйте `win-Portable.zip` и запустите `Filee.exe`. + - На ПК с Windows on ARM (в «Параметры → Система → О программе» указано «процессор на базе ARM») берите `win-arm64-Setup.exe` или `win-arm64-Portable.zip`: они работают нативно, без эмуляции x64. - Setup — собственный установщик Filee: он говорит на тех же языках, что и Filee, и ничего не требует от компьютера. - Он может добавить пункт в меню Проводника, автозапуск при входе в систему, команду `filee` и дополнительные движки. - Для тихой установки подходят ключи Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.th.md b/docs/readme/README.th.md index 3fc0192ef..f2e9aede4 100644 --- a/docs/readme/README.th.md +++ b/docs/readme/README.th.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: รัน `Filee--win-Setup.exe` หรือแตกไฟล์ `win-Portable.zip` แล้วเปิด `Filee.exe` + - บนพีซี Windows on ARM (การตั้งค่า → ระบบ → เกี่ยวกับ แสดงว่า "ARM-based processor") ให้ใช้ `win-arm64-Setup.exe` หรือ `win-arm64-Portable.zip` แทน ซึ่งทำงานแบบเนทีฟ ไม่ต้องผ่านการจำลอง x64 - ตัวติดตั้ง Setup เป็นของ Filee เอง มีเมนูภาษาไทย และไม่ต้องติดตั้งโปรแกรมเสริมใดๆ - สามารถเพิ่มลงในเมนูคลิกขวาของ Explorer, ตั้งให้เปิดพร้อมระบบ, เพิ่มคำสั่ง `filee` และดาวน์โหลดเครื่องมือแปลงไฟล์เพิ่มเติมได้ - รองรับการติดตั้งแบบเงียบด้วยพารามิเตอร์ของ Inno Setup (`/VERYSILENT /SUPPRESSMSGBOXES`) diff --git a/docs/readme/README.tr.md b/docs/readme/README.tr.md index 51b2ab29b..8dad65df9 100644 --- a/docs/readme/README.tr.md +++ b/docs/readme/README.tr.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11**: `Filee--win-Setup.exe` dosyasını çalıştırın veya `win-Portable.zip` arşivini açıp `Filee.exe` dosyasını başlatın. + - Windows on ARM bilgisayarda (Ayarlar → Sistem → Hakkında bölümünde "ARM tabanlı işlemci" yazar) bunun yerine `win-arm64-Setup.exe` veya `win-arm64-Portable.zip` dosyasını alın: x64 öykünmesi olmadan yerel olarak çalışır. - Kurulum sihirbazı, Filee'nin kendi dillerini içeren yerel yükleyicisidir ve bilgisayarda başka hiçbir şeye ihtiyaç duymaz. - Dosya Gezgini menüsünü, oturum açılışında başlatmayı, `filee` komutunu ve isteğe bağlı motorları ekleyebilir. - Sessiz kurulumlar Inno Setup anahtarlarını destekler (`/VERYSILENT /SUPPRESSMSGBOXES`). diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index 99f1b7fff..ce4f9f6c9 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11** 运行 `Filee--win-Setup.exe`,或解压 `win-Portable.zip` 后运行 `Filee.exe`。 + - Windows on ARM 电脑(设置 → 系统 → 系统信息中显示“基于 ARM 的处理器”)请改用 `win-arm64-Setup.exe` 或 `win-arm64-Portable.zip`,它原生运行,不经过 x64 仿真。 - 安装程序是 Filee 自己的,使用与 Filee 相同的语言,电脑上无需另外安装任何组件。 - 安装时可以添加资源管理器菜单、登录时启动、`filee` 命令和可选引擎。 - 静默安装沿用 Inno Setup 的参数(`/VERYSILENT /SUPPRESSMSGBOXES`)。 diff --git a/docs/readme/README.zh-TW.md b/docs/readme/README.zh-TW.md index 0bc064c46..65b3165f3 100644 --- a/docs/readme/README.zh-TW.md +++ b/docs/readme/README.zh-TW.md @@ -93,6 +93,7 @@ winget install KnifeLemon.Filee ``` - **Windows 10/11** 執行 `Filee--win-Setup.exe`,或解壓縮 `win-Portable.zip` 後執行 `Filee.exe`。 + - Windows on ARM 電腦(設定 → 系統 → 關於中顯示「ARM 型處理器」)請改用 `win-arm64-Setup.exe` 或 `win-arm64-Portable.zip`,它以原生方式執行,不經過 x64 模擬。 - 安裝程式是 Filee 自己的,使用與 Filee 相同的語言,電腦上無需另外安裝任何元件。 - 安裝時可以新增檔案總管選單、登入時啟動、`filee` 命令和可選引擎。 - 靜默安裝沿用 Inno Setup 的參數(`/VERYSILENT /SUPPRESSMSGBOXES`)。 diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.cs index 58a1a759c..bd56dfb4a 100644 --- a/src/Filee.App/Services/UpdateService.cs +++ b/src/Filee.App/Services/UpdateService.cs @@ -131,13 +131,24 @@ internal static string GetLinuxRid(Architecture architecture) => var arch => throw new PlatformNotSupportedException($"Unsupported Linux architecture: {arch}"), }; - /// Target platform for release assets ("win", "linux-x64", "linux-arm64"). Tests can override this. + /// + /// The Windows release files for a process of : "win-arm64" for the native ARM64 + /// build, "win" (the x64 files) otherwise. It is the process, not the PC: the x64 build on Windows on ARM keeps + /// updating to the x64 build it is. + /// + internal static string GetWindowsTarget(Architecture architecture) => architecture == Architecture.Arm64 ? "win-arm64" : "win"; + + private static bool IsWindowsTarget(string target) => target is "win" or "win-arm64"; + + /// + /// Target platform for release assets ("win", "win-arm64", "linux-x64", "linux-arm64"). Tests can override this. + /// internal string TargetPlatform { get; set; } = DefaultTargetPlatform(); private static string DefaultTargetPlatform() { if (OperatingSystem.IsWindows()) - return "win"; + return GetWindowsTarget(RuntimeInformation.ProcessArchitecture); if (OperatingSystem.IsLinux()) { try @@ -268,6 +279,11 @@ internal async Task RefreshAsync(bool announce, CancellationToken cancella (_installer, _checksums) = TargetPlatform != "unsupported" ? FindFiles(json.RootElement, TargetPlatform) : (null, null); + // No other platform's installer instead: on an ARM64 build, a release with only the x64 Setup would install + // fine over it, but turn a native install into an emulated one without asking. Update then fails like for + // any release without this platform's installer, and the download page is still there. + if (newer is not null && _installer is null) + _log.LogInformation("Update check: {Tag} has no {Target} installer", tag, TargetPlatform); IReadOnlyList notes = []; if (newer is not null) { @@ -367,7 +383,7 @@ public async Task UpdateAsync() return; } - if (TargetPlatform == "win") + if (IsWindowsTarget(TargetPlatform)) { var folder = Path.Combine(Path.GetTempPath(), "Filee-update"); string installer; @@ -774,9 +790,12 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array) return (null, null); + // The x64 Windows files are the only ones without the platform in full: Filee--win-Setup.exe and + // Filee--SHA256SUMS.txt (older builds look for these names). var isLinux = target.StartsWith("linux-", StringComparison.OrdinalIgnoreCase); - var expectedInstallerSuffix = isLinux ? $"-{target}.tar.gz" : "-win-Setup.exe"; - var expectedChecksumsSuffix = isLinux ? $"-{target}-SHA256SUMS.txt" : "-SHA256SUMS.txt"; + var isX64Windows = target == "win"; + var expectedInstallerSuffix = isLinux ? $"-{target}.tar.gz" : $"-{target}-Setup.exe"; + var expectedChecksumsSuffix = isX64Windows ? "-SHA256SUMS.txt" : $"-{target}-SHA256SUMS.txt"; foreach (var asset in assets.EnumerateArray()) { @@ -792,8 +811,10 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE } else if (name.EndsWith(expectedChecksumsSuffix, StringComparison.OrdinalIgnoreCase)) { - // When targeting Windows, exclude platform-specific checksum files (e.g. -linux-x64-SHA256SUMS.txt, -osx-...) - if (!isLinux && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase))) + // Every other platform's checksum file ends in -SHA256SUMS.txt too (-linux-x64-, -osx-arm64-, -win-arm64-). + if (isX64Windows && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) + || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase) + || name.Contains("-win-arm64-", StringComparison.OrdinalIgnoreCase))) continue; checksums = new ReleaseFile(name, url, size); diff --git a/src/Filee.Engines/Infrastructure/EngineDownloads.cs b/src/Filee.Engines/Infrastructure/EngineDownloads.cs index 6d3d5320b..4be69cfa3 100644 --- a/src/Filee.Engines/Infrastructure/EngineDownloads.cs +++ b/src/Filee.Engines/Infrastructure/EngineDownloads.cs @@ -45,7 +45,13 @@ internal static string DownloadRuntime(string runtimeIdentifier, int windowsBuil /// /// Packages offered in Settings → Engines and on first run. rhwp and 7-Zip are not listed: they are small and bundled. /// - public static IReadOnlyList Packages { get; } = + public static IReadOnlyList Packages { get; } = PackagesFor(RuntimeInformation.ProcessArchitecture); + + /// + /// for a build of on this operating system: the ARM64 Setup + /// is packed on an x64 PC too (build/sign-release.ps1), and must offer what the ARM64 app can download. + /// + public static IReadOnlyList PackagesFor(Architecture architecture) => [ new("libreoffice", OperatingSystem.IsWindows() ? ["libreoffice", "h2orestart", "jre"] : ["libreoffice"], 1_265_000_000, ["libreoffice"]), new("pandoc", ["pandoc"], 236_000_000, ["pandoc"]), @@ -54,7 +60,7 @@ internal static string DownloadRuntime(string runtimeIdentifier, int windowsBuil new("ffmpeg", ["ffmpeg"], 272_000_000, ["ffmpeg"]), new("calibre", ["calibre"], 663_000_000, ["calibre"]), new("tesseract", ["tesseract"], 168_000_000, ["tesseract"]), - new("upscayl-bin", OperatingSystem.IsWindows() && RuntimeInformation.ProcessArchitecture != Architecture.Arm64 ? ["upscayl-bin", "vcruntime", "vcomp14"] : OperatingSystem.IsWindows() ? [] : ["upscayl-bin"], 8_600_000, ["upscaler"]), + new("upscayl-bin", OperatingSystem.IsWindows() && architecture != Architecture.Arm64 ? ["upscayl-bin", "vcruntime", "vcomp14"] : OperatingSystem.IsWindows() ? [] : ["upscayl-bin"], 8_600_000, ["upscaler"]), .. (OperatingSystem.IsWindows() ? [new EnginePackage("whisper", ["whisper", "whisper-model"], 156_880_105, ["whisper"])] : Array.Empty()), // The Metadata tool reads with it and its conversions write with it (Filee.Engines.Metadata). new("exiftool", ["exiftool"], 30_000_000, ["exiftool"]), diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.cs index 2d5367894..a1dc04b16 100644 --- a/tests/Filee.App.Tests/UpdateServiceTests.cs +++ b/tests/Filee.App.Tests/UpdateServiceTests.cs @@ -110,6 +110,81 @@ public void Release_files_picks_windows_installer_and_exact_checksums_even_when_ Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums?.Name); } + // A release as sign-release.ps1 leaves it: x64 and ARM64 Windows files next to the Linux and macOS packages. + private static JsonDocument ReleaseWithEveryPlatform() => JsonDocument.Parse($$""" + {"tag_name": "v9.9.9", "assets": [ + {"name": "Filee-9.9.9-linux-arm64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-linux-arm64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-linux-arm64.tar.gz", "size": 4000, "browser_download_url": "{{Base}}Filee-9.9.9-linux-arm64.tar.gz"}, + {"name": "Filee-9.9.9-linux-x64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-linux-x64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-linux-x64.tar.gz", "size": 4100, "browser_download_url": "{{Base}}Filee-9.9.9-linux-x64.tar.gz"}, + {"name": "Filee-9.9.9-osx-arm64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-osx-arm64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-osx-x64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-osx-x64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-SHA256SUMS.txt.sig", "size": 89, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt.sig"}, + {"name": "Filee-9.9.9-win-Portable.zip", "size": 5000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Portable.zip"}, + {"name": "Filee-9.9.9-win-Setup.exe", "size": 6000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Setup.exe"}, + {"name": "Filee-9.9.9-win-arm64-Portable.zip", "size": 5100, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-Portable.zip"}, + {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt", "size": 199, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt.sig", "size": 89, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt.sig"}, + {"name": "Filee-9.9.9-win-arm64-Setup.exe", "size": 6100, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-Setup.exe"} + ]} + """); + + [Fact] + public void X64_windows_takes_the_x64_files_even_when_arm64_files_are_listed_after_them() + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = UpdateService.FindFiles(release.RootElement, "win"); + + Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-Setup.exe", Base + "Filee-9.9.9-win-Setup.exe", 6000), installer); + Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums?.Name); + } + + [Fact] + public void Arm64_windows_takes_the_arm64_files() + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = UpdateService.FindFiles(release.RootElement, "win-arm64"); + + Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-arm64-Setup.exe", Base + "Filee-9.9.9-win-arm64-Setup.exe", 6100), installer); + Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-arm64-SHA256SUMS.txt", Base + "Filee-9.9.9-win-arm64-SHA256SUMS.txt", 199), checksums); + } + + [Fact] + public void Linux_still_takes_its_own_files_next_to_both_windows_builds() + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = UpdateService.FindFiles(release.RootElement, "linux-arm64"); + + Assert.Equal("Filee-9.9.9-linux-arm64.tar.gz", installer?.Name); + Assert.Equal("Filee-9.9.9-linux-arm64-SHA256SUMS.txt", checksums?.Name); + } + + [Fact] + public void Arm64_windows_does_not_fall_back_to_the_x64_setup_of_an_older_release() + { + using var release = JsonDocument.Parse($$""" + {"tag_name": "v9.9.9", "assets": [ + {"name": "Filee-9.9.9-linux-x64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-linux-x64-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-win-Portable.zip", "size": 5000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Portable.zip"}, + {"name": "Filee-9.9.9-win-Setup.exe", "size": 6000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Setup.exe"} + ]} + """); + + Assert.Equal((null, null), UpdateService.FindFiles(release.RootElement, "win-arm64")); + } + + [Fact] + public void The_windows_target_follows_the_process_architecture() + { + Assert.Equal("win", UpdateService.GetWindowsTarget(Architecture.X64)); + Assert.Equal("win-arm64", UpdateService.GetWindowsTarget(Architecture.Arm64)); + } + [Fact] public void Release_without_files_or_with_plain_http_links_has_no_installer() { diff --git a/tests/Filee.Engines.Tests/PortableEngineTests.cs b/tests/Filee.Engines.Tests/PortableEngineTests.cs index 5a3b3e5c3..25d52a529 100644 --- a/tests/Filee.Engines.Tests/PortableEngineTests.cs +++ b/tests/Filee.Engines.Tests/PortableEngineTests.cs @@ -1,5 +1,6 @@ using System.Formats.Tar; using System.IO.Compression; +using System.Runtime.InteropServices; using System.Text; using Filee.Engines.Infrastructure; @@ -67,6 +68,26 @@ public void Windows_on_ARM64_downloads_the_x64_engines_from_Windows_11_on(string Assert.Empty(EngineDownloads.ComponentsForRuntime("win-arm64")); } + [Fact] + public void The_ARM64_Setup_packed_on_an_x64_PC_offers_what_the_ARM64_app_downloads() + { + static IEnumerable Names(IEnumerable packages) => packages.Select(p => p.Id + ":" + string.Join(',', p.Components)); + Assert.Equal(Names(EngineDownloads.Packages), Names(EngineDownloads.PackagesFor(RuntimeInformation.ProcessArchitecture))); + var arm64 = EngineDownloads.PackagesFor(Architecture.Arm64).Single(p => p.Id == "upscayl-bin"); + var x64 = EngineDownloads.PackagesFor(Architecture.X64).Single(p => p.Id == "upscayl-bin"); + if (OperatingSystem.IsWindows()) + { + // The ARM64 app offers no upscaler download on Windows, so its Setup must not either. + Assert.Empty(arm64.Components); + Assert.False(EngineDownloads.CanDownload(arm64)); + Assert.Contains("vcomp14", x64.Components); + } + else + { + Assert.Equal(x64.Components, arm64.Components); + } + } + [Theory] [InlineData("libreoffice", "LibreOffice.app/Contents/MacOS", "soffice")] [InlineData("calibre", "calibre.app/Contents/MacOS", "ebook-convert")] From b0b1daf3c1b121c135fd129d78c055bd1d41cf54 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Tue, 10 Nov 2026 17:04:37 +0900 Subject: [PATCH 02/95] fix(release): one Windows checksum file for x64 and ARM64 Filee 2.4.0 and older take the last asset ending in -SHA256SUMS.txt that isn't Linux or macOS, so a separate Filee--win-arm64-SHA256SUMS.txt could become their pick and break every x64 update. sign-release.ps1 now appends the ARM64 hashes to Filee--SHA256SUMS.txt (one file, one .sig) and refuses to publish a draft with another Windows sums file; the ARM64 updater uses that same file. A test runs 2.4.0's matching rules over the new assets. The Explorer menu package registered for the other architecture (an install switched between x64 and ARM64 in place) is now Outdated and is removed before this build's is added, by Setup and by Settings. Refs #236 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 10 ++- CONTRIBUTING.md | 3 +- build/build-installer.ps1 | 3 +- build/sign-release.ps1 | 33 +++++--- docs/ENGINES.md | 4 +- src/Filee.App/Services/UpdateService.cs | 17 ++-- .../ExplorerMenuRegistration.cs | 44 +++++++++-- src/Filee.Setup/Platform/SetupSystem.cs | 17 +++- tests/Filee.App.Tests/ExplorerMenuTests.cs | 25 ++++++ tests/Filee.App.Tests/UpdateServiceTests.cs | 79 ++++++++++++++++--- 10 files changed, 190 insertions(+), 45 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 20d0676b1..dc989d055 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,9 +2,10 @@ # Trigger: push a tag like v1.0.0 (git tag v1.0.0 && git push origin v1.0.0) # # Output (build/build-installer.ps1): Filee--win-Setup.exe (Filee's own installer, src/Filee.Setup), -# Filee--win-Portable.zip and Filee--SHA256SUMS.txt for x64, and the same for Windows on ARM64 -# (#236), built and tested on an ARM64 runner: Filee--win-arm64-Setup.exe, -win-arm64-Portable.zip and -# -win-arm64-SHA256SUMS.txt. +# Filee--win-Portable.zip and Filee--SHA256SUMS.txt for x64, and for Windows on ARM64 (#236), built +# and tested on an ARM64 runner, Filee--win-arm64-Setup.exe and -win-arm64-Portable.zip. Their hashes go into +# the same Filee--SHA256SUMS.txt (sign-release.ps1): Filee 2.4.0 and older take the last Windows-looking +# SHA256SUMS file of a release, so a separate ARM64 one would break their updates. # The release is a draft with the Linux and macOS packages: the Windows files are signed on a PC signed in to Certum's # SimplySign cloud (its key needs a phone token), so this run keeps the tested, unsigned builds as the artifacts # windows-unsigned and windows-arm64-unsigned, and build/sign-release.ps1 signs them, packs both Setups again, uploads @@ -225,7 +226,8 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | $version = '${{ steps.version.outputs.value }}' - # Linux and macOS only: build/sign-release.ps1 adds the signed Windows files. + # Linux and macOS only: build/sign-release.ps1 adds the signed Windows files. The ARM64 build's own sums file + # never ships (its hashes go into Filee--SHA256SUMS.txt). $windows = "Filee-$version-win-Setup.exe", "Filee-$version-win-Portable.zip", "Filee-$version-SHA256SUMS.txt", "Filee-$version-win-arm64-Setup.exe", "Filee-$version-win-arm64-Portable.zip", "Filee-$version-win-arm64-SHA256SUMS.txt" $files = Get-ChildItem Releases -File -Filter "Filee-$version-*" | Where-Object Name -notin $windows | ForEach-Object FullName diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 71f160153..a4a27a7e0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -132,7 +132,8 @@ pwsh build/sign-release.ps1 -Version X.Y.Z -CertificateThumbprint -Update It signs every unsigned program in both builds and their Setup programs, packs and signs `Filee-X.Y.Z-win-Setup.exe` and `Filee-X.Y.Z-win-arm64-Setup.exe`, zips the portable copies, checks the signed x64 Setup in a sandbox install (and the ARM64 one too on an ARM64 PC; on an x64 PC it checks the ARM64 signatures without running it) and uploads the -files with their SHA-256 sums (`Filee-X.Y.Z-SHA256SUMS.txt`, `Filee-X.Y.Z-win-arm64-SHA256SUMS.txt`). It signs +files with their SHA-256 sums, all in one `Filee-X.Y.Z-SHA256SUMS.txt` (Filee 2.4.0 and older would take a separate +ARM64 sums file for theirs, and fail to update; the script refuses to publish a draft that has one). It signs every `SHA256SUMS` file of the release (Windows, Linux and macOS) with Filee's update key and uploads the `.sig` files next to them (`build/sign-checksums.ps1`; it asks for the key's passphrase once). It also copies the Windows files to the download mirror `https://dl.filee.sh/X.Y.Z/` (Cloudflare R2; needs `npx wrangler login` once), which the diff --git a/build/build-installer.ps1 b/build/build-installer.ps1 index 5f0d5ec96..8a4d13b2d 100644 --- a/build/build-installer.ps1 +++ b/build/build-installer.ps1 @@ -146,7 +146,8 @@ if ($sign) { & $sign -Path $PublishDir, $SetupProgram -CertificateThumbprint $CertificateThumbprint } -# The x64 names are the ones Filee's updater looks for (-win-Setup.exe, -SHA256SUMS.txt). +# The x64 names are the ones Filee's updater looks for (-win-Setup.exe, -SHA256SUMS.txt). The ARM64 build writes its own +# sums file; a release adds those lines to the x64 one instead (sign-release.ps1). $prefix = if ($Runtime -eq 'win-x64') { "Filee-$Version-win" } else { "Filee-$Version-$Runtime" } $setupExe = Join-Path $OutputDir "$prefix-Setup.exe" Write-Host "pack installer $Version" diff --git a/build/sign-release.ps1 b/build/sign-release.ps1 index 5834cd5de..e6c9460a9 100644 --- a/build/sign-release.ps1 +++ b/build/sign-release.ps1 @@ -11,16 +11,18 @@ 1. downloads those builds, exactly as they were tested; 2. checks out the tag in a worktree and runs its build-installer.ps1 with -CertificateThumbprint for each, which signs the unsigned programs and the Setup program, packs Setup.exe, signs it, zips the portable copy and writes - the SHA-256 sums (x64: Filee--win-Setup.exe, -win-Portable.zip and Filee--SHA256SUMS.txt; - ARM64: Filee--win-arm64-Setup.exe, -win-arm64-Portable.zip and -win-arm64-SHA256SUMS.txt); + the SHA-256 sums (x64: Filee--win-Setup.exe and -win-Portable.zip; ARM64: + Filee--win-arm64-Setup.exe and -win-arm64-Portable.zip). The ARM64 sums are added to + Filee--SHA256SUMS.txt, the one Windows checksum file: Filee 2.4.0 and older take the last Windows-looking + SHA256SUMS file of a release, and a separate ARM64 one would leave them without their Setup's hash; 3. installs the signed Setup into a sandbox (nothing on the PC is touched) and checks that Filee.exe and uninstall.exe come out signed, then uninstalls it. An x64 PC can't run the ARM64 Setup: there it checks the signatures of the ARM64 Setup.exe and of the signed files that went into it instead (the release workflow ran the ARM64 Setup program in a sandbox on Windows on ARM, around a stub app); - 4. signs every SHA256SUMS file of the release (both Windows ones, and the Linux and macOS ones from the draft) with + 4. signs every SHA256SUMS file of the release (the Windows one, and the Linux and macOS ones from the draft) with Filee's update key (build/sign-checksums.ps1, -UpdateKey), which writes a .sig file next to each; 5. uploads the Windows files and the .sig files to the draft; - 6. copies the Windows files and their checksum signatures to the download mirror, Cloudflare R2 behind + 6. copies the Windows files and their checksum signature to the download mirror, Cloudflare R2 behind https://dl.filee.sh//, and checks that each one is served there as is (no redirect, the same size). The Microsoft Store takes the Setup programs from that address, because GitHub's download links redirect; 7. with -Publish, publishes the release. @@ -120,12 +122,20 @@ finally { } $setup = Join-Path $out "Filee-$Version-win-Setup.exe" -$files = @($setup, (Join-Path $out "Filee-$Version-win-Portable.zip"), (Join-Path $out "Filee-$Version-SHA256SUMS.txt")) +$windowsSums = Join-Path $out "Filee-$Version-SHA256SUMS.txt" +$files = @($setup, (Join-Path $out "Filee-$Version-win-Portable.zip"), $windowsSums) $setupArm64 = Join-Path $out "Filee-$Version-win-arm64-Setup.exe" if ($arm64) { - $files += @($setupArm64, (Join-Path $out "Filee-$Version-win-arm64-Portable.zip"), (Join-Path $out "Filee-$Version-win-arm64-SHA256SUMS.txt")) + $files += @($setupArm64, (Join-Path $out "Filee-$Version-win-arm64-Portable.zip")) } foreach ($file in $files) { if (-not (Test-Path $file)) { throw "$file was not written." } } +if ($arm64) { + # One checksum file for both (see the description): the ARM64 lines after the x64 ones, which stay as they were. + $arm64Sums = Join-Path $out "Filee-$Version-win-arm64-SHA256SUMS.txt" + Add-Content $windowsSums (Get-Content $arm64Sums) -Encoding ascii + Remove-Item $arm64Sums + Write-Host "added the ARM64 checksums to $(Split-Path $windowsSums -Leaf)" +} # The signed Setup still finds its payload, and what it installs is signed, the uninstaller too. $sandbox = Join-Path $work 'sandbox' @@ -163,13 +173,13 @@ elseif ($arm64) { } # Every SHA256SUMS file of the release, signed in one go (one passphrase): the Linux and macOS ones the workflow put -# on the draft, and the new Windows ones. +# on the draft, and the new Windows one. $signatures = @() if ($UpdateKey) { $sums = Join-Path $work 'sums' New-Item -ItemType Directory -Force -Path $sums | Out-Null Invoke-Checked 'gh release download' { gh release download $tag --pattern '*SHA256SUMS.txt' --dir $sums --clobber } - Copy-Item @($files | Where-Object { $_ -like '*SHA256SUMS.txt' }) $sums -Force + Copy-Item $windowsSums $sums -Force $signatures = @(& (Join-Path $PSScriptRoot 'sign-checksums.ps1') -Folder $sums -PrivateKeyPath $UpdateKey -PublicKey $publicKey) } @@ -182,8 +192,7 @@ if (-not $NoMirror) { $mirror = "https://dl.filee.sh/$Version" $types = @{ '.exe' = 'application/vnd.microsoft.portable-executable'; '.zip' = 'application/zip'; '.txt' = 'text/plain; charset=utf-8' '.sig' = 'text/plain; charset=utf-8' } - $windowsSignatures = @($files | Where-Object { $_ -like '*SHA256SUMS.txt' } | ForEach-Object { "$(Split-Path $_ -Leaf).sig" }) - $mirrored = $files + @($signatures | Where-Object { (Split-Path $_ -Leaf) -in $windowsSignatures }) + $mirrored = $files + @($signatures | Where-Object { (Split-Path $_ -Leaf) -eq "Filee-$Version-SHA256SUMS.txt.sig" }) foreach ($file in $mirrored) { $name = Split-Path $file -Leaf Write-Host "copy $name to $mirror" @@ -205,6 +214,10 @@ if ($publicKey) { $unsigned = @($assets | Where-Object { $_ -like '*SHA256SUMS.txt' -and "$_.sig" -notin $assets }) if ($unsigned.Count) { throw "Not signed on the draft of ${tag}: $($unsigned -join ', '). Run again with -UpdateKey." } } +# A Windows checksum file besides Filee--SHA256SUMS.txt (uploaded by hand) could be the one Filee 2.4.0 and +# older pick, without the hash of their Setup. +$extraSums = @((gh release view $tag --json assets | ConvertFrom-Json).assets.name | Where-Object { $_ -like 'Filee-*-win-*SHA256SUMS.txt*' }) +if ($extraSums.Count) { throw "Remove from the draft of ${tag}: $($extraSums -join ', '). The Windows hashes all go in Filee-$Version-SHA256SUMS.txt." } if ($Publish) { Invoke-Checked 'gh release edit' { gh release edit $tag --draft=false --latest } Write-Host "published $tag" diff --git a/docs/ENGINES.md b/docs/ENGINES.md index bac07963c..efa837d99 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -196,7 +196,9 @@ available on this platform. CI's `build (win-arm64)` job builds and tests on Win in it also builds the package (artifact `windows-arm64-package`). Releases ship it next to the x64 files: the release workflow's `windows-arm64` job builds and tests it the same way and keeps it unsigned for `build/sign-release.ps1` (see [Releasing](../CONTRIBUTING.md#releasing-maintainers)), and the in-app updater of an ARM64 build takes -`-win-arm64-Setup.exe` and `-win-arm64-SHA256SUMS.txt` (an x64 build keeps to the x64 files, also on Windows on ARM). +`-win-arm64-Setup.exe` (an x64 build keeps to the x64 Setup, also on Windows on ARM). Both are in the one Windows +`Filee--SHA256SUMS.txt`: Filee 2.4.0 and older take the last Windows-looking SHA256SUMS file of a release, +so a separate ARM64 one would break their updates. ## Images and vector graphics diff --git a/src/Filee.App/Services/UpdateService.cs b/src/Filee.App/Services/UpdateService.cs index bd56dfb4a..259bd1421 100644 --- a/src/Filee.App/Services/UpdateService.cs +++ b/src/Filee.App/Services/UpdateService.cs @@ -790,12 +790,12 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE if (!release.TryGetProperty("assets", out var assets) || assets.ValueKind != JsonValueKind.Array) return (null, null); - // The x64 Windows files are the only ones without the platform in full: Filee--win-Setup.exe and - // Filee--SHA256SUMS.txt (older builds look for these names). + // Windows has one checksum file for x64 and ARM64, Filee--SHA256SUMS.txt: Filee 2.4.0 and older take the + // last file ending in -SHA256SUMS.txt that isn't Linux or macOS, so an ARM64 one next to it would break their + // updates. The x64 Setup is Filee--win-Setup.exe, the ARM64 one Filee--win-arm64-Setup.exe. var isLinux = target.StartsWith("linux-", StringComparison.OrdinalIgnoreCase); - var isX64Windows = target == "win"; var expectedInstallerSuffix = isLinux ? $"-{target}.tar.gz" : $"-{target}-Setup.exe"; - var expectedChecksumsSuffix = isX64Windows ? "-SHA256SUMS.txt" : $"-{target}-SHA256SUMS.txt"; + var expectedChecksumsSuffix = isLinux ? $"-{target}-SHA256SUMS.txt" : "-SHA256SUMS.txt"; foreach (var asset in assets.EnumerateArray()) { @@ -811,10 +811,11 @@ internal static (ReleaseFile? Installer, ReleaseFile? Checksums) FindFiles(JsonE } else if (name.EndsWith(expectedChecksumsSuffix, StringComparison.OrdinalIgnoreCase)) { - // Every other platform's checksum file ends in -SHA256SUMS.txt too (-linux-x64-, -osx-arm64-, -win-arm64-). - if (isX64Windows && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) - || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase) - || name.Contains("-win-arm64-", StringComparison.OrdinalIgnoreCase))) + // The other platforms' checksum files end in -SHA256SUMS.txt too (-linux-x64-, -osx-arm64-), and so does + // the ARM64 build's own one (CI's package), should one ever be attached. + if (!isLinux && (name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) + || name.Contains("-osx-", StringComparison.OrdinalIgnoreCase) + || name.Contains("-win-arm64-", StringComparison.OrdinalIgnoreCase))) continue; checksums = new ReleaseFile(name, url, size); diff --git a/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs b/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs index 147b3471f..11d257a6d 100644 --- a/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs +++ b/src/Filee.Platform.Windows/ExplorerMenuRegistration.cs @@ -26,7 +26,15 @@ public static class ExplorerMenuRegistration /// Package full name, e.g. Filee.ExplorerMenu_1.0.0.0_x64__c73vxh346rtay. /// Identity version from the full name. /// Folder the package points at (null when Windows does not say). - public sealed record RegisteredPackage(string FullName, Version Version, string? ExternalLocation); + /// Identity architecture from the full name ("x64" or "arm64"). + public sealed record RegisteredPackage(string FullName, Version Version, string? ExternalLocation, string Architecture = ""); + + /// + /// The package architecture of the running build ("x64" or "arm64"): the DLL next to Filee.exe and the package's + /// manifest are built for it (build/build-explorer-menu.ps1 -Architecture). + /// + public static string BuildArchitecture => + RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "arm64" : ExplorerMenuPackage.Architecture; /// /// Windows 11 on x64 or ARM64: the new context menu exists, and Explorer can load the DLL shipped with this build @@ -50,15 +58,32 @@ public static ModernContextMenuState GetState(string installFolder) { if (!IsSupportedOs || !HasFiles(installFolder)) return ModernContextMenuState.Unsupported; - var package = Find(); + return StateOf(Find(), installFolder, BuildArchitecture); + } + + /// + /// On when is this build's: registered for , at least at + /// this manifest version and for . Setup switches an install between x64 and ARM64 + /// in place (same folder, same version), after which the package registered before is the other architecture's: + /// Outdated, so it is registered again. + /// + public static ModernContextMenuState StateOf(RegisteredPackage? package, string installFolder, string architecture) + { if (package is null) return ModernContextMenuState.Off; var sameFolder = package.ExternalLocation is null || SamePath(package.ExternalLocation, installFolder); - return sameFolder && package.Version >= ExplorerMenuPackage.ManifestVersion + return sameFolder && !IsOtherArchitecture(package, architecture) && package.Version >= ExplorerMenuPackage.ManifestVersion ? ModernContextMenuState.On : ModernContextMenuState.Outdated; } + /// + /// Registered for another architecture than . To Windows that is another package + /// of the same family, so it is removed before this build's is added rather than updated. + /// + public static bool IsOtherArchitecture(RegisteredPackage package, string architecture) => + !string.Equals(package.Architecture, architecture, StringComparison.OrdinalIgnoreCase); + /// The package as registered for the current user, or null. public static unsafe RegisteredPackage? Find() { @@ -82,7 +107,7 @@ public static ModernContextMenuState GetState(string installFolder) // Full name = Name_Version_Architecture_ResourceId_PublisherId. var parts = fullName.Split('_'); var version = parts.Length > 1 && Version.TryParse(parts[1], out var v) ? v : new Version(0, 0); - return new RegisteredPackage(fullName, version, ExternalLocationOf(fullName)); + return new RegisteredPackage(fullName, version, ExternalLocationOf(fullName), parts.Length > 2 ? parts[2] : ""); } /// @@ -128,7 +153,8 @@ public static async Task AddAsync(string installFolder) return new ModernContextMenuResult(false, Error: $"{ExplorerMenuPackage.PackageFileName} or {ExplorerMenuPackage.DllFileName} is missing in {installFolder}."); var package = Path.Combine(installFolder, ExplorerMenuPackage.PackageFileName); - var result = await RunPowerShellAsync(errorFile => BuildAddScript(package, installFolder, errorFile), elevated: true); + var replace = Find() is { } registered && IsOtherArchitecture(registered, BuildArchitecture); + var result = await RunPowerShellAsync(errorFile => BuildAddScript(package, installFolder, errorFile, removeFirst: replace), elevated: true); if (result.Succeeded && GetState(installFolder) != ModernContextMenuState.On) { return new ModernContextMenuResult(false, Error: @@ -153,9 +179,13 @@ public static async Task RemoveAsync(bool allowElevatio : result; } - /// PowerShell that registers the package and writes the error message to . - public static string BuildAddScript(string packagePath, string externalLocation, string errorFile) => + /// + /// PowerShell that registers the package and writes the error message to ; with + /// it removes the registered one first (see ). + /// + public static string BuildAddScript(string packagePath, string externalLocation, string errorFile, bool removeFirst = false) => WrapScript( + (removeFirst ? $"Get-AppxPackage -Name {Quote(ExplorerMenuPackage.PackageName)} | Remove-AppxPackage; " : "") + $"Add-AppxPackage -Path {Quote(packagePath)} -ExternalLocation {Quote(externalLocation)} -AllowUnsigned -ForceUpdateFromAnyVersion", errorFile); diff --git a/src/Filee.Setup/Platform/SetupSystem.cs b/src/Filee.Setup/Platform/SetupSystem.cs index 670146859..356a3f7e0 100644 --- a/src/Filee.Setup/Platform/SetupSystem.cs +++ b/src/Filee.Setup/Platform/SetupSystem.cs @@ -101,12 +101,27 @@ public virtual bool IsExplorerMenuCurrent(string installFolder) public virtual string? RegisterExplorerMenu(string installFolder, bool removeFirst) { - if (removeFirst) + // An update that switched the install between x64 and ARM64 finds the other architecture's package, which + // Windows can't update into this one. + if (removeFirst || RegisteredForOtherArchitecture()) UnregisterExplorerMenu(); var package = Path.Combine(installFolder, ExplorerMenuPackage.PackageFileName); return RunPowerShell(errorFile => ExplorerMenuRegistration.BuildAddScript(package, installFolder, errorFile)); } + private static bool RegisteredForOtherArchitecture() + { + try + { + return ExplorerMenuRegistration.Find() is { } package + && ExplorerMenuRegistration.IsOtherArchitecture(package, ExplorerMenuRegistration.BuildArchitecture); + } + catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) + { + return false; + } + } + public virtual void UnregisterExplorerMenu() { if (!IsExplorerMenuRegistered()) diff --git a/tests/Filee.App.Tests/ExplorerMenuTests.cs b/tests/Filee.App.Tests/ExplorerMenuTests.cs index 791e0658e..10ef343e7 100644 --- a/tests/Filee.App.Tests/ExplorerMenuTests.cs +++ b/tests/Filee.App.Tests/ExplorerMenuTests.cs @@ -8,6 +8,7 @@ using System.Text.RegularExpressions; using System.Xml.Linq; using Filee.App.Services; +using Filee.Core.Platform; using Filee.Platform.Windows; namespace Filee.App.Tests; @@ -124,6 +125,30 @@ public void Reading_the_registered_package_never_throws() _ = ExplorerMenuRegistration.GetState(BuiltFolder); } + [Fact] + public void A_package_of_the_other_architecture_is_outdated_and_replaced() + { + // Setup switches an install between x64 and ARM64 in place: same folder, same package version. + const string folder = @"C:\Program Files\Filee"; + var version = ExplorerMenuPackage.ManifestVersion; + var x64 = new ExplorerMenuRegistration.RegisteredPackage($"Filee.ExplorerMenu_{version}_x64__c73vxh346rtay", version, folder, "x64"); + var arm64 = x64 with { FullName = $"Filee.ExplorerMenu_{version}_arm64__c73vxh346rtay", Architecture = "arm64" }; + + Assert.Equal(ModernContextMenuState.On, ExplorerMenuRegistration.StateOf(x64, folder, "x64")); + Assert.Equal(ModernContextMenuState.On, ExplorerMenuRegistration.StateOf(arm64, folder, "arm64")); + Assert.Equal(ModernContextMenuState.Outdated, ExplorerMenuRegistration.StateOf(x64, folder, "arm64")); + Assert.Equal(ModernContextMenuState.Outdated, ExplorerMenuRegistration.StateOf(arm64, folder, "x64")); + Assert.Equal(ModernContextMenuState.Outdated, ExplorerMenuRegistration.StateOf(x64, @"D:\Other\Filee", "x64")); + Assert.Equal(ModernContextMenuState.Off, ExplorerMenuRegistration.StateOf(null, folder, "x64")); + Assert.True(ExplorerMenuRegistration.IsOtherArchitecture(x64, "arm64")); + Assert.False(ExplorerMenuRegistration.IsOtherArchitecture(arm64, "ARM64")); + Assert.Equal(RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "arm64" : "x64", ExplorerMenuRegistration.BuildArchitecture); + + var replace = ExplorerMenuRegistration.BuildAddScript(@"C:\Program Files\Filee\FileeExplorerMenu.msix", folder, @"C:\Temp\err.txt", removeFirst: true); + Assert.Matches(@"Get-AppxPackage -Name 'Filee\.ExplorerMenu' \| Remove-AppxPackage; Add-AppxPackage ", replace); + Assert.DoesNotContain("Remove-AppxPackage", ExplorerMenuRegistration.BuildAddScript(@"C:\a.msix", folder, @"C:\Temp\err.txt")); + } + [Fact] public void PowerShell_literals_escape_straight_and_typographic_single_quotes() { diff --git a/tests/Filee.App.Tests/UpdateServiceTests.cs b/tests/Filee.App.Tests/UpdateServiceTests.cs index a1dc04b16..90f5552b4 100644 --- a/tests/Filee.App.Tests/UpdateServiceTests.cs +++ b/tests/Filee.App.Tests/UpdateServiceTests.cs @@ -110,28 +110,33 @@ public void Release_files_picks_windows_installer_and_exact_checksums_even_when_ Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums?.Name); } - // A release as sign-release.ps1 leaves it: x64 and ARM64 Windows files next to the Linux and macOS packages. - private static JsonDocument ReleaseWithEveryPlatform() => JsonDocument.Parse($$""" - {"tag_name": "v9.9.9", "assets": [ + // A release as sign-release.ps1 leaves it: x64 and ARM64 Windows files with one checksum file for both, next to the + // Linux and macOS packages. + private const string EveryPlatformAssets = $$""" {"name": "Filee-9.9.9-linux-arm64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-linux-arm64-SHA256SUMS.txt"}, {"name": "Filee-9.9.9-linux-arm64.tar.gz", "size": 4000, "browser_download_url": "{{Base}}Filee-9.9.9-linux-arm64.tar.gz"}, {"name": "Filee-9.9.9-linux-x64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-linux-x64-SHA256SUMS.txt"}, {"name": "Filee-9.9.9-linux-x64.tar.gz", "size": 4100, "browser_download_url": "{{Base}}Filee-9.9.9-linux-x64.tar.gz"}, {"name": "Filee-9.9.9-osx-arm64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-osx-arm64-SHA256SUMS.txt"}, {"name": "Filee-9.9.9-osx-x64-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-osx-x64-SHA256SUMS.txt"}, - {"name": "Filee-9.9.9-SHA256SUMS.txt", "size": 189, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt"}, + {"name": "Filee-9.9.9-SHA256SUMS.txt", "size": 384, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt"}, {"name": "Filee-9.9.9-SHA256SUMS.txt.sig", "size": 89, "browser_download_url": "{{Base}}Filee-9.9.9-SHA256SUMS.txt.sig"}, {"name": "Filee-9.9.9-win-Portable.zip", "size": 5000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Portable.zip"}, {"name": "Filee-9.9.9-win-Setup.exe", "size": 6000, "browser_download_url": "{{Base}}Filee-9.9.9-win-Setup.exe"}, {"name": "Filee-9.9.9-win-arm64-Portable.zip", "size": 5100, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-Portable.zip"}, - {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt", "size": 199, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt"}, - {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt.sig", "size": 89, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt.sig"}, {"name": "Filee-9.9.9-win-arm64-Setup.exe", "size": 6100, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-Setup.exe"} - ]} - """); + """; + + private static JsonDocument ReleaseWithEveryPlatform(string extraAssets = "") => + JsonDocument.Parse($$"""{"tag_name": "v9.9.9", "assets": [{{EveryPlatformAssets}}{{extraAssets}}]}"""); + + // Filee-9.9.9-SHA256SUMS.txt as sign-release.ps1 writes it: the x64 lines, then the ARM64 ones. + private static readonly string CombinedSums = + $"{new string('a', 64)} Filee-9.9.9-win-Setup.exe\r\n{new string('b', 64)} Filee-9.9.9-win-Portable.zip\r\n" + + $"{new string('c', 64)} Filee-9.9.9-win-arm64-Setup.exe\r\n{new string('d', 64)} Filee-9.9.9-win-arm64-Portable.zip\r\n"; [Fact] - public void X64_windows_takes_the_x64_files_even_when_arm64_files_are_listed_after_them() + public void X64_windows_takes_the_x64_setup_and_the_windows_checksums() { using var release = ReleaseWithEveryPlatform(); @@ -139,17 +144,67 @@ public void X64_windows_takes_the_x64_files_even_when_arm64_files_are_listed_aft Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-Setup.exe", Base + "Filee-9.9.9-win-Setup.exe", 6000), installer); Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums?.Name); + Assert.Equal(new string('a', 64), UpdateService.ParseChecksum(CombinedSums, installer!.Name)); } [Fact] - public void Arm64_windows_takes_the_arm64_files() + public void Arm64_windows_takes_the_arm64_setup_and_the_same_windows_checksums() { using var release = ReleaseWithEveryPlatform(); var (installer, checksums) = UpdateService.FindFiles(release.RootElement, "win-arm64"); Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-arm64-Setup.exe", Base + "Filee-9.9.9-win-arm64-Setup.exe", 6100), installer); - Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-win-arm64-SHA256SUMS.txt", Base + "Filee-9.9.9-win-arm64-SHA256SUMS.txt", 199), checksums); + Assert.Equal(new UpdateService.ReleaseFile("Filee-9.9.9-SHA256SUMS.txt", Base + "Filee-9.9.9-SHA256SUMS.txt", 384), checksums); + Assert.Equal(new string('c', 64), UpdateService.ParseChecksum(CombinedSums, installer!.Name)); + } + + [Theory] + [InlineData("win")] + [InlineData("win-arm64")] + public void A_separate_arm64_checksum_file_is_never_taken(string target) + { + // The ARM64 build's own sums file (CI's package): a release doesn't ship it, but if one were attached after + // the Windows one, neither target may take it. + using var release = ReleaseWithEveryPlatform($$""" + , {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt", "size": 199, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt"} + """); + + Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", UpdateService.FindFiles(release.RootElement, target).Checksums?.Name); + } + + /// FindFiles as Filee 2.4.0 and older have it (v2.4.0 UpdateService.cs), for Windows. + private static (string? Installer, string? Checksums) FindFilesLikeFilee240(JsonElement release) + { + string? installer = null, checksums = null; + foreach (var asset in release.GetProperty("assets").EnumerateArray()) + { + var name = asset.GetProperty("name").GetString()!; + if (name.EndsWith("-win-Setup.exe", StringComparison.OrdinalIgnoreCase)) + installer = name; + else if (name.EndsWith("-SHA256SUMS.txt", StringComparison.OrdinalIgnoreCase) + && !name.Contains("-linux-", StringComparison.OrdinalIgnoreCase) && !name.Contains("-osx-", StringComparison.OrdinalIgnoreCase)) + checksums = name; // the last one wins + } + return (installer, checksums); + } + + [Fact] + public void An_installed_2_4_0_still_finds_its_setup_and_its_checksum() + { + using var release = ReleaseWithEveryPlatform(); + + var (installer, checksums) = FindFilesLikeFilee240(release.RootElement); + + Assert.Equal("Filee-9.9.9-win-Setup.exe", installer); + Assert.Equal("Filee-9.9.9-SHA256SUMS.txt", checksums); + Assert.Equal(new string('a', 64), UpdateService.ParseChecksum(CombinedSums, installer)); + + // Why the ARM64 hashes share the file: a separate one listed after it would be 2.4.0's pick, without the x64 Setup. + using var separate = ReleaseWithEveryPlatform($$""" + , {"name": "Filee-9.9.9-win-arm64-SHA256SUMS.txt", "size": 199, "browser_download_url": "{{Base}}Filee-9.9.9-win-arm64-SHA256SUMS.txt"} + """); + Assert.Equal("Filee-9.9.9-win-arm64-SHA256SUMS.txt", FindFilesLikeFilee240(separate.RootElement).Checksums); } [Fact] @@ -175,7 +230,7 @@ public void Arm64_windows_does_not_fall_back_to_the_x64_setup_of_an_older_releas ]} """); - Assert.Equal((null, null), UpdateService.FindFiles(release.RootElement, "win-arm64")); + Assert.Null(UpdateService.FindFiles(release.RootElement, "win-arm64").Installer); } [Fact] From f607b78ca4690b120213dada4a6e094d8c4438a3 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Thu, 12 Nov 2026 15:34:57 +0900 Subject: [PATCH 03/95] fix(setup): never follow a junction or link when deleting a folder tree Setup runs elevated for an install for all users, and some of the trees it deletes are the user's own: Filee 1.1's %LocalAppData%\Filee and, at uninstall, the settings in %AppData%. Directory.EnumerateFiles with AllDirectories enters junctions, so a junction planted there made Setup delete files anywhere with admin rights. FileSwap.DeleteTree now walks the tree one level at a time and removes a link itself instead of entering it. Each entry is opened without following a link and deleted through that handle, and only when its real path is inside the tree, so swapping a folder for a junction while Setup runs doesn't help either. A tree reached through a link isn't touched. In the user's folders nothing is left for the next restart, since that deletes by path. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Setup/Installation/FileSwap.cs | 92 +++++++--- .../Installation/LinkSafeDelete.cs | 162 ++++++++++++++++++ .../Installation/PreviousInstall.cs | 31 ++-- src/Filee.Setup/Installation/Uninstaller.cs | 2 +- .../Filee.Setup.Tests/LinkSafeDeleteTests.cs | 119 +++++++++++++ 5 files changed, 371 insertions(+), 35 deletions(-) create mode 100644 src/Filee.Setup/Installation/LinkSafeDelete.cs create mode 100644 tests/Filee.Setup.Tests/LinkSafeDeleteTests.cs diff --git a/src/Filee.Setup/Installation/FileSwap.cs b/src/Filee.Setup/Installation/FileSwap.cs index d502604e8..4bfcc6747 100644 --- a/src/Filee.Setup/Installation/FileSwap.cs +++ b/src/Filee.Setup/Installation/FileSwap.cs @@ -98,38 +98,86 @@ public void Commit() /// Deletes the work folder; what is still in use goes at the next restart. public void Cleanup() => DeleteTree(workFolder, system, log); - /// Deletes a folder tree; files still in use are deleted at the next restart. - public static void DeleteTree(string folder, ISetupSystem system, SetupLog log) + /// + /// Deletes a folder tree; files still in use are deleted at the next restart. Junctions and links inside are + /// removed themselves, never followed: Setup runs elevated, and a link could otherwise point it at any folder. + /// + /// + /// A folder the user can change (%LocalAppData%, %AppData%), not the install folder: nothing is left for the next + /// restart, which deletes by path when the folders on the way may have been swapped for links meanwhile. + /// + public static void DeleteTree(string folder, ISetupSystem system, SetupLog log, bool userFolder = false) { - if (!Directory.Exists(folder)) + if (!OperatingSystem.IsWindows() || !Directory.Exists(folder)) return; - foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) + if (new DirectoryInfo(folder).Attributes.HasFlag(FileAttributes.ReparsePoint)) { - try - { - File.SetAttributes(file, FileAttributes.Normal); - File.Delete(file); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - log.Info($"In use, deleted at the next restart: {file}"); - system.DeleteAtRestart(file); - } + // The folder itself is a link: only the link goes. Its parent was checked by the caller, or is ours. + log.Info($"{folder} is a link; removing only the link"); + var parent = LinkSafeDelete.RealFolder(Path.GetDirectoryName(Path.GetFullPath(folder))!); + if (parent is null || LinkSafeDelete.Entry(folder, parent) != LinkSafeDelete.Outcome.Deleted) + log.Warn($"Could not remove the link {folder}"); + return; } - foreach (var dir in Directory.EnumerateDirectories(folder, "*", SearchOption.AllDirectories) - .OrderByDescending(d => d.Length).Append(folder)) + if (LinkSafeDelete.RealFolder(folder) is not { } root) { - try - { - Directory.Delete(dir); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + log.Warn($"Not deleting {folder}: it is reached through a junction or link"); + return; + } + DeleteContents(root, root, system, log, userFolder); + // The root itself is checked against its parent, which is where it really is. + if (LinkSafeDelete.Entry(root, Path.GetDirectoryName(root)!) == LinkSafeDelete.Outcome.Failed) + Later(root, system, log, userFolder); + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static void DeleteContents(string folder, string root, ISetupSystem system, SetupLog log, bool userFolder) + { + IEnumerable entries; + try + { + // Not recursive: a link found is deleted, not entered. + entries = new DirectoryInfo(folder).EnumerateFileSystemInfos("*", ListOnly).ToList(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + log.Warn($"Could not list {folder}: {ex.Message}"); + return; + } + foreach (var entry in entries) + { + if (entry is DirectoryInfo && !entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) + DeleteContents(entry.FullName, root, system, log, userFolder); + switch (LinkSafeDelete.Entry(entry.FullName, root)) { - system.DeleteAtRestart(dir); + case LinkSafeDelete.Outcome.Failed: + Later(entry.FullName, system, log, userFolder); + break; + case LinkSafeDelete.Outcome.Outside: + log.Warn($"Not deleting {entry.FullName}: it is no longer inside {root}"); + break; } } } + private static readonly EnumerationOptions ListOnly = new() + { + RecurseSubdirectories = false, + AttributesToSkip = 0, + IgnoreInaccessible = false, + }; + + private static void Later(string path, ISetupSystem system, SetupLog log, bool userFolder) + { + if (userFolder) + { + log.Info($"In use, left in place: {path}"); + return; + } + log.Info($"In use, deleted at the next restart: {path}"); + system.DeleteAtRestart(path); + } + /// Removes empty folders below (not the root itself). public static void RemoveEmptyFolders(string root, string? keep = null) { diff --git a/src/Filee.Setup/Installation/LinkSafeDelete.cs b/src/Filee.Setup/Installation/LinkSafeDelete.cs new file mode 100644 index 000000000..6c48f0bfe --- /dev/null +++ b/src/Filee.Setup/Installation/LinkSafeDelete.cs @@ -0,0 +1,162 @@ +// Deleting from an elevated Setup in folders a standard user can change (Filee 1.1's %LocalAppData%\Filee, the +// settings in %AppData%). The user could put a junction or symbolic link there, or swap a folder for one while Setup +// runs, so that Setup deletes files somewhere else with admin rights. So a link is removed itself and never followed, +// and every entry is opened first (without following a link) and deleted through that handle only once its real path +// is inside the folder being deleted. Checking a path and then deleting by path would leave a gap to swap a folder in. + +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using Microsoft.Win32.SafeHandles; + +namespace Filee.Setup.Installation; + +[SupportedOSPlatform("windows")] +internal static partial class LinkSafeDelete +{ + public enum Outcome + { + Deleted, + /// Not there (any more). + Gone, + /// Open in a program, read-only to us, or a folder that isn't empty. + Failed, + /// Its real path is outside the folder being deleted: a folder on the way was swapped for a link. + Outside, + } + + private const uint Delete = 0x00010000; + private const uint ReadAttributes = 0x0080; + private const uint WriteAttributes = 0x0100; + private const uint ShareAll = 0x1 | 0x2 | 0x4; + private const uint OpenExisting = 3; + private const uint BackupSemantics = 0x02000000; // also opens folders + private const uint OpenReparsePoint = 0x00200000; // the link itself, not what it points to + private const int ErrorFileNotFound = 2; + private const int ErrorPathNotFound = 3; + private const int FileBasicInfo = 0; + private const int FileDispositionInfo = 4; + private const int FileDispositionInfoEx = 21; + private const uint DispositionDelete = 0x1; + private const uint DispositionPosixSemantics = 0x2; // the name goes when the handle closes, even if others have it open + private const uint DispositionIgnoreReadOnly = 0x10; + private const uint AttributeReadOnly = 0x1; + private const uint AttributeNormal = 0x80; + + /// + /// The real path of , or null when it isn't there or is reached through a junction or + /// link (it or a folder above it): then nothing in it is deleted. + /// + public static string? RealFolder(string folder) + { + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + using var handle = CreateFileW(full, 0, ShareAll, 0, OpenExisting, BackupSemantics, 0); + if (handle.IsInvalid || FinalPath(handle) is not { } real) + return null; + // The long form, as the final path has it (a temp folder can be given as C:\Users\RUNNER~1\...). + return string.Equals(real, LongPath(full), StringComparison.OrdinalIgnoreCase) ? real : null; + } + + /// + /// Deletes the file, empty folder or link at if it really is inside + /// (from ). A link is deleted itself. + /// + public static Outcome Entry(string path, string realRoot) + { + using var handle = CreateFileW(path, Delete | ReadAttributes | WriteAttributes, ShareAll, 0, OpenExisting, + BackupSemantics | OpenReparsePoint, 0); + if (handle.IsInvalid) + return Marshal.GetLastPInvokeError() is ErrorFileNotFound or ErrorPathNotFound ? Outcome.Gone : Outcome.Failed; + if (FinalPath(handle) is not { } real || !real.StartsWith(realRoot + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + return Outcome.Outside; + return MarkForDeletion(handle) ? Outcome.Deleted : Outcome.Failed; + } + + private static unsafe bool MarkForDeletion(SafeFileHandle handle) + { + var flags = DispositionDelete | DispositionPosixSemantics | DispositionIgnoreReadOnly; + if (SetFileInformationByHandle(handle, FileDispositionInfoEx, &flags, sizeof(uint))) + return true; + // A volume without POSIX deletes (FAT): the older call, which refuses a read-only file until that is cleared. + byte delete = 1; + if (SetFileInformationByHandle(handle, FileDispositionInfo, &delete, sizeof(byte))) + return true; + BasicInfo basic; + if (!GetFileInformationByHandleEx(handle, FileBasicInfo, &basic, (uint)sizeof(BasicInfo)) + || (basic.Attributes & AttributeReadOnly) == 0) + return false; + var writable = new BasicInfo { Attributes = basic.Attributes & ~AttributeReadOnly }; + if (writable.Attributes == 0) + writable.Attributes = AttributeNormal; + return SetFileInformationByHandle(handle, FileBasicInfo, &writable, (uint)sizeof(BasicInfo)) + && SetFileInformationByHandle(handle, FileDispositionInfo, &delete, sizeof(byte)); + } + + private static unsafe string? FinalPath(SafeFileHandle handle) + { + var buffer = new char[1024]; + while (true) + { + uint length; + fixed (char* chars = buffer) + length = GetFinalPathNameByHandleW(handle, chars, (uint)buffer.Length, 0); + if (length == 0) + return null; + if (length < buffer.Length) + return WithoutPrefix(new string(buffer, 0, (int)length)); + buffer = new char[length]; // too small: length is the size needed, terminator included + } + } + + private static unsafe string LongPath(string path) + { + var buffer = new char[1024]; + while (true) + { + uint length; + fixed (char* chars = buffer) + length = GetLongPathNameW(path, chars, (uint)buffer.Length); + if (length == 0) + return path; + if (length < buffer.Length) + return new string(buffer, 0, (int)length); + buffer = new char[length]; + } + } + + /// \\?\C:\x → C:\x, \\?\UNC\server\share → \\server\share. + internal static string WithoutPrefix(string path) + { + if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase)) + return @"\\" + path[8..]; + if (path.StartsWith(@"\\?\", StringComparison.Ordinal)) + return path[4..]; + return path; + } + + [StructLayout(LayoutKind.Sequential)] + private struct BasicInfo + { + public long CreationTime; + public long LastAccessTime; + public long LastWriteTime; + public long ChangeTime; + public uint Attributes; + } + + [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static partial SafeFileHandle CreateFileW(string name, uint access, uint share, nint security, uint creation, uint flags, nint template); + + [LibraryImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", SetLastError = true)] + private static unsafe partial uint GetFinalPathNameByHandleW(SafeFileHandle handle, char* buffer, uint size, uint flags); + + [LibraryImport("kernel32.dll", EntryPoint = "GetLongPathNameW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static unsafe partial uint GetLongPathNameW(string path, char* buffer, uint size); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool SetFileInformationByHandle(SafeFileHandle handle, int infoClass, void* info, uint size); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool GetFileInformationByHandleEx(SafeFileHandle handle, int infoClass, void* info, uint size); +} diff --git a/src/Filee.Setup/Installation/PreviousInstall.cs b/src/Filee.Setup/Installation/PreviousInstall.cs index fac4e8a54..7d9a17dc1 100644 --- a/src/Filee.Setup/Installation/PreviousInstall.cs +++ b/src/Filee.Setup/Installation/PreviousInstall.cs @@ -101,26 +101,33 @@ public static void Remove(SetupPaths paths, ISetupRegistry registry, ISetupSyste log.Info($"Removing Filee 1.1 (Velopack) from {root}; settings and engines stay"); // Its Explorer menu entry points into the folder that goes next. system.UnregisterExplorerMenu(); + // All of it is the user's own and Setup may be elevated: nothing through a link, nothing left for the restart. foreach (var file in new[] { "Update.exe", SetupNames.AppExe }) - DeleteFile(Path.Combine(root, file), system, log); - FileSwap.DeleteTree(Path.Combine(root, "current"), system, log); - FileSwap.DeleteTree(Path.Combine(root, "packages"), system, log); - DeleteFile(Path.Combine(paths.UserStartMenu, SetupNames.ShortcutName), system, log); - DeleteFile(Path.Combine(paths.UserDesktop, SetupNames.ShortcutName), system, log); + DeleteFile(Path.Combine(root, file), log); + FileSwap.DeleteTree(Path.Combine(root, "current"), system, log, userFolder: true); + FileSwap.DeleteTree(Path.Combine(root, "packages"), system, log, userFolder: true); + DeleteFile(Path.Combine(paths.UserStartMenu, SetupNames.ShortcutName), log); + DeleteFile(Path.Combine(paths.UserDesktop, SetupNames.ShortcutName), log); registry.DeleteKey(Hive.CurrentUser, SetupNames.VelopackUninstallKey); } - private static void DeleteFile(string path, ISetupSystem system, SetupLog log) + private static void DeleteFile(string path, SetupLog log) { - try + if (!OperatingSystem.IsWindows() || !Path.Exists(path)) + return; + if (LinkSafeDelete.RealFolder(Path.GetDirectoryName(path)!) is not { } folder) { - if (File.Exists(path)) - File.Delete(path); + log.Warn($"Not deleting {path}: its folder is reached through a junction or link"); + return; } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + switch (LinkSafeDelete.Entry(path, folder)) { - log.Info($"In use, deleted at the next restart: {path}"); - system.DeleteAtRestart(path); + case LinkSafeDelete.Outcome.Failed: + log.Info($"In use, left in place: {path}"); + break; + case LinkSafeDelete.Outcome.Outside: + log.Warn($"Not deleting {path}: it is no longer inside {folder}"); + break; } } } diff --git a/src/Filee.Setup/Installation/Uninstaller.cs b/src/Filee.Setup/Installation/Uninstaller.cs index 05014b0c9..de1e0ed99 100644 --- a/src/Filee.Setup/Installation/Uninstaller.cs +++ b/src/Filee.Setup/Installation/Uninstaller.cs @@ -136,7 +136,7 @@ public IReadOnlyList Run(string folder, InstallRecord record, bool delet if (deleteSettings) { Log.Info($"Deleting the settings in {context.Paths.SettingsFolder}"); - FileSwap.DeleteTree(context.Paths.SettingsFolder, System, Log); + FileSwap.DeleteTree(context.Paths.SettingsFolder, System, Log, userFolder: true); } releaseUninstaller?.Invoke(); diff --git a/tests/Filee.Setup.Tests/LinkSafeDeleteTests.cs b/tests/Filee.Setup.Tests/LinkSafeDeleteTests.cs new file mode 100644 index 000000000..a473d69b5 --- /dev/null +++ b/tests/Filee.Setup.Tests/LinkSafeDeleteTests.cs @@ -0,0 +1,119 @@ +// Setup runs elevated and deletes inside folders the user can change. A junction there (which any user can make) must +// never take a delete outside the folder. The junctions here are real ones, made with mklink /J. + +using System.Diagnostics; +using Filee.Setup.Installation; +using Filee.Setup.Platform; + +namespace Filee.Setup.Tests; + +[System.Runtime.Versioning.SupportedOSPlatform("windows")] +public class LinkSafeDeleteTests +{ + private static void Junction(string link, string target) + { + Directory.CreateDirectory(Path.GetDirectoryName(link)!); + var start = new ProcessStartInfo("cmd.exe", $"/c mklink /J \"{link}\" \"{target}\"") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + using var process = Process.Start(start)!; + process.WaitForExit(); + Assert.True(Directory.Exists(link), $"mklink /J failed: {process.StandardError.ReadToEnd()}"); + } + + [Fact] + public void A_junction_inside_the_tree_goes_but_what_it_points_to_stays() + { + using var temp = new TempFolder(); + var outside = temp.Write(@"outside\canary.txt", "keep"); + temp.Write(@"tree\a.txt"); + temp.Write(@"tree\sub\b.txt"); + Junction(temp.Sub(@"tree\sub\link"), temp.Sub("outside")); + var system = new FakeSystem(); + + FileSwap.DeleteTree(temp.Sub("tree"), system, new SetupLog(null)); + + Assert.False(Directory.Exists(temp.Sub("tree"))); + Assert.Equal("keep", File.ReadAllText(outside)); + Assert.Empty(system.Calls); + } + + [Fact] + public void A_folder_that_is_a_junction_loses_only_the_junction() + { + using var temp = new TempFolder(); + var outside = temp.Write(@"outside\canary.txt", "keep"); + Junction(temp.Sub("tree"), temp.Sub("outside")); + + FileSwap.DeleteTree(temp.Sub("tree"), new FakeSystem(), new SetupLog(null)); + + Assert.False(Path.Exists(temp.Sub("tree"))); + Assert.Equal("keep", File.ReadAllText(outside)); + } + + [Fact] + public void Nothing_is_deleted_in_a_folder_reached_through_a_junction() + { + using var temp = new TempFolder(); + var outside = temp.Write(@"outside\current\canary.txt", "keep"); + Junction(temp.Sub("root"), temp.Sub("outside")); + + FileSwap.DeleteTree(temp.Sub(@"root\current"), new FakeSystem(), new SetupLog(null), userFolder: true); + + Assert.Equal("keep", File.ReadAllText(outside)); + } + + [Fact] + public void A_file_whose_folder_was_swapped_for_a_junction_is_not_deleted() + { + using var temp = new TempFolder(); + var root = LinkSafeDelete.RealFolder(Directory.CreateDirectory(temp.Sub("tree")).FullName)!; + var outside = temp.Write(@"outside\canary.txt", "keep"); + // As if a folder inside the tree was swapped for a junction after the tree was checked. + Junction(temp.Sub(@"tree\sub"), temp.Sub("outside")); + + Assert.Equal(LinkSafeDelete.Outcome.Outside, LinkSafeDelete.Entry(temp.Sub(@"tree\sub\canary.txt"), root)); + Assert.Equal("keep", File.ReadAllText(outside)); + Assert.Equal(LinkSafeDelete.Outcome.Deleted, LinkSafeDelete.Entry(temp.Sub(@"tree\sub"), root)); + Assert.True(File.Exists(outside)); + } + + [Fact] + public void Read_only_files_go_and_a_file_in_use_waits_for_the_restart_only_outside_the_users_folders() + { + using var temp = new TempFolder(); + File.SetAttributes(temp.Write(@"tree\read-only.txt"), FileAttributes.ReadOnly); + var busy = temp.Write(@"tree\busy.txt"); + var system = new FakeSystem(); + using (new FileStream(busy, FileMode.Open, FileAccess.Read, FileShare.None)) + { + FileSwap.DeleteTree(temp.Sub("tree"), system, new SetupLog(null)); + Assert.False(File.Exists(temp.Sub(@"tree\read-only.txt"))); + Assert.Contains($"delete-at-restart {busy}", system.Calls); + + var users = new FakeSystem(); + FileSwap.DeleteTree(temp.Sub("tree"), users, new SetupLog(null), userFolder: true); + Assert.DoesNotContain(users.Calls, call => call.StartsWith("delete-at-restart", StringComparison.Ordinal)); + } + } + + [Fact] + public void Filee_1_1_removal_never_follows_a_junction_planted_in_its_folder() + { + using var bench = new SetupBench(); + var root = VelopackInstall.Root(bench.Paths); + bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), "Update.exe")); + bench.Temp.Write(Path.Combine(Path.GetRelativePath(bench.Temp.Path, root), @"current\Filee.exe")); + var canary = bench.Temp.Write(@"admin-only\canary.txt", "keep"); + Junction(Path.Combine(root, @"current\j"), bench.Temp.Sub("admin-only")); + + Assert.True(bench.Install().Succeeded); + + Assert.False(Directory.Exists(Path.Combine(root, "current"))); + Assert.Equal("keep", File.ReadAllText(canary)); + } +} From fd1d1f516642a7d139b4801cc172eb5079cc4abe Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Thu, 12 Nov 2026 15:47:32 +0900 Subject: [PATCH 04/95] fix(setup): elevate the uninstaller before it copies itself An uninstall for all users started without administrator rights copied uninstall.exe into the user's %TEMP% and started that copy with "runas". Any program of the same user could swap the copy between the copy and the start, and the prompt and the administrator token went to it. The unelevated uninstaller now asks for administrator rights for the uninstall.exe in the install folder itself, which only administrators can change. The elevated one makes the copy in a new folder in %SystemRoot%\Temp, created with SYSTEM and Administrators as the only ones allowed to change it and nothing inherited from the parent, and holds the copy open without write or delete sharing while it starts it with its own token (CreateProcess, no shell lookup). Standard users have no delete-child right on %SystemRoot%\Temp, so they can't rename the folder away either, as they could in their own %TEMP%. The trash for files in use stays inside that folder. Both uninstallers in the install folder run from the file the copy deletes, so /FIRSTPHASE now takes a list and the copy waits for both. An uninstall without administrator rights still copies to %TEMP%. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Setup/Platform/NativeMethods.cs | 48 +++++++ src/Filee.Setup/Platform/SetupPaths.cs | 13 +- src/Filee.Setup/Program.cs | 124 ++++++++++++++---- src/Filee.Setup/SetupOptions.cs | 24 +++- tests/Filee.Setup.Tests/SetupOptionsTests.cs | 7 +- tests/Filee.Setup.Tests/UninstallCopyTests.cs | 118 +++++++++++++++++ 6 files changed, 299 insertions(+), 35 deletions(-) create mode 100644 tests/Filee.Setup.Tests/UninstallCopyTests.cs diff --git a/src/Filee.Setup/Platform/NativeMethods.cs b/src/Filee.Setup/Platform/NativeMethods.cs index 8ec31ee70..4fc1b7eda 100644 --- a/src/Filee.Setup/Platform/NativeMethods.cs +++ b/src/Filee.Setup/Platform/NativeMethods.cs @@ -1,5 +1,6 @@ // Win32 functions Setup calls (source-generated P/Invoke, trim- and AOT-safe). +using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Principal; @@ -294,6 +295,53 @@ private static unsafe bool CreateAsShellUser(string executable, string arguments public static void BroadcastEnvironmentChange() => SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", SMTO_ABORTIFHUNG, 5000, out _); + [StructLayout(LayoutKind.Sequential)] + private struct SecurityAttributes + { + public int Length; + public nint SecurityDescriptor; + public int InheritHandle; + } + + [LibraryImport("advapi32.dll", EntryPoint = "ConvertStringSecurityDescriptorToSecurityDescriptorW", SetLastError = true, + StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool ConvertStringSecurityDescriptorToSecurityDescriptor(string sddl, uint revision, out nint descriptor, nint size); + + [LibraryImport("kernel32.dll", EntryPoint = "CreateDirectoryW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + [return: MarshalAs(UnmanagedType.Bool)] + private static unsafe partial bool CreateDirectory(string path, SecurityAttributes* attributes); + + [LibraryImport("kernel32.dll")] + private static partial nint LocalFree(nint memory); + + /// + /// Creates a new folder, with the security of from the start when given (else the inherited + /// one). Unlike Directory.CreateDirectory it fails when something is there already, so the folder is always this + /// process's own and never one somebody else made first. + /// + /// The folder exists or can't be created. + public static unsafe void CreateNewFolder(string path, string? sddl) + { + nint descriptor = 0; + if (sddl is not null && !ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, out descriptor, 0)) + throw new Win32Exception(Marshal.GetLastPInvokeError()); + try + { + var attributes = new SecurityAttributes { Length = sizeof(SecurityAttributes), SecurityDescriptor = descriptor }; + if (!CreateDirectory(path, sddl is null ? null : &attributes)) + { + var error = Marshal.GetLastPInvokeError(); + throw new Win32Exception(error, $"Could not create {path}: {new Win32Exception(error).Message}"); + } + } + finally + { + if (descriptor != 0) + LocalFree(descriptor); + } + } + /// The Windows display language, e.g. "ko-KR" (with InvariantGlobalization .NET can't tell). public static unsafe string UiLanguage() { diff --git a/src/Filee.Setup/Platform/SetupPaths.cs b/src/Filee.Setup/Platform/SetupPaths.cs index 96c6dbc06..05f55bcfd 100644 --- a/src/Filee.Setup/Platform/SetupPaths.cs +++ b/src/Filee.Setup/Platform/SetupPaths.cs @@ -13,6 +13,10 @@ namespace Filee.Setup.Platform; /// %LocalAppData%: downloaded engines (LocalAppData\Filee\engines), Filee 1.1's Velopack copy. /// Setup's temporary files. /// System32 (the Microsoft C++ runtime, if installed). +/// +/// %SystemRoot%\Temp: where an elevated uninstaller puts its copy. Standard users may create folders in it but can't +/// rename or delete what an administrator made there, unlike in their own %TEMP%. +/// public sealed record SetupPaths( string ProgramFiles, string UserPrograms, @@ -23,7 +27,8 @@ public sealed record SetupPaths( string AppData, string LocalAppData, string Temp, - string SystemFolder) + string SystemFolder, + string SystemTemp) { /// Filee's settings folder (UserDataStore.DefaultDirectory without FILEE_DATA_DIR). public string SettingsFolder => Path.Combine(AppData, "Filee"); @@ -55,7 +60,8 @@ static string Folder(Environment.SpecialFolder folder) => Folder(Environment.SpecialFolder.ApplicationData), localAppData, Path.GetTempPath(), - Environment.SystemDirectory); + Environment.SystemDirectory, + Path.Combine(Folder(Environment.SpecialFolder.Windows), "Temp")); } /// Every folder inside (System32 stays the real one: it is only read). @@ -73,6 +79,7 @@ public static SetupPaths Sandbox(string root) Sub("AppData"), Sub("LocalAppData"), Sub("Temp"), - Environment.SystemDirectory); + Environment.SystemDirectory, + Sub(Path.Combine("Windows", "Temp"))); } } diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.cs index daf56d45f..ea1616500 100644 --- a/src/Filee.Setup/Program.cs +++ b/src/Filee.Setup/Program.cs @@ -4,8 +4,9 @@ // Rights: the program starts without administrator rights (asInvoker). An install for all users starts itself again // with them (one UAC prompt) and waits; the elevated copy writes what to start at the end into a file, and this // unelevated one starts Filee as the signed-in user: Filee must not run elevated (Windows blocks drag and drop from -// Explorer into elevated windows). The uninstaller first copies itself to %TEMP% and runs from there (with -// administrator rights when needed), so the install folder can be deleted. +// Explorer into elevated windows). The uninstaller first copies itself out of the install folder and runs from there, +// so the install folder can be deleted. One for all users asks for administrator rights before that, from the install +// folder, and the elevated one makes the copy where standard users can't change it (see CopyUninstaller). using System.ComponentModel; using System.Diagnostics; @@ -210,20 +211,26 @@ private static int Uninstall(string[] args, SetupOptions options, string exe, Se texts.SetLanguage(language); var needsAdmin = record.Scope == InstallScope.Machine && sandbox is null && !NativeMethods.IsElevated(); - // Phase 1: running from the install folder, which can't be deleted while this runs. Copy to %TEMP% and wait. + // Phase 1: running from the install folder, which can't be deleted while this runs. Copy out of it and wait. var exeFolder = Path.TrimEndingDirectorySeparator(Path.GetDirectoryName(exe)!); if (exeFolder.Equals(folder, StringComparison.OrdinalIgnoreCase)) { - var temp = Path.Combine(paths.Temp, $"Filee-Uninstall-{Guid.NewGuid():N}"); - Directory.CreateDirectory(temp); - var copy = Path.Combine(temp, SetupNames.UninstallerExe); - File.Copy(exe, copy); - var childArgs = args.Where(a => !HasName(a, "/DIR") && !HasName(a, "/LOG") && !HasName(a, "/UNINSTALL") && !HasName(a, "/FIRSTPHASE")) - .Concat(["/UNINSTALL", $"/DIR={folder}", $"/LOG={log.File}", $"/FIRSTPHASE={Environment.ProcessId}"]); + // Administrator rights first, for this file: only administrators can change an install for all users, so + // the prompt is never answered for a file another program of this user has put there. The elevated one + // makes the copy, and its copy waits for this one to end too: both run from the uninstall.exe it deletes. + if (needsAdmin) + return RunElevated(exe, [.. args.Where(a => !HasName(a, "/FIRSTPHASE")), $"/FIRSTPHASE={Environment.ProcessId}"], log, launchFile: null); + var copy = CopyUninstaller(exe, paths, NativeMethods.IsElevated()); + var temp = Path.GetDirectoryName(copy)!; log.Info($"Continuing from {copy}"); - // Waits for the copy, or for its word that only this uninstall.exe is left (it then deletes it). + // Waits for the copy, or for its word that only uninstall.exe is left (it then deletes it). var released = Path.Combine(temp, ReleasedFile); - var code = RunAndWait(copy, childArgs, elevated: needsAdmin, log, until: () => File.Exists(released)); + int code; + // Held open without write or delete sharing while it starts, on top of the folder's rights: nothing can + // change the copy between here and its start. + using (new FileStream(copy, FileMode.Open, FileAccess.Read, FileShare.Read)) + code = RunAndWait(copy, SecondPhaseArgs(args, folder, log.File, [Environment.ProcessId, .. options.FirstPhase]), elevated: false, log, + until: () => File.Exists(released)); if (code == ExitCancelled) TryDeleteFolder(temp); return code; @@ -231,12 +238,13 @@ private static int Uninstall(string[] args, SetupOptions options, string exe, Se if (needsAdmin) return RunElevated(exe, args, log, launchFile: null); - // Phase 2: from a copy in %TEMP%. - var fromTemp = Path.GetFileName(exeFolder).StartsWith("Filee-Uninstall-", StringComparison.OrdinalIgnoreCase); - var trash = fromTemp ? Path.Combine(exeFolder, "trash") : Path.Combine(paths.Temp, $"Filee-Uninstall-{Guid.NewGuid():N}"); + // Phase 2: from the copy. + var fromTemp = Path.GetFileName(exeFolder).StartsWith(CopyFolderPrefix, StringComparison.OrdinalIgnoreCase); + // In the copy's folder, the files still in use are out of reach for standard users too until the restart. + var trash = fromTemp ? Path.Combine(exeFolder, "trash") : Path.Combine(paths.Temp, $"{CopyFolderPrefix}{Guid.NewGuid():N}"); var runner = new SetupRunner(context, null, null, folder, record, trash) { - ReleaseFirstPhase = options.FirstPhase is { } first && fromTemp ? () => ReleaseFirstPhase(exeFolder, first, log) : null, + ReleaseFirstPhase = options.FirstPhase.Count > 0 && fromTemp ? () => ReleaseFirstPhase(exeFolder, options.FirstPhase, log) : null, }; int exitCode; if (options.Ui == SetupUi.VerySilent) @@ -273,23 +281,86 @@ int Fail(Exception error) /// Written by the uninstaller's copy when only uninstall.exe is left (see ). private const string ReleasedFile = "released"; - /// Tells the uninstaller in the install folder that it may end, and waits until it has. - private static void ReleaseFirstPhase(string temp, int processId, SetupLog log) + /// The name of the uninstaller copy's folder, followed by a new GUID: the copy knows itself by it. + internal const string CopyFolderPrefix = "Filee-Uninstall-"; + + /// + /// The rights of an elevated uninstaller's copy folder: SYSTEM and administrators only, nothing inherited from the + /// parent (in %SystemRoot%\Temp users may add files to what is below). The OWNER RIGHTS entry takes away what an + /// owner may otherwise always do, change these rights, should Windows make the signed-in user the owner rather + /// than Administrators. + /// + internal const string AdminOnlyFolder = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;OW)"; + + /// + /// Copies the uninstaller into a new folder and returns the copy. An elevated one goes to %SystemRoot%\Temp with + /// : in the user's %TEMP% any program of theirs could swap the copy before it starts + /// with administrator rights, and even a folder they can't open could be renamed away and replaced there, since + /// %TEMP% lets them delete what is in it. Without administrator rights there is nothing to guard. + /// + internal static string CopyUninstaller(string exe, SetupPaths paths, bool elevated) { + var parent = elevated ? paths.SystemTemp : paths.Temp; + Directory.CreateDirectory(parent); + var temp = Path.Combine(parent, $"{CopyFolderPrefix}{Guid.NewGuid():N}"); + NativeMethods.CreateNewFolder(temp, elevated ? AdminOnlyFolder : null); + var copy = Path.Combine(temp, SetupNames.UninstallerExe); + File.Copy(exe, copy); + return copy; + } + + /// The copy's command line. : the uninstallers in the install folder that wait for it. + internal static IEnumerable SecondPhaseArgs(string[] args, string folder, string? logFile, IEnumerable firstPhase) => + args.Where(a => !HasName(a, "/DIR") && !HasName(a, "/LOG") && !HasName(a, "/UNINSTALL") && !HasName(a, "/FIRSTPHASE")) + .Concat(["/UNINSTALL", $"/DIR={folder}", $"/LOG={logFile}", $"/FIRSTPHASE={string.Join(',', firstPhase)}"]); + + /// + /// Tells the uninstallers in the install folder that they may end, and waits until they have: the elevated one + /// ends on the word, and then the unelevated one that waited for it. + /// + private static void ReleaseFirstPhase(string temp, IReadOnlyList processIds, SetupLog log) + { + // Looked up before the word, while they all still run and wait for it. + var first = new List(); + foreach (var id in processIds) + { + try + { + first.Add(Process.GetProcessById(id)); + } + catch (ArgumentException) + { + // Ended already. + } + } try { - using var first = Process.GetProcessById(processId); + if (first.Count == 0) + return; File.WriteAllText(Path.Combine(temp, ReleasedFile), "0"); - if (!first.WaitForExit(TimeSpan.FromSeconds(30))) - log.Warn("The first uninstaller did not end"); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + foreach (var process in first) + { + try + { + var left = deadline - DateTime.UtcNow; + if (!process.WaitForExit(left > TimeSpan.Zero ? left : TimeSpan.Zero)) + log.Warn($"The first uninstaller (process {process.Id}) did not end"); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) + { + log.Warn($"Could not wait for the first uninstaller (process {process.Id}): {ex.Message}"); + } + } } - catch (ArgumentException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - // Ended already. + log.Warn($"Could not release the first uninstaller: {ex.Message}"); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or Win32Exception or InvalidOperationException) + finally { - log.Warn($"Could not release the first uninstaller: {ex.Message}"); + foreach (var process in first) + process.Dispose(); } } @@ -349,9 +420,12 @@ private static int RunElevated(string exe, string[] args, SetupLog log, string? /// Stops waiting early when true (checked every 100 ms); the exit code is then 0. private static int RunAndWait(string exe, IEnumerable args, bool elevated, SetupLog log, Func? until = null) { + // Only the prompt for administrator rights needs the shell. Otherwise CreateProcess starts exactly this file: + // the shell would look up how to open it, also in the user's own part of the registry, which an elevated + // uninstaller must not follow. var info = new ProcessStartInfo(exe, SetupOptions.Join(args)) { - UseShellExecute = true, + UseShellExecute = elevated, WorkingDirectory = Environment.SystemDirectory, }; if (elevated) diff --git a/src/Filee.Setup/SetupOptions.cs b/src/Filee.Setup/SetupOptions.cs index 09f4bfe1f..848e2c183 100644 --- a/src/Filee.Setup/SetupOptions.cs +++ b/src/Filee.Setup/SetupOptions.cs @@ -28,8 +28,9 @@ // /UNINSTALL uninstall (uninstall.exe, which has no payload, does this without the switch) // /LAUNCHFILE="file" internal: the unelevated Setup that asked for administrator rights starts Filee as the // signed-in user from what the elevated one writes into this file -// /FIRSTPHASE= internal: the uninstaller's copy in %TEMP% lets the uninstaller in the install folder -// (process ) end before it deletes its file +// /FIRSTPHASE=, internal: the uninstaller's copy lets the uninstallers in the install folder (these +// processes: the one that started it, and the unelevated one that asked for administrator +// rights before) end before it deletes their file namespace Filee.Setup; @@ -74,7 +75,7 @@ public sealed record SetupOptions public bool Uninstall { get; init; } public string? Sandbox { get; init; } public string? LaunchFile { get; init; } - public int? FirstPhase { get; init; } + public IReadOnlyList FirstPhase { get; init; } = []; /// Inno Setup switches that are accepted but change nothing. public IReadOnlyList Ignored { get; init; } = []; @@ -157,8 +158,8 @@ public static SetupOptions Parse(IReadOnlyList args) case "SANDBOX" when !string.IsNullOrWhiteSpace(value): options = options with { Sandbox = value }; break; - case "FIRSTPHASE" when int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id): - options = options with { FirstPhase = id }; + case "FIRSTPHASE" when ProcessIds(value) is { } ids: + options = options with { FirstPhase = ids }; break; case "LAUNCHFILE" when !string.IsNullOrWhiteSpace(value): options = options with { LaunchFile = value }; @@ -176,6 +177,19 @@ public static SetupOptions Parse(IReadOnlyList args) return options with { Ignored = ignored, Unknown = unknown }; } + /// "12,34": the process numbers, or null when a part isn't one. + private static List? ProcessIds(string? value) + { + var ids = new List(); + foreach (var part in (value ?? "").Split(',')) + { + if (!int.TryParse(part, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id)) + return null; + ids.Add(id); + } + return ids; + } + /// Inno Setup takes /DIR="C:\a b" and /DIR=C:\a b alike; quotes left over from a hand-made command line go. private static string Unquote(string value) { diff --git a/tests/Filee.Setup.Tests/SetupOptionsTests.cs b/tests/Filee.Setup.Tests/SetupOptionsTests.cs index d4ab00763..bceb8d589 100644 --- a/tests/Filee.Setup.Tests/SetupOptionsTests.cs +++ b/tests/Filee.Setup.Tests/SetupOptionsTests.cs @@ -75,8 +75,11 @@ public void Scope_portable_and_logging() public void Filee_switches_and_unknown_arguments() { var options = SetupOptions.Parse(["/NOLAUNCH", "/UNINSTALL", "/SANDBOX=D:\\scratch", "/LAUNCHFILE=C:\\t\\x.launch", "/FIRSTPHASE=4242", "--weird", "/WHAT", "file.txt"]); - Assert.Equal(4242, options.FirstPhase); - Assert.Null(SetupOptions.Parse(["/FIRSTPHASE=-1"]).FirstPhase); + Assert.Equal([4242], options.FirstPhase); + Assert.Equal([4242, 17], SetupOptions.Parse(["/FIRSTPHASE=4242,17"]).FirstPhase); + Assert.Empty(SetupOptions.Parse(["/FIRSTPHASE=-1"]).FirstPhase); + Assert.Empty(SetupOptions.Parse(["/FIRSTPHASE=1,x"]).FirstPhase); + Assert.Empty(SetupOptions.Parse([]).FirstPhase); Assert.True(options.NoLaunch); Assert.True(options.Uninstall); Assert.Equal(@"D:\scratch", options.Sandbox); diff --git a/tests/Filee.Setup.Tests/UninstallCopyTests.cs b/tests/Filee.Setup.Tests/UninstallCopyTests.cs new file mode 100644 index 000000000..f2a1d759c --- /dev/null +++ b/tests/Filee.Setup.Tests/UninstallCopyTests.cs @@ -0,0 +1,118 @@ +using System.ComponentModel; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; +using Filee.Setup.Platform; + +namespace Filee.Setup.Tests; + +/// Where the uninstaller copies itself before it deletes the install folder, and what the copy is told. +[SupportedOSPlatform("windows")] +public class UninstallCopyTests +{ + private static readonly SecurityIdentifier OwnerRights = new("S-1-3-4"); + + [Fact] + public void Without_administrator_rights_the_copy_goes_to_a_new_folder_in_the_users_temp() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "The uninstaller is for Windows."); + using var temp = new TempFolder(); + var paths = SetupPaths.Sandbox(temp.Sub("pc")); + var exe = temp.Write(@"Filee\uninstall.exe", "uninstaller"); + + var copy = Program.CopyUninstaller(exe, paths, elevated: false); + var folder = Path.GetDirectoryName(copy)!; + Assert.Equal(paths.Temp, Path.GetDirectoryName(folder)); + // Phase 2 knows it runs from a copy by this name. + Assert.StartsWith(Program.CopyFolderPrefix, Path.GetFileName(folder)); + Assert.Equal("uninstall.exe", Path.GetFileName(copy)); + Assert.Equal("uninstaller", File.ReadAllText(copy)); + Assert.NotEqual(folder, Path.GetDirectoryName(Program.CopyUninstaller(exe, paths, elevated: false))); + } + + [Fact] + public void An_elevated_copy_goes_where_only_administrators_can_change_it() + { + Assert.SkipUnless(OperatingSystem.IsWindows() && NativeMethods.IsElevated(), "Needs administrator rights, like the CI runner."); + using var temp = new TempFolder(); + var paths = SetupPaths.Sandbox(temp.Sub("pc")); + var exe = temp.Write(@"Filee\uninstall.exe", "uninstaller"); + + var copy = Program.CopyUninstaller(exe, paths, elevated: true); + var folder = Path.GetDirectoryName(copy)!; + Assert.Equal(paths.SystemTemp, Path.GetDirectoryName(folder)); + Assert.StartsWith(Program.CopyFolderPrefix, Path.GetFileName(folder)); + Assert.Equal("uninstaller", File.ReadAllText(copy)); + AssertAdminOnly(new DirectoryInfo(folder).GetAccessControl()); + // The copy and the trash phase 2 makes next to it take the folder's rights. + AssertAdminOnly(new FileInfo(copy).GetAccessControl(), inherited: true); + Directory.CreateDirectory(Path.Combine(folder, "trash")); + AssertAdminOnly(new DirectoryInfo(Path.Combine(folder, "trash")).GetAccessControl(), inherited: true); + } + + [Fact] + public void The_admin_only_folder_takes_nothing_from_its_parent() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "The uninstaller is for Windows."); + using var temp = new TempFolder(); + // The scratch folder gives this user full control, and the new folder must not inherit it. Without + // administrator rights the test can still read the rights (the owner's), and delete the empty folder through + // the parent, which is what the uninstaller's own folder must never allow. + var folder = temp.Sub(Program.CopyFolderPrefix + "test"); + NativeMethods.CreateNewFolder(folder, Program.AdminOnlyFolder); + try + { + AssertAdminOnly(new DirectoryInfo(folder).GetAccessControl()); + } + finally + { + Directory.Delete(folder); + } + } + + [Fact] + public void A_folder_that_is_there_already_is_never_taken_over() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "The uninstaller is for Windows."); + using var temp = new TempFolder(); + var folder = temp.Sub("taken"); + Directory.CreateDirectory(folder); + const int ErrorAlreadyExists = 183; + Assert.Equal(ErrorAlreadyExists, Assert.Throws(() => NativeMethods.CreateNewFolder(folder, Program.AdminOnlyFolder)).NativeErrorCode); + Assert.Equal(ErrorAlreadyExists, Assert.Throws(() => NativeMethods.CreateNewFolder(folder, null)).NativeErrorCode); + } + + [Fact] + public void The_copy_waits_for_every_uninstaller_in_the_install_folder() + { + string[] args = ["/SILENT", "/DIR=old", "/LOG=old.log", "/FIRSTPHASE=9", "/UNINSTALL", "/LANG=ko"]; + var child = Program.SecondPhaseArgs(args, @"C:\Program Files\Filee", @"C:\Users\a b\Temp\u.log", [12, 34]).ToArray(); + Assert.Equal(["/SILENT", "/LANG=ko", "/UNINSTALL", @"/DIR=C:\Program Files\Filee", @"/LOG=C:\Users\a b\Temp\u.log", "/FIRSTPHASE=12,34"], child); + var options = SetupOptions.Parse(child); + Assert.Equal([12, 34], options.FirstPhase); + Assert.Equal(@"C:\Program Files\Filee", options.Directory); + } + + /// + /// SYSTEM and administrators may do anything, the owner only read, nobody else anything. The folder takes nothing + /// from its parent; what is in it () takes the folder's rights. + /// + private static void AssertAdminOnly(FileSystemSecurity security, bool inherited = false) + { + Assert.Equal(!inherited, security.AreAccessRulesProtected); + var rules = security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)) + .Cast().ToList(); + Assert.NotEmpty(rules); + foreach (var rule in rules) + { + Assert.Equal(AccessControlType.Allow, rule.AccessControlType); + var who = (SecurityIdentifier)rule.IdentityReference; + if (who.IsWellKnown(WellKnownSidType.LocalSystemSid) || who.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid)) + Assert.Equal(FileSystemRights.FullControl, rule.FileSystemRights & FileSystemRights.FullControl); + else if (who == OwnerRights) + Assert.Equal(FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize, rule.FileSystemRights); + else + Assert.Fail($"Unexpected entry for {who}: {rule.FileSystemRights}"); + } + } +} From 23dac2c0470fe1f2343e921beb3426d46744569d Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Thu, 12 Nov 2026 16:36:09 +0900 Subject: [PATCH 05/95] fix(setup): carry Skia and HarfBuzz instead of letting .NET unpack them Setup and the uninstaller were published single-file with IncludeNativeLibrariesForSelfExtract, so the .NET host unpacked libSkiaSharp.dll, libHarfBuzzSharp.dll and av_libglesv2.dll into %TEMP%\.net\\ and, on later starts, reused whatever files it found there without checking them. That folder belongs to the signed-in user, so when Setup or the uninstaller ran with administrator rights it could load native code another program of that user had put there. The publish now embeds Skia and HarfBuzz as resources of Filee.Setup.dll and leaves them out of the bundle and deps.json, so the host has nothing to unpack. Before the window opens, Setup writes them into a folder made new for this run (elevated: in %SystemRoot%\Temp with the admin-only rights the uninstaller copy uses; otherwise in %TEMP%) and loads them right away by full path through a DllImport resolver. Old folders are removed on a later run, this run's after it ends. Setup draws in software with the redirection surface (transparency kept), so ANGLE is no longer carried at all. At start Setup also limits the default DLL search to System32 and resolves every other library named without a folder from System32, instead of next to Setup.exe or on the PATH. A publish check fails if any DLL would land next to the exe. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 6 +- src/Filee.Setup/Filee.Setup.csproj | 30 ++- src/Filee.Setup/Platform/NativeLibraries.cs | 212 ++++++++++++++++++ src/Filee.Setup/Program.cs | 23 +- .../Filee.Setup.Tests/NativeLibrariesTests.cs | 70 ++++++ 5 files changed, 335 insertions(+), 6 deletions(-) create mode 100644 src/Filee.Setup/Platform/NativeLibraries.cs create mode 100644 tests/Filee.Setup.Tests/NativeLibrariesTests.cs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f80436ab5..5c15d9304 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -699,7 +699,11 @@ have no semibold) instead of the app's embedded Noto fonts. update Setup starts Filee with `--background --whats-new`, so the slides show once in the app as well. - **Build** (`build/build-installer.ps1`): Setup is published as one self-contained, trimmed file - (`-p:FileeSetupPublish=true`), so it runs on Windows 10 1809+ x64 without .NET. `build/tools/make-setup.cs` appends + (`-p:FileeSetupPublish=true`), so it runs on Windows 10 1809+ x64 without .NET. Skia and HarfBuzz are resources of + `Filee.Setup.dll` rather than files .NET unpacks at start: `NativeLibraries` writes them into a new folder of its + own before the window opens (elevated, one in `%SystemRoot%\Temp` only administrators can change) and loads them by + full path; other libraries come from System32 only. Setup draws in software, so ANGLE isn't carried. + `build/tools/make-setup.cs` appends the app's publish folder as the payload: `[program][LZMA streams of all files][manifest JSON][72-byte trailer]` (`SetupPayload`): ~48 MB segments compressed in parallel with SharpCompress's LZMA (48 MB dictionary), programs first through the x86 branch filter (`X86Filter`, from the LZMA SDK) as 7-Zip and Inno Setup do. The manifest lists diff --git a/src/Filee.Setup/Filee.Setup.csproj b/src/Filee.Setup/Filee.Setup.csproj index 470a05d73..b1922b763 100644 --- a/src/Filee.Setup/Filee.Setup.csproj +++ b/src/Filee.Setup/Filee.Setup.csproj @@ -27,7 +27,9 @@ true true - true + + false true true full @@ -70,6 +72,32 @@ + + + + <_SetupNative Include="@(NativeCopyLocalItems)" Condition="'%(Filename)%(Extension)' == 'libSkiaSharp.dll' or '%(Filename)%(Extension)' == 'libHarfBuzzSharp.dll'" /> + + + false + + + + + + + + + <_SetupLeftOut Include="$(PublishDir)*.dll" /> + + + + <_Parameter1>RepositoryUrl diff --git a/src/Filee.Setup/Platform/NativeLibraries.cs b/src/Filee.Setup/Platform/NativeLibraries.cs new file mode 100644 index 000000000..ce3cef06e --- /dev/null +++ b/src/Filee.Setup/Platform/NativeLibraries.cs @@ -0,0 +1,212 @@ +// Where Setup's native code comes from. Setup and the uninstaller run with administrator rights for an install for all +// users, so no library they load may come from a folder the signed-in user can change. +// +// A single-file .NET program normally unpacks its native libraries at start into %TEMP%\.net\\ and, on the +// next start, takes whatever files it finds there as its own: any program of the user's could put its own +// libSkiaSharp.dll there first. So the publish carries Skia and HarfBuzz as resources of Filee.Setup.dll instead (see +// Filee.Setup.csproj) and Setup writes them out itself, into a folder made new for this run: with administrator rights +// in %SystemRoot%\Temp with Program.AdminOnlyFolder's rights, where no standard user can change, rename or replace +// anything between writing and loading; without them in the user's %TEMP%, where there are no rights to gain. They are +// loaded right away, by full path. ANGLE (av_libglesv2.dll) isn't published at all: Setup draws in software. +// +// Libraries named without a folder are the other way in: .NET first tries the folder of Setup.exe (for a download, +// Downloads), and Windows then searches the PATH too. Setup only needs Windows' own libraries besides the two above, so +// those come from System32 only. (.NET's own start-up code, before Main, still tries Setup.exe's folder for a few of +// Windows' libraries: that folder must not be one a standard user can change when Setup runs elevated.) + +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; + +namespace Filee.Setup.Platform; + +[SupportedOSPlatform("windows")] +internal static class NativeLibraries +{ + /// The name of an unpacked libraries folder, followed by a new GUID. + internal const string FolderPrefix = "Filee-Native-"; + + /// The libraries the publish carries, by the name SkiaSharp's and HarfBuzzSharp's P/Invokes use. + internal static readonly IReadOnlyList Carried = ["libSkiaSharp", "libHarfBuzzSharp"]; + + private const uint LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x100; + private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x800; + + private static readonly Lock Gate = new(); + private static unsafe delegate* unmanaged _loadLibraryEx; + private static readonly Dictionary Loaded = new(StringComparer.OrdinalIgnoreCase); + + /// This run's folder, once has written the libraries. + public static string? Folder { get; private set; } + + /// True in the published Setup, which carries the libraries; false in a build (they sit next to it). + public static readonly bool AreCarried = typeof(NativeLibraries).Assembly.GetManifestResourceInfo(ResourceName(Carried[0])) is not null; + + private static string ResourceName(string library) => $"native.{library}.dll"; + + /// + /// First thing at start, before any P/Invoke of Setup's: Windows looks only in System32 for libraries loaded + /// without a folder, and .NET asks for every P/Invoke of every assembly (CoreLib's never ask). + /// + public static unsafe void Guard() + { + // Through kernel32 by its full path, not P/Invokes: those would themselves be looked up next to Setup.exe + // first, and the resolver can't use them for the same reason. + var kernel32 = NativeLibrary.Load(Path.Combine(Environment.SystemDirectory, "kernel32.dll")); + _loadLibraryEx = (delegate* unmanaged)NativeLibrary.GetExport(kernel32, "LoadLibraryExW"); + var setDefaultDllDirectories = (delegate* unmanaged)NativeLibrary.GetExport(kernel32, "SetDefaultDllDirectories"); + if (setDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32) == 0) + throw new Win32Exception(Marshal.GetLastSystemError()); + AppDomain.CurrentDomain.AssemblyLoad += (_, e) => Register(e.LoadedAssembly); + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + Register(assembly); + } + + private static unsafe nint LoadLibraryEx(string name, uint flags) + { + fixed (char* chars = name) + return _loadLibraryEx(chars, 0, flags); + } + + private static void Register(Assembly assembly) + { + if (assembly == typeof(object).Assembly) + return; + try + { + NativeLibrary.SetDllImportResolver(assembly, Resolve); + } + catch (InvalidOperationException) + { + // Registered already (the load event and the first list can both see an assembly). + } + } + + /// + /// A carried library: the one loaded. Another library named without a folder: System32's. A + /// path is loaded as it is (0: .NET's own search). In the published Setup, nothing else is looked for anywhere. + /// + internal static nint Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + var library = name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? name[..^4] : name; + if (Carried.Contains(library, StringComparer.OrdinalIgnoreCase)) + { + lock (Gate) + { + if (Loaded.TryGetValue(library, out var handle)) + return handle; + } + return AreCarried ? throw new DllNotFoundException($"{library} is used before Setup has unpacked it.") : 0; + } + if (name.Contains('\\') || name.Contains('/')) + return 0; + var system = LoadLibraryEx(name, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (system != 0 || !AreCarried) + return system; + throw new DllNotFoundException($"{name} is not in System32, and Setup loads no other library by name."); + } + + /// + /// Writes the carried libraries into a new folder and loads them from there; before Avalonia starts. Does nothing in + /// a build (no resources) or when done already. Removes what earlier runs left in the same place first. + /// + public static void Unpack(SetupPaths paths, bool elevated, SetupLog log) + { + if (Folder is not null || !AreCarried) + return; + var parent = elevated ? paths.SystemTemp : paths.Temp; + Directory.CreateDirectory(parent); + RemoveOld(parent, elevated, log); + var folder = Path.Combine(parent, $"{FolderPrefix}{Guid.NewGuid():N}"); + NativeMethods.CreateNewFolder(folder, elevated ? Program.AdminOnlyFolder : null); + Folder = folder; + foreach (var library in Carried) + { + var file = Path.Combine(folder, library + ".dll"); + using (var source = typeof(NativeLibraries).Assembly.GetManifestResourceStream(ResourceName(library)) + ?? throw new InvalidDataException($"{library} is missing from Setup.")) + using (var target = new FileStream(file, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + source.CopyTo(target); + // Its own imports (fontsub.dll and the like) from System32 too, or from this folder. + var handle = LoadLibraryEx(file, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + if (handle == 0) + { + var error = Marshal.GetLastSystemError(); + throw new Win32Exception(error, $"Could not load {file}: {new Win32Exception(error).Message}"); + } + lock (Gate) + Loaded[library] = handle; + } + log.Info($"Native libraries in {folder}"); + } + + /// + /// Deletes the folders earlier runs left in ; one still in use (another Setup runs from + /// it) stays. With administrator rights only folders an administrator made: in %SystemRoot%\Temp a standard user + /// may make folders of this name too, and swap what is in them for links to elsewhere. + /// + internal static void RemoveOld(string parent, bool elevated, SetupLog log) + { + // A folder this new may be another Setup's that is still writing its libraries. + var before = DateTime.UtcNow - TimeSpan.FromMinutes(10); + IEnumerable folders; + try + { + folders = Directory.EnumerateDirectories(parent, FolderPrefix + "*").ToList(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return; + } + foreach (var folder in folders) + { + try + { + var info = new DirectoryInfo(folder); + if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.CreationTimeUtc > before) + continue; + if (elevated && !MadeByAdministrators(info)) + continue; + // Only the files Setup writes, then the folder if that left it empty: nothing is deleted recursively. + foreach (var library in Carried) + File.Delete(Path.Combine(folder, library + ".dll")); + Directory.Delete(folder); + log.Info($"Removed {folder}"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // In use or not ours to delete: a later run tries again. + } + } + } + + /// Owned by Administrators or SYSTEM, which a standard user can't make the owner of anything. + private static bool MadeByAdministrators(DirectoryInfo folder) => + folder.GetAccessControl(AccessControlSections.Owner).GetOwner(typeof(SecurityIdentifier)) is SecurityIdentifier owner + && (owner.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) || owner.IsWellKnown(WellKnownSidType.LocalSystemSid)); + + /// Deletes this run's folder once the process has ended (a later run removes it otherwise). + public static void RemoveAfterExit(SetupLog log) + { + if (Folder is not { } folder) + return; + try + { + using var _ = Process.Start(new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe"), + $"/d /c ping -n 4 127.0.0.1 >nul & rd /s /q \"{folder}\"") + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = Environment.SystemDirectory, + }); + } + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) + { + log.Warn($"Could not clean up {folder}: {ex.Message}"); + } + } +} diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.cs index ea1616500..c2aa04e73 100644 --- a/src/Filee.Setup/Program.cs +++ b/src/Filee.Setup/Program.cs @@ -35,6 +35,8 @@ public static int Main(string[] args) { if (!OperatingSystem.IsWindows()) return ExitInitFailed; + // Before anything loads a native library: Windows' own only from System32 (see NativeLibraries). + NativeLibraries.Guard(); // Never hold a folder Setup may delete (the install folder) as the current directory. Environment.CurrentDirectory = Environment.SystemDirectory; NativeMethods.QuietErrors(); @@ -92,6 +94,7 @@ public static int Main(string[] args) finally { payload?.Dispose(); + NativeLibraries.RemoveAfterExit(log); } } @@ -153,7 +156,7 @@ private static int Install(string[] args, SetupOptions options, string exe, Setu { LogFile = log.File, }; - RunWindow(model, texts, options.Ui == SetupUi.Silent); + RunWindow(model, texts, options.Ui == SetupUi.Silent, paths, log); result = model.Result; exitCode = model.ExitCode; launch = options.Ui == SetupUi.Silent ? result?.Launch : model.Launch; @@ -261,7 +264,7 @@ private static int Uninstall(string[] args, SetupOptions options, string exe, Se LogFile = log.File, SettingsFolder = paths.SettingsFolder, }; - RunWindow(model, texts, options.Ui == SetupUi.Silent); + RunWindow(model, texts, options.Ui == SetupUi.Silent, paths, log); exitCode = model.ExitCode; if (exitCode == 1 && options.IsSilent) Tell(options, model.ErrorText, NativeMethods.MB_ICONERROR); @@ -373,18 +376,30 @@ private static SetupContext CreateContext(string? sandbox, SetupPaths paths, Set new SandboxSetupSystem(log, paths.SettingsFolder), paths, log, Sandbox: true); } - private static void RunWindow(SetupViewModel model, SetupTexts texts, bool silent) + private static void RunWindow(SetupViewModel model, SetupTexts texts, bool silent, SetupPaths paths, SetupLog log) { + // Skia and HarfBuzz: from a folder of this run's own, where only administrators can change them when this one + // is elevated. + NativeLibraries.Unpack(paths, NativeMethods.IsElevated(), log); App.Model = model; App.Texts = texts; App.Silent = silent; BuildAvaloniaApp().StartWithClassicDesktopLifetime([]); } - /// Also used by the XAML previewer and the tests' headless platform (with their own builder). + /// + /// Also used by the XAML previewer (the tests have their own, headless, builder). Software rendering: Setup's one + /// small window doesn't need the GPU, and without ANGLE there is no av_libglesv2.dll to carry (see + /// NativeLibraries). The redirection surface keeps the window's transparency. + /// public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() + .With(new Win32PlatformOptions + { + RenderingMode = [Win32RenderingMode.Software], + CompositionMode = [Win32CompositionMode.RedirectionSurface], + }) .LogToTrace(); /// diff --git a/tests/Filee.Setup.Tests/NativeLibrariesTests.cs b/tests/Filee.Setup.Tests/NativeLibrariesTests.cs new file mode 100644 index 000000000..247ceab86 --- /dev/null +++ b/tests/Filee.Setup.Tests/NativeLibrariesTests.cs @@ -0,0 +1,70 @@ +using System.Runtime.Versioning; +using Filee.Setup.Platform; + +namespace Filee.Setup.Tests; + +/// What earlier runs left of Setup's own copies of Skia and HarfBuzz, and what of it a later run deletes. +[SupportedOSPlatform("windows")] +public class NativeLibrariesTests +{ + [Fact] + public void A_build_carries_no_libraries_of_its_own() + { + // Only the publish embeds them (Filee.Setup.csproj); a build finds them next to it, like the tests do. + Assert.False(NativeLibraries.AreCarried); + } + + [Fact] + public void Old_folders_go_and_new_ones_stay() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Setup is for Windows."); + using var temp = new TempFolder(); + var old = Folder(temp, "old", TimeSpan.FromHours(2)); + var recent = Folder(temp, "recent", TimeSpan.Zero); + var log = new SetupLog(null); + + NativeLibraries.RemoveOld(temp.Path, elevated: false, log); + + Assert.False(Directory.Exists(old)); + // Possibly another Setup's, still writing its libraries. + Assert.True(File.Exists(Path.Combine(recent, "libSkiaSharp.dll"))); + } + + [Fact] + public void Only_the_files_Setup_writes_are_deleted() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Setup is for Windows."); + using var temp = new TempFolder(); + var old = Folder(temp, "old", TimeSpan.FromHours(2), extra: "notes.txt"); + var unrelated = temp.Write(@"Other\libSkiaSharp.dll"); + + NativeLibraries.RemoveOld(temp.Path, elevated: false, new SetupLog(null)); + + Assert.False(File.Exists(Path.Combine(old, "libSkiaSharp.dll"))); + Assert.True(File.Exists(Path.Combine(old, "notes.txt"))); + Assert.True(File.Exists(unrelated)); + } + + [Fact] + public void With_administrator_rights_a_folder_a_user_made_stays() + { + Assert.SkipUnless(OperatingSystem.IsWindows() && !NativeMethods.IsElevated(), "Needs a folder owned by a standard user."); + using var temp = new TempFolder(); + var old = Folder(temp, "old", TimeSpan.FromHours(2)); + + NativeLibraries.RemoveOld(temp.Path, elevated: true, new SetupLog(null)); + + Assert.True(File.Exists(Path.Combine(old, "libSkiaSharp.dll"))); + } + + private static string Folder(TempFolder temp, string name, TimeSpan age, string? extra = null) + { + var folder = temp.Sub(NativeLibraries.FolderPrefix + name); + foreach (var library in NativeLibraries.Carried) + temp.Write(Path.Combine(folder, library + ".dll")); + if (extra is not null) + temp.Write(Path.Combine(folder, extra)); + Directory.SetCreationTimeUtc(folder, DateTime.UtcNow - age); + return folder; + } +} From 64ff12b927d86709e82848185f8720437d4b24ab Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:46 +0900 Subject: [PATCH 06/95] fix(ods): cap repeated spaces and expanded cells in ODS sheets A text:s element now stands for at most 1,024 spaces, all cell text of a workbook is counted against the size of an XML part, and repeated rows and columns with text expand to at most 10 million cells; past that the sheet is refused as too large. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Office/Sheets/OdsReader.cs | 40 ++++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/Filee.Engines/Office/Sheets/OdsReader.cs b/src/Filee.Engines/Office/Sheets/OdsReader.cs index d06f8f4f3..32f9e265d 100644 --- a/src/Filee.Engines/Office/Sheets/OdsReader.cs +++ b/src/Filee.Engines/Office/Sheets/OdsReader.cs @@ -10,6 +10,7 @@ using System.Text; using System.Xml; using System.Xml.Linq; +using Filee.Core.Conversion; using Filee.Engines.Infrastructure; namespace Filee.Engines.Office.Sheets; @@ -35,6 +36,21 @@ internal sealed class OdsReader /// private const int MaxStyledRepeat = 256; + /// + /// Most spaces one text:s stands for. It stands for a run of spaces in the text, rarely more than a line of them; + /// its count is the file's to choose, and a billion would be gigabytes of spaces from a few bytes. + /// + private const int MaxSpaces = 1024; + + /// All cell text of a workbook together: no more characters than its content.xml may hold. + private const long MaxTextCharacters = BoundedXml.MaxPartBytes; + + /// + /// Most cells (and merges) a workbook expands to. Repeated rows and columns with text are expanded one cell each; + /// a few bytes can repeat a cell over a whole sheet (1,048,576 × 16,384), far more than any real sheet holds. + /// + private const long MaxCells = 10_000_000; + /// Points per character of column width (7 pixels of Calibri 11 at 96 dpi), as in the XLSX writer. internal const double PointsPerCharacter = 5.25; @@ -45,6 +61,8 @@ internal sealed class OdsReader private readonly Dictionary _frozenRows = []; private readonly NumberFormatter _formatter = new(); private XElement? _defaultCellStyle; + private long _textLeft = MaxTextCharacters; + private long _cellsLeft = MaxCells; /// Reads every visible sheet of . public static Workbook Read(string path) @@ -322,6 +340,9 @@ private Worksheet ReadTable(XElement table) var cells = Cells(row, columns); var hasText = cells.Any(run => run.Cell is { Text.Length: > 0 } || run.ColumnSpan > 1 || run.RowSpan > 1); var copies = hasText ? count : cells.Any(run => run.Cell is not null) && count <= MaxStyledRepeat ? count : 0; + _cellsLeft -= (long)copies * cells.Sum(run => (long)run.Count); + if (_cellsLeft < 0) + throw new ConversionRefusedException("error.document_too_large", $"{name}: over {MaxCells:N0} cells"); for (var copy = 0; copy < copies; copy++) { foreach (var run in cells) @@ -470,7 +491,7 @@ private SheetCell Cell(XElement element, string? styleName) } /// The text of a cell: its paragraphs joined by line breaks; null when it has none. - private static string? Paragraphs(XElement cell) + private string? Paragraphs(XElement cell) { var paragraphs = cell.Elements().Where(e => e.Name == Text + "p" || e.Name == Text + "h").ToList(); if (paragraphs.Count == 0) @@ -485,12 +506,13 @@ private SheetCell Cell(XElement element, string? styleName) return sb.ToString(); } - private static void Inline(XElement element, StringBuilder sb) + private void Inline(XElement element, StringBuilder sb) { foreach (var node in element.Nodes()) { if (node is XText text) { + Spend(text.Value.Length); // ODF collapses white space in text; extra spaces are text:s elements. foreach (var ch in text.Value) { @@ -502,7 +524,11 @@ private static void Inline(XElement element, StringBuilder sb) else if (node is XElement child) { if (child.Name == Text + "s") - sb.Append(' ', Repeat(child, Text + "c")); + { + var spaces = Math.Min(Repeat(child, Text + "c"), MaxSpaces); + Spend(spaces); + sb.Append(' ', spaces); + } else if (child.Name == Text + "tab") sb.Append('\t'); else if (child.Name == Text + "line-break") @@ -515,4 +541,12 @@ private static void Inline(XElement element, StringBuilder sb) private static int Repeat(XElement element, XName attribute) => int.TryParse((string?)element.Attribute(attribute), out var count) && count > 0 ? count : 1; + + /// Counts of cell text against the workbook's total. + private void Spend(long characters) + { + _textLeft -= characters; + if (_textLeft < 0) + throw new ConversionRefusedException("error.document_too_large", $"the cell text is over {MaxTextCharacters:N0} characters"); + } } From 92959d827cb02b595cb1b1fb6468c0f8b9f74409 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:47 +0900 Subject: [PATCH 07/95] fix(tables): cut cell spans to the table and cap table size PlaceCells cuts row spans at the table's last row and column spans at 16,384 columns, tracks covered positions per column instead of a set of every spanned cell, and refuses tables over 10 million positions. The Markdown writer and the document-to-sheet tables use the same bounds, and the HWPX reader cuts column addresses and spans when it reads them. The HWPX reader also joins the text of a run in a StringBuilder: joining it one piece at a time cost the square of the run's length. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs | 40 +++++++++++++--- src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs | 48 ++++++++++++++----- src/Filee.Engines/Hwp/Hwpx/MarkdownWriter.cs | 15 +++--- .../Office/Sheets/TableSheets.cs | 38 +++++++++------ 4 files changed, 104 insertions(+), 37 deletions(-) diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs index 3980799f8..021c9b838 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs @@ -78,6 +78,13 @@ private sealed class ParagraphBuilder private readonly HListRef? _list; private bool _afterTable; + // Text joined to the HText at _joinedAt in _joinedSink, kept in a StringBuilder until something else is + // added there: joining strings one piece at a time costs the square of the run's length (a run of a + // hundred thousand hp:nbSpace elements). + private StringBuilder? _joined; + private List? _joinedSink; + private int _joinedAt; + public ParagraphBuilder(List output, List fields, HParaFormat format, int heading, HListRef? list) { _output = output; @@ -103,10 +110,28 @@ public void AddText(string text, HCharFormat format) if (text.Length == 0) return; var sink = Sink; - if (sink.Count > 0 && sink[^1] is HText last && last.Format == format) - sink[^1] = new HText(last.Text + text, format); - else + if (sink.Count == 0 || sink[^1] is not HText last || last.Format != format) + { sink.Add(new HText(text, format)); + return; + } + if (_joined is null || !ReferenceEquals(_joinedSink, sink) || _joinedAt != sink.Count - 1) + { + FinishJoin(); + (_joined, _joinedSink, _joinedAt) = (new StringBuilder(last.Text), sink, sink.Count - 1); + } + _joined.Append(text); + // The text is written to the HText when the paragraph is finished (FinishJoin). + } + + /// Writes the text joined so far to its HText. + private void FinishJoin() + { + if (_joined is null || _joinedSink is null) + return; + var last = (HText)_joinedSink[_joinedAt]; + _joinedSink[_joinedAt] = new HText(_joined.ToString(), last.Format); + (_joined, _joinedSink) = (null, null); } public void OpenLink(string target) @@ -130,6 +155,7 @@ public void CloseLink() public void Table(HTable table) { + FinishJoin(); // Breaks and column changes have no place on a table, so they keep an empty paragraph in front of it. if (HasContent || Current.PageBreakBefore || Current.ColumnBreakBefore || Current.ColumnsChange is not null) Emit(); @@ -141,6 +167,7 @@ public void Table(HTable table) public void Finish() { + FinishJoin(); if (!_afterTable || HasContent) Emit(); } @@ -502,7 +529,7 @@ private void FieldEnd(XElement control, ParagraphBuilder builder) private HTable Table(XElement tbl) { - var table = new HTable { ColumnCount = Math.Max(0, Int(tbl, "colCnt")) }; + var table = new HTable { ColumnCount = Math.Clamp(Int(tbl, "colCnt"), 0, HwpxWriter.MaxTableColumns) }; var pos = Child(tbl, "pos"); if (pos is not null && !Flag(pos, "treatAsChar")) { @@ -535,13 +562,14 @@ private HTable Table(XElement tbl) var span = Part("cellSpan"); var size = Part("cellSz"); var subList = Child(tc, "subList"); + // Addresses and spans past the widest table written (HwpxWriter.MaxTableColumns) are cut there. var cell = new HCell { - Column = address is null ? -1 : Math.Max(0, Int(address, "colAddr")), - ColSpan = Math.Max(1, Int(span, "colSpan", 1)), + Column = address is null ? -1 : Math.Clamp(Int(address, "colAddr"), 0, HwpxWriter.MaxTableColumns - 1), RowSpan = Math.Max(1, Int(span, "rowSpan", 1)), VerticalAlign = VerticalAlign(Attr(subList, "vertAlign")), }; + cell.ColSpan = Math.Clamp(Int(span, "colSpan", 1), 1, HwpxWriter.MaxTableColumns - Math.Max(0, cell.Column)); if (BorderFill(Attr(tc, "borderFillIDRef")) is { } borderFill) (cell.Borders, cell.Fill) = borderFill; cell.Blocks.AddRange(ReadSubList(subList)); diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs index f552da1e1..fc4610178 100644 --- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs +++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs @@ -5,6 +5,7 @@ using System.Text; using System.Xml.Linq; +using Filee.Core.Conversion; namespace Filee.Engines.Hwp.Hwpx; @@ -383,39 +384,64 @@ private string Table(HTable table, string? leadingRun) return paragraph + string.Concat(table.Caption.Select(b => Block(b))); } + /// Widest table placed: Excel's sheet width, far wider than 한글 or Word lay out a table. + internal const int MaxTableColumns = 16_384; + + /// + /// Largest table placed, in grid positions (rows × columns, and the positions its merged cells cover). A table of + /// 100,000 rows of 100 columns fits; a few bytes of row and column spans can claim billions. + /// + internal const long MaxTableCells = 10_000_000; + /// /// Grid position of every cell: explicit cell columns (DOCX) or the next free position (Pandoc), skipping - /// positions covered by cells spanning rows from above. + /// positions covered by cells spanning rows from above. Spans are cut to the table: a row span ends at its last + /// row, a column span at . /// + /// The table is larger than . internal static (List> Placed, int Columns) PlaceCells(HTable table) { var placed = new List>(); - var occupied = new HashSet<(int Row, int Column)>(); - var columnCount = table.ColumnCount; - for (var r = 0; r < table.Rows.Count; r++) + // Per column, the first row not covered by a cell spanning rows from above (or from the left in this row). + var freeFrom = new List(); + var columnCount = Math.Clamp(table.ColumnCount, 0, MaxTableColumns); + var rows = table.Rows.Count; + long covered = 0; + for (var r = 0; r < rows; r++) { var row = new List<(HCell, int)>(); var column = 0; foreach (var cell in table.Rows[r].Cells) { if (cell.Column >= 0) - column = cell.Column; - while (occupied.Contains((r, column))) + column = Math.Min(cell.Column, MaxTableColumns); + while (column < freeFrom.Count && freeFrom[column] > r) column++; - for (var dr = 0; dr < cell.RowSpan; dr++) - { - for (var dc = 0; dc < cell.ColSpan; dc++) - occupied.Add((r + dr, column + dc)); - } + if (column >= MaxTableColumns) + throw TableTooLarge(); + cell.RowSpan = Math.Clamp(cell.RowSpan, 1, rows - r); + cell.ColSpan = Math.Clamp(cell.ColSpan, 1, MaxTableColumns - column); + covered += (long)cell.RowSpan * cell.ColSpan; + if (covered > MaxTableCells) + throw TableTooLarge(); + while (freeFrom.Count < column + cell.ColSpan) + freeFrom.Add(0); + for (var c = column; c < column + cell.ColSpan; c++) + freeFrom[c] = Math.Max(freeFrom[c], r + cell.RowSpan); row.Add((cell, column)); column += cell.ColSpan; columnCount = Math.Max(columnCount, column); } placed.Add(row); + if ((long)(r + 1) * columnCount > MaxTableCells) + throw TableTooLarge(); } return (placed, Math.Max(1, columnCount)); } + internal static ConversionRefusedException TableTooLarge() => + new("error.document_too_large", $"a table of over {MaxTableCells:N0} cells"); + /// Column widths that fit : absolute (scaled down if too wide), relative or equal. internal static int[] ColumnWidths(HTable table, int columns, int available) { diff --git a/src/Filee.Engines/Hwp/Hwpx/MarkdownWriter.cs b/src/Filee.Engines/Hwp/Hwpx/MarkdownWriter.cs index 8b9037896..40d3d5f76 100644 --- a/src/Filee.Engines/Hwp/Hwpx/MarkdownWriter.cs +++ b/src/Filee.Engines/Hwp/Hwpx/MarkdownWriter.cs @@ -112,16 +112,20 @@ private void Table(HTable table, StringBuilder sb, string prefix) { if (table.Rows.Count == 0) return; - var columns = Math.Max(table.ColumnCount, table.Rows.Max(r => r.Cells.Sum(c => c.ColSpan))); + HwpxWriter.PlaceCells(table); // cuts the spans to the table, refuses tables past its size limit + var columns = (int)Math.Min(HwpxWriter.MaxTableColumns, Math.Max(table.ColumnCount, table.Rows.Max(r => r.Cells.Sum(c => (long)c.ColSpan)))); + if ((long)columns * table.Rows.Count > HwpxWriter.MaxTableCells) + throw HwpxWriter.TableTooLarge(); var grid = new List(); - var covered = new Dictionary<(int Row, int Column), bool>(); + // Per column, the first row not covered by a cell spanning rows from above (or from the left in this row). + var freeFrom = new int[columns]; for (var r = 0; r < table.Rows.Count; r++) { var cells = new string[columns]; var column = 0; foreach (var cell in table.Rows[r].Cells) { - while (column < columns && covered.ContainsKey((r, column))) + while (column < columns && freeFrom[column] > r) column++; if (column >= columns) break; @@ -131,9 +135,8 @@ private void Table(HTable table, StringBuilder sb, string prefix) .Select(p => header ? p.Inlines.Select(i => i is HText t ? new HText(t.Text, t.Format with { Bold = null }) : i).ToList() : p.Inlines) .Select(inlines => Inlines(inlines).Replace("\\\n", " ", StringComparison.Ordinal).Replace("\n", " ", StringComparison.Ordinal))) .Replace("|", "\\|", StringComparison.Ordinal); - for (var rr = r; rr < r + cell.RowSpan; rr++) - for (var cc = column; cc < Math.Min(columns, column + cell.ColSpan); cc++) - covered[(rr, cc)] = true; + for (var cc = column; cc < Math.Min(columns, column + cell.ColSpan); cc++) + freeFrom[cc] = Math.Max(freeFrom[cc], r + cell.RowSpan); column += cell.ColSpan; } grid.Add(cells); diff --git a/src/Filee.Engines/Office/Sheets/TableSheets.cs b/src/Filee.Engines/Office/Sheets/TableSheets.cs index 4ad70c26e..c2f29bf50 100644 --- a/src/Filee.Engines/Office/Sheets/TableSheets.cs +++ b/src/Filee.Engines/Office/Sheets/TableSheets.cs @@ -62,7 +62,7 @@ public static void SetColumnWidths(Worksheet sheet, HTable table) private static Dictionary LongestLines(HTable table) { var longest = new Dictionary(); - foreach (var (cell, _, column) in Grid(table)) + foreach (var (cell, _, column, _, _) in Grid(table)) { if (cell.ColSpan > 1) continue; @@ -83,28 +83,40 @@ private static int DisplayWidth(string line) return width; } - /// Every cell of the table with its grid row (0-based within the table) and column, row spans skipped. - private static IEnumerable<(HCell Cell, int Row, int Column)> Grid(HTable table, int skip = 0) + /// + /// Every cell of the table with its grid row (0-based within the table), column and the rows and columns it covers, + /// row spans skipped. Spans end at the table's last row and at . + /// + /// The cells cover more than positions. + private static IEnumerable<(HCell Cell, int Row, int Column, int Rows, int Columns)> Grid(HTable table, int skip = 0) { - var taken = new HashSet<(int, int)>(); + // Per column, the first row not covered by a cell spanning rows from above (or from the left in this row). + var freeFrom = new List(); var rowCount = table.Rows.Count - skip; var row = 0; + long covered = 0; foreach (var source in table.Rows.Skip(skip)) { var column = 0; foreach (var cell in source.Cells) { if (cell.Column >= 0) - column = cell.Column; - while (taken.Contains((row, column))) + column = Math.Min(cell.Column, HwpxWriter.MaxTableColumns); + while (column < freeFrom.Count && freeFrom[column] > row) column++; + if (column >= HwpxWriter.MaxTableColumns) + throw HwpxWriter.TableTooLarge(); // An HTML rowspan may claim more rows than the table has; the merge ends at its last row. var rows = Math.Clamp(cell.RowSpan, 1, Math.Max(1, rowCount - row)); - var columns = Math.Max(1, cell.ColSpan); - for (var r = row; r < row + rows; r++) - for (var c = column; c < column + columns; c++) - taken.Add((r, c)); - yield return (cell, row, column); + var columns = Math.Clamp(cell.ColSpan, 1, HwpxWriter.MaxTableColumns - column); + covered += (long)rows * columns; + if (covered > HwpxWriter.MaxTableCells) + throw HwpxWriter.TableTooLarge(); + while (freeFrom.Count < column + columns) + freeFrom.Add(0); + for (var c = column; c < column + columns; c++) + freeFrom[c] = Math.Max(freeFrom[c], row + rows); + yield return (cell, row, column, rows, columns); column += columns; } row++; @@ -134,13 +146,11 @@ public static int Place(Worksheet sheet, HTable table, int top, int skip, bool d } var next = top + Math.Max(0, table.Rows.Count - skip); var defaults = table.Borders ?? HBorders.Grid; - foreach (var (cell, row, column) in Grid(table, skip)) + foreach (var (cell, row, column, rows, columns) in Grid(table, skip)) { var style = StyleOf(cell, drawn ? null : cell.Borders ?? defaults); var at = top + row; sheet.Set(at, column, Shown(Text(cell), style)); - var rows = Math.Clamp(cell.RowSpan, 1, Math.Max(1, next - at)); - var columns = Math.Max(1, cell.ColSpan); for (var r = at; r < at + rows; r++) for (var c = column; c < column + columns; c++) if (r != at || c != column) From 70ed9afa8b7f7dc7526ab00ed606e050e817ddcf Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:48 +0900 Subject: [PATCH 08/95] fix(archives): refuse entries nested in more than 512 folders Unpacked folders are walked level by level (links removed, folders merged into place); entry paths and hard-link targets with more than 512 names are refused in the listing check and when an entry path is resolved. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Archives/ArchiveSafety.cs | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/Filee.Engines/Archives/ArchiveSafety.cs b/src/Filee.Engines/Archives/ArchiveSafety.cs index c5bbfd2e1..add6cb965 100644 --- a/src/Filee.Engines/Archives/ArchiveSafety.cs +++ b/src/Filee.Engines/Archives/ArchiveSafety.cs @@ -11,6 +11,12 @@ internal static class ArchiveSafety /// More entries than this are refused: real archives stay far below, "entry bombs" do not. public const int MaxEntries = 1_000_000; + /// + /// Deepest folder nesting of an entry path. Real archives nest a few dozen folders; tens of thousands fit in one + /// name, and the folders are walked level by level after unpacking (links removed, moved into place). + /// + public const int MaxPathDepth = 512; + /// Space that must stay free on the drive after unpacking. private const long Reserve = 64L * 1024 * 1024; @@ -36,6 +42,18 @@ public static bool IsUnsafePath(string entryPath) return entryPath.Split('/', '\\').Any(part => part == ".."); } + /// True if an entry path has more than names (folders and the file). + public static bool IsTooDeep(string entryPath) + { + var names = 0; + foreach (var part in entryPath.Split('/', '\\')) + { + if (part is not ("" or ".") && ++names > MaxPathDepth) + return true; + } + return false; + } + /// /// Refuses a 7-Zip listing with encrypted entries, entries or hard links pointing outside the target folder, /// too many entries, or more data than the drive of can hold. @@ -50,6 +68,8 @@ public static void CheckListing(IReadOnlyList entries, string arc throw Encrypted(archiveName); if (IsUnsafePath(entry.Path) || entry.HardLink is { Length: > 0 } link && IsUnsafePath(link)) throw Unsafe(archiveName, entry.Path); + if (IsTooDeep(entry.Path) || entry.HardLink is { Length: > 0 } target && IsTooDeep(target)) + throw TooDeep(archiveName); } EnsureRoom(entries.Where(e => !e.IsFolder).Sum(e => e.Size), targetDirectory, archiveName); } @@ -112,6 +132,8 @@ public static string ResolveEntryPath(string root, string entryName, string arch { if (IsUnsafePath(entryName)) throw Unsafe(archiveName, entryName); + if (IsTooDeep(entryName)) + throw TooDeep(archiveName); var parts = entryName.Split(['/', '\\'], StringSplitOptions.RemoveEmptyEntries) .Where(part => part != ".") .Select(SanitizeSegment) @@ -154,6 +176,9 @@ public static Exception Encrypted(string archiveName) => public static Exception Unsafe(string archiveName, string entry) => new InvalidDataException($"{archiveName} was not unpacked: the entry \"{entry}\" points outside the target folder."); + public static Exception TooDeep(string archiveName) => + new InvalidDataException($"{archiveName} was not unpacked: an entry is nested in more than {MaxPathDepth} folders."); + public static Exception Damaged(string archiveName, string detail) => new InvalidDataException($"{archiveName} is damaged or incomplete ({detail})."); From 18ee011520972b822b21798059657b19bac6471b Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:49 +0900 Subject: [PATCH 09/95] fix(mobi): limit what a book's text unpacks to HUFF/CDIC phrases can be made of phrases, so a small dictionary can stand for terabytes. The decompressor counts everything it unpacks, phrases included, and the text of a book may unpack to 64 times the file's size (at least 16 MB, at most 256 MB); past that the book is refused as too large. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Ebooks/Mobi/HuffCdic.cs | 16 ++++++++- src/Filee.Engines/Ebooks/Mobi/MobiReader.cs | 34 +++++++++++++++++-- src/Filee.Engines/Ebooks/Mobi/PalmDatabase.cs | 3 ++ 3 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/Filee.Engines/Ebooks/Mobi/HuffCdic.cs b/src/Filee.Engines/Ebooks/Mobi/HuffCdic.cs index d80ca560d..da7684b51 100644 --- a/src/Filee.Engines/Ebooks/Mobi/HuffCdic.cs +++ b/src/Filee.Engines/Ebooks/Mobi/HuffCdic.cs @@ -3,6 +3,8 @@ // dictionary (CDIC records); a phrase may itself be compressed and is unpacked on first use. using System.Buffers.Binary; +using Filee.Core.Conversion; +using Filee.Engines.Infrastructure; namespace Filee.Engines.Ebooks; @@ -13,6 +15,8 @@ internal sealed class HuffCdic private readonly ulong[] _minCode = new ulong[33]; private readonly ulong[] _maxCode = new ulong[33]; private readonly List _phrases = []; + private readonly long _maxBytes; + private long _left; private sealed class Phrase(byte[] data, bool unpacked) { @@ -23,8 +27,14 @@ private sealed class Phrase(byte[] data, bool unpacked) /// The HUFF record. /// The CDIC records that follow it. - public HuffCdic(ReadOnlySpan huff, IEnumerable cdics) + /// + /// Most bytes unpacked from all records together, the dictionary's own phrases included. A phrase may be made of + /// phrases, so each level multiplies the text: a few kilobytes of dictionary can stand for terabytes. + /// + public HuffCdic(ReadOnlySpan huff, IEnumerable cdics, long maxBytes) { + _maxBytes = maxBytes; + _left = maxBytes; if (huff.Length < 24 || !huff[..4].SequenceEqual("HUFF"u8)) throw new InvalidDataException("The book's HUFF compression table is damaged."); var table1 = (int)BinaryPrimitives.ReadUInt32BigEndian(huff[8..]); @@ -68,6 +78,7 @@ public HuffCdic(ReadOnlySpan huff, IEnumerable cdics) } /// Decompresses one text record. + /// The text has unpacked to more than the limit. public byte[] Decompress(ReadOnlySpan data) { var output = new List(data.Length * 3); @@ -122,6 +133,9 @@ private void Unpack(ReadOnlySpan data, List output, int depth) phrase.Unpacked = true; phrase.Busy = false; } + _left -= phrase.Data.Length; + if (_left < 0) + throw new ConversionRefusedException("error.document_too_large", $"the book's text unpacks to over {BoundedXml.Size(_maxBytes)}"); output.AddRange(phrase.Data); } } diff --git a/src/Filee.Engines/Ebooks/Mobi/MobiReader.cs b/src/Filee.Engines/Ebooks/Mobi/MobiReader.cs index 0807e3214..89758cf26 100644 --- a/src/Filee.Engines/Ebooks/Mobi/MobiReader.cs +++ b/src/Filee.Engines/Ebooks/Mobi/MobiReader.cs @@ -11,7 +11,9 @@ using System.Buffers.Binary; using System.Text; using System.Text.RegularExpressions; +using Filee.Core.Conversion; using Filee.Engines.Hwp.Hwpx; +using Filee.Engines.Infrastructure; namespace Filee.Engines.Ebooks; @@ -95,14 +97,29 @@ private static PalmDatabase Open(string path) // ───────────────────────── Text records ───────────────────────── + /// Most text a book unpacks to: the text of the longest books is some tens of megabytes. + private const long MaxTextBytes = BoundedXml.MaxPartBytes; + + /// + /// Text a book may unpack to at least, and per byte of the file above that: HUFF/CDIC and PalmDOC records unpack to + /// two or three times their size, and the file holds the pictures and indexes as well. + /// + private const long MinTextBytes = 16L * 1024 * 1024; + private const int MaxTextRatio = 64; + + /// What the text of may unpack to. + internal static long TextLimit(PalmDatabase database) => + Math.Min(MaxTextBytes, Math.Max(MinTextBytes, (long)MaxTextRatio * database.Length)); + /// The decompressed text of the book whose header is at record . private static byte[] Text(PalmDatabase database, MobiHeader header, int start) { + var limit = TextLimit(database); Func, byte[]> decompress = header.Compression switch { 1 => data => data.ToArray(), 2 => PalmDocCompression.Decompress, - 17480 => HuffCdicReader(database, header, start).Decompress, + 17480 => HuffCdicReader(database, header, start, limit).Decompress, var other => throw new InvalidDataException($"The book uses an unknown compression ({other})."), }; using var text = new MemoryStream(); @@ -111,15 +128,22 @@ private static byte[] Text(PalmDatabase database, MobiHeader header, int start) var record = database.Record(start + i); var size = record.Length - TrailingSize(record, header.ExtraFlags); text.Write(decompress(record[..Math.Max(0, size)])); + CheckTextSize(text.Length, limit); } var bytes = text.ToArray(); return header.TextLength > 0 && header.TextLength < bytes.Length ? bytes[..(int)header.TextLength] : bytes; } - private static HuffCdic HuffCdicReader(PalmDatabase database, MobiHeader header, int start) + private static HuffCdic HuffCdicReader(PalmDatabase database, MobiHeader header, int start, long limit) { var huff = start + header.HuffRecord; - return new HuffCdic(database.Record(huff), Enumerable.Range(huff + 1, Math.Max(0, header.HuffCount - 1)).Select(database.RecordArray)); + return new HuffCdic(database.Record(huff), Enumerable.Range(huff + 1, Math.Max(0, header.HuffCount - 1)).Select(database.RecordArray), limit); + } + + private static void CheckTextSize(long length, long limit) + { + if (length > limit) + throw new ConversionRefusedException("error.document_too_large", $"the book's text unpacks to over {BoundedXml.Size(limit)}"); } /// @@ -157,8 +181,12 @@ private static byte[] PalmDocText(PalmDatabase database) var compression = PalmDatabase.U16(header, 0); var records = PalmDatabase.U16(header, 8); using var text = new MemoryStream(); + var limit = TextLimit(database); for (var i = 1; i <= records && i < database.Count; i++) + { text.Write(compression == 2 ? PalmDocCompression.Decompress(database.Record(i)) : database.Record(i)); + CheckTextSize(text.Length, limit); + } return text.ToArray(); } diff --git a/src/Filee.Engines/Ebooks/Mobi/PalmDatabase.cs b/src/Filee.Engines/Ebooks/Mobi/PalmDatabase.cs index ae665c7d5..20ab1821c 100644 --- a/src/Filee.Engines/Ebooks/Mobi/PalmDatabase.cs +++ b/src/Filee.Engines/Ebooks/Mobi/PalmDatabase.cs @@ -28,6 +28,9 @@ private PalmDatabase(byte[] data, string name, string typeCreator, int[] offsets public int Count => _offsets.Length; + /// Size of the whole file in bytes. + public int Length => _data.Length; + public static PalmDatabase Open(byte[] data) { if (data.Length < 78) From 9894e09b55ad5503d678b92a2f9f1d9c8d72ccfd Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:49 +0900 Subject: [PATCH 10/95] fix(packages): count re-zipped copies against the unpack limit EPUB/KEPUB rewriting, Office variant conversion and the workbook prepared for sheet printing copied package entries without a size limit. They now copy through UnpackLimit, which also reads a whole entry with a per-entry limit for the chapters Kepub parses. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Ebooks/Kepub.cs | 24 ++++------- .../Infrastructure/UnpackLimit.cs | 40 +++++++++++++++---- src/Filee.Engines/Office/OoxmlConverter.cs | 8 ++-- .../Office/Sheets/SpreadsheetPrintPlan.cs | 4 +- 4 files changed, 47 insertions(+), 29 deletions(-) diff --git a/src/Filee.Engines/Ebooks/Kepub.cs b/src/Filee.Engines/Ebooks/Kepub.cs index 9f583f087..39ca80031 100644 --- a/src/Filee.Engines/Ebooks/Kepub.cs +++ b/src/Filee.Engines/Ebooks/Kepub.cs @@ -14,6 +14,7 @@ using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; +using Filee.Engines.Infrastructure; namespace Filee.Engines.Ebooks; @@ -55,6 +56,9 @@ private static void Rewrite(string input, string output, Func t EpubReader.CheckDrm(source); var documents = ContentDocuments(source); + // The copy unpacks to no more than other copies of the book may (UnpackLimit), a chapter to no more than an XML + // part (BoundedXml): it is parsed as a whole. + var limit = UnpackLimit.For(input); using var stream = File.Create(output); using var target = new ZipArchive(stream, ZipArchiveMode.Create); var mimetype = target.CreateEntry("mimetype", CompressionLevel.NoCompression); @@ -71,8 +75,7 @@ private static void Rewrite(string input, string output, Func t byte[]? rewritten = null; if (documents.Contains(entry.FullName)) { - using var read = entry.Open(); - var bytes = ReadAll(read); + var bytes = limit.Read(entry, BoundedXml.MaxPartBytes); if (Load(bytes) is { } document && transform(document)) rewritten = Save(document); rewritten ??= bytes; @@ -84,8 +87,7 @@ private static void Rewrite(string input, string output, Func t } else { - using var read = entry.Open(); - read.CopyTo(write); + limit.Copy(entry, write); } } } @@ -168,21 +170,11 @@ private static bool IsHtmlName(string name) => return parts.Count == 0 ? null : string.Join('/', parts); } - private static XDocument? LoadEntry(ZipArchiveEntry entry) - { - using var stream = entry.Open(); - return Load(ReadAll(stream)); - } + private static XDocument? LoadEntry(ZipArchiveEntry entry) => + Load(new UnpackLimit(BoundedXml.MaxPartBytes).Read(entry, BoundedXml.MaxPartBytes)); // ───────────────────────── XML ───────────────────────── - private static byte[] ReadAll(Stream stream) - { - using var memory = new MemoryStream(); - stream.CopyTo(memory); - return memory.ToArray(); - } - /// /// Parses an XHTML document with its whitespace. HTML entities that XML does not define (&nbsp; …) become /// character references first; external DTDs are never loaded. Null when it is not well-formed XML. diff --git a/src/Filee.Engines/Infrastructure/UnpackLimit.cs b/src/Filee.Engines/Infrastructure/UnpackLimit.cs index 59ed4d891..5875cfb4d 100644 --- a/src/Filee.Engines/Infrastructure/UnpackLimit.cs +++ b/src/Filee.Engines/Infrastructure/UnpackLimit.cs @@ -1,5 +1,7 @@ -// What one document's reader unpacks to files next to it, its pictures mostly. A few kilobytes can unpack to terabytes, -// so it is counted while it is written (a lying header doesn't help) and the document is refused past the limit. +// What one document's reader unpacks to files next to it, its pictures mostly, and what a converter copies of a package +// into a new one (a KEPUB, a cleaned-up Office file, a workbook prepared for printing). A few kilobytes can unpack to +// terabytes, so it is counted while it is written (a lying header doesn't help) and the document is refused past the +// limit. using System.IO.Compression; using Filee.Core.Conversion; @@ -19,22 +21,46 @@ internal sealed class UnpackLimit(long maxBytes) /// Writes to . /// The document has unpacked to more than the limit. public void Extract(ZipArchiveEntry entry, string path) + { + using var output = File.Create(path); + Copy(entry, output, long.MaxValue); + } + + /// Copies into (an entry of the package being written). + /// The document has unpacked to more than the limit. + public void Copy(ZipArchiveEntry entry, Stream output) => Copy(entry, output, long.MaxValue); + + /// The content of , which may be no larger than . + /// The entry or the document has unpacked to more than its limit. + public byte[] Read(ZipArchiveEntry entry, long maxBytes) + { + using var memory = new MemoryStream(); + Copy(entry, memory, maxBytes); + return memory.ToArray(); + } + + private void Copy(ZipArchiveEntry entry, Stream output, long maxBytes) { if (entry.Length > _left) - throw TooLarge(entry); + throw TooLarge(entry, _max); + if (entry.Length > maxBytes) + throw TooLarge(entry, maxBytes); using var source = entry.Open(); - using var output = File.Create(path); var buffer = new byte[81920]; + long written = 0; int count; while ((count = source.Read(buffer)) > 0) { _left -= count; + written += count; if (_left < 0) - throw TooLarge(entry); + throw TooLarge(entry, _max); + if (written > maxBytes) + throw TooLarge(entry, maxBytes); output.Write(buffer, 0, count); } } - private ConversionRefusedException TooLarge(ZipArchiveEntry entry) => - new("error.document_too_large", $"{entry.FullName}: unpacks to over {BoundedXml.Size(_max)}"); + private static ConversionRefusedException TooLarge(ZipArchiveEntry entry, long limit) => + new("error.document_too_large", $"{entry.FullName}: unpacks to over {BoundedXml.Size(limit)}"); } diff --git a/src/Filee.Engines/Office/OoxmlConverter.cs b/src/Filee.Engines/Office/OoxmlConverter.cs index d083913d1..63c0e8d5d 100644 --- a/src/Filee.Engines/Office/OoxmlConverter.cs +++ b/src/Filee.Engines/Office/OoxmlConverter.cs @@ -125,6 +125,7 @@ internal static void Rewrite(string input, string output, string to) // Relationships to removed parts, by source part (the workbook's sheet list refers to them by id). var removedIds = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var limit = UnpackLimit.For(input); using (var file = File.Create(output)) using (var zip = new ZipArchive(file, ZipArchiveMode.Create)) { @@ -151,7 +152,7 @@ internal static void Rewrite(string input, string output, string to) } else { - Copy(entry, zip); + Copy(entry, zip, limit); } } } @@ -261,10 +262,9 @@ private static void Save(ZipArchive zip, string name, XDocument xml) xml.Save(stream, SaveOptions.DisableFormatting); } - private static void Copy(ZipArchiveEntry entry, ZipArchive zip) + private static void Copy(ZipArchiveEntry entry, ZipArchive zip, UnpackLimit limit) { - using var source = entry.Open(); using var target = zip.CreateEntry(entry.FullName, CompressionLevel.Optimal).Open(); - source.CopyTo(target); + limit.Copy(entry, target); } } diff --git a/src/Filee.Engines/Office/Sheets/SpreadsheetPrintPlan.cs b/src/Filee.Engines/Office/Sheets/SpreadsheetPrintPlan.cs index 54fa60561..7bfa1061a 100644 --- a/src/Filee.Engines/Office/Sheets/SpreadsheetPrintPlan.cs +++ b/src/Filee.Engines/Office/Sheets/SpreadsheetPrintPlan.cs @@ -415,6 +415,7 @@ public static void Create(string source, string destination, SpreadsheetWorkbook if (!SpreadsheetPrintInspector.IsValidRange(region.Range)) throw new ArgumentException("The print area is not a valid A1 cell range.", nameof(region)); Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + var limit = UnpackLimit.For(source); using var input = ZipFile.OpenRead(source); using var output = ZipFile.Open(destination, ZipArchiveMode.Create); foreach (var entry in input.Entries) @@ -430,8 +431,7 @@ public static void Create(string source, string destination, SpreadsheetWorkbook RewriteSheetSelection(entry, to, selected: false); else { - using var from = entry.Open(); - from.CopyTo(to); + limit.Copy(entry, to); } } } From 83098cd400d579213a2c119274fd9dac8dd8fdaa Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:51 +0900 Subject: [PATCH 11/95] fix(images): restrict ImageMagick to the formats Filee converts Before ImageMagick's first use its policy registers only the modules of the formats Filee reads or writes, keeps PDF write-only (reading it runs Ghostscript) and turns off MSVG; SVG stays, rasterized by librsvg. Memory, map, area, disk, width, height and list length are limited. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Magick/MagickSecurity.cs | 125 +++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 src/Filee.Engines/Magick/MagickSecurity.cs diff --git a/src/Filee.Engines/Magick/MagickSecurity.cs b/src/Filee.Engines/Magick/MagickSecurity.cs new file mode 100644 index 000000000..c26f512f8 --- /dev/null +++ b/src/Filee.Engines/Magick/MagickSecurity.cs @@ -0,0 +1,125 @@ +// ImageMagick reads a few hundred formats and picks one by the file's content, whatever the file is called: a picture +// in a document or a book named cover.jpg can be PostScript (run by Ghostscript when it is installed), an HTML page, a +// text file or a URL. Filee hands ImageMagick the raster formats it converts, so before ImageMagick's first use its +// policy is set to register only the modules of those formats (ImageMagick reads its policy once, when it starts). +// SVG stays: HTML pictures are rasterized through it, by librsvg, which loads nothing from outside the SVG's folder; +// MSVG, ImageMagick's own SVG renderer that follows any file or URL, stays off. The policy also limits the pixels +// ImageMagick holds: a header of a few bytes can claim a picture of millions of pixels a side. + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using System.Text; +using ImageMagick; +using ImageMagick.Configuration; + +namespace Filee.Engines.Magick; + +/// Sets ImageMagick's security policy and resource limits before it is first used. +internal static class MagickSecurity +{ + /// + /// The ImageMagick modules Filee reads or writes (a module holds a format and its variants: JPEG also JPG and JPE, + /// PNM the Netpbm family, DNG every camera RAW format, HEIC also AVIF). XC, GRADIENT and PLASMA make pictures + /// out of nothing, and RGB, GRAY and CMYK are raw pixel data. PDF is only written: reading it would run Ghostscript. + /// DIB, a BMP without its file header, is looked up by Magick.NET whenever it lists its formats. + /// + internal static readonly string[] Modules = + [ + "BMP", "CMYK", "DCM", "DDS", "DIB", "DNG", "EMF", "EXR", "GIF", "GRADIENT", "GRAY", "HDR", "HEIC", "ICON", "JP2", + "JPEG", "JXL", "MIFF", "PCD", "PCX", "PDF", "PLASMA", "PNG", "PNM", "PSD", "QOI", "RGB", "SGI", "SUN", "SVG", "TGA", + "TIFF", "WBMP", "WEBP", "XBM", "XC", "XCF", "XPM", + ]; + + /// + /// Widest and tallest picture: far beyond a "Long image" of a PDF (PdfiumConverter.MaxStackedPixels at a narrow + /// page) or a panorama. + /// + internal const int MaxSide = 1_048_576; + + /// + /// The policy, after the defaults Magick.NET comes with. The last policy that matches decides, so every module + /// is refused first and those of allowed again. Pictures larger than the memory and area + /// limits are kept on disk, up to the disk limit; more frames than the list length are refused. + /// + internal static string Policy(string defaults) => defaults.Replace("", $$""" + + + + + + + + + + + + + """, StringComparison.Ordinal); + + private static readonly Lock Gate = new(); + private static bool _initialized; + + /// Runs when Filee.Engines is loaded, before any of its code can use ImageMagick. + [ModuleInitializer] + [SuppressMessage("Usage", "CA2255", Justification = "ImageMagick reads its policy once, at its first use; it must be in place before.")] + internal static void Initialize() + { + lock (Gate) + { + if (_initialized) + return; + _initialized = true; + var files = ConfigurationFiles.Default; + files.Policy.Data = Policy(files.Policy.Data); + try + { + MagickNET.Initialize(Folder(files)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The shared folder could not be written or checked: a folder of this process's own. + try + { + MagickNET.Initialize(files); + } + catch (Exception inner) when (inner is IOException or UnauthorizedAccessException) + { + // Nowhere to write: ImageMagick keeps Magick.NET's defaults (MVG, MSL and "@file" are off there). + } + } + } + } + + /// + /// A folder in the temp folder with the configuration files, named after their content, so every Filee process + /// with the same files shares it instead of leaving one behind each. A folder whose files were changed is not used. + /// + private static string Folder(IConfigurationFiles files) + { + var all = files.All.ToList(); + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(string.Concat(all.Select(f => f.FileName + "\0" + f.Data + "\0")))); + var folder = Path.Combine(Path.GetTempPath(), "filee-magick-" + Convert.ToHexStringLower(hash)[..16]); + if (!Directory.Exists(folder)) + { + var staging = folder + "-" + Guid.NewGuid().ToString("N")[..8]; + Directory.CreateDirectory(staging); + foreach (var file in all) + File.WriteAllText(Path.Combine(staging, file.FileName), file.Data); + try + { + Directory.Move(staging, folder); + } + catch (IOException) when (Directory.Exists(folder)) + { + Directory.Delete(staging, recursive: true); // another Filee process was first + } + } + foreach (var file in all) + { + if (File.ReadAllText(Path.Combine(folder, file.FileName)) != file.Data) + throw new IOException($"{folder} holds other configuration files."); + } + return folder; + } +} From 7a6a1d6edd1317064b5ca0c328df2b60d398fefc Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:21:53 +0900 Subject: [PATCH 12/95] test: oversized and malformed inputs give a bounded result or a refusal Every input is built in code: repeated ODS spaces and cells, table spans over billions of cells, a run of 300,000 spaces, deeply nested archive paths, nested HUFF/CDIC phrases, package copies past the unpack limit, and pictures in formats Filee does not convert. Co-Authored-By: Claude Opus 5.5 --- .../ConversionBudgetTests.cs | 346 ++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 tests/Filee.Engines.Tests/ConversionBudgetTests.cs diff --git a/tests/Filee.Engines.Tests/ConversionBudgetTests.cs b/tests/Filee.Engines.Tests/ConversionBudgetTests.cs new file mode 100644 index 000000000..da0b540b4 --- /dev/null +++ b/tests/Filee.Engines.Tests/ConversionBudgetTests.cs @@ -0,0 +1,346 @@ +// Files a few bytes long that ask for gigabytes or hours: repeated spaces in a spreadsheet cell, table spans over +// billions of cells, a run of a hundred thousand spaces, folders nested tens of thousands deep, a MOBI dictionary of +// phrases made of phrases, copies of packages that unpack without end, and pictures that are not pictures. Each must +// give a bounded result or a reasoned refusal, quickly. Every input is built here. + +using System.Buffers.Binary; +using System.Diagnostics.CodeAnalysis; +using System.IO.Compression; +using System.Runtime.CompilerServices; +using System.Text; +using Filee.Core.Conversion; +using Filee.Engines.Archives; +using Filee.Engines.Ebooks; +using Filee.Engines.Hwp.Hwpx; +using Filee.Engines.Infrastructure; +using Filee.Engines.Magick; +using Filee.Engines.Office.Sheets; +using ImageMagick; + +namespace Filee.Engines.Tests; + +public class ConversionBudgetTests(EngineFixture fx) : IClassFixture +{ + private const string TooLarge = "error.document_too_large"; + + // ───────────────────────── ODS ───────────────────────── + + private string Ods(string rows) + { + var path = Path.Combine(fx.NewFolder(), "a.ods"); + using var zip = ZipFile.Open(path, ZipArchiveMode.Create); + using (var writer = new StreamWriter(zip.CreateEntry("mimetype", CompressionLevel.NoCompression).Open())) + writer.Write("application/vnd.oasis.opendocument.spreadsheet"); + using (var writer = new StreamWriter(zip.CreateEntry("content.xml").Open())) + { + writer.Write("" + + "" + rows + + ""); + } + return path; + } + + [Fact] + public void Ods_repeated_spaces_are_cut_at_a_thousand() + { + var book = OdsReader.Read(Ods("" + + "abc")); + + Assert.Equal("a" + new string(' ', 1024) + "b c", book.Sheets[0].Get(0, 0)!.Text); + } + + [Fact] + public void An_ods_cell_repeated_over_the_whole_sheet_is_refused() + { + var path = Ods("x"); + + Assert.Equal(TooLarge, Assert.Throws(() => OdsReader.Read(path)).ErrorKey); + } + + // ───────────────────────── Tables ───────────────────────── + + private static HCell Cell(string text, int rowSpan = 1, int colSpan = 1, int column = -1) + { + var cell = new HCell { RowSpan = rowSpan, ColSpan = colSpan, Column = column }; + var paragraph = new HParagraph(); + paragraph.Inlines.Add(new HText(text, default)); + cell.Blocks.Add(paragraph); + return cell; + } + + private static HDocument WithTable(HTable table) + { + var section = new HSection(); + section.Blocks.Add(table); + var document = new HDocument(); + document.Sections.Add(section); + return document; + } + + [Fact] + public void Spans_past_the_table_are_cut_to_it() + { + var table = new HTable(); + var row = new HRow(); + row.Cells.Add(Cell("wide", rowSpan: 100_000, colSpan: int.MaxValue)); + table.Rows.Add(row); + + var (placed, columns) = HwpxWriter.PlaceCells(table); + + Assert.Equal(1, row.Cells[0].RowSpan); + Assert.Equal(HwpxWriter.MaxTableColumns, row.Cells[0].ColSpan); + Assert.Equal(HwpxWriter.MaxTableColumns, columns); + Assert.Equal(0, Assert.Single(placed[0]).Column); + } + + [Fact] + public void A_cell_past_the_widest_table_is_refused() + { + var table = new HTable(); + var row = new HRow(); + row.Cells.Add(Cell("far", column: 2_000_000_000)); + table.Rows.Add(row); + + Assert.Equal(TooLarge, Assert.Throws(() => HwpxWriter.PlaceCells(table)).ErrorKey); + } + + [Fact] + public void A_table_of_spans_over_billions_of_cells_is_refused_by_the_writers() + { + var table = new HTable(); + for (var r = 0; r < 1000; r++) + { + var row = new HRow(); + row.Cells.Add(Cell("x", rowSpan: 100_000, colSpan: 16_384)); + table.Rows.Add(row); + } + var document = WithTable(table); + var folder = fx.NewFolder(); + + Assert.Equal(TooLarge, Assert.Throws(() => HwpxWriter.Write(document, Path.Combine(folder, "a.hwpx"))).ErrorKey); + Assert.Equal(TooLarge, Assert.Throws(() => MarkdownWriter.Write(document, _ => null)).ErrorKey); + } + + [Fact] + public void Ordinary_spans_place_as_before() + { + var table = new HTable(); + var first = new HRow(); + first.Cells.Add(Cell("a", rowSpan: 2)); + first.Cells.Add(Cell("b", colSpan: 2)); + var second = new HRow(); + second.Cells.Add(Cell("c")); + second.Cells.Add(Cell("d")); + table.Rows.Add(first); + table.Rows.Add(second); + + var (placed, columns) = HwpxWriter.PlaceCells(table); + + Assert.Equal(3, columns); + Assert.Equal(new[] { 0, 1 }, placed[0].Select(p => p.Column)); + Assert.Equal(new[] { 1, 2 }, placed[1].Select(p => p.Column)); + Assert.Contains("| a | b |", MarkdownWriter.Write(WithTable(table), _ => null)); + } + + // ───────────────────────── HWPX text ───────────────────────── + + [Fact] + public void A_run_of_a_hundred_thousand_spaces_reads_in_one_piece() + { + const int Spaces = 300_000; + var paragraph = new HParagraph(); + paragraph.Inlines.Add(new HText("MARK", default)); + var section = new HSection(); + section.Blocks.Add(paragraph); + var document = new HDocument(); + document.Sections.Add(section); + var folder = fx.NewFolder(); + var path = Path.Combine(folder, "a.hwpx"); + HwpxWriter.Write(document, path); + using (var zip = ZipFile.Open(path, ZipArchiveMode.Update)) + { + var entry = zip.GetEntry("Contents/section0.xml")!; + string xml; + using (var reader = new StreamReader(entry.Open())) + xml = reader.ReadToEnd(); + Assert.Contains("MARK", xml); + xml = xml.Replace("MARK", "MARK" + string.Concat(Enumerable.Repeat("", Spaces)) + "END", StringComparison.Ordinal); + entry.Delete(); + using var writer = new StreamWriter(zip.CreateEntry("Contents/section0.xml").Open()); + writer.Write(xml); + } + + var read = HwpxReader.Read(path, Path.Combine(folder, "media")); + + var text = string.Concat(read.Sections.SelectMany(s => s.Blocks).OfType().SelectMany(p => p.Inlines).OfType().Select(t => t.Text)); + Assert.Equal("MARK" + new string('\u00A0', Spaces) + "END", text); // hp:nbSpace is a no-break space + } + + // ───────────────────────── Archives ───────────────────────── + + private static string Deep(int folders) => string.Concat(Enumerable.Repeat("a/", folders)) + "f.txt"; + + [Fact] + public void Entries_nested_in_more_than_512_folders_are_refused() + { + var root = fx.NewFolder(); + + Assert.Throws(() => ArchiveSafety.ResolveEntryPath(root, Deep(16_000), "deep.alz")); + Assert.Throws(() => ArchiveSafety.CheckListing([new SevenZipEntry(Deep(16_000), false, 1, false, null, null)], "deep.tar", root)); + Assert.Throws(() => ArchiveSafety.CheckListing([new SevenZipEntry("f.txt", false, 1, false, null, Deep(600))], "deep.tar", root)); + Assert.False(ArchiveSafety.IsTooDeep(Deep(ArchiveSafety.MaxPathDepth - 1))); + Assert.True(ArchiveSafety.IsTooDeep(Deep(ArchiveSafety.MaxPathDepth))); + Assert.False(ArchiveSafety.IsTooDeep("./a//b/./c.txt")); + } + + // ───────────────────────── MOBI HUFF/CDIC ───────────────────────── + + /// A HUFF table of 8-bit codes: byte b stands for phrase 255 − b. + private static byte[] Huff() + { + var huff = new byte[24 + 256 * 4 + 32 * 8]; + "HUFF"u8.CopyTo(huff); + BinaryPrimitives.WriteUInt32BigEndian(huff.AsSpan(4), 24); + BinaryPrimitives.WriteUInt32BigEndian(huff.AsSpan(8), 24); + BinaryPrimitives.WriteUInt32BigEndian(huff.AsSpan(12), 24 + 256 * 4); + for (var i = 0; i < 256; i++) + BinaryPrimitives.WriteUInt32BigEndian(huff.AsSpan(24 + i * 4), (255u << 8) | 0x80 | 8); + return huff; + } + + /// A CDIC record of the phrases; a phrase is stored as it is (true) or HUFF-coded itself. + private static byte[] Cdic(params (byte[] Data, bool Literal)[] phrases) + { + using var data = new MemoryStream(); + var offsets = new List(); + foreach (var (bytes, literal) in phrases) + { + offsets.Add(phrases.Length * 2 + (int)data.Length); + data.Write([(byte)((bytes.Length >> 8) | (literal ? 0x80 : 0)), (byte)bytes.Length]); + data.Write(bytes); + } + var cdic = new byte[16 + phrases.Length * 2 + data.Length]; + "CDIC"u8.CopyTo(cdic); + BinaryPrimitives.WriteUInt32BigEndian(cdic.AsSpan(4), 16); + BinaryPrimitives.WriteUInt32BigEndian(cdic.AsSpan(8), (uint)phrases.Length); + BinaryPrimitives.WriteUInt32BigEndian(cdic.AsSpan(12), 8); + for (var i = 0; i < offsets.Count; i++) + BinaryPrimitives.WriteUInt16BigEndian(cdic.AsSpan(16 + i * 2), (ushort)offsets[i]); + data.ToArray().CopyTo(cdic, 16 + phrases.Length * 2); + return cdic; + } + + private static byte[] Codes(int phrase, int count) => Enumerable.Repeat((byte)(255 - phrase), count).ToArray(); + + [Fact] + public void Huff_cdic_text_unpacks_as_written() + { + var huff = new HuffCdic(Huff(), [Cdic(("AB"u8.ToArray(), true), (Codes(0, 3), false))], 1024); + + Assert.Equal("ABABABAB", Encoding.ASCII.GetString(huff.Decompress([.. Codes(1, 1), .. Codes(0, 1)]))); + } + + [Fact] + public void Huff_cdic_phrases_of_phrases_stop_at_the_text_limit() + { + // Each level multiplies by 4000: the record stands for 4000^4 × 2 bytes, some 500 TB. + var huff = new HuffCdic(Huff(), [Cdic(("AB"u8.ToArray(), true), (Codes(0, 4000), false), (Codes(1, 4000), false), (Codes(2, 4000), false))], + 16 * 1024 * 1024); + + Assert.Equal(TooLarge, Assert.Throws(() => huff.Decompress(Codes(3, 4000))).ErrorKey); + } + + // ───────────────────────── Copies of packages ───────────────────────── + + private string Zip(params (string Name, int Bytes)[] entries) + { + var path = Path.Combine(fx.NewFolder(), "a.zip"); + using var zip = ZipFile.Open(path, ZipArchiveMode.Create); + foreach (var (name, bytes) in entries) + { + using var stream = zip.CreateEntry(name).Open(); + stream.Write(new byte[bytes]); + } + return path; + } + + [Fact] + public void Package_copies_are_counted_against_the_unpack_limit() + { + using var zip = ZipFile.OpenRead(Zip(("a", 60_000), ("b", 60_000))); + var limit = new UnpackLimit(100_000); + + limit.Copy(zip.Entries[0], Stream.Null); + Assert.Equal(TooLarge, Assert.Throws(() => limit.Copy(zip.Entries[1], Stream.Null)).ErrorKey); + } + + [Fact] + public void A_part_read_whole_has_its_own_limit() + { + using var zip = ZipFile.OpenRead(Zip(("chapter.xhtml", 500_000))); + var limit = new UnpackLimit(10_000_000); + + Assert.Equal(500_000, limit.Read(zip.Entries[0], 500_000).Length); + Assert.Equal(TooLarge, Assert.Throws(() => limit.Read(zip.Entries[0], 499_999)).ErrorKey); + } + + // ───────────────────────── ImageMagick ───────────────────────── + + [Fact] + public void Every_format_imagemagick_converts_for_filee_is_allowed() + { + var formats = ImageEncoder.Readable.Concat(ImageEncoder.Writable).Concat(ImageEncoder.Metafiles) + .Where(f => f is not ("fits" or "ani")) // read by Filee itself + .Distinct(); + foreach (var format in formats) + { + var magick = format switch + { + "raw" => MagickFormat.Dng, + "xcf" => MagickFormat.Xcf, + "emf" => MagickFormat.Emf, + "wmf" => MagickFormat.Wmf, + _ => ImageEncoder.ToMagickFormat(format), + }; + var module = MagickFormatInfo.Create(magick)!.ModuleFormat.ToString().ToUpperInvariant(); + Assert.True(MagickSecurity.Modules.Contains(module), $"{format}: module {module} is not allowed"); + } + } + + [Fact] + public void Imagemagick_refuses_what_filee_does_not_convert() + { + var postScript = "%!PS-Adobe-3.0\n%%BoundingBox: 0 0 10 10\nshowpage\n"u8.ToArray(); + var svg = ""u8.ToArray(); + + Assert.Throws(() => new MagickImage(postScript)); + Assert.Throws(() => new MagickImage("hello"u8.ToArray(), MagickFormat.Txt)); + Assert.Throws(() => new MagickImage(svg, MagickFormat.Msvg)); + Assert.NotEmpty(MagickNET.SupportedFormats); // Magick.NET looks up formats of its own when it lists them + using (var red = new MagickImage(MagickColors.Red, 2, 2)) + { + var pdf = red.ToByteArray(MagickFormat.Pdf); // written: PDF is only read through Ghostscript + Assert.Throws(() => new MagickImage(pdf)); + } + Assert.ThrowsAny(() => new MagickImage(MagickColors.Red, MagickSecurity.MaxSide + 1, 1)); + + // SVG pictures of HTML documents are still rasterized (by librsvg). + var folder = fx.NewFolder(); + var path = Path.Combine(folder, "a.svg"); + File.WriteAllBytes(path, svg); + var png = HtmlReader.UsableImage(path, Path.Combine(folder, "media")); + Assert.NotNull(png); + using var image = new MagickImage(png); + Assert.Equal(MagickFormat.Png, image.Format); + } +} + +/// ImageMagick reads its policy once: it is set before any test of this assembly can start ImageMagick. +internal static class MagickPolicyFirst +{ + [ModuleInitializer] + [SuppressMessage("Usage", "CA2255", Justification = "Tests that use ImageMagick directly may run before any engine code.")] + internal static void Initialize() => MagickSecurity.Initialize(); +} From fa043f908f83e4e7946457dc9ae5981547297f16 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 01:31:09 +0900 Subject: [PATCH 13/95] Keep ImageMagick's configuration in the user's own work folder The shared configuration folder was made in the temp folder, which on Linux is /tmp: another user could create it first and change the files between the check and ImageMagick reading them. It now lives in WorkFolders.Root (%TEMP%\Filee on Windows, the mode-700 cache folder on Linux and macOS). The app also sets the policy as it starts, since it calls ImageMagick itself for crops and previews. Co-Authored-By: Claude Opus 5.5 --- src/Filee.App/Program.cs | 2 ++ src/Filee.Engines/Magick/MagickSecurity.cs | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Filee.App/Program.cs b/src/Filee.App/Program.cs index a72099247..7cd9ee4ed 100644 --- a/src/Filee.App/Program.cs +++ b/src/Filee.App/Program.cs @@ -57,6 +57,8 @@ public static int Main(string[] args) return PortableStartupFailure.Show(message); } using var portableScope = portable; + // ImageMagick reads its policy once, at its first use; the app also calls it directly (crop, previews). + Filee.Engines.Magick.MagickSecurity.Initialize(); Options = CommandLine.Parse(args); PreloadedStore = null; Log = StartupDiagnostics.CreateEarlyLogger(Path.Combine(UserDataStore.DefaultDirectory, "logs"), out var earlyStoreLogger); diff --git a/src/Filee.Engines/Magick/MagickSecurity.cs b/src/Filee.Engines/Magick/MagickSecurity.cs index c26f512f8..14ae95b5e 100644 --- a/src/Filee.Engines/Magick/MagickSecurity.cs +++ b/src/Filee.Engines/Magick/MagickSecurity.cs @@ -10,6 +10,7 @@ using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; +using Filee.Core.Platform; using ImageMagick; using ImageMagick.Configuration; @@ -92,14 +93,16 @@ internal static void Initialize() } /// - /// A folder in the temp folder with the configuration files, named after their content, so every Filee process + /// A folder with the configuration files in Filee's work root, named after their content, so every Filee process /// with the same files shares it instead of leaving one behind each. A folder whose files were changed is not used. + /// The work root is the user's own (%TEMP%\Filee, or the cache folder with mode 700 on Linux and macOS, see + /// ): in a shared /tmp another user could make the folder first and loosen the policy. /// private static string Folder(IConfigurationFiles files) { var all = files.All.ToList(); var hash = SHA256.HashData(Encoding.UTF8.GetBytes(string.Concat(all.Select(f => f.FileName + "\0" + f.Data + "\0")))); - var folder = Path.Combine(Path.GetTempPath(), "filee-magick-" + Convert.ToHexStringLower(hash)[..16]); + var folder = Path.Combine(WorkFolders.Root, "magick-" + Convert.ToHexStringLower(hash)[..16]); if (!Directory.Exists(folder)) { var staging = folder + "-" + Guid.NewGuid().ToString("N")[..8]; From c8e4b30ad4c98da34cace5f37bf0232593f94491 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sat, 14 Nov 2026 02:07:47 +0900 Subject: [PATCH 14/95] Check content nesting before PDFsharp parses a page or form PDFsharp's ContentReader parses arrays and dictionaries recursively without a limit, so a page of a million "[" overflowed the stack in Compress PDF and Remove blank pages. PdfContentNesting scans the content first and treats anything nested deeper than 64 as content that can't be read, as other unreadable content already is. Co-Authored-By: Claude Opus 5.5 --- src/Filee.Engines/Pdf/PdfBlankPages.cs | 1 + src/Filee.Engines/Pdf/PdfContentNesting.cs | 139 ++++++++++++++++++ src/Filee.Engines/Pdf/PdfPictureUses.cs | 3 +- .../Filee.Engines.Tests/PdfBlankPagesTests.cs | 23 +++ 4 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 src/Filee.Engines/Pdf/PdfContentNesting.cs diff --git a/src/Filee.Engines/Pdf/PdfBlankPages.cs b/src/Filee.Engines/Pdf/PdfBlankPages.cs index edfe17580..1b80e7a98 100644 --- a/src/Filee.Engines/Pdf/PdfBlankPages.cs +++ b/src/Filee.Engines/Pdf/PdfBlankPages.cs @@ -63,6 +63,7 @@ internal static bool IsBlank(PdfPage page) return false; try { + PdfContentNesting.Check(page); return !Paints(ContentReader.ReadContent(page)); } catch (Exception ex) when (ex is not OperationCanceledException) diff --git a/src/Filee.Engines/Pdf/PdfContentNesting.cs b/src/Filee.Engines/Pdf/PdfContentNesting.cs new file mode 100644 index 000000000..d6f956615 --- /dev/null +++ b/src/Filee.Engines/Pdf/PdfContentNesting.cs @@ -0,0 +1,139 @@ +// PDFsharp's ContentReader parses the arrays and dictionaries of a content stream recursively, with no limit: a stream +// of a million "[" (about a kilobyte deflated) overflows the stack, even a 64 MB one, and the process dies. Callers +// that hand untrusted content to ContentReader (PdfPictureUses for Compress PDF, PdfBlankPages) scan it here first and +// treat a stream nested too deeply as one that can't be read. + +using PdfSharp.Pdf; + +namespace Filee.Engines.Pdf; + +/// Refuses content streams whose arrays and dictionaries nest too deeply for PDFsharp's parser. +internal static class PdfContentNesting +{ + /// Arrays and dictionaries inside each other at most; content streams use two or three. + public const int MaxDepth = 64; + + /// The page's content, all its streams together, checked. + /// The content nests deeper than . + public static void Check(PdfPage page) + { + using var content = new MemoryStream(); + switch (PdfCompressor.Resolve(page.Elements["/Contents"])) + { + case PdfDictionary { Stream: not null } stream: + content.Write(stream.Stream.UnfilteredValue); + break; + case PdfArray parts: + foreach (var part in parts.Elements.Select(PdfCompressor.Resolve).OfType()) + { + if (part.Stream is not null) + { + content.Write(part.Stream.UnfilteredValue); + content.WriteByte((byte)'\n'); + } + } + break; + } + Checked(content.GetBuffer().AsSpan(0, (int)content.Length)); + } + + /// , once checked. + /// The content nests deeper than . + public static byte[] Checked(byte[] content) + { + Checked(content.AsSpan()); + return content; + } + + private static void Checked(ReadOnlySpan data) + { + var depth = 0; + var i = 0; + while (i < data.Length) + { + var c = data[i]; + switch (c) + { + case (byte)'%': + while (i < data.Length && data[i] is not 10 and not 13) + i++; + continue; + case (byte)'(': + i = AfterString(data, i); + continue; + case (byte)'<' when i + 1 < data.Length && data[i + 1] == '<': + i += 2; + Enter(ref depth); + continue; + case (byte)'<': + while (i < data.Length && data[i] != '>') + i++; + i++; + continue; + case (byte)'>' when i + 1 < data.Length && data[i + 1] == '>': + i += 2; + depth = Math.Max(0, depth - 1); + continue; + case (byte)'[': + i++; + Enter(ref depth); + continue; + case (byte)']': + i++; + depth = Math.Max(0, depth - 1); + continue; + } + if (IsRegular(c)) + { + var start = i; + while (i < data.Length && IsRegular(data[i])) + i++; + // An inline image's data is binary: it ends at "EI" between white space. + if (i - start == 2 && data[start] == 'I' && data[start + 1] == 'D' && (start == 0 || data[start - 1] != '/')) + i = AfterInlineImage(data, i); + continue; + } + i++; + } + } + + private static void Enter(ref int depth) + { + if (++depth > MaxDepth) + throw new InvalidDataException($"The content stream nests arrays or dictionaries more than {MaxDepth} deep."); + } + + private static int AfterString(ReadOnlySpan data, int i) + { + var open = 0; + for (; i < data.Length; i++) + { + switch (data[i]) + { + case (byte)'\\': + i++; + break; + case (byte)'(': + open++; + break; + case (byte)')' when --open == 0: + return i + 1; + } + } + return i; + } + + private static int AfterInlineImage(ReadOnlySpan data, int i) + { + for (var at = i + 1; at + 1 < data.Length; at++) + { + if (data[at] == 'E' && data[at + 1] == 'I' && IsSpace(data[at - 1]) && (at + 2 == data.Length || IsSpace(data[at + 2]))) + return at + 2; + } + return data.Length; + } + + private static bool IsRegular(byte c) => !IsSpace(c) && c is not ((byte)'(' or (byte)')' or (byte)'<' or (byte)'>' or (byte)'[' or (byte)']' or (byte)'{' or (byte)'}' or (byte)'/' or (byte)'%'); + + private static bool IsSpace(byte c) => c is 0 or 9 or 10 or 12 or 13 or 32; +} diff --git a/src/Filee.Engines/Pdf/PdfPictureUses.cs b/src/Filee.Engines/Pdf/PdfPictureUses.cs index 70e88327f..653d4d8ec 100644 --- a/src/Filee.Engines/Pdf/PdfPictureUses.cs +++ b/src/Filee.Engines/Pdf/PdfPictureUses.cs @@ -52,6 +52,7 @@ public Matrix Then(Matrix outer) => CSequence? content = null; try { + PdfContentNesting.Check(page); content = ContentReader.ReadContent(page); } catch (Exception ex) when (ex is not OperationCanceledException) @@ -168,7 +169,7 @@ private void WalkForm(PdfDictionary form, PdfDictionary? inherited, Matrix paren CSequence content; try { - content = ContentReader.ReadContent(form.Stream.UnfilteredValue); + content = ContentReader.ReadContent(PdfContentNesting.Checked(form.Stream.UnfilteredValue)); } catch (Exception ex) when (ex is not OperationCanceledException) { diff --git a/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs b/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs index e06ffce9e..26e11f682 100644 --- a/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs +++ b/tests/Filee.Engines.Tests/PdfBlankPagesTests.cs @@ -10,6 +10,29 @@ namespace Filee.Engines.Tests; public class PdfBlankPagesTests { + [Fact] + public void A_page_nested_too_deeply_for_the_content_parser_is_read_as_not_blank_instead_of_overflowing_the_stack() + { + // A million "[" in a row: PDFsharp's ContentReader would recurse once per bracket and kill the process. + using var document = new PdfDocument(); + var page = document.AddPage(); + var content = new PdfDictionary(document); + document.Internals.AddObject(content); + content.CreateStream(Enumerable.Repeat((byte)'[', 1_000_000).ToArray()); + page.Elements["/Contents"] = content.Reference; + + Assert.Throws(() => PdfContentNesting.Check(page)); + Assert.False(PdfBlankPages.IsBlank(page)); + Assert.Empty(PdfPictureUses.Find(document)); + } + + [Fact] + public void Ordinary_content_passes_the_nesting_check() + { + var content = "q [1 2] 0 d /P <> BDC (a [ ( b) Tj EMC BI /W 1 /H 1 ID [[ EI Q"u8.ToArray(); + Assert.Same(content, PdfContentNesting.Checked(content)); + } + [Fact] public void Removes_only_pages_without_any_painting_operation() { From d6f96d1417c6d385929446ccc9834fb7d3dd1f46 Mon Sep 17 00:00:00 2001 From: Feraris20 <222025665+Feraris20@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:37:31 +0200 Subject: [PATCH 15/95] Add optional UDF 2.01 image creation while retaining Joliet defaults --- Directory.Packages.props | 3 +- THIRD-PARTY-NOTICES.md | 2 +- docs/ENGINES.md | 18 +- src/Filee.App/Assets/i18n/ar.json | 1 + src/Filee.App/Assets/i18n/bn-BD.json | 1 + src/Filee.App/Assets/i18n/de.json | 1 + src/Filee.App/Assets/i18n/en.json | 1 + src/Filee.App/Assets/i18n/es.json | 1 + src/Filee.App/Assets/i18n/fa.json | 1 + src/Filee.App/Assets/i18n/fr.json | 1 + src/Filee.App/Assets/i18n/hi.json | 1 + src/Filee.App/Assets/i18n/id.json | 1 + src/Filee.App/Assets/i18n/it.json | 1 + src/Filee.App/Assets/i18n/ja.json | 1 + src/Filee.App/Assets/i18n/ko.json | 1 + src/Filee.App/Assets/i18n/ne.json | 1 + src/Filee.App/Assets/i18n/pl.json | 1 + src/Filee.App/Assets/i18n/pt-BR.json | 1 + src/Filee.App/Assets/i18n/pt-PT.json | 1 + src/Filee.App/Assets/i18n/ru.json | 1 + src/Filee.App/Assets/i18n/th.json | 1 + src/Filee.App/Assets/i18n/tr.json | 1 + src/Filee.App/Assets/i18n/vi.json | 1 + src/Filee.App/Assets/i18n/zh-CN.json | 1 + src/Filee.App/Assets/i18n/zh-TW.json | 1 + .../ViewModels/PresetEditorViewModel.cs | 11 +- src/Filee.App/Views/PresetEditorView.axaml | 8 + src/Filee.Cli/Cli.cs | 9 + src/Filee.Cli/CliOptions.cs | 7 + src/Filee.Cli/Help.cs | 3 + src/Filee.Core/Presets/Preset.cs | 11 + .../Archives/FolderIsoConverter.cs | 36 ++- src/Filee.Engines/Filee.Engines.csproj | 3 +- tests/Filee.App.Tests/Udf1443Tests.cs | 40 ++++ tests/Filee.Cli.Tests/CliTests.cs | 19 ++ tests/Filee.Cli.Tests/UdfOptionsTests.cs | 25 +++ tests/Filee.Core.Tests/Udf1443Tests.cs | 21 ++ .../Filee.Engines.Tests/FolderIso632Tests.cs | 5 +- tests/Filee.Engines.Tests/Udf1443Tests.cs | 205 ++++++++++++++++++ 39 files changed, 428 insertions(+), 20 deletions(-) create mode 100644 tests/Filee.App.Tests/Udf1443Tests.cs create mode 100644 tests/Filee.Cli.Tests/UdfOptionsTests.cs create mode 100644 tests/Filee.Core.Tests/Udf1443Tests.cs create mode 100644 tests/Filee.Engines.Tests/Udf1443Tests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 0f0798a82..83243ed3e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,7 +9,8 @@ - + + diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index ce5a3465c..bb445af47 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -20,7 +20,7 @@ Each component remains under its own license. | Svg.Skia (incl. Svg, ShimSkiaSharp, ExCSS; text shaping in `Filee.Engines/Vector/OutlinedTextPlayback.cs` adapted from it) | MIT | https://github.com/wieslawsoltes/Svg.Skia | | HarfBuzzSharp | MIT | https://github.com/mono/SkiaSharp | | SharpCompress (zstd decompression for engine downloads; RAR, 7z and TAR comics) | MIT | https://github.com/adamhathcock/sharpcompress | -| DiscUtils.Iso9660 (including DiscUtils.Core and DiscUtils.Streams; ISO creation) | MIT | https://github.com/DiscUtils/DiscUtils | +| LTRData.DiscUtils.Iso9660 and LTRData.DiscUtils.Udf (including Core and Streams; Joliet and UDF 2.01 image creation) | MIT | https://github.com/LTRData/DiscUtils | | QRCoder | MIT | https://github.com/codebude/QRCoder | | Unhwp | MIT | https://github.com/iyulab/unhwp | | Markdig | BSD-2-Clause | https://github.com/xoofx/markdig | diff --git a/docs/ENGINES.md b/docs/ENGINES.md index 26af1d666..5b67e1203 100644 --- a/docs/ENGINES.md +++ b/docs/ENGINES.md @@ -1709,15 +1709,21 @@ safely extracts them into its temporary work folder, then writes their contents Password-protected archives fail with a clear message. CLI: `filee convert "path/to/folder" --to iso` or `filee convert "backup.zip" --to iso`. -DiscUtils.Iso9660 writes ISO 9660 with Joliet in-process, preserving Unicode BMP names and empty directories. -There are no filesystem or compression options. ISO writing needs no external program; archive reading uses -the existing extraction engine. Images are data discs, not bootable clones. UDF is not included. +LTRData DiscUtils writes ISO 9660 with Joliet (the default) or UDF 2.01 in-process. Choose the filesystem in the ISO +preset, or use `--iso-filesystem udf201` with `--to iso` in the CLI (`--iso-filesystem joliet` selects the default). +No new donut slice is added. Existing presets retain Joliet without a schema migration. Images are data discs, +not bootable clones. Archive reading still uses the existing extraction engine. -Individual names must fit 62 UTF-16 characters, leaving room for DiscUtils' version suffix; relative disc paths +UDF supports approximately 234 GiB per file and 8 TiB per partition. The library encodes filenames in OSTA compressed +Unicode (up to 254 bytes before the file identifier prefix); names outside its supported range are refused before replacing the +destination. Source permissions, extended attributes and per-file timestamps are not imported into UDF images. +UDF is revision 2.01 only; there are no revision, compression or boot options. + +For Joliet, individual names must fit 62 UTF-16 characters, leaving room for DiscUtils' version suffix; relative disc paths must fit 240 characters. Control characters, semicolons, backslashes, `*`, `:`, `?` and supplementary Unicode characters are rejected clearly. Individual files must be smaller than 4 GiB. Drive roots and symbolic links/junctions -are refused. Timestamps are clamped to 1900-2155 in the image; -source timestamps are unchanged. On Windows, a marked input file transfers Mark of the Web to the image. +are refused for both filesystems. Joliet timestamps are clamped to 1900-2155 in the image; +source timestamps are unchanged. On Windows, a marked input file transfers Mark of the Web to either image type. File contents are streamed, progress reports bytes written, and cancellation is checked during enumeration and streaming. A previous destination inside the source is excluded. A new image replaces its destination only after diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index d177155b5..349d140cc 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "نظام ملفات ISO", "app.name": "Filee", "app.tagline": "اسحب، أفلت، وحوّل.", "fields.title": "المجالات", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index a6af940d0..445fc2755 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO ফাইল সিস্টেম", "portable.import_existing": "বিদ্যমান ডেটা আমদানি করুন", "portable.start_fresh": "নতুন করে শুরু করুন", "portable.import_summary": "আপনার সেটিংস, প্রিসেট, ইতিহাস এবং ডাউনলোড করা ইঞ্জিন এই পোর্টেবল ফোল্ডারে কপি করুন। মূল ফাইল পরিবর্তন বা মুছে ফেলা হবে না।", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index ec1daea0f..f5bf4a96b 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO-Dateisystem", "app.name": "Filee", "app.tagline": "Ziehen, ablegen, fertig.", "fields.title": "Bereiche", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index 808824c90..5a0c09b10 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO filesystem", "app.name": "Filee", "app.tagline": "Drag, drop, converted.", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index a7268adbc..887ce0618 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Sistema de archivos ISO", "app.name": "Filee", "app.tagline": "Arrastra, suelta y convierte.", "fields.title": "Áreas", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 933e1106b..801ef852a 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "سیستم فایل ISO", "portable.import_existing": "وارد کردن داده‌های موجود", "portable.start_fresh": "شروع تازه", "portable.import_summary": "تنظیمات، پیش‌تنظیم‌ها، تاریخچه و موتورهای دانلودشده را در این پوشه پرتابل کپی کنید. فایل‌های اصلی تغییر نمی‌کنند و حذف نمی‌شوند.", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index e03bb8fd3..740cfac57 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Système de fichiers ISO", "app.name": "Filee", "app.tagline": "Glissez, déposez, c'est converti.", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 0259a27fe..7720f2a79 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO फ़ाइल सिस्टम", "app.name": "Filee", "app.tagline": "खींचें, छोड़ें, कन्वर्ट हो गया।", "fields.title": "क्षेत्र", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index 65565ba6e..c8cc20be0 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Sistem berkas ISO", "app.name": "Filee", "app.tagline": "Seret, lepas, terkonversi.", "fields.title": "Bidang", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index 6b7ba9eca..bb828a2dd 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "File system ISO", "app.name": "Filee", "app.tagline": "Trascina, rilascia, converti.", "fields.title": "Settori", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index fb8347781..b63926a9e 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO ファイルシステム", "app.name": "Filee", "app.tagline": "ドラッグ。ドロップ。\n変換完了。", "fields.title": "分野", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index 0c2702212..98a56879f 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO 파일 시스템", "app.name": "Filee", "app.tagline": "끌어서 놓으면, 변환 끝.", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index c426f29d7..46245f9f4 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO फाइल प्रणाली", "app.name": "Filee", "app.tagline": "तान्नुहोस्, छाड्नुहोस्, रूपान्तरण भयो।", "fields.title": "क्षेत्रहरू", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index b0fbe90a0..4117a4bf9 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "System plików ISO", "app.name": "Filee", "app.tagline": "Przeciągnij, upuść, gotowe.", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 23bf9c688..189514795 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Sistema de arquivos ISO", "app.name": "Filee", "app.tagline": "Arraste, solte, convertido.", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index cd7c75a3e..799c2151a 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Sistema de ficheiros ISO", "app.name": "Filee", "app.tagline": "Arrasta, larga, convertido.", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index e28b0ea71..b523c4b55 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Файловая система ISO", "app.name": "Filee", "app.tagline": "Перетащил — и готово.", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index 876d19f73..3ade78446 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ระบบไฟล์ ISO", "app.name": "Filee", "app.tagline": "ลาก วาง แปลงไฟล์ทันที", "fields.title": "สาขา", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 32cea3ca6..8b5d3d5ae 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO dosya sistemi", "app.name": "Filee", "app.tagline": "Sürükle, bırak, dönüştür.", "fields.title": "Alanlar", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index b1e424d56..ff2d47751 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "Hệ thống tệp ISO", "app.name": "Filee", "app.tagline": "Kéo, thả, xong.", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 59df23064..7c7f59778 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO 文件系统", "app.name": "Filee", "app.tagline": "拖一拖,放一放,转换完成。", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index bf333ad19..aa11dcfe0 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -1,4 +1,5 @@ { + "presets.iso_filesystem": "ISO 檔案系統", "app.name": "Filee", "app.tagline": "拖一拖,放一放,轉換完成。", diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs index 850e45039..c62f62121 100644 --- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs +++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs @@ -202,6 +202,7 @@ .. VideoCrop.Ratios.Append(_edit.Media.CropFrame).Where(r => VideoCrop.TryParseR SampleRates = Steps(SampleRateSteps, _edit.Media.AudioSampleRate, r => r == 0 ? loc["presets.sample_rate.source"] : $"{r / 1000.0:0.##} kHz"); WavFormats = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.wav_format.{v}"])).ToList(); + IsoFileSystems = Enum.GetValues().Select(v => new Choice(v, v == Core.Presets.IsoFileSystem.Joliet ? "ISO 9660 + Joliet" : "UDF 2.01")).ToList(); ArchiveLevels = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.archive_level.{v}"])).ToList(); TraceModes = Enum.GetValues().Select(v => new Choice(v, loc[$"presets.trace_mode.{v}"])).ToList(); // Version names stay as AutoCAD calls them, in every language. @@ -313,6 +314,7 @@ .. WhisperLanguages.All _upscaleScale = _edit.Upscale.Scale > 0 ? _edit.Upscale.Scale : 4; _selectedUpscaleModel = UpscaleModels.FirstOrDefault(m => string.Equals(m.Id, _edit.Upscale.Model, StringComparison.OrdinalIgnoreCase)) ?? UpscaleModels.FirstOrDefault(); + _isoFileSystem = IsoFileSystems.First(v => v.Value == _edit.Archive.IsoFileSystem); _archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level); _combineIntoOne = _edit.Archive.CombineIntoOne; _saveEveryFrame = _edit.Media.SaveEveryFrame; @@ -505,6 +507,7 @@ public async Task TestTranslationAsync() public IReadOnlyList> AudioChannelChoices { get; } public IReadOnlyList> SampleRates { get; } public IReadOnlyList> WavFormats { get; } + public IReadOnlyList> IsoFileSystems { get; } public IReadOnlyList> ArchiveLevels { get; } public IReadOnlyList> TraceModes { get; } @@ -535,7 +538,7 @@ public async Task TestTranslationAsync() nameof(ShowVideoSplit), nameof(ShowVideoParts), nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding), nameof(ShowCaption), nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec), nameof(ShowRingtone), - nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), + nameof(ShowIso), nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote), nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowCad), nameof(ShowCadColors), nameof(ShowExtractMotionPhoto), nameof(ShowSlideshow), nameof(ShowLivePhotoChoice), nameof(LivePhotoKinds), nameof(LivePhotoChoice), nameof(IsLivePhoto), nameof(LivePhotoHint), nameof(ShowImageSize), nameof(SizeRangeError), nameof(CustomSizeError), nameof(IsValid))] @@ -1012,6 +1015,10 @@ partial void OnVideoSplitKindChanged(Choice? oldValue, ChoiceLanguage spoken in the audio for Whisper transcription (MediaOptions.SpokenLanguage). [ObservableProperty] private Choice _spokenLanguage; + [ObservableProperty] private Choice _isoFileSystem; + + partial void OnIsoFileSystemChanged(Choice? oldValue, Choice newValue) => + Choices.Restore(oldValue, newValue, value => IsoFileSystem = value); [ObservableProperty] private Choice _archiveLevel; [ObservableProperty] private bool _combineIntoOne; [ObservableProperty] private bool _saveEveryFrame; @@ -1228,6 +1235,7 @@ partial void OnAnimationSpeedChanged(Choice? oldValue, Choice ne && !ShowCropFrame; public bool ShowVideoParts => ShowVideoSplit && VideoOutput.Value; /// ISO creation has no archive compression settings. + public bool ShowIso => TargetId == "iso"; public bool ShowArchive => TargetCategory == FormatCategory.Archive && TargetId != "iso"; public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder; /// "Extract" has nothing to set; a line says what it does instead. @@ -1468,6 +1476,7 @@ static double Seconds(double value, double fallback, double min, double max) => media.LivePhotoCover = Seconds(LivePhotoCover, 1.5, 0, MediaOptions.MaxLivePhotoLength); media.RingtoneStart = Seconds(RingtoneStart, 0, 0, 24 * 3600); media.RingtoneLength = Seconds(RingtoneLength, MediaOptions.DefaultRingtoneLength, MediaOptions.MinRingtoneLength, MediaOptions.MaxRingtoneLength); + _original.Archive.IsoFileSystem = IsoFileSystem.Value; _original.Archive.Level = ArchiveLevel.Value; _original.Archive.CombineIntoOne = TargetId != "iso" && CombineIntoOne; _original.Trace.Mode = TraceMode.Value; diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml index 80223ec51..351d85e99 100644 --- a/src/Filee.App/Views/PresetEditorView.axaml +++ b/src/Filee.App/Views/PresetEditorView.axaml @@ -466,6 +466,14 @@ + + + + + + + diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs index 430653089..31ff13c09 100644 --- a/src/Filee.Cli/Cli.cs +++ b/src/Filee.Cli/Cli.cs @@ -310,6 +310,15 @@ private static void WriteFileFields(Utf8JsonWriter json, FileResult file, ILocal preset = found.Clone(); } preset = host.Store.Settings.WithDefaultOutput(preset); + if (options.IsoFileSystem is { } filesystem) + { + if (preset.TargetFormat != "iso") + { + errors.WriteLine("filee: --iso-filesystem requires an ISO target."); + return null; + } + preset.Archive.IsoFileSystem = filesystem; + } if (preset.Translate.Enabled && string.IsNullOrWhiteSpace(preset.Translate.Model)) preset.Translate.Model = host.Store.Settings.PreferredOllamaModel; if (options.Quality is { } quality) diff --git a/src/Filee.Cli/CliOptions.cs b/src/Filee.Cli/CliOptions.cs index f89efd20d..da446d82a 100644 --- a/src/Filee.Cli/CliOptions.cs +++ b/src/Filee.Cli/CliOptions.cs @@ -20,6 +20,7 @@ internal sealed record CliOptions public FileSortOrder? Sort { get; set; } public int? Quality { get; set; } public string? Pages { get; set; } + public Filee.Core.Presets.IsoFileSystem? IsoFileSystem { get; set; } /// --split-every: PDF → PDF in files of this many pages (#1259). public int? SplitEvery { get; set; } @@ -78,6 +79,12 @@ public static CliOptions Parse(IReadOnlyList args) switch (arg.ToLowerInvariant()) { + case "--iso-filesystem": + var filesystem = Value()?.ToLowerInvariant(); + if (filesystem == "joliet") options.IsoFileSystem = Filee.Core.Presets.IsoFileSystem.Joliet; + else if (filesystem == "udf201") options.IsoFileSystem = Filee.Core.Presets.IsoFileSystem.Udf201; + else options.Error ??= "--iso-filesystem must be joliet or udf201."; + break; case "-t" or "--to": options.To = Value(); break; diff --git a/src/Filee.Cli/Help.cs b/src/Filee.Cli/Help.cs index 3108aca69..b84151c8e 100644 --- a/src/Filee.Cli/Help.cs +++ b/src/Filee.Cli/Help.cs @@ -38,6 +38,7 @@ filee help [] filee version Examples: + filee convert folder --to iso --iso-filesystem udf201 filee convert photo.heic --to jpg filee convert *.png --to webp --quality 80 -o converted filee convert D:\Scans --recursive --preset to-pdf @@ -84,6 +85,8 @@ Files can be wildcards (*.heic). Folders convert the files in them that Filee kn Options: -t, --to Target format, e.g. jpg, png, pdf, docx, mp4 (see 'filee formats') -p, --preset A preset from the app, by id or name (see 'filee presets') + --iso-filesystem + ISO filesystem; an explicit choice overrides the preset (default: Joliet). -o, --output Save there instead of next to the sources -r, --recursive Include sub folders --sort The order files merge in: name, name-desc, modified, modified-desc, created or diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs index 13613bb84..1c5301e07 100644 --- a/src/Filee.Core/Presets/Preset.cs +++ b/src/Filee.Core/Presets/Preset.cs @@ -1792,6 +1792,8 @@ public enum ArchiveLevel /// Archive options. public sealed class ArchiveOptions { + /// Filesystem used for ISO creation; absent values retain Joliet. + public IsoFileSystem IsoFileSystem { get; set; } /// Put all dropped files into one archive instead of one archive per file. public bool CombineIntoOne { get; set; } @@ -1800,6 +1802,15 @@ public sealed class ArchiveOptions public ArchiveOptions Clone() => (ArchiveOptions)MemberwiseClone(); } +/// Filesystems available when creating a disc image. +public enum IsoFileSystem +{ + /// ISO 9660 with Joliet, the existing default. + Joliet, + /// Universal Disk Format revision 2.01. + Udf201, +} + /// How a raster image is traced. public enum TracingMode { diff --git a/src/Filee.Engines/Archives/FolderIsoConverter.cs b/src/Filee.Engines/Archives/FolderIsoConverter.cs index bbbbef323..c4fb5be37 100644 --- a/src/Filee.Engines/Archives/FolderIsoConverter.cs +++ b/src/Filee.Engines/Archives/FolderIsoConverter.cs @@ -1,6 +1,7 @@ // Creates data ISO images in-process; folder contents become the disc root without an external program. using DiscUtils.Iso9660; +using DiscUtils.Udf; using Filee.Core.Conversion; using Filee.Core.Formats; using Filee.Core.Platform; @@ -8,7 +9,7 @@ namespace Filee.Engines.Archives; -/// Writes ISO 9660 with Joliet names from explicitly identified folder inputs. +/// Writes Joliet or UDF 2.01 data images from explicitly identified folder inputs. public sealed class FolderIsoConverter : IConverter { private static readonly DateTime MinimumTimestamp = new(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc); @@ -23,7 +24,7 @@ public sealed class FolderIsoConverter : IConverter /// public IReadOnlyList Edges { get; } = [new(FormatRegistry.Folder, "iso", DirectOnly: true)]; /// - public EngineStatus GetStatus() => EngineStatus.Available(version: "DiscUtils 0.16.13"); + public EngineStatus GetStatus() => EngineStatus.Available(version: "LTRData.DiscUtils 1.0.90"); /// public Task> ConvertAsync(ConversionStep step, IProgress? progress, CancellationToken ct) => @@ -41,6 +42,11 @@ public Task> ConvertAsync(ConversionStep step, IProgress(); string? mark = null; void Add(DirectoryInfo directory, string prefix) { @@ -51,23 +57,29 @@ void Add(DirectoryInfo directory, string prefix) if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new ConversionRefusedException("error.iso_link", entry.Name); var name = prefix + entry.Name; + // A literal backslash in a Unix filename must not become an image path separator. + if (udf is not null && entry.Name.Contains('\\')) + throw new ArgumentException($"UDF cannot preserve a backslash in a filename: {entry.Name}"); // DiscUtils appends a version suffix (;1), and a dot for extensionless files. - if (entry.Name.Length > 62 || entry.Name.Any(c => char.IsControl(c) || char.IsSurrogate(c) || c is ';' or '\\' or '*' or ':' or '?') || name.Length > 240) + if (udf is null && (entry.Name.Length > 62 || entry.Name.Any(c => char.IsControl(c) || char.IsSurrogate(c) || c is ';' or '\\' or '*' or ':' or '?') || name.Length > 240)) throw new ConversionRefusedException("error.iso_name", name); - BuildDirectoryMember member; + BuildDirectoryMember? member = null; if (entry is DirectoryInfo child) { - member = builder.AddDirectory(name); + if (udf is null) member = builder.AddDirectory(name); + else udf.AddDirectory(name); Add(child, name + "\\"); } else { - if (((FileInfo)entry).Length > uint.MaxValue) + sources.Add((entry.FullName, ((FileInfo)entry).Length, entry.LastWriteTimeUtc)); + if (udf is null && ((FileInfo)entry).Length > uint.MaxValue) throw new ConversionRefusedException("error.iso_file_size", name); - member = builder.AddFile(name, entry.FullName); + if (udf is null) member = builder.AddFile(name, entry.FullName); + else udf.AddFile(name, entry.FullName); mark ??= MarkOfTheWeb.Read(entry.FullName); } - member.CreationTime = new DateTime( + if (member is not null) member.CreationTime = new DateTime( Math.Clamp(entry.LastWriteTimeUtc.Ticks, MinimumTimestamp.Ticks, MaximumTimestamp.Ticks), DateTimeKind.Utc); } } @@ -77,7 +89,7 @@ void Add(DirectoryInfo directory, string prefix) var temporary = Path.Combine(Path.GetDirectoryName(output)!, ".filee-iso-" + Guid.NewGuid().ToString("N") + ".tmp"); try { - using (var image = builder.Build()) + using (var image = udf is null ? builder.Build() : udf.Build()) using (var destination = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { var buffer = new byte[65536]; @@ -100,6 +112,12 @@ void Add(DirectoryInfo directory, string prefix) throw new ConversionRefusedException("error.iso_changed"); } ct.ThrowIfCancellationRequested(); + foreach (var source in sources) + { + var current = new FileInfo(source.Path); + if (!current.Exists || current.Length != source.Length || current.LastWriteTimeUtc != source.Modified) + throw new ConversionRefusedException("error.iso_changed"); + } if (mark is not null) MarkOfTheWeb.TryWrite(temporary, mark); File.Move(temporary, output, overwrite: true); diff --git a/src/Filee.Engines/Filee.Engines.csproj b/src/Filee.Engines/Filee.Engines.csproj index ca5dda08f..90cb3698a 100644 --- a/src/Filee.Engines/Filee.Engines.csproj +++ b/src/Filee.Engines/Filee.Engines.csproj @@ -13,7 +13,8 @@ - + + diff --git a/tests/Filee.App.Tests/Udf1443Tests.cs b/tests/Filee.App.Tests/Udf1443Tests.cs new file mode 100644 index 000000000..065859357 --- /dev/null +++ b/tests/Filee.App.Tests/Udf1443Tests.cs @@ -0,0 +1,40 @@ +// The ISO editor retains Joliet for old presets and saves an explicit UDF choice on the same preset. + +using Avalonia.Headless.XUnit; +using Filee.App.Services; +using Filee.App.ViewModels; +using Filee.App.Views; +using Filee.Core.Localization; +using Filee.Core.Presets; +using Filee.Core.Settings; + +namespace Filee.App.Tests; + +public sealed class Udf1443Tests +{ + [AvaloniaFact] + public void Filesystem_choice_round_trips_without_changing_the_default() + { + TestServices.EnsureInitialized("en"); + var preset = new Preset { Name = "ISO image", TargetFormat = "iso" }; + var editor = new PresetEditorViewModel(preset, AppHost.Get()); + Assert.True(editor.ShowIso); + Assert.False(editor.ShowArchive); + Assert.Equal(IsoFileSystem.Joliet, editor.IsoFileSystem.Value); + editor.IsoFileSystem = editor.IsoFileSystems.Single(c => c.Value == IsoFileSystem.Udf201); + Assert.True(editor.Apply()); + Assert.Equal(IsoFileSystem.Udf201, preset.Archive.IsoFileSystem); + Assert.Equal(IsoFileSystem.Udf201, preset.Clone().Archive.IsoFileSystem); + var reopened = new PresetEditorViewModel(preset, AppHost.Get()); + Assert.Equal(IsoFileSystem.Udf201, reopened.IsoFileSystem.Value); + var window = new PresetEditorWindow { DataContext = reopened }; + try + { + AppHost.Get().Apply(new ThemeSettings { Mode = ThemeMode.Dark, ReduceMotion = true }, "en"); + window.Show(); + RenderTests.Pump(); + RenderTests.Save(window, "iso-filesystem-udf.png"); + } + finally { window.Close(); } + } +} diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs index 8fe88913f..4e6eaf013 100644 --- a/tests/Filee.Cli.Tests/CliTests.cs +++ b/tests/Filee.Cli.Tests/CliTests.cs @@ -19,6 +19,25 @@ namespace Filee.Cli.Tests; [Collection("Cli")] // shares EngineEnvironment state with EnginesCommandTests public sealed class CliTests : IDisposable { + [Fact] + public async Task Udf_filesystem_option_creates_a_readable_image_and_rejects_other_targets() + { + var folder = Directory.CreateDirectory(Path.Combine(_folder, "udf-source")).FullName; + Directory.CreateDirectory(Path.Combine(folder, "empty")); + var name = new string('a', 100) + ".txt"; + File.WriteAllText(Path.Combine(folder, name), "CLI UDF"); + var result = await Run("convert", folder, "--to", "iso", "--iso-filesystem", "udf201", "--output", _folder); + Assert.True(result.Code == 0, result.Errors + result.Output); + using var image = File.OpenRead(folder + ".iso"); + using var udf = new DiscUtils.Udf.UdfReader(image); + Assert.True(udf.DirectoryExists("empty")); + using var reader = new StreamReader(udf.OpenFile(name, FileMode.Open)); + Assert.Equal("CLI UDF", reader.ReadToEnd()); + var rejected = await Run("convert", folder, "--to", "zip", "--iso-filesystem", "udf201"); + Assert.NotEqual(0, rejected.Code); + Assert.Contains("requires an ISO target", rejected.Errors); + } + [Fact] public async Task Folder_to_zip_keeps_the_folder_tree_instead_of_converting_its_individual_files() { diff --git a/tests/Filee.Cli.Tests/UdfOptionsTests.cs b/tests/Filee.Cli.Tests/UdfOptionsTests.cs new file mode 100644 index 000000000..7a96a43ac --- /dev/null +++ b/tests/Filee.Cli.Tests/UdfOptionsTests.cs @@ -0,0 +1,25 @@ +// UDF is explicit; command-line parsing never silently changes an existing Joliet preset. + +using Filee.Core.Presets; + +namespace Filee.Cli.Tests; + +public sealed class UdfOptionsTests +{ + [Theory] + [InlineData("joliet", IsoFileSystem.Joliet)] + [InlineData("udf201", IsoFileSystem.Udf201)] + public void Filesystem_is_parsed_explicitly(string value, IsoFileSystem expected) + { + var options = CliOptions.Parse(["convert", "folder", "--to", "iso", "--iso-filesystem", value]); + Assert.Null(options.Error); + Assert.Equal(expected, options.IsoFileSystem); + } + + [Fact] + public void Missing_choice_keeps_the_preset_and_unknown_revisions_are_rejected() + { + Assert.Null(CliOptions.Parse(["convert", "folder", "--to", "iso"]).IsoFileSystem); + Assert.NotNull(CliOptions.Parse(["convert", "folder", "--to", "iso", "--iso-filesystem", "udf250"]).Error); + } +} diff --git a/tests/Filee.Core.Tests/Udf1443Tests.cs b/tests/Filee.Core.Tests/Udf1443Tests.cs new file mode 100644 index 000000000..36bf80306 --- /dev/null +++ b/tests/Filee.Core.Tests/Udf1443Tests.cs @@ -0,0 +1,21 @@ +// Missing filesystem values preserve old behavior and explicit UDF values survive the real preset JSON path. + +using System.Text.Json; +using Filee.Core.Presets; +using Filee.Core.Settings; + +namespace Filee.Core.Tests; + +public sealed class Udf1443Tests +{ + [Fact] + public void Legacy_presets_default_to_joliet_and_udf_is_serialized_explicitly() + { + var old = JsonSerializer.Deserialize("{\"targetFormat\":\"iso\"}", FileeJsonContext.Default.Preset)!; + Assert.Equal(IsoFileSystem.Joliet, old.Archive.IsoFileSystem); + old.Archive.IsoFileSystem = IsoFileSystem.Udf201; + var saved = JsonSerializer.Serialize(old, FileeJsonContext.Default.Preset); + var reloaded = JsonSerializer.Deserialize(saved, FileeJsonContext.Default.Preset)!; + Assert.Equal(IsoFileSystem.Udf201, reloaded.Archive.IsoFileSystem); + } +} diff --git a/tests/Filee.Engines.Tests/FolderIso632Tests.cs b/tests/Filee.Engines.Tests/FolderIso632Tests.cs index 5a15b659c..5e5175dac 100644 --- a/tests/Filee.Engines.Tests/FolderIso632Tests.cs +++ b/tests/Filee.Engines.Tests/FolderIso632Tests.cs @@ -286,7 +286,10 @@ public async Task Names_at_the_62_character_boundary_are_preserved(bool withExte using var stream = File.OpenRead(Assert.Single(job.Outputs)); using var iso = new CDReader(stream, true); Assert.True(iso.DirectoryExists(directory)); - using var reader = new StreamReader(iso.OpenFile(name, FileMode.Open)); + // LTRData's reader retains the ISO trailing dot for an extensionless name; the old reader normalized it. + var stored = Assert.Single(iso.GetFiles("\\")); + Assert.Equal(name, stored.TrimStart('\\', '/').Split(';')[0].TrimEnd('.')); + using var reader = new StreamReader(iso.OpenFile(stored, FileMode.Open)); Assert.Equal("boundary", reader.ReadToEnd()); } diff --git a/tests/Filee.Engines.Tests/Udf1443Tests.cs b/tests/Filee.Engines.Tests/Udf1443Tests.cs new file mode 100644 index 000000000..f2ca0499f --- /dev/null +++ b/tests/Filee.Engines.Tests/Udf1443Tests.cs @@ -0,0 +1,205 @@ +// Generated UDF images verify names, directory layout and atomic cancellation without committed fixtures. + +using System.IO.Compression; +using DiscUtils.Udf; +using Filee.Core.Conversion; +using Filee.Core.Presets; +using Filee.Engines.Archives; +using Filee.Engines.Infrastructure; + +namespace Filee.Engines.Tests; + +public sealed class Udf1443Tests : IDisposable +{ + private readonly string _root = Directory.CreateTempSubdirectory("filee-udf-").FullName; + + [Fact] + public async Task An_actual_sparse_file_over_four_gib_converts_and_reads_back() + { + var folder = Directory.CreateDirectory(Path.Combine(_root, "source")).FullName; + var source = Path.Combine(folder, "large.bin"); + using (File.Create(source)) { } + if (OperatingSystem.IsWindows()) + { + var result = await ProcessRunner.RunAsync("fsutil.exe", ["sparse", "setflag", source], TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + Assert.Equal(0, result.ExitCode); + } + var length = (1L << 32) + 65536; + using (var file = File.OpenWrite(source)) + { + file.SetLength(length); + file.WriteByte(42); + file.Position = length - 1; + file.WriteByte(99); + } + var output = Path.Combine(_root, "large.iso"); + await Write(folder, output, ct: TestContext.Current.CancellationToken); + using var image = File.OpenRead(output); + using var udf = new UdfReader(image); + using var stored = udf.OpenFile("large.bin", FileMode.Open); + Assert.Equal(length, stored.Length); + Assert.Equal(42, stored.ReadByte()); + stored.Position = (1L << 32) + 1; + Assert.Equal(0, stored.ReadByte()); + stored.Position = length - 1; + Assert.Equal(99, stored.ReadByte()); + var sevenZip = SevenZip.Locate(); + Assert.NotNull(sevenZip); + var entries = await sevenZip.ListAsync(output, TestContext.Current.CancellationToken); + Assert.Contains(entries, e => e.Path == "large.bin" && e.Size == length); + } + + [Fact] + public async Task Zip_to_udf_preserves_the_selected_filesystem_and_readable_contents() + { + var archive = Path.Combine(_root, "source.zip"); + using (var zip = ZipFile.Open(archive, ZipArchiveMode.Create)) + { + zip.CreateEntry("empty/"); + using var writer = new StreamWriter(zip.CreateEntry(new string('x', 90) + ".txt").Open()); + writer.Write("archive contents"); + } + var output = Path.Combine(_root, "archive.iso"); + await new ArchiveConverter().ConvertAsync(new ConversionStep(archive, "zip", "iso", + new Preset { TargetFormat = "iso", Archive = { IsoFileSystem = IsoFileSystem.Udf201 } }, new Output(output), _root), null, TestContext.Current.CancellationToken); + using var stream = File.OpenRead(output); + using var udf = new UdfReader(stream); + Assert.True(udf.DirectoryExists("empty")); + using var reader = new StreamReader(udf.OpenFile(new string('x', 90) + ".txt", FileMode.Open)); + Assert.Equal("archive contents", reader.ReadToEnd()); + } + + [Fact] + public async Task Unsupported_names_leave_existing_image_untouched() + { + var folder = Directory.CreateDirectory(Path.Combine(_root, "source")).FullName; + // Fits a Unix filesystem's 255-byte UTF-8 component, but exceeds UDF's 254-byte wide-name payload. + File.WriteAllText(Path.Combine(folder, new string('\u0100', 126) + "ab"), "invalid UDF identifier"); + var output = Path.Combine(_root, "result.iso"); + File.WriteAllText(output, "keep"); + await Assert.ThrowsAnyAsync(() => Write(folder, output, ct: TestContext.Current.CancellationToken)); + Assert.Equal("keep", File.ReadAllText(output)); + Assert.Empty(Directory.GetFiles(_root, ".filee-iso-*.tmp")); + } + + [Fact] + public async Task Source_changes_during_streaming_preserve_the_previous_image() + { + var folder = Directory.CreateDirectory(Path.Combine(_root, "source")).FullName; + var source = Path.Combine(folder, "data.bin"); + File.WriteAllBytes(source, new byte[2 * 1024 * 1024]); + var output = Path.Combine(_root, "result.iso"); + File.WriteAllText(output, "keep"); + var progress = new CallbackProgress(value => + { + if (value > 0) File.SetLastWriteTimeUtc(source, DateTime.UtcNow.AddDays(-1)); + }); + await Assert.ThrowsAnyAsync(() => Write(folder, output, progress, TestContext.Current.CancellationToken)); + Assert.Equal("keep", File.ReadAllText(output)); + Assert.Empty(Directory.GetFiles(_root, ".filee-iso-*.tmp")); + } + + [Fact] + public async Task Mark_of_the_web_is_preserved_on_udf_output() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "NTFS mark of the web."); + var folder = Directory.CreateDirectory(Path.Combine(_root, "source")).FullName; + var source = Path.Combine(folder, "file.txt"); + File.WriteAllText(source, "marked"); + Assert.SkipUnless(Filee.Core.Platform.MarkOfTheWeb.TryWrite(source, Filee.Core.Platform.MarkOfTheWeb.Internet()), "NTFS required."); + var output = Path.Combine(_root, "marked.iso"); + await Write(folder, output, ct: TestContext.Current.CancellationToken); + Assert.NotNull(Filee.Core.Platform.MarkOfTheWeb.Read(output)); + } + + private sealed class CallbackProgress(Action callback) : IProgress + { + public void Report(double value) => callback(value); + } + + [Fact] + public void A_large_generated_file_is_readable_beyond_four_gib_without_materializing_the_image() + { + // A synthetic seekable source represents a sparse file without allocating multi-gigabyte test data. + var length = (1L << 32) + 65536; + var builder = new UdfBuilder(); + builder.AddFile("large.bin", length, () => new ZeroStream(length)); + using var image = builder.Build(); + using var udf = new UdfReader(image); + using var file = udf.OpenFile("large.bin", FileMode.Open); + Assert.Equal(length, file.Length); + file.Position = length - 1; + Assert.Equal(0, file.ReadByte()); + Assert.Equal(-1, file.ReadByte()); + } + + [Fact] + public async Task Unicode_long_names_and_empty_directories_round_trip() + { + var folder = Path.Combine(_root, "source"); + Directory.CreateDirectory(Path.Combine(folder, "empty")); + var name = new string('a', 100) + "-한글.txt"; + File.WriteAllText(Path.Combine(folder, name), "UDF contents"); + var output = Path.Combine(_root, "result.iso"); + await Write(folder, output, ct: TestContext.Current.CancellationToken); + using var image = File.OpenRead(output); + using var udf = new UdfReader(image); + Assert.True(udf.DirectoryExists("empty")); + using var reader = new StreamReader(udf.OpenFile(name, FileMode.Open)); + Assert.Equal("UDF contents", reader.ReadToEnd()); + } + + [Fact] + public async Task Cancellation_preserves_existing_destination_and_removes_temporary_output() + { + var folder = Directory.CreateDirectory(Path.Combine(_root, "source")).FullName; + File.WriteAllBytes(Path.Combine(folder, "large.bin"), new byte[2 * 1024 * 1024]); + var output = Path.Combine(_root, "result.iso"); + File.WriteAllText(output, "keep"); + using var cancel = new CancellationTokenSource(); + await Assert.ThrowsAnyAsync(() => Write(folder, output, new CancelProgress(cancel), cancel.Token)); + Assert.Equal("keep", File.ReadAllText(output)); + Assert.Empty(Directory.GetFiles(_root, ".filee-iso-*.tmp")); + } + + private Task> Write(string folder, string output, IProgress? progress = null, CancellationToken ct = default) => + new FolderIsoConverter().ConvertAsync(new ConversionStep(folder, "folder", "iso", + new Preset { TargetFormat = "iso", Archive = { IsoFileSystem = IsoFileSystem.Udf201 } }, new Output(output), _root), progress, ct); + + private sealed class Output(string path) : IOutputAllocator + { + public string? Allocate(string extension, string? suffix = null) => path; + } + + private sealed class ZeroStream(long length) : Stream + { + public override bool CanRead => true; + public override bool CanSeek => true; + public override bool CanWrite => false; + public override long Length => length; + public override long Position { get; set; } + public override int Read(byte[] buffer, int offset, int count) + { + var read = (int)Math.Min(count, length - Position); + Array.Clear(buffer, offset, read); + Position += read; + return read; + } + public override long Seek(long offset, SeekOrigin origin) => Position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => Position + offset, + _ => length + offset, + }; + public override void Flush() { } + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class CancelProgress(CancellationTokenSource cancel) : IProgress + { + public void Report(double value) { if (value > 0) cancel.Cancel(); } + } + + public void Dispose() => Directory.Delete(_root, recursive: true); +} From 12e4d44a5a60b8ffde27ca80e409614ed5da0643 Mon Sep 17 00:00:00 2001 From: manish0467 Date: Sat, 14 Nov 2026 00:07:44 +0530 Subject: [PATCH 16/95] feat(linux): add Yazi file manager integration plugin - Add Yazi plugin in installer/linux/yazi/filee.yazi/ supporting quick conversion and Donut GUI trigger - Bundle yazi integration in build/build-portable.ps1 - Document setup instructions and keybinding in installer/linux/INSTALL.txt --- build/build-portable.ps1 | 1 + installer/linux/INSTALL.txt | 13 ++ installer/linux/yazi/filee.yazi/README.md | 39 +++++ installer/linux/yazi/filee.yazi/init.lua | 200 ++++++++++++++++++++++ 4 files changed, 253 insertions(+) create mode 100644 installer/linux/yazi/filee.yazi/README.md create mode 100644 installer/linux/yazi/filee.yazi/init.lua diff --git a/build/build-portable.ps1 b/build/build-portable.ps1 index a5e2b36b2..a76bb17ab 100644 --- a/build/build-portable.ps1 +++ b/build/build-portable.ps1 @@ -181,6 +181,7 @@ else { Copy-Item -LiteralPath (Join-Path $root 'installer/linux/kwin') -Destination $package -Recurse Copy-Item -LiteralPath (Join-Path $root 'installer/linux/gnome') -Destination $package -Recurse Copy-Item -LiteralPath (Join-Path $root 'installer/linux/hyprland') -Destination $package -Recurse + Copy-Item -LiteralPath (Join-Path $root 'installer/linux/yazi') -Destination $package -Recurse Copy-Item -LiteralPath (Join-Path $root 'docs/GNOME-WAYLAND.md') -Destination $package } Invoke-Checked 'Installer permissions' { chmod +x (Join-Path $package 'install.sh') (Join-Path $package 'uninstall.sh') } diff --git a/installer/linux/INSTALL.txt b/installer/linux/INSTALL.txt index 0f2ec0da3..ab2aecd43 100644 --- a/installer/linux/INSTALL.txt +++ b/installer/linux/INSTALL.txt @@ -127,6 +127,19 @@ libwayland-client0 on Ubuntu). To turn it on: windowrulev2 = noblur, title:^(Filee Donut)$ Hyprland reloads its config when the file changes; hyprctl reload forces it. +Yazi terminal file manager integration: +The Linux package includes a Yazi plugin (filee.yazi) for converting selected or +hovered files directly within Yazi, or opening them in the Filee Donut. +To set up: +1. Link or copy the plugin into your Yazi plugins directory: + mkdir -p ~/.config/yazi/plugins + ln -s "${XDG_DATA_HOME:-$HOME/.local/share}/filee/application/yazi/filee.yazi" ~/.config/yazi/plugins/filee.yazi +2. Add a keybinding in ~/.config/yazi/keymap.toml: + [[manager.prepend_keymap]] + on = [ "c", "f" ] + run = "plugin filee" + desc = "Convert with Filee" + Native Wayland Backend (experimental, off by default): By default, Filee runs through XWayland on Wayland desktops for maximum compatibility. To opt into the native Wayland backend (Avalonia.Wayland): diff --git a/installer/linux/yazi/filee.yazi/README.md b/installer/linux/yazi/filee.yazi/README.md new file mode 100644 index 000000000..5ab921f37 --- /dev/null +++ b/installer/linux/yazi/filee.yazi/README.md @@ -0,0 +1,39 @@ +# Filee Yazi Plugin + +Yazi plugin to convert selected or hovered files with [Filee](https://github.com/KnifeLemon/Filee), or open them directly in the interactive Filee Donut UI. + +## Features + +- Works on multi-file selections or the currently hovered file. +- Fast key menu (`ya.which`) for popular conversion targets: + - **Images**: WebP, JPEG, PNG, AVIF, Remove Background + - **Documents**: PDF, OCR to Markdown (`.md`), OCR to Text (`.txt`) + - **Media**: MP3 (extract audio), MP4 (video compression) + - **Archives**: ZIP, Extract + - **Custom Format**: Prompt for any custom extension or preset supported by Filee + - **GUI**: Open directly in the Filee Donut +- Non-blocking asynchronous conversion. +- Terminal notifications via Yazi's `ya.notify` and desktop notifications via `notify-send`. + +## Installation + +1. Copy or symlink this folder to your Yazi plugins directory: + + ```sh + mkdir -p ~/.config/yazi/plugins + ln -s "${XDG_DATA_HOME:-$HOME/.local/share}/filee/application/yazi/filee.yazi" ~/.config/yazi/plugins/filee.yazi + ``` + +2. Add a keybinding in `~/.config/yazi/keymap.toml`: + + ```toml + [[manager.prepend_keymap]] + on = [ "c", "f" ] + run = "plugin filee" + desc = "Convert with Filee" + ``` + +## Requirements + +- `filee` CLI on `$PATH` (installed automatically to `~/.local/bin/filee` by `install.sh`). +- Optional: `notify-send` for desktop notifications. diff --git a/installer/linux/yazi/filee.yazi/init.lua b/installer/linux/yazi/filee.yazi/init.lua new file mode 100644 index 000000000..8bc9522fa --- /dev/null +++ b/installer/linux/yazi/filee.yazi/init.lua @@ -0,0 +1,200 @@ +--- @sync entry +--- Yazi plugin to convert selected or hovered files with Filee offline converter + +local get_targets = ya.sync(function() + local tab = cx.active + local paths = {} + + -- Check for selected files + if tab.selected then + for _, url in pairs(tab.selected) do + table.insert(paths, tostring(url)) + end + end + + -- Fallback to currently hovered file if no explicit selection + if #paths == 0 and tab.current and tab.current.hovered then + table.insert(paths, tostring(tab.current.hovered.url)) + end + + return paths +end) + +local function is_successful(status) + if not status then + return false + end + if type(status.success) == "function" then + return status:success() + end + if status.success == true then + return true + end + if type(status.code) == "function" then + return status:code() == 0 + end + if status.code == 0 then + return true + end + return false +end + +local function notify(title, content, level) + ya.notify({ + title = title, + content = content, + level = level or "info", + timeout = 4, + }) + -- Best-effort freedesktop desktop notification if notify-send exists + Command("notify-send") + :arg(title) + :arg(content) + :spawn() +end + +local M = {} + +function M:entry() + local targets = get_targets() + if #targets == 0 then + ya.notify({ + title = "Filee", + content = "No file selected or hovered", + level = "warn", + timeout = 3, + }) + return + end + + local idx = ya.which({ + cands = { + { on = "w", desc = "WebP (Image)" }, + { on = "p", desc = "PDF (Document)" }, + { on = "j", desc = "JPEG (Image)" }, + { on = "n", desc = "PNG (Image)" }, + { on = "a", desc = "AVIF (Modern Image)" }, + { on = "o", desc = "OCR / Text (Markdown)" }, + { on = "t", desc = "OCR / Plain Text (.txt)" }, + { on = "m", desc = "MP3 (Extract Audio)" }, + { on = "v", desc = "MP4 (Video)" }, + { on = "b", desc = "Remove Background (PNG)" }, + { on = "z", desc = "ZIP Archive" }, + { on = "x", desc = "Extract Archive" }, + { on = "c", desc = "Custom Format..." }, + { on = "d", desc = "Open in Filee Donut (GUI)" }, + }, + }) + + if not idx then + return + end + + local format = nil + local preset = nil + + if idx == 1 then + format = "webp" + elseif idx == 2 then + format = "pdf" + elseif idx == 3 then + format = "jpg" + elseif idx == 4 then + format = "png" + elseif idx == 5 then + format = "avif" + elseif idx == 6 then + format = "md" + elseif idx == 7 then + format = "txt" + elseif idx == 8 then + format = "mp3" + elseif idx == 9 then + format = "mp4" + elseif idx == 10 then + preset = "remove-background" + elseif idx == 11 then + format = "zip" + elseif idx == 12 then + preset = "extract" + elseif idx == 13 then + local val, event = ya.input({ + title = "Target format or preset (e.g. svg, docx, csv):", + position = { "center", w = 50 }, + }) + if event ~= 1 or not val or val == "" then + return + end + format = val:gsub("^%.", ""):gsub("%s+", "") + elseif idx == 14 then + -- Open in Filee GUI Donut + local home = os.getenv("HOME") or "" + local xdg_data = os.getenv("XDG_DATA_HOME") + local default_app = (xdg_data and #xdg_data > 0 and xdg_data or (home .. "/.local/share")) .. "/filee/application/Filee" + + local cmd = Command(default_app) + cmd:arg("--convert") + for _, target in ipairs(targets) do + cmd:arg(target) + end + local child, _ = cmd:spawn() + if not child then + -- Fallback to Filee on PATH + local path_cmd = Command("Filee"):arg("--convert") + for _, target in ipairs(targets) do + path_cmd:arg(target) + end + local fallback_child = path_cmd:spawn() + if not fallback_child then + -- Final fallback: filee CLI wrapper + local cli_cmd = Command("filee"):arg("--convert") + for _, target in ipairs(targets) do + cli_cmd:arg(target) + end + cli_cmd:spawn() + end + end + ya.notify({ + title = "Filee", + content = ("Opened %d file(s) in Filee Donut"):format(#targets), + timeout = 3, + }) + return + end + + local label = (format or preset):upper() + ya.notify({ + title = "Filee", + content = ("Converting %d file(s) to %s..."):format(#targets, label), + timeout = 3, + }) + + local cmd = Command("filee") + cmd:arg("convert") + for _, target in ipairs(targets) do + cmd:arg(target) + end + + if preset then + cmd:arg("--preset"):arg(preset) + elseif format then + cmd:arg("--to"):arg(format) + end + + local output, err = cmd:output() + + if output and is_successful(output.status) then + local msg = ("Converted %d file(s) to %s"):format(#targets, label) + notify("Filee", msg, "info") + else + local err_msg = "Conversion failed" + if output and output.stderr and #output.stderr > 0 then + err_msg = output.stderr:gsub("[\r\n]+", " ") + elseif err then + err_msg = tostring(err) + end + notify("Filee Error", err_msg:sub(1, 120), "error") + end +end + +return M From 67af732505a8680e55176ad6c445447a20ac6e18 Mon Sep 17 00:00:00 2001 From: manish0467 Date: Sat, 14 Nov 2026 00:56:24 +0530 Subject: [PATCH 17/95] fix(linux): address PR review comments for Yazi integration - Remove @sync entry to keep execution asynchronous - Update keymap to modern [[mgr.prepend_keymap]] (Yazi 25.5+) in docs - Drop CLI fallbacks and notify on error if GUI launcher fails --- installer/linux/INSTALL.txt | 3 ++- installer/linux/yazi/filee.yazi/README.md | 3 ++- installer/linux/yazi/filee.yazi/init.lua | 28 ++++++++--------------- 3 files changed, 14 insertions(+), 20 deletions(-) diff --git a/installer/linux/INSTALL.txt b/installer/linux/INSTALL.txt index ab2aecd43..1fa126c83 100644 --- a/installer/linux/INSTALL.txt +++ b/installer/linux/INSTALL.txt @@ -130,12 +130,13 @@ libwayland-client0 on Ubuntu). To turn it on: Yazi terminal file manager integration: The Linux package includes a Yazi plugin (filee.yazi) for converting selected or hovered files directly within Yazi, or opening them in the Filee Donut. +Requires Yazi 25.5 or newer (for Yazi 0.3.x or older, use [[manager.prepend_keymap]]). To set up: 1. Link or copy the plugin into your Yazi plugins directory: mkdir -p ~/.config/yazi/plugins ln -s "${XDG_DATA_HOME:-$HOME/.local/share}/filee/application/yazi/filee.yazi" ~/.config/yazi/plugins/filee.yazi 2. Add a keybinding in ~/.config/yazi/keymap.toml: - [[manager.prepend_keymap]] + [[mgr.prepend_keymap]] on = [ "c", "f" ] run = "plugin filee" desc = "Convert with Filee" diff --git a/installer/linux/yazi/filee.yazi/README.md b/installer/linux/yazi/filee.yazi/README.md index 5ab921f37..b3889c9c3 100644 --- a/installer/linux/yazi/filee.yazi/README.md +++ b/installer/linux/yazi/filee.yazi/README.md @@ -27,7 +27,7 @@ Yazi plugin to convert selected or hovered files with [Filee](https://github.com 2. Add a keybinding in `~/.config/yazi/keymap.toml`: ```toml - [[manager.prepend_keymap]] + [[mgr.prepend_keymap]] on = [ "c", "f" ] run = "plugin filee" desc = "Convert with Filee" @@ -35,5 +35,6 @@ Yazi plugin to convert selected or hovered files with [Filee](https://github.com ## Requirements +- Yazi 25.5 or newer (for Yazi 0.3.x or older, use `[[manager.prepend_keymap]]` instead of `[[mgr.prepend_keymap]]`). - `filee` CLI on `$PATH` (installed automatically to `~/.local/bin/filee` by `install.sh`). - Optional: `notify-send` for desktop notifications. diff --git a/installer/linux/yazi/filee.yazi/init.lua b/installer/linux/yazi/filee.yazi/init.lua index 8bc9522fa..9b95e90fe 100644 --- a/installer/linux/yazi/filee.yazi/init.lua +++ b/installer/linux/yazi/filee.yazi/init.lua @@ -1,4 +1,3 @@ ---- @sync entry --- Yazi plugin to convert selected or hovered files with Filee offline converter local get_targets = ya.sync(function() @@ -130,29 +129,22 @@ function M:entry() -- Open in Filee GUI Donut local home = os.getenv("HOME") or "" local xdg_data = os.getenv("XDG_DATA_HOME") - local default_app = (xdg_data and #xdg_data > 0 and xdg_data or (home .. "/.local/share")) .. "/filee/application/Filee" + local app_bin = (xdg_data and #xdg_data > 0 and xdg_data or (home .. "/.local/share")) .. "/filee/application/Filee" - local cmd = Command(default_app) + local cmd = Command(app_bin) cmd:arg("--convert") for _, target in ipairs(targets) do cmd:arg(target) end - local child, _ = cmd:spawn() + local child, err = cmd:spawn() if not child then - -- Fallback to Filee on PATH - local path_cmd = Command("Filee"):arg("--convert") - for _, target in ipairs(targets) do - path_cmd:arg(target) - end - local fallback_child = path_cmd:spawn() - if not fallback_child then - -- Final fallback: filee CLI wrapper - local cli_cmd = Command("filee"):arg("--convert") - for _, target in ipairs(targets) do - cli_cmd:arg(target) - end - cli_cmd:spawn() - end + ya.notify({ + title = "Filee Error", + content = "Could not launch Filee Donut (is Filee installed in " .. app_bin .. "?)", + level = "error", + timeout = 5, + }) + return end ya.notify({ title = "Filee", From 87c4f70ef8bd43f8f4b97fedde7cd60310a93b4a Mon Sep 17 00:00:00 2001 From: Feraris20 <222025665+Feraris20@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:39:43 +0200 Subject: [PATCH 18/95] Suggest UDF in Joliet filename and size limit errors --- src/Filee.App/Assets/i18n/ar.json | 4 ++-- src/Filee.App/Assets/i18n/bn-BD.json | 4 ++-- src/Filee.App/Assets/i18n/de.json | 4 ++-- src/Filee.App/Assets/i18n/en.json | 4 ++-- src/Filee.App/Assets/i18n/es.json | 4 ++-- src/Filee.App/Assets/i18n/fa.json | 4 ++-- src/Filee.App/Assets/i18n/fr.json | 4 ++-- src/Filee.App/Assets/i18n/hi.json | 4 ++-- src/Filee.App/Assets/i18n/id.json | 4 ++-- src/Filee.App/Assets/i18n/it.json | 4 ++-- src/Filee.App/Assets/i18n/ja.json | 4 ++-- src/Filee.App/Assets/i18n/ko.json | 4 ++-- src/Filee.App/Assets/i18n/ne.json | 4 ++-- src/Filee.App/Assets/i18n/pl.json | 4 ++-- src/Filee.App/Assets/i18n/pt-BR.json | 4 ++-- src/Filee.App/Assets/i18n/pt-PT.json | 4 ++-- src/Filee.App/Assets/i18n/ru.json | 4 ++-- src/Filee.App/Assets/i18n/th.json | 4 ++-- src/Filee.App/Assets/i18n/tr.json | 4 ++-- src/Filee.App/Assets/i18n/vi.json | 4 ++-- src/Filee.App/Assets/i18n/zh-CN.json | 4 ++-- src/Filee.App/Assets/i18n/zh-TW.json | 4 ++-- tests/Filee.App.Tests/Udf1443Tests.cs | 12 ++++++++++++ 23 files changed, 56 insertions(+), 44 deletions(-) diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 963d3d0a7..8deffd018 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -1738,8 +1738,8 @@ "general.collect_dropped_hint": "تبقى الملفات المسحوبة أو المختارة في قائمة الصفحة الرئيسية، ويحوّلها «اختر إجراءً» معًا بالترتيب المعروض. مغلق: كل سحب يفتح القائمة الدائرية كما كان من قبل.", "error.iso_root": "لا يدعم إنشاء ISO جذور محركات الأقراص أو أنظمة الملفات. اختر مجلدًا داخل محرك الأقراص.", "error.iso_link": "لا يتبع إنشاء ISO الروابط الرمزية أو وصلات المجلدات. اختر مجلدًا أصليًا لا يحتوي على روابط.", - "error.iso_name": "يجب ألا تتجاوز أسماء Joliet عدد 62 محرفًا من Unicode BMP، وألا تحتوي على محارف تحكم أو فواصل منقوطة أو شرطات مائلة عكسية أو * أو : أو ?. يجب ألا تتجاوز المسارات النسبية 240 محرفًا.", - "error.iso_file_size": "يتطلب إنشاء ISO أن يكون حجم كل ملف أقل من 4 GiB.", + "error.iso_name": "يجب ألا تتجاوز أسماء Joliet عدد 62 محرفًا من Unicode BMP، وألا تحتوي على محارف تحكم أو فواصل منقوطة أو شرطات مائلة عكسية أو * أو : أو ?. يجب ألا تتجاوز المسارات النسبية 240 محرفًا. للأسماء الأطول أو الملفات الأكبر، اختر UDF 2.01 في خيار نظام ملفات ISO للإعداد المسبق.", + "error.iso_file_size": "يتطلب إنشاء ISO أن يكون حجم كل ملف أقل من 4 GiB. للأسماء الأطول أو الملفات الأكبر، اختر UDF 2.01 في خيار نظام ملفات ISO للإعداد المسبق.", "error.iso_changed": "توقف إنشاء ISO قبل كتابة جميع البيانات. ربما تغيّر أحد الملفات المصدر أثناء التحويل.", "engine.iso.name": "ISO", "engine.iso.description": "ينشئ صور ISO من المجلدات أو محتويات الأرشيف، مع الحفاظ على أسماء Unicode والمجلدات الفارغة.", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index 83d8cdd90..49afb917a 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -1736,8 +1736,8 @@ "general.collect_dropped_hint": "ড্রপ করা ও নির্বাচিত ফাইলগুলো হোম পেজের একটি তালিকায় অপেক্ষা করে, এবং প্রদর্শিত ক্রম অনুযায়ী ‘অ্যাকশন নির্বাচন করুন’ সেগুলোকে একসাথে রূপান্তর করে। বন্ধ থাকলে: প্রতিটি ড্রপ আগের মতো ডোনাট খুলবে।", "error.iso_root": "ড্রাইভ বা ফাইল সিস্টেমের রুট থেকে ISO তৈরি করা যায় না। এর বদলে ড্রাইভের ভেতরের একটি ফোল্ডার নির্বাচন করুন।", "error.iso_link": "ISO তৈরির সময় সিম্বলিক লিংক বা জাংশন অনুসরণ করা হয় না। লিংক করা এন্ট্রি নেই এমন একটি মূল ফোল্ডার নির্বাচন করুন।", - "error.iso_name": "Joliet নামে সর্বোচ্চ ৬২টি BMP ইউনিকোড অক্ষর থাকতে পারে এবং কোনো কন্ট্রোল অক্ষর, সেমিকোলন বা ব্যাকস্ল্যাশ, *, :, ? থাকতে পারবে না। আপেক্ষিক পাথ সর্বোচ্চ ২৪০ অক্ষরের হতে হবে।", - "error.iso_file_size": "ISO তৈরি করতে প্রতিটি ফাইল ৪ GiB-এর চেয়ে ছোট হতে হবে।", + "error.iso_name": "Joliet নামে সর্বোচ্চ ৬২টি BMP ইউনিকোড অক্ষর থাকতে পারে এবং কোনো কন্ট্রোল অক্ষর, সেমিকোলন বা ব্যাকস্ল্যাশ, *, :, ? থাকতে পারবে না। আপেক্ষিক পাথ সর্বোচ্চ ২৪০ অক্ষরের হতে হবে। দীর্ঘ নাম বা বড় ফাইলের জন্য প্রিসেটের ISO ফাইল সিস্টেম বিকল্পে UDF 2.01 নির্বাচন করুন।", + "error.iso_file_size": "ISO তৈরি করতে প্রতিটি ফাইল ৪ GiB-এর চেয়ে ছোট হতে হবে। দীর্ঘ নাম বা বড় ফাইলের জন্য প্রিসেটের ISO ফাইল সিস্টেম বিকল্পে UDF 2.01 নির্বাচন করুন।", "error.iso_changed": "সব ডেটা লেখার আগেই ISO তৈরি বন্ধ হয়ে গেছে। রূপান্তরের সময় কোনো উৎস ফাইল বদলে গিয়ে থাকতে পারে।", "engine.iso.name": "ISO", "engine.iso.description": "ফোল্ডার বা আর্কাইভের বিষয়বস্তু থেকে ISO ইমেজ তৈরি করে, ইউনিকোড নাম ও খালি ফোল্ডার অক্ষুণ্ণ রেখে।", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index 2333d6268..ce83b32a8 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -1737,8 +1737,8 @@ "general.collect_dropped_hint": "Abgelegte oder ausgewählte Dateien warten auf der Startseite in einer Liste, und Aktion wählen konvertiert sie gemeinsam in der angezeigten Reihenfolge. Aus: jedes Ablegen öffnet das Rad, wie bisher.", "error.iso_root": "ISO-Abbilder können nicht aus Laufwerks- oder Dateisystemwurzeln erstellt werden. Wählen Sie stattdessen einen Unterordner.", "error.iso_link": "Beim Erstellen von ISO-Abbildern werden symbolische Links und Verzeichnisverknüpfungen nicht verfolgt. Wählen Sie einen Originalordner ohne verknüpfte Einträge.", - "error.iso_name": "Joliet-Namen dürfen höchstens 62 Unicode-BMP-Zeichen und keine Steuerzeichen, Semikolons oder umgekehrten Schrägstriche sowie *, : oder ? enthalten. Relative Pfade dürfen höchstens 240 Zeichen lang sein.", - "error.iso_file_size": "Beim Erstellen von ISO-Abbildern muss jede einzelne Datei kleiner als 4 GiB sein.", + "error.iso_name": "Joliet-Namen dürfen höchstens 62 Unicode-BMP-Zeichen und keine Steuerzeichen, Semikolons oder umgekehrten Schrägstriche sowie *, : oder ? enthalten. Relative Pfade dürfen höchstens 240 Zeichen lang sein. Für längere Namen oder größere Dateien im Preset unter ISO-Dateisystem UDF 2.01 auswählen.", + "error.iso_file_size": "Beim Erstellen von ISO-Abbildern muss jede einzelne Datei kleiner als 4 GiB sein. Für längere Namen oder größere Dateien im Preset unter ISO-Dateisystem UDF 2.01 auswählen.", "error.iso_changed": "Die ISO-Erstellung wurde beendet, bevor alle Daten geschrieben waren. Eine Quelldatei könnte während der Konvertierung verändert worden sein.", "engine.iso.name": "ISO", "engine.iso.description": "Erstellt ISO-Abbilder aus Ordnern oder Archivinhalten und erhält Unicode-Namen und leere Ordner.", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index c762e6d2a..f4ed75b81 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Dropped and picked files wait in a list on the Home page, and Choose action converts them together in the order shown. Off: each drop opens the donut, as before.", "error.iso_root": "ISO creation does not support drive or filesystem roots. Select a folder inside the drive instead.", "error.iso_link": "ISO creation does not follow symbolic links or junctions. Select an original folder without linked entries.", - "error.iso_name": "Joliet names must contain at most 62 BMP Unicode characters and no control characters, semicolons or backslashes, *, : or ?. Relative paths must be at most 240 characters.", - "error.iso_file_size": "ISO creation requires individual files smaller than 4 GiB.", + "error.iso_name": "Joliet names must contain at most 62 BMP Unicode characters and no control characters, semicolons or backslashes, *, : or ?. Relative paths must be at most 240 characters. For longer names or larger files, select UDF 2.01 in the preset\u0027s ISO filesystem option.", + "error.iso_file_size": "Joliet requires individual files smaller than 4 GiB. For longer names or larger files, select UDF 2.01 in the preset\u0027s ISO filesystem option.", "error.iso_changed": "ISO creation stopped before all data was written. A source file may have changed during conversion.", "engine.iso.name": "ISO", "engine.iso.description": "Creates ISO images from folders or archive contents, preserving Unicode names and empty folders.", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index c079b73f5..5e3557b97 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -1739,8 +1739,8 @@ "general.collect_dropped_hint": "Los archivos soltados o elegidos esperan en una lista en la pantalla Inicio, y Elegir acción los convierte juntos en el orden mostrado. Desactivado: cada suelta abre el donut, como antes.", "error.iso_root": "No se pueden crear imágenes ISO desde la raíz de una unidad o sistema de archivos. Selecciona una carpeta dentro de la unidad.", "error.iso_link": "La creación de ISO no sigue enlaces simbólicos ni uniones de directorios. Selecciona una carpeta original sin entradas enlazadas.", - "error.iso_name": "Los nombres Joliet deben tener como máximo 62 caracteres Unicode BMP, sin caracteres de control, puntos y coma ni barras inversas ni *, : o ?. Las rutas relativas no deben superar los 240 caracteres.", - "error.iso_file_size": "Para crear una ISO, cada archivo debe ocupar menos de 4 GiB.", + "error.iso_name": "Los nombres Joliet deben tener como máximo 62 caracteres Unicode BMP, sin caracteres de control, puntos y coma ni barras inversas ni *, : o ?. Las rutas relativas no deben superar los 240 caracteres. Para nombres más largos o archivos más grandes, selecciona UDF 2.01 en la opción de sistema de archivos ISO del preajuste.", + "error.iso_file_size": "Para crear una ISO, cada archivo debe ocupar menos de 4 GiB. Para nombres más largos o archivos más grandes, selecciona UDF 2.01 en la opción de sistema de archivos ISO del preajuste.", "error.iso_changed": "La creación de ISO se detuvo antes de escribir todos los datos. Es posible que un archivo de origen haya cambiado durante la conversión.", "engine.iso.name": "ISO", "engine.iso.description": "Crea imágenes ISO a partir de carpetas o del contenido de archivos comprimidos, conservando los nombres Unicode y las carpetas vacías.", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index 5840a7a66..7004ef739 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -1736,8 +1736,8 @@ "general.collect_dropped_hint": "فایل‌های رهاشده و انتخاب‌شده در یک لیست در صفحه خانه منتظر می‌مانند و گزینه «انتخاب عملیات» آن‌ها را با هم و به ترتیب نمایش‌داده‌شده تبدیل می‌کند. خاموش: هر بار رها کردن فایل، منوی دونات را مانند قبل باز می‌کند.", "error.iso_root": "ساخت ISO از ریشهٔ درایو یا سیستم فایل پشتیبانی نمی‌شود. به‌جای آن، پوشه‌ای داخل درایو را انتخاب کنید.", "error.iso_link": "ساخت ISO پیوندهای نمادین یا junctionها را دنبال نمی‌کند. پوشهٔ اصلی‌ای را انتخاب کنید که مورد پیوندی ندارد.", - "error.iso_name": "نام‌های Joliet باید حداکثر ۶۲ نویسهٔ یونیکد BMP داشته باشند و نویسهٔ کنترلی، نقطه‌ویرگول یا بک‌اسلش، *، : یا ? نداشته باشند. مسیرهای نسبی باید حداکثر ۲۴۰ نویسه باشند.", - "error.iso_file_size": "برای ساخت ISO، حجم هر فایل باید کمتر از ۴ GiB باشد.", + "error.iso_name": "نام‌های Joliet باید حداکثر ۶۲ نویسهٔ یونیکد BMP داشته باشند و نویسهٔ کنترلی، نقطه‌ویرگول یا بک‌اسلش، *، : یا ? نداشته باشند. مسیرهای نسبی باید حداکثر ۲۴۰ نویسه باشند. برای نام‌های طولانی‌تر یا فایل‌های بزرگ‌تر، UDF 2.01 را در گزینه سیستم فایل ISO پیش‌تنظیم انتخاب کنید.", + "error.iso_file_size": "برای ساخت ISO، حجم هر فایل باید کمتر از ۴ GiB باشد. برای نام‌های طولانی‌تر یا فایل‌های بزرگ‌تر، UDF 2.01 را در گزینه سیستم فایل ISO پیش‌تنظیم انتخاب کنید.", "error.iso_changed": "ساخت ISO پیش از نوشتن همهٔ داده‌ها متوقف شد. ممکن است یک فایل مبدأ در حین تبدیل تغییر کرده باشد.", "engine.iso.name": "ISO", "engine.iso.description": "از پوشه‌ها یا محتوای آرشیوها تصویر ISO می‌سازد و نام‌های یونیکد و پوشه‌های خالی را حفظ می‌کند.", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index 68ba83435..76939fd01 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Les fichiers déposés ou choisis attendent dans une liste sur l'accueil, et Choisir une action les convertit ensemble, dans l'ordre affiché. Désactivé : chaque dépôt ouvre le donut, comme avant.", "error.iso_root": "La création ISO ne prend pas en charge la racine des lecteurs ou des systèmes de fichiers. Sélectionnez un dossier à l’intérieur du lecteur.", "error.iso_link": "La création ISO ne suit pas les liens symboliques ni les jonctions. Sélectionnez un dossier original sans éléments liés.", - "error.iso_name": "Les noms Joliet sont limités à 62 caractères Unicode BMP, sans caractères de contrôle, points-virgules ni barres obliques inverses ni *, : ou ?. Les chemins relatifs sont limités à 240 caractères.", - "error.iso_file_size": "Pour créer une ISO, chaque fichier doit faire moins de 4 GiB.", + "error.iso_name": "Les noms Joliet sont limités à 62 caractères Unicode BMP, sans caractères de contrôle, points-virgules ni barres obliques inverses ni *, : ou ?. Les chemins relatifs sont limités à 240 caractères. Pour des noms plus longs ou des fichiers plus volumineux, choisissez UDF 2.01 dans l’option de système de fichiers ISO du préréglage.", + "error.iso_file_size": "Pour créer une ISO, chaque fichier doit faire moins de 4 GiB. Pour des noms plus longs ou des fichiers plus volumineux, choisissez UDF 2.01 dans l’option de système de fichiers ISO du préréglage.", "error.iso_changed": "La création ISO s’est arrêtée avant l’écriture de toutes les données. Un fichier source a peut-être changé pendant la conversion.", "engine.iso.name": "ISO", "engine.iso.description": "Crée des images ISO à partir de dossiers ou du contenu des archives, en conservant les noms Unicode et les dossiers vides.", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 5de402d63..e187ed2f9 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -1739,8 +1739,8 @@ "general.collect_dropped_hint": "खींची या चुनी गई फ़ाइलें होम की सूची में रहती हैं, और \"क्रिया चुनें\" उन्हें दिखाए गए क्रम में एक साथ बदलता है। बंद: हर ड्रॉप पहले की तरह डोनट खोलता है।", "error.iso_root": "ISO बनाने के लिए ड्राइव या फ़ाइल सिस्टम की रूट निर्देशिका समर्थित नहीं है। ड्राइव के अंदर कोई फ़ोल्डर चुनें।", "error.iso_link": "ISO बनाते समय प्रतीकात्मक लिंक या जंक्शन का अनुसरण नहीं किया जाता। लिंक वाली प्रविष्टियों के बिना मूल फ़ोल्डर चुनें।", - "error.iso_name": "Joliet नामों में अधिकतम 62 Unicode BMP वर्ण हो सकते हैं। नियंत्रण वर्ण, अर्धविराम और बैकस्लैश, *, :, ? की अनुमति नहीं है। सापेक्ष पथ अधिकतम 240 वर्ण के हो सकते हैं।", - "error.iso_file_size": "ISO बनाने के लिए प्रत्येक फ़ाइल का आकार 4 GiB से कम होना चाहिए।", + "error.iso_name": "Joliet नामों में अधिकतम 62 Unicode BMP वर्ण हो सकते हैं। नियंत्रण वर्ण, अर्धविराम और बैकस्लैश, *, :, ? की अनुमति नहीं है। सापेक्ष पथ अधिकतम 240 वर्ण के हो सकते हैं। लंबे नाम या बड़ी फ़ाइलों के लिए प्रीसेट के ISO फ़ाइल सिस्टम विकल्प में UDF 2.01 चुनें।", + "error.iso_file_size": "ISO बनाने के लिए प्रत्येक फ़ाइल का आकार 4 GiB से कम होना चाहिए। लंबे नाम या बड़ी फ़ाइलों के लिए प्रीसेट के ISO फ़ाइल सिस्टम विकल्प में UDF 2.01 चुनें।", "error.iso_changed": "सभी डेटा लिखे जाने से पहले ISO बनाना रुक गया। रूपांतरण के दौरान कोई स्रोत फ़ाइल बदल गई होगी।", "engine.iso.name": "ISO", "engine.iso.description": "फ़ोल्डर या आर्काइव की सामग्री से ISO इमेज बनाता है और Unicode नाम तथा खाली फ़ोल्डर सुरक्षित रखता है।", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index 456f8720b..abac3563c 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -1737,8 +1737,8 @@ "general.collect_dropped_hint": "File yang dijatuhkan atau dipilih menunggu dalam daftar di halaman Beranda, dan Pilih tindakan mengonversinya bersama sesuai urutan yang ditampilkan. Mati: setiap jatuhan membuka donat, seperti sebelumnya.", "error.iso_root": "Pembuatan ISO tidak mendukung akar drive atau sistem berkas. Pilih folder di dalam drive.", "error.iso_link": "Pembuatan ISO tidak mengikuti tautan simbolis atau junction. Pilih folder asli tanpa entri tertaut.", - "error.iso_name": "Nama Joliet maksimal 62 karakter Unicode BMP, tanpa karakter kontrol, titik koma, atau garis miring terbalik, *, :, atau ?. Jalur relatif maksimal 240 karakter.", - "error.iso_file_size": "Untuk membuat ISO, setiap berkas harus lebih kecil dari 4 GiB.", + "error.iso_name": "Nama Joliet maksimal 62 karakter Unicode BMP, tanpa karakter kontrol, titik koma, atau garis miring terbalik, *, :, atau ?. Jalur relatif maksimal 240 karakter. Untuk nama yang lebih panjang atau berkas yang lebih besar, pilih UDF 2.01 pada opsi sistem berkas ISO prasetel.", + "error.iso_file_size": "Untuk membuat ISO, setiap berkas harus lebih kecil dari 4 GiB. Untuk nama yang lebih panjang atau berkas yang lebih besar, pilih UDF 2.01 pada opsi sistem berkas ISO prasetel.", "error.iso_changed": "Pembuatan ISO berhenti sebelum semua data ditulis. Berkas sumber mungkin berubah selama konversi.", "engine.iso.name": "ISO", "engine.iso.description": "Membuat citra ISO dari folder atau isi arsip, mempertahankan nama Unicode dan folder kosong.", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index f6e01bc23..88add60da 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -1736,8 +1736,8 @@ "general.collect_dropped_hint": "I file trascinati o scelti restano in un elenco nella schermata Inizio, e Scegli azione li converte insieme nell'ordine mostrato. Disattivato: ogni trascinamento apre il donut, come prima.", "error.iso_root": "La creazione ISO non supporta la radice di un’unità o di un file system. Seleziona una cartella all’interno dell’unità.", "error.iso_link": "La creazione ISO non segue collegamenti simbolici o giunzioni. Seleziona una cartella originale senza elementi collegati.", - "error.iso_name": "I nomi Joliet possono contenere al massimo 62 caratteri Unicode BMP, senza caratteri di controllo, punti e virgola o barre rovesciate, *, : o ?. I percorsi relativi non possono superare 240 caratteri.", - "error.iso_file_size": "Per creare un’immagine ISO, ogni file deve essere più piccolo di 4 GiB.", + "error.iso_name": "I nomi Joliet possono contenere al massimo 62 caratteri Unicode BMP, senza caratteri di controllo, punti e virgola o barre rovesciate, *, : o ?. I percorsi relativi non possono superare 240 caratteri. Per nomi più lunghi o file più grandi, seleziona UDF 2.01 nel file system ISO della preimpostazione.", + "error.iso_file_size": "Per creare un’immagine ISO, ogni file deve essere più piccolo di 4 GiB. Per nomi più lunghi o file più grandi, seleziona UDF 2.01 nel file system ISO della preimpostazione.", "error.iso_changed": "La creazione ISO si è interrotta prima della scrittura di tutti i dati. Un file di origine potrebbe essere cambiato durante la conversione.", "engine.iso.name": "ISO", "engine.iso.description": "Crea immagini ISO da cartelle o dal contenuto degli archivi, mantenendo i nomi Unicode e le cartelle vuote.", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index 669a05409..af540f5f0 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -1739,8 +1739,8 @@ "general.collect_dropped_hint": "ドロップまたは選択したファイルはホームのリストで待ち、「操作を選択」で表示順にまとめて変換します。オフ:ドロップごとに従来どおりドーナツが開きます。", "error.iso_root": "ドライブやファイルシステムのルートからは ISO を作成できません。ドライブ内のフォルダーを選択してください。", "error.iso_link": "ISO 作成ではシンボリックリンクやジャンクションをたどりません。リンクを含まない元のフォルダーを選択してください。", - "error.iso_name": "Joliet 名は Unicode BMP の 62 文字以内で、制御文字、セミコロン、バックスラッシュ、*、:、?は使用できません。相対パスは 240 文字以内にしてください。", - "error.iso_file_size": "ISO を作成するには、各ファイルのサイズを 4 GiB 未満にしてください。", + "error.iso_name": "Joliet 名は Unicode BMP の 62 文字以内で、制御文字、セミコロン、バックスラッシュ、*、:、?は使用できません。相対パスは 240 文字以内にしてください。 長い名前や大きなファイルには、プリセットの ISO ファイルシステムで UDF 2.01 を選択してください。", + "error.iso_file_size": "ISO を作成するには、各ファイルのサイズを 4 GiB 未満にしてください。 長い名前や大きなファイルには、プリセットの ISO ファイルシステムで UDF 2.01 を選択してください。", "error.iso_changed": "すべてのデータを書き込む前に ISO 作成が停止しました。変換中に元のファイルが変更された可能性があります。", "engine.iso.name": "ISO", "engine.iso.description": "フォルダーまたはアーカイブの内容から ISO イメージを作成し、Unicode 名と空のフォルダーを保持します。", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index d7237b0da..8e15003b2 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "끌어 놓거나 고른 파일이 홈의 목록에 모이고, 작업 선택을 누르면 보이는 순서대로 함께 변환해요. 끄면 예전처럼 놓을 때마다 도넛이 열려요.", "error.iso_root": "드라이브 또는 파일 시스템 루트에서는 ISO를 만들 수 없습니다. 드라이브 안의 폴더를 선택하세요.", "error.iso_link": "ISO 생성은 심볼릭 링크나 정션을 따라가지 않습니다. 연결된 항목이 없는 원본 폴더를 선택하세요.", - "error.iso_name": "Joliet 이름은 Unicode BMP 문자 62자 이내여야 하며 제어 문자, 세미콜론, 역슬래시, *, :, ?를 포함할 수 없습니다. 상대 경로는 240자 이내여야 합니다.", - "error.iso_file_size": "ISO를 만들려면 개별 파일 크기가 4 GiB보다 작아야 합니다.", + "error.iso_name": "Joliet 이름은 Unicode BMP 문자 62자 이내여야 하며 제어 문자, 세미콜론, 역슬래시, *, :, ?를 포함할 수 없습니다. 상대 경로는 240자 이내여야 합니다. 더 긴 이름이나 더 큰 파일에는 프리셋의 ISO 파일 시스템 옵션에서 UDF 2.01을 선택하세요.", + "error.iso_file_size": "ISO를 만들려면 개별 파일 크기가 4 GiB보다 작아야 합니다. 더 긴 이름이나 더 큰 파일에는 프리셋의 ISO 파일 시스템 옵션에서 UDF 2.01을 선택하세요.", "error.iso_changed": "모든 데이터를 쓰기 전에 ISO 생성이 중지되었습니다. 변환 중 원본 파일이 변경되었을 수 있습니다.", "engine.iso.name": "ISO", "engine.iso.description": "폴더 또는 압축 파일의 내용으로 ISO 이미지를 만들고 유니코드 이름과 빈 폴더를 보존합니다.", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index b74c4cf19..a0caad63d 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -1739,8 +1739,8 @@ "general.collect_dropped_hint": "तानिएका वा चयन गरिएका फाइलहरू होमको सूचीमा बस्छन्, र \"कार्य छान्नुहोस्\" ले देखाइएको क्रममा सबै एकसाथ रूपान्तरण गर्छ। बन्द: हरेक ड्रप पहिलेजस्तै डोनट खोल्छ।", "error.iso_root": "ड्राइभ वा फाइल प्रणालीको मूलबाट ISO बनाउन मिल्दैन। ड्राइभभित्रको फोल्डर छान्नुहोस्।", "error.iso_link": "ISO बनाउँदा प्रतीकात्मक लिङ्क वा जङ्क्सन पछ्याइँदैन। लिङ्क भएका प्रविष्टिहरू नभएको मूल फोल्डर छान्नुहोस्।", - "error.iso_name": "Joliet नाममा बढीमा 62 Unicode BMP अक्षर हुन सक्छन्। नियन्त्रण अक्षर, अर्धविराम वा ब्याकस्ल्यास, *, :, ? राख्न मिल्दैन। सापेक्ष पथ बढीमा 240 अक्षरको हुनुपर्छ।", - "error.iso_file_size": "ISO बनाउन प्रत्येक फाइलको आकार 4 GiB भन्दा सानो हुनुपर्छ।", + "error.iso_name": "Joliet नाममा बढीमा 62 Unicode BMP अक्षर हुन सक्छन्। नियन्त्रण अक्षर, अर्धविराम वा ब्याकस्ल्यास, *, :, ? राख्न मिल्दैन। सापेक्ष पथ बढीमा 240 अक्षरको हुनुपर्छ। लामा नाम वा ठूला फाइलका लागि प्रिसेटको ISO फाइल प्रणाली विकल्पमा UDF 2.01 छान्नुहोस्।", + "error.iso_file_size": "ISO बनाउन प्रत्येक फाइलको आकार 4 GiB भन्दा सानो हुनुपर्छ। लामा नाम वा ठूला फाइलका लागि प्रिसेटको ISO फाइल प्रणाली विकल्पमा UDF 2.01 छान्नुहोस्।", "error.iso_changed": "सबै डेटा लेखिनुअघि ISO बनाउने काम रोकियो। रूपान्तरणका बेला स्रोत फाइल परिवर्तन भएको हुन सक्छ।", "engine.iso.name": "ISO", "engine.iso.description": "फोल्डर वा अभिलेखको सामग्रीबाट ISO छवि बनाउँछ र Unicode नाम तथा खाली फोल्डरहरू सुरक्षित राख्छ।", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index bbc027472..a0a937b03 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Upuszczone lub wybrane pliki czekają na liście na ekranie Start, a Wybierz działanie konwertuje je razem w pokazanej kolejności. Wyłączone: każde upuszczenie otwiera pierścień, jak dotąd.", "error.iso_root": "Nie można tworzyć ISO z katalogu głównego dysku lub systemu plików. Wybierz folder na dysku.", "error.iso_link": "Tworzenie ISO nie podąża za dowiązaniami symbolicznymi ani punktami połączeń. Wybierz oryginalny folder bez dowiązanych elementów.", - "error.iso_name": "Nazwy Joliet mogą mieć najwyżej 62 znaki Unicode BMP i nie mogą zawierać znaków sterujących, średników ani ukośników odwrotnych ani *, : lub ?. Ścieżki względne mogą mieć najwyżej 240 znaków.", - "error.iso_file_size": "Aby utworzyć ISO, każdy plik musi być mniejszy niż 4 GiB.", + "error.iso_name": "Nazwy Joliet mogą mieć najwyżej 62 znaki Unicode BMP i nie mogą zawierać znaków sterujących, średników ani ukośników odwrotnych ani *, : lub ?. Ścieżki względne mogą mieć najwyżej 240 znaków. Dla dłuższych nazw lub większych plików wybierz UDF 2.01 w opcji systemu plików ISO ustawienia wstępnego.", + "error.iso_file_size": "Aby utworzyć ISO, każdy plik musi być mniejszy niż 4 GiB. Dla dłuższych nazw lub większych plików wybierz UDF 2.01 w opcji systemu plików ISO ustawienia wstępnego.", "error.iso_changed": "Tworzenie ISO zatrzymało się przed zapisaniem wszystkich danych. Plik źródłowy mógł się zmienić podczas konwersji.", "engine.iso.name": "ISO", "engine.iso.description": "Tworzy obrazy ISO z folderów lub zawartości archiwów, zachowując nazwy Unicode i puste foldery.", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index 69b381e77..02a8a7370 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Os arquivos soltos ou escolhidos ficam numa lista na tela Início, e Escolher ação converte todos juntos, na ordem mostrada. Desligado: cada solta abre o donut, como antes.", "error.iso_root": "Não é possível criar uma ISO a partir da raiz de uma unidade ou sistema de arquivos. Selecione uma pasta dentro da unidade.", "error.iso_link": "A criação de ISO não segue links simbólicos nem junções. Selecione uma pasta original sem itens vinculados.", - "error.iso_name": "Os nomes Joliet devem ter no máximo 62 caracteres Unicode BMP, sem caracteres de controle, ponto e vírgula ou barras invertidas, *, : ou ?. Os caminhos relativos devem ter no máximo 240 caracteres.", - "error.iso_file_size": "Para criar uma ISO, cada arquivo deve ter menos de 4 GiB.", + "error.iso_name": "Os nomes Joliet devem ter no máximo 62 caracteres Unicode BMP, sem caracteres de controle, ponto e vírgula ou barras invertidas, *, : ou ?. Os caminhos relativos devem ter no máximo 240 caracteres. Para nomes mais longos ou arquivos maiores, selecione UDF 2.01 na opção de sistema de arquivos ISO da predefinição.", + "error.iso_file_size": "Para criar uma ISO, cada arquivo deve ter menos de 4 GiB. Para nomes mais longos ou arquivos maiores, selecione UDF 2.01 na opção de sistema de arquivos ISO da predefinição.", "error.iso_changed": "A criação de ISO parou antes de gravar todos os dados. Um arquivo de origem pode ter mudado durante a conversão.", "engine.iso.name": "ISO", "engine.iso.description": "Cria imagens ISO de pastas ou do conteúdo de arquivos compactados, preservando nomes Unicode e pastas vazias.", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index 7237dc6fc..3e1a27e27 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Os ficheiros largados ou escolhidos ficam numa lista no ecrã Início, e Escolher ação converte-os todos juntos, pela ordem mostrada. Desligado: cada largada abre o donut, como antes.", "error.iso_root": "Não é possível criar uma ISO a partir da raiz de uma unidade ou sistema de ficheiros. Selecione uma pasta dentro da unidade.", "error.iso_link": "A criação de ISO não segue ligações simbólicas nem junções. Selecione uma pasta original sem itens ligados.", - "error.iso_name": "Os nomes Joliet devem ter, no máximo, 62 carateres Unicode BMP, sem carateres de controlo, pontos e vírgulas ou barras invertidas, *, : ou ?. Os caminhos relativos devem ter, no máximo, 240 carateres.", - "error.iso_file_size": "Para criar uma ISO, cada ficheiro deve ter menos de 4 GiB.", + "error.iso_name": "Os nomes Joliet devem ter, no máximo, 62 carateres Unicode BMP, sem carateres de controlo, pontos e vírgulas ou barras invertidas, *, : ou ?. Os caminhos relativos devem ter, no máximo, 240 carateres. Para nomes mais longos ou ficheiros maiores, selecione UDF 2.01 na opção de sistema de ficheiros ISO da predefinição.", + "error.iso_file_size": "Para criar uma ISO, cada ficheiro deve ter menos de 4 GiB. Para nomes mais longos ou ficheiros maiores, selecione UDF 2.01 na opção de sistema de ficheiros ISO da predefinição.", "error.iso_changed": "A criação de ISO parou antes de escrever todos os dados. Um ficheiro de origem pode ter sido alterado durante a conversão.", "engine.iso.name": "ISO", "engine.iso.description": "Cria imagens ISO de pastas ou do conteúdo de arquivos comprimidos, preservando nomes Unicode e pastas vazias.", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index c1798aa71..a2db9ffa8 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Перетащенные или выбранные файлы ждут в списке на главной, и «Выбрать действие» конвертирует их вместе в показанном порядке. Выключено: каждое перетаскивание открывает круговое меню, как раньше.", "error.iso_root": "Создание ISO из корня диска или файловой системы не поддерживается. Выберите папку внутри диска.", "error.iso_link": "При создании ISO символические ссылки и точки соединения не обходятся. Выберите исходную папку без ссылок.", - "error.iso_name": "Имена Joliet должны содержать не более 62 символов Unicode BMP без управляющих символов, точек с запятой и обратных косых черт, *, : и ?. Относительные пути должны содержать не более 240 символов.", - "error.iso_file_size": "Для создания ISO размер каждого файла должен быть меньше 4 GiB.", + "error.iso_name": "Имена Joliet должны содержать не более 62 символов Unicode BMP без управляющих символов, точек с запятой и обратных косых черт, *, : и ?. Относительные пути должны содержать не более 240 символов. Для более длинных имён или файлов большего размера выберите UDF 2.01 в параметре файловой системы ISO пресета.", + "error.iso_file_size": "Для создания ISO размер каждого файла должен быть меньше 4 GiB. Для более длинных имён или файлов большего размера выберите UDF 2.01 в параметре файловой системы ISO пресета.", "error.iso_changed": "Создание ISO остановлено до записи всех данных. Возможно, исходный файл изменился во время преобразования.", "engine.iso.name": "ISO", "engine.iso.description": "Создаёт образы ISO из папок или содержимого архивов, сохраняя имена Unicode и пустые папки.", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index d3b86f82d..75e2b99f9 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -1739,8 +1739,8 @@ "general.collect_dropped_hint": "ไฟล์ที่ลากวางหรือเลือกจะรออยู่ในรายการหน้าแรก และ \"เลือกการทำงาน\" จะแปลงทั้งหมดพร้อมกันตามลำดับที่แสดง ปิดอยู่: ทุกครั้งที่ลากวางจะเปิดโดนัทเหมือนเดิม", "error.iso_root": "ไม่รองรับการสร้าง ISO จากรากของไดรฟ์หรือระบบไฟล์ โปรดเลือกโฟลเดอร์ภายในไดรฟ์", "error.iso_link": "การสร้าง ISO จะไม่ติดตามลิงก์สัญลักษณ์หรือจังก์ชัน โปรดเลือกโฟลเดอร์ต้นฉบับที่ไม่มีรายการลิงก์", - "error.iso_name": "ชื่อ Joliet ต้องยาวไม่เกิน 62 อักขระ Unicode BMP และไม่มีอักขระควบคุม อัฒภาค หรือแบ็กสแลช หรือ *, :, ? เส้นทางสัมพัทธ์ต้องยาวไม่เกิน 240 อักขระ", - "error.iso_file_size": "การสร้าง ISO กำหนดให้แต่ละไฟล์มีขนาดเล็กกว่า 4 GiB", + "error.iso_name": "ชื่อ Joliet ต้องยาวไม่เกิน 62 อักขระ Unicode BMP และไม่มีอักขระควบคุม อัฒภาค หรือแบ็กสแลช หรือ *, :, ? เส้นทางสัมพัทธ์ต้องยาวไม่เกิน 240 อักขระ สำหรับชื่อที่ยาวกว่าหรือไฟล์ที่ใหญ่กว่า ให้เลือก UDF 2.01 ในตัวเลือกระบบไฟล์ ISO ของพรีเซ็ต", + "error.iso_file_size": "การสร้าง ISO กำหนดให้แต่ละไฟล์มีขนาดเล็กกว่า 4 GiB สำหรับชื่อที่ยาวกว่าหรือไฟล์ที่ใหญ่กว่า ให้เลือก UDF 2.01 ในตัวเลือกระบบไฟล์ ISO ของพรีเซ็ต", "error.iso_changed": "การสร้าง ISO หยุดก่อนเขียนข้อมูลครบ ไฟล์ต้นฉบับอาจเปลี่ยนแปลงระหว่างการแปลง", "engine.iso.name": "ISO", "engine.iso.description": "สร้างอิมเมจ ISO จากโฟลเดอร์หรือเนื้อหาในไฟล์บีบอัด โดยคงชื่อ Unicode และโฟลเดอร์ว่างไว้", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 1f2a6f295..984ac0202 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -1737,8 +1737,8 @@ "general.collect_dropped_hint": "Bırakılan ya da seçilen dosyalar Başlangıç ekranındaki listede bekler; İşlem seç hepsini gösterilen sırayla dönüştürür. Kapalıyken her bırakma donut'u açar, eskisi gibi.", "error.iso_root": "Sürücü veya dosya sistemi kökünden ISO oluşturulamaz. Sürücünün içindeki bir klasörü seçin.", "error.iso_link": "ISO oluşturulurken sembolik bağlantılar veya birleşim noktaları izlenmez. Bağlantılı öğeler içermeyen özgün bir klasör seçin.", - "error.iso_name": "Joliet adları en fazla 62 Unicode BMP karakteri içermeli; denetim karakterleri, noktalı virgül veya ters eğik çizgi, *, : veya ? içermemelidir. Göreli yollar en fazla 240 karakter olmalıdır.", - "error.iso_file_size": "ISO oluşturmak için her dosyanın boyutu 4 GiB’den küçük olmalıdır.", + "error.iso_name": "Joliet adları en fazla 62 Unicode BMP karakteri içermeli; denetim karakterleri, noktalı virgül veya ters eğik çizgi, *, : veya ? içermemelidir. Göreli yollar en fazla 240 karakter olmalıdır. Daha uzun adlar veya daha büyük dosyalar için ön ayarın ISO dosya sistemi seçeneğinde UDF 2.01 seçin.", + "error.iso_file_size": "ISO oluşturmak için her dosyanın boyutu 4 GiB’den küçük olmalıdır. Daha uzun adlar veya daha büyük dosyalar için ön ayarın ISO dosya sistemi seçeneğinde UDF 2.01 seçin.", "error.iso_changed": "Tüm veriler yazılmadan ISO oluşturma durdu. Dönüştürme sırasında bir kaynak dosya değişmiş olabilir.", "engine.iso.name": "ISO", "engine.iso.description": "Klasörlerden veya arşiv içeriğinden ISO kalıpları oluşturur, Unicode adları ve boş klasörleri korur.", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 5ac84e81d..8c8483b14 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "Tệp được thả hoặc chọn sẽ chờ trong một danh sách ở Trang chủ, và Chọn thao tác sẽ chuyển đổi chúng cùng lúc theo thứ tự hiển thị. Tắt: mỗi lần thả sẽ mở thanh công cụ vòng tròn như trước.", "error.iso_root": "Không hỗ trợ tạo ISO từ thư mục gốc của ổ đĩa hoặc hệ thống tệp. Hãy chọn một thư mục bên trong ổ đĩa.", "error.iso_link": "Quá trình tạo ISO không đi theo liên kết tượng trưng hoặc điểm nối. Hãy chọn thư mục gốc không chứa mục liên kết.", - "error.iso_name": "Tên Joliet có tối đa 62 ký tự Unicode BMP, không có ký tự điều khiển, dấu chấm phẩy hoặc dấu gạch chéo ngược, *, : hoặc ?. Đường dẫn tương đối có tối đa 240 ký tự.", - "error.iso_file_size": "Để tạo ISO, mỗi tệp phải nhỏ hơn 4 GiB.", + "error.iso_name": "Tên Joliet có tối đa 62 ký tự Unicode BMP, không có ký tự điều khiển, dấu chấm phẩy hoặc dấu gạch chéo ngược, *, : hoặc ?. Đường dẫn tương đối có tối đa 240 ký tự. Với tên dài hơn hoặc tệp lớn hơn, hãy chọn UDF 2.01 trong tùy chọn hệ thống tệp ISO của thiết lập sẵn.", + "error.iso_file_size": "Để tạo ISO, mỗi tệp phải nhỏ hơn 4 GiB. Với tên dài hơn hoặc tệp lớn hơn, hãy chọn UDF 2.01 trong tùy chọn hệ thống tệp ISO của thiết lập sẵn.", "error.iso_changed": "Quá trình tạo ISO đã dừng trước khi ghi đủ dữ liệu. Tệp nguồn có thể đã thay đổi trong khi chuyển đổi.", "engine.iso.name": "ISO", "engine.iso.description": "Tạo ảnh ISO từ thư mục hoặc nội dung tệp nén, giữ nguyên tên Unicode và thư mục trống.", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index 4870acb24..686be88f3 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "拖放或选择的文件会在首页列表中等待,“选择操作”会按显示顺序一起转换。关闭时,每次拖放都像以前一样打开圆形菜单。", "error.iso_root": "不支持从驱动器或文件系统根目录创建 ISO。请选择驱动器内的文件夹。", "error.iso_link": "创建 ISO 时不会跟随符号链接或目录联接。请选择不含链接项的原始文件夹。", - "error.iso_name": "Joliet 名称最多包含 62 个 Unicode BMP 字符,不能包含控制字符、分号或反斜杠、*、:、?。相对路径最多为 240 个字符。", - "error.iso_file_size": "创建 ISO 时,每个文件的大小必须小于 4 GiB。", + "error.iso_name": "Joliet 名称最多包含 62 个 Unicode BMP 字符,不能包含控制字符、分号或反斜杠、*、:、?。相对路径最多为 240 个字符。 对于更长的名称或更大的文件,请在预设的 ISO 文件系统选项中选择 UDF 2.01。", + "error.iso_file_size": "创建 ISO 时,每个文件的大小必须小于 4 GiB。 对于更长的名称或更大的文件,请在预设的 ISO 文件系统选项中选择 UDF 2.01。", "error.iso_changed": "ISO 创建在写入全部数据之前停止。源文件可能在转换过程中发生了变化。", "engine.iso.name": "ISO", "engine.iso.description": "从文件夹或压缩包内容创建 ISO 映像,保留 Unicode 名称和空文件夹。", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index 81c02fc4f..7c6788d5d 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -1759,8 +1759,8 @@ "general.collect_dropped_hint": "拖放或選取的檔案會在首頁清單中等待,「選擇動作」會依顯示順序一起轉換。關閉時,每次拖放都像以前一樣開啟圓形選單。", "error.iso_root": "不支援從磁碟機或檔案系統根目錄建立 ISO。請選擇磁碟機內的資料夾。", "error.iso_link": "建立 ISO 時不會跟隨符號連結或目錄接合點。請選擇不含連結項目的原始資料夾。", - "error.iso_name": "Joliet 名稱最多包含 62 個 Unicode BMP 字元,不能包含控制字元、分號或反斜線、*、:、?。相對路徑最多為 240 個字元。", - "error.iso_file_size": "建立 ISO 時,每個檔案的大小必須小於 4 GiB。", + "error.iso_name": "Joliet 名稱最多包含 62 個 Unicode BMP 字元,不能包含控制字元、分號或反斜線、*、:、?。相對路徑最多為 240 個字元。 若名稱較長或檔案較大,請在預設的 ISO 檔案系統選項中選擇 UDF 2.01。", + "error.iso_file_size": "建立 ISO 時,每個檔案的大小必須小於 4 GiB。 若名稱較長或檔案較大,請在預設的 ISO 檔案系統選項中選擇 UDF 2.01。", "error.iso_changed": "ISO 建立在寫入所有資料之前停止。來源檔案可能在轉換過程中發生變更。", "engine.iso.name": "ISO", "engine.iso.description": "從資料夾或壓縮檔內容建立 ISO 映像,保留 Unicode 名稱和空資料夾。", diff --git a/tests/Filee.App.Tests/Udf1443Tests.cs b/tests/Filee.App.Tests/Udf1443Tests.cs index 065859357..ea48eda33 100644 --- a/tests/Filee.App.Tests/Udf1443Tests.cs +++ b/tests/Filee.App.Tests/Udf1443Tests.cs @@ -12,6 +12,18 @@ namespace Filee.App.Tests; public sealed class Udf1443Tests { + [AvaloniaFact] + public void Every_language_suggests_udf_for_joliet_limits() + { + TestServices.EnsureInitialized("en"); + foreach (var language in LocalizationService.Languages) + { + var strings = LocalizationService.LoadStrings(language.Code); + foreach (var key in new[] { "error.iso_name", "error.iso_file_size" }) + Assert.Contains("UDF 2.01", strings[key]); + } + } + [AvaloniaFact] public void Filesystem_choice_round_trips_without_changing_the_default() { From 1b80e646ff79fa51011d0e28b80db5b2fcf6a497 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Sat, 14 Nov 2026 12:17:26 +0530 Subject: [PATCH 19/95] feat: add per-preset option to move the original to the Trash after converting Adds OutputRule.TrashOriginalAfterConvert (off by default) and a checkbox in the preset editor's output card. After a conversion to another format completes, the original goes to the Recycle Bin / Trash. If the Trash refuses, the original stays with a note saying why. Never applied for watch folders, 'Ask where to save', files from a browser, the command line, merges, ZIP results, 'Only if smaller' copies, or results in the same format as the source (that is 'Replace the original'). Adds tests in TrashOriginalTests and a CLI test. Refs #1387 --- .../ViewModels/PresetEditorViewModel.cs | 4 + src/Filee.App/Views/PresetEditorView.axaml | 5 + src/Filee.Cli/Cli.cs | 2 + src/Filee.Core/Conversion/JobQueue.cs | 35 +++ src/Filee.Core/Presets/AskedLocation.cs | 1 + src/Filee.Core/Presets/OutputRule.cs | 9 + src/Filee.Core/Watching/WatchRule.cs | 1 + tests/Filee.Cli.Tests/CliTests.cs | 14 + tests/Filee.Core.Tests/TrashOriginalTests.cs | 272 ++++++++++++++++++ 9 files changed, 343 insertions(+) create mode 100644 tests/Filee.Core.Tests/TrashOriginalTests.cs diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs index d4b3feb52..7a6120a31 100644 --- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs +++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs @@ -399,6 +399,7 @@ .. WhisperLanguages.All _keepDates = _edit.Output.KeepDates; _zipResult = _edit.Output.ZipResult; _replaceOriginal = _edit.Output.ReplaceOriginal; + _trashOriginal = _edit.Output.TrashOriginalAfterConvert; _moveInsteadOfCopy = _edit.Output.MoveInsteadOfCopy; } @@ -981,6 +982,8 @@ private void ShowOcrDownloads() [ObservableProperty] private bool _zipResult; /// The result takes the original's place, which goes to the Recycle Bin / Trash (OutputRule.ReplaceOriginal). [ObservableProperty] private bool _replaceOriginal; + /// The original goes to the Recycle Bin / Trash after a conversion to another format (OutputRule.TrashOriginalAfterConvert, #1387). + [ObservableProperty] private bool _trashOriginal; /// Copy to folder: the files are moved instead of copied (OutputRule.MoveInsteadOfCopy, #856). [ObservableProperty, NotifyPropertyChangedFor(nameof(CopyHint), nameof(CopyAction))] private bool _moveInsteadOfCopy; @@ -1550,6 +1553,7 @@ static double Seconds(double value, double fallback, double min, double max) => // Only for geospatial targets, where it is offered: a box ticked for Shapefile must not zip a later PNG. output.ZipResult = ShowZipResult && ZipResult; output.ReplaceOriginal = ShowReplaceOriginal && ReplaceOriginal; + output.TrashOriginalAfterConvert = ShowReplaceOriginal && TrashOriginal; output.MoveInsteadOfCopy = IsCopyToFolder && MoveInsteadOfCopy; return true; } diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml index 2e52942ea..2d9c4fff4 100644 --- a/src/Filee.App/Views/PresetEditorView.axaml +++ b/src/Filee.App/Views/PresetEditorView.axaml @@ -817,6 +817,11 @@ + + + + diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs index 430653089..8eb396eaf 100644 --- a/src/Filee.Cli/Cli.cs +++ b/src/Filee.Cli/Cli.cs @@ -310,6 +310,8 @@ private static void WriteFileFields(Utf8JsonWriter json, FileResult file, ILocal preset = found.Clone(); } preset = host.Store.Settings.WithDefaultOutput(preset); + // The command line never moves an original to the Trash, whatever the saved preset says (#1387). + preset.Output.TrashOriginalAfterConvert = false; if (preset.Translate.Enabled && string.IsNullOrWhiteSpace(preset.Translate.Model)) preset.Translate.Model = host.Store.Settings.PreferredOllamaModel; if (options.Quality is { } quality) diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs index 8a8df69c9..7d0ecf5e1 100644 --- a/src/Filee.Core/Conversion/JobQueue.cs +++ b/src/Filee.Core/Conversion/JobQueue.cs @@ -1008,6 +1008,8 @@ private async Task> RunFileAsync( var mark = finalOutput ? Platform.MarkOfTheWeb.Read(file.SourcePath) : null; if (finalOutput && !zipResult && inputs.Count == 1) inputs = [ReplaceOriginal(job, file, source.Id, inputs[0], copiedSource)]; + if (finalOutput && !zipResult && !copiedSource) + TrashOriginal(job, file, source.Id, inputs); // A name the engine took but wrote nothing to is free again. final?.Release(except: inputs); @@ -1344,6 +1346,39 @@ string Kept(Platform.TrashRefusal why, string result) } } + /// + /// "Move the original to the Recycle Bin / Trash" (, #1387): once + /// every result of is complete and none has the source's format, the source goes to the + /// Trash. A result of the source's own format is "Replace the original"'s, and a result at the source's own path + /// would be moved with it, so either leaves the source alone. When the Trash refuses, the source stays and the + /// file gets a note saying why; nothing is ever deleted for good. + /// + private void TrashOriginal(ConversionJob job, FileResult file, string sourceFormat, IReadOnlyList outputs) + { + var source = file.SourcePath; + if (!job.Preset.Output.TrashOriginalAfterConvert || job.Fetcher is not null || file.OriginalInTrash + || outputs.Count == 0 || !File.Exists(source)) + return; + foreach (var output in outputs) + { + if (string.Equals(Path.GetFullPath(output), Path.GetFullPath(source), Platform.FileSystemPaths.Comparison)) + return; + if (Directory.Exists(output)) + continue; // an output folder (Extract) + if (!File.Exists(output) || FormatRegistry.Detect(output)?.Id == sourceFormat) + return; + } + + var refusal = _moveToTrash is null ? new Platform.TrashRefusal("trash.no_recycle_bin") : _moveToTrash(source); + file.OriginalInTrash = refusal is null; + if (refusal is null) + return; + _log.LogInformation("Kept the original {Source}: {Reason} {Detail}", source, refusal.ReasonKey, refusal.Detail); + file.NoticeKey = "notice.trash_original_kept"; + file.NoticeReasonKey = refusal.ReasonKey; + file.NoticeDetail = refusal.Detail; + } + /// Extensions that only spell the same kind of file differently ("Replace the original" may swap them). private static readonly string[][] Spellings = [ diff --git a/src/Filee.Core/Presets/AskedLocation.cs b/src/Filee.Core/Presets/AskedLocation.cs index 2eb34357b..958883909 100644 --- a/src/Filee.Core/Presets/AskedLocation.cs +++ b/src/Filee.Core/Presets/AskedLocation.cs @@ -75,6 +75,7 @@ private static Preset InFolder(Preset preset, string folder) copy.Output.SubfolderOnlyForSeveralFiles = false; // The place the user picked is where the result goes, not back over the original. copy.Output.ReplaceOriginal = false; + copy.Output.TrashOriginalAfterConvert = false; return copy; } } diff --git a/src/Filee.Core/Presets/OutputRule.cs b/src/Filee.Core/Presets/OutputRule.cs index 1f9040d32..0acc5e8b3 100644 --- a/src/Filee.Core/Presets/OutputRule.cs +++ b/src/Filee.Core/Presets/OutputRule.cs @@ -115,6 +115,15 @@ public sealed class OutputRule /// public bool ReplaceOriginal { get; set; } + /// + /// The original goes to the Recycle Bin / Trash once its result is complete (#1387). Off by default. Where + /// covers a result of the source's own format, this covers one in another format + /// (DOCX → PDF). Never for watch folders, "Ask every time", files from a browser, the command line, merges and + /// packing (a ZIP result, a combined archive), or an "Only if smaller" copy of the source. Only ever moved to the + /// Recycle Bin / Trash, never deleted: when that isn't possible the original stays, with a note saying why. + /// + public bool TrashOriginalAfterConvert { get; set; } + /// /// Copy to folder only (#856): the files are moved into instead of copied, so they are /// gone from where they were. Off by default. An original is removed only once its copy is complete; files from a diff --git a/src/Filee.Core/Watching/WatchRule.cs b/src/Filee.Core/Watching/WatchRule.cs index 9f85821d5..603039012 100644 --- a/src/Filee.Core/Watching/WatchRule.cs +++ b/src/Filee.Core/Watching/WatchRule.cs @@ -71,6 +71,7 @@ public Preset Apply(Preset preset) applied.Output.KeepFoldersFrom = Folder; // A watch folder never replaces what it watches: the result would be converted again. applied.Output.ReplaceOriginal = false; + applied.Output.TrashOriginalAfterConvert = false; if (!string.IsNullOrWhiteSpace(FileNamePattern)) applied.Output.FileNamePattern = FileNamePattern.Trim(); // Steps without a pattern are being typed; leaving them out keeps the name as it is. diff --git a/tests/Filee.Cli.Tests/CliTests.cs b/tests/Filee.Cli.Tests/CliTests.cs index c9b8cf3f4..31f5ea716 100644 --- a/tests/Filee.Cli.Tests/CliTests.cs +++ b/tests/Filee.Cli.Tests/CliTests.cs @@ -918,6 +918,20 @@ private void AddPresets(params Preset[] presets) store.SaveLibrary(); } + [Fact] + public async Task The_command_line_never_moves_an_original_to_the_trash() + { + // A preset saved in the app with "Move the original to the Recycle Bin / Trash" (#1387) runs here without it. + AddPresets(new Preset { Id = "trashing", Name = "Trashing", TargetFormat = "jpg", Output = { TrashOriginalAfterConvert = true } }); + var png = Png("a.png"); + + var (code, _, errors) = await Run("convert", png, "--preset", "trashing"); + + Assert.Equal(Cli.Success, code); + Assert.True(File.Exists(Path.Combine(_folder, "a.jpg")), errors); + Assert.True(File.Exists(png)); + } + [Fact] public async Task A_group_is_never_run_listed_or_in_the_way_of_a_conversion_of_the_same_name() { diff --git a/tests/Filee.Core.Tests/TrashOriginalTests.cs b/tests/Filee.Core.Tests/TrashOriginalTests.cs new file mode 100644 index 000000000..a2b3f88ca --- /dev/null +++ b/tests/Filee.Core.Tests/TrashOriginalTests.cs @@ -0,0 +1,272 @@ +// "Move the original to the Recycle Bin / Trash after converting" (#1387): the original goes once its result in another +// format is complete, or stays, with a note saying why. + +using Filee.Core.Conversion; +using Filee.Core.Platform; +using Filee.Core.Presets; +using Filee.Core.Watching; + +namespace Filee.Core.Tests; + +public class TrashOriginalTests +{ + private static Preset Trashing(string target = "png") => + new() { TargetFormat = target, Output = { TrashOriginalAfterConvert = true } }; + + /// Moves files into a folder, or refuses with . + private sealed class FakeTrash(string folder, TrashRefusal? refuse = null) + { + public List Moved { get; } = []; + + public TrashRefusal? Move(string path) + { + if (refuse is not null) + return refuse; + File.Move(path, Path.Combine(folder, Path.GetFileName(path))); + Moved.Add(path); + return null; + } + } + + private static readonly ConversionEdge[] Edges = + [new ConversionEdge("jpg", "png"), new ConversionEdge("jpg", "jpg"), new ConversionEdge("docx", "pdf")]; + + private static async Task Run(FakeTrash? trash, string source, Preset preset, ISourceFetcher? fetcher = null) + { + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("fake", Edges)]), moveToTrash: trash?.Move); + var job = new ConversionJob([source], preset, "Test", fetcher); + await queue.RunAsync(job); + return job; + } + + [Fact] + public async Task The_original_goes_to_the_trash_after_a_conversion_to_another_format() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("report.docx"); + var trash = new FakeTrash(bin.Path); + + var job = await Run(trash, source, Trashing("pdf")); + + Assert.Equal(JobState.Completed, job.State); + Assert.Equal([source], trash.Moved); + Assert.Equal([Path.Combine(dir.Path, "report.pdf")], job.Outputs); + Assert.True(File.Exists(Path.Combine(dir.Path, "report.pdf"))); + Assert.False(File.Exists(source)); + Assert.True(File.Exists(Path.Combine(bin.Path, "report.docx"))); + Assert.Null(job.Files[0].NoticeKey); + Assert.True(job.Files[0].OriginalInTrash); + } + + [Fact] + public async Task Off_by_default() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("report.docx"); + var trash = new FakeTrash(bin.Path); + + await Run(trash, source, new Preset { TargetFormat = "pdf" }); + + Assert.False(new OutputRule().TrashOriginalAfterConvert); + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + } + + [Fact] + public async Task A_conversion_that_fails_keeps_the_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("report.docx"); + var trash = new FakeTrash(bin.Path); + await using var queue = new JobQueue( + new ConverterCatalog([new FakeConverter("fake", new ConversionEdge("docx", "pdf")) { Throw = true }]), moveToTrash: trash.Move); + var job = new ConversionJob([source], Trashing("pdf"), "Test"); + + await queue.RunAsync(job); + + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + Assert.Equal(FileState.Failed, job.Files[0].State); + } + + [Fact] + public async Task A_cancelled_conversion_keeps_the_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("report.docx"); + var trash = new FakeTrash(bin.Path); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("fake", new ConversionEdge("docx", "pdf"))]), moveToTrash: trash.Move); + var job = new ConversionJob([source], Trashing("pdf"), "Test"); + job.Cancel(); // before it runs, so nothing converts + await queue.RunAsync(job); + + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + } + + [Fact] + public async Task When_the_trash_refuses_the_original_stays_with_the_reason() + { + using var dir = new TempDir(); + var source = dir.File("report.docx"); + + var job = await Run(new FakeTrash(dir.Path, new TrashRefusal("trash.in_use")), source, Trashing("pdf")); + + Assert.Equal(JobState.Completed, job.State); + Assert.True(File.Exists(source)); + Assert.True(File.Exists(Path.Combine(dir.Path, "report.pdf"))); + Assert.Equal("notice.trash_original_kept", job.Files[0].NoticeKey); + Assert.Equal("trash.in_use", job.Files[0].NoticeReasonKey); + Assert.False(job.Files[0].OriginalInTrash); + } + + [Fact] + public async Task Without_a_trash_the_original_stays() + { + using var dir = new TempDir(); + var source = dir.File("report.docx"); + + var job = await Run(null, source, Trashing("pdf")); + + Assert.True(File.Exists(source)); + Assert.Equal("notice.trash_original_kept", job.Files[0].NoticeKey); + Assert.Equal("trash.no_recycle_bin", job.Files[0].NoticeReasonKey); + } + + [Fact] + public async Task Files_from_a_browser_keep_their_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("a.jpg"); + var trash = new FakeTrash(bin.Path); + + await Run(trash, source, Trashing(), new LocalFetcher()); + + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + } + + [Fact] + public async Task A_result_in_the_same_format_is_left_to_replace_the_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("a.jpg"); + var trash = new FakeTrash(bin.Path); + + var job = await Run(trash, source, Trashing("jpg")); + + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + Assert.Equal(2, Directory.GetFiles(dir.Path).Length); // "a.jpg" and the result beside it + Assert.Null(job.Files[0].NoticeKey); + } + + [Fact] + public async Task With_both_options_the_format_decides_which_one_applies() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var trash = new FakeTrash(bin.Path); + var sameFormat = new Preset { TargetFormat = "jpg", Output = { ReplaceOriginal = true, TrashOriginalAfterConvert = true } }; + var otherFormat = new Preset { TargetFormat = "png", Output = { ReplaceOriginal = true, TrashOriginalAfterConvert = true } }; + + // The same format: "Replace the original" does it, the result takes the original's place. + var same = dir.File("a.jpg"); + var replaced = await Run(trash, same, sameFormat); + Assert.Equal([same], trash.Moved); + Assert.Equal([same], replaced.Outputs); + Assert.Equal("a.jpg→jpg by fake", File.ReadAllText(same)); + + // Another format: the new option does it, and the result keeps its own name. + var other = dir.File("b.jpg"); + var converted = await Run(trash, other, otherFormat); + Assert.Equal([same, other], trash.Moved); + Assert.Equal([Path.Combine(dir.Path, "b.png")], converted.Outputs); + Assert.False(File.Exists(other)); + } + + [Fact] + public async Task Only_if_smaller_keeps_the_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("a.jpg"); + var trash = new FakeTrash(bin.Path); + var preset = Trashing("jpg"); + preset.Output.OnlyIfSmaller = true; + + await Run(trash, source, preset); // the fake result is larger than "x", so the source is copied as the result + + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + } + + [Fact] + public async Task A_result_packed_into_a_zip_keeps_the_original() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var source = dir.File("a.jpg"); + var trash = new FakeTrash(bin.Path); + var preset = Trashing(); + preset.Output.ZipResult = true; + + var job = await Run(trash, source, preset); + + Assert.EndsWith(".zip", Assert.Single(job.Outputs)); + Assert.Empty(trash.Moved); + Assert.True(File.Exists(source)); + } + + [Fact] + public async Task Merged_pdfs_keep_their_originals() + { + using var dir = new TempDir(); + using var bin = new TempDir(); + var first = dir.File("1.jpg"); + var second = dir.File("2.jpg"); + var trash = new FakeTrash(bin.Path); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("fake", new ConversionEdge("jpg", "pdf"))]), new FakeMerger(), + moveToTrash: trash.Move); + var preset = new Preset { TargetFormat = "pdf", Pdf = { MergeIntoSingle = true }, Output = { TrashOriginalAfterConvert = true } }; + var job = new ConversionJob([first, second], preset, "Test"); + + await queue.RunAsync(job); + + Assert.Equal(JobState.Completed, job.State); + Assert.Empty(trash.Moved); + Assert.True(File.Exists(first)); + Assert.True(File.Exists(second)); + } + + [Fact] + public void Watch_folders_and_asked_locations_clear_it_and_leave_the_preset_as_it_was() + { + var preset = Trashing(); + + Assert.False(new WatchRule { Folder = "in", OutputFolder = "out" }.Apply(preset).Output.TrashOriginalAfterConvert); + Assert.False(AskedLocation.ForFolder(preset, "somewhere").Output.TrashOriginalAfterConvert); + Assert.False(AskedLocation.ForFile(preset, Path.Combine("somewhere", "a.png")).Output.TrashOriginalAfterConvert); + Assert.True(preset.Output.TrashOriginalAfterConvert); + } + + [Fact] + public void Survives_a_preset_round_trip() + { + Assert.True(Trashing().Clone().Output.TrashOriginalAfterConvert); + } + + /// A browser drop whose files are already on disk. + private sealed class LocalFetcher : ISourceFetcher + { + public bool Fetches(string source) => false; + public Task FetchAsync(string source, IProgress progress, CancellationToken cancellationToken) => Task.FromResult(source); + public void Release(ConversionJob job) { } + } +} From 2d4b2b5a1e1ac5e39712ff5afb9f55e5564109cf Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Sat, 14 Nov 2026 12:17:47 +0530 Subject: [PATCH 20/95] i18n: add strings for moving the original to the Trash after converting Adds presets.trash_original, presets.trash_original_hint and notice.trash_original_kept to all 23 language files. Refs #1387 --- src/Filee.App/Assets/i18n/ar.json | 3 +++ src/Filee.App/Assets/i18n/bn-BD.json | 3 +++ src/Filee.App/Assets/i18n/de.json | 3 +++ src/Filee.App/Assets/i18n/en.json | 3 +++ src/Filee.App/Assets/i18n/es.json | 3 +++ src/Filee.App/Assets/i18n/fa.json | 3 +++ src/Filee.App/Assets/i18n/fr.json | 3 +++ src/Filee.App/Assets/i18n/hi.json | 3 +++ src/Filee.App/Assets/i18n/id.json | 3 +++ src/Filee.App/Assets/i18n/it.json | 3 +++ src/Filee.App/Assets/i18n/ja.json | 3 +++ src/Filee.App/Assets/i18n/ko.json | 3 +++ src/Filee.App/Assets/i18n/mn.json | 3 +++ src/Filee.App/Assets/i18n/ne.json | 3 +++ src/Filee.App/Assets/i18n/pl.json | 3 +++ src/Filee.App/Assets/i18n/pt-BR.json | 3 +++ src/Filee.App/Assets/i18n/pt-PT.json | 3 +++ src/Filee.App/Assets/i18n/ru.json | 3 +++ src/Filee.App/Assets/i18n/th.json | 3 +++ src/Filee.App/Assets/i18n/tr.json | 3 +++ src/Filee.App/Assets/i18n/vi.json | 3 +++ src/Filee.App/Assets/i18n/zh-CN.json | 3 +++ src/Filee.App/Assets/i18n/zh-TW.json | 3 +++ 23 files changed, 69 insertions(+) diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 5df39016d..d2a4140de 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "هذا الملف بنظام CMYK، لكن Ghostscript لم يتمكن من رسمه، لذلك حُفظ بنظام RGB", "notice.original_kept": "تم الاحتفاظ بالأصل وحُفظت النتيجة كنسخة", "notice.original_in_trash": "الأصل في سلة المحذوفات، واحتفظت النتيجة باسمها", + "notice.trash_original_kept": "تم الاحتفاظ بالأصل لأنه تعذّر نقله إلى سلة المحذوفات", "notice.original_unchanged": "تعذّر تصغيره، لذا تُرك الأصل كما هو", "notice.move_original_kept": "تم النسخ، لكن تعذّر حذف الأصل", "trash.no_recycle_bin": "لا توجد سلة محذوفات على هذا القرص", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "تُجمَّع ملفات النتيجة (مثل ‎.shp و‎.shx و‎.dbf و‎.prj و‎.cpg في Shapefile) في ZIP واحد بجانب الأصل، بدلًا من ملفات منفصلة.", "presets.replace_original": "استبدال الأصل", "presets.replace_original_hint": "تأخذ النتيجة اسم الأصل ومكانه، وينتقل الأصل إلى سلة المحذوفات. فقط عندما يكون للنتيجة التنسيق نفسه، ولا يحدث أبدًا لمجلدات المراقبة أو الملفات القادمة من متصفح. إذا تعذّر نقل الأصل، يبقى في مكانه وتُحفظ النتيجة كنسخة. تُحفظ النتيجة في مجلد الأصل أيًّا كان إعداد «الحفظ في».", + "presets.trash_original": "نقل الأصل إلى سلة المحذوفات بعد التحويل", + "presets.trash_original_hint": "بعد اكتمال النتيجة ينتقل الأصل إلى سلة المحذوفات ويمكنك استعادته منها. فقط عندما يكون للنتيجة تنسيق مختلف (خيار «استبدال الأصل» للتنسيق نفسه). ولا يحدث أبدًا لمجلدات المراقبة أو الملفات القادمة من متصفح أو سطر الأوامر أو الدمج أو نتائج ZIP. إذا تعذّر نقل الأصل يبقى في مكانه.", "presets.conflict": "إذا كان الملف موجودًا", "presets.conflict.Rename": "إضافة رقم", "presets.conflict.Overwrite": "استبداله", diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index d99bc260f..e3561f365 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -210,6 +210,7 @@ "notice.cmyk_render_failed": "এই ফাইলটি CMYK, কিন্তু Ghostscript এটি আঁকতে পারেনি, তাই RGB হিসেবে সংরক্ষণ করা হয়েছে", "notice.original_kept": "মূল ফাইলটি রাখা হয়েছে, ফলাফলটি একটি কপি হিসেবে সংরক্ষণ করা হয়েছে", "notice.original_in_trash": "মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে রয়েছে, ফলাফলটি নিজস্ব নাম বজায় রেখেছে", + "notice.trash_original_kept": "মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে সরানো যায়নি, তাই রাখা হয়েছে", "notice.original_unchanged": "আরও ছোট করা যায়নি, তাই মূল ফাইলটি অপরিবর্তিত রাখা হয়েছে", "notice.move_original_kept": "কপি করা হয়েছে, তবে মূল ফাইলটি অপসারণ করা যায়নি", "trash.no_recycle_bin": "এই ড্রাইভে কোনো রিসাইকেল বিন / ট্র্যাশ নেই", @@ -1185,6 +1186,8 @@ "presets.zip_result_hint": "ফলাফলের ফাইলগুলো (Shapefile-এর .shp, .shx, .dbf, .prj এবং .cpg) আলাদা ফাইলের বদলে উৎসের পাশে একটি ZIP-এ প্যাক করা হয়।", "presets.replace_original": "মূল ফাইলটি প্রতিস্থাপন করুন", "presets.replace_original_hint": "ফলাফল মূল ফাইলের নাম ও স্থান নেয় এবং মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে চলে যায়। কেবল ফলাফলের একই ফরম্যাট থাকলে এটি প্রযোজ্য, ওয়াচ ফোল্ডার বা ব্রাউজার থেকে নেওয়া ফাইলের ক্ষেত্রে কখনো নয়। মূল ফাইলটি ট্র্যাশে পাঠানো না গেলে সেটি থেকে যায় এবং ফলাফল কপি হিসেবে সংরক্ষণ করা হয়। \"সংরক্ষণের অবস্থান\" যাই হোক না কেন, ফলাফলটি মূল ফাইলের ফোল্ডারেই সংরক্ষিত হয়।", + "presets.trash_original": "রূপান্তরের পর মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে সরান", + "presets.trash_original_hint": "ফলাফল সম্পূর্ণ হলে মূল ফাইলটি রিসাইকেল বিন / ট্র্যাশে চলে যায়, সেখান থেকে ফিরিয়ে আনা যায়। কেবল ফলাফলের ফরম্যাট আলাদা হলে প্রযোজ্য (একই ফরম্যাটের জন্য আছে \"মূল ফাইলটি প্রতিস্থাপন করুন\")। ওয়াচ ফোল্ডার, ব্রাউজার থেকে নেওয়া ফাইল, কমান্ড লাইন, মার্জ বা ZIP ফলাফলের ক্ষেত্রে কখনো নয়। মূল ফাইলটি সেখানে যেতে না পারলে সেটি থেকে যায়।", "presets.conflict": "ফাইলটি ইতিমধ্যে বিদ্যমান থাকলে", "presets.conflict.Rename": "একটি সংখ্যা যোগ করুন", "presets.conflict.Overwrite": "প্রতিস্থাপন করুন", diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index ab9cf21bf..74dc65e6f 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "Diese Datei ist CMYK, aber Ghostscript konnte sie nicht zeichnen, daher wurde sie als RGB gespeichert", "notice.original_kept": "Das Original wurde beibehalten und das Ergebnis als Kopie gespeichert", "notice.original_in_trash": "Das Original liegt im Papierkorb. Das Ergebnis hat seinen eigenen Namen behalten", + "notice.trash_original_kept": "Das Original wurde beibehalten, weil es sich nicht in den Papierkorb verschieben ließ", "notice.original_unchanged": "Die Datei ließ sich nicht verkleinern. Das Original blieb unverändert", "notice.move_original_kept": "Kopiert, aber das Original konnte nicht entfernt werden", "trash.no_recycle_bin": "dieses Laufwerk hat keinen Papierkorb", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "Die Ergebnisdateien (bei Shapefiles .shp, .shx, .dbf, .prj und .cpg) werden gemeinsam in einer ZIP neben der Quelldatei gespeichert statt als einzelne Dateien.", "presets.replace_original": "Original ersetzen", "presets.replace_original_hint": "Das Ergebnis übernimmt Namen und Speicherort des Originals. Das Original wird in den Papierkorb verschoben. Gilt nur bei gleichem Format, nie für überwachte Ordner oder Dateien aus dem Browser. Lässt sich das Original nicht in den Papierkorb verschieben, bleibt es erhalten und das Ergebnis wird als Kopie gespeichert. Das Ergebnis wird unabhängig von „Speichern in“ im Ordner des Originals gespeichert.", + "presets.trash_original": "Original nach dem Umwandeln in den Papierkorb verschieben", + "presets.trash_original_hint": "Sobald das Ergebnis fertig ist, wird das Original in den Papierkorb verschoben und kann dort wiederhergestellt werden. Gilt nur bei einem anderen Format („Original ersetzen“ gilt für das gleiche Format), nie für überwachte Ordner, Dateien aus dem Browser, die Befehlszeile, Zusammenführungen oder ZIP-Ergebnisse. Lässt sich das Original nicht verschieben, bleibt es erhalten.", "presets.conflict": "Wenn die Datei bereits existiert", "presets.conflict.Rename": "Nummer anhängen", "presets.conflict.Overwrite": "Ersetzen", diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index b9eebb3f2..f38f564bf 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "This file is CMYK, but Ghostscript couldn't draw it, so it was saved as RGB", "notice.original_kept": "The original was kept, the result was saved as a copy", "notice.original_in_trash": "The original is in the Recycle Bin / Trash, the result kept its own name", + "notice.trash_original_kept": "The original was kept, it couldn't be moved to the Recycle Bin / Trash", "notice.original_unchanged": "Couldn't make it smaller, so the original was left as it is", "notice.move_original_kept": "Copied, but the original couldn't be removed", "trash.no_recycle_bin": "this drive has no Recycle Bin / Trash", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "The files of the result (a Shapefile's .shp, .shx, .dbf, .prj and .cpg) are packed into one ZIP next to the source, in place of loose files.", "presets.replace_original": "Replace the original", "presets.replace_original_hint": "The result takes the original's name and place, and the original goes to the Recycle Bin / Trash. Only when the result has the same format, never for watch folders or files from a browser. When the original can't go there, it stays and the result is saved as a copy. The result is saved in the original's folder, whatever \"Save to\" says.", + "presets.trash_original": "Move the original to the Recycle Bin / Trash after converting", + "presets.trash_original_hint": "Once the result is complete, the original goes to the Recycle Bin / Trash, where you can restore it. Only when the result has a different format (\"Replace the original\" is for the same format). Never for watch folders, files from a browser, the command line, merges or ZIP results. When the original can't go there, it stays.", "presets.conflict": "If the file exists", "presets.conflict.Rename": "Add a number", "presets.conflict.Overwrite": "Replace it", diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index f496216e4..c4e5b9335 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "Este archivo es CMYK, pero Ghostscript no pudo dibujarlo, así que se guardó en RGB", "notice.original_kept": "Se conservó el original, el resultado se guardó como copia", "notice.original_in_trash": "El original está en la Papelera, el resultado conservó su propio nombre", + "notice.trash_original_kept": "Se conservó el original porque no se pudo mover a la Papelera de reciclaje", "notice.original_unchanged": "No se pudo hacer más pequeño, así que el original se dejó como estaba", "notice.move_original_kept": "Copiado, pero no se pudo quitar el original", "trash.no_recycle_bin": "esta unidad no tiene Papelera de reciclaje", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "Los archivos del resultado (.shp, .shx, .dbf, .prj y .cpg de un Shapefile) se empaquetan en un solo ZIP junto al origen, en lugar de archivos sueltos.", "presets.replace_original": "Reemplazar el original", "presets.replace_original_hint": "El resultado toma el nombre y el lugar del original, y el original va a la Papelera de reciclaje. Solo cuando el resultado tiene el mismo formato, nunca en carpetas vigiladas ni con archivos de un navegador. Si el original no puede ir a la Papelera, se queda y el resultado se guarda como copia. El resultado se guarda en la carpeta del original, diga lo que diga «Guardar en».", + "presets.trash_original": "Mover el original a la Papelera de reciclaje tras convertir", + "presets.trash_original_hint": "Cuando el resultado está completo, el original va a la Papelera de reciclaje, donde puedes restaurarlo. Solo cuando el resultado tiene otro formato («Reemplazar el original» es para el mismo formato). Nunca en carpetas vigiladas, con archivos de un navegador, en la línea de comandos, en uniones ni con resultados ZIP. Si el original no puede ir a la Papelera, se queda donde está.", "presets.conflict": "Si el archivo existe", "presets.conflict.Rename": "Añadir un número", "presets.conflict.Overwrite": "Reemplazarlo", diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index ddf929c3d..1f7b3c0ae 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -210,6 +210,7 @@ "notice.cmyk_render_failed": "این فایل CMYK است، اما Ghostscript نتوانست آن را رسم کند، بنابراین به صورت RGB ذخیره شد", "notice.original_kept": "فایل اصلی حفظ شد و نتیجه به عنوان نسخه کپی ذخیره گردید", "notice.original_in_trash": "فایل اصلی در سطل زباله است، نتیجه نام خود را حفظ کرد", + "notice.trash_original_kept": "فایل اصلی حفظ شد، چون انتقال آن به سطل زباله ممکن نبود", "notice.original_unchanged": "امکان کوچک‌تر کردن فایل نبود، بنابراین فایل اصلی بدون تغییر باقی ماند", "notice.move_original_kept": "کپی شد، اما فایل اصلی حذف نشد", "trash.no_recycle_bin": "این درایو سطل زباله ندارد", @@ -1185,6 +1186,8 @@ "presets.zip_result_hint": "فایل‌های نتیجه (مانند .shp، .shx، .dbf، .prj و .cpg یک فایل Shapefile) به جای فایل‌های جداگانه، درون یک فایل ZIP در کنار فایل اصلی بسته‌بندی می‌شوند.", "presets.replace_original": "جایگزینی فایل اصلی", "presets.replace_original_hint": "فایل نتیجه نام و جایگاه فایل اصلی را می‌گیرد و فایل اصلی به سطل زباله منتقل می‌شود. فقط زمانی که نتیجه همان فرمت را داشته باشد اعمال می‌گردد، و هرگز برای پوشه‌های تحت‌نظر یا فایل‌های دریافتی از مرورگر استفاده نمی‌شود. اگر امکان انتقال فایل اصلی به سطل زباله نباشد، فایل اصلی باقی مانده و نتیجه به عنوان یک نسخه کپی ذخیره می‌شود. صرف‌نظر از اینکه «ذخیره در» چه باشد، نتیجه در پوشه فایل اصلی ذخیره می‌گردد.", + "presets.trash_original": "انتقال فایل اصلی به سطل زباله پس از تبدیل", + "presets.trash_original_hint": "پس از کامل شدن نتیجه، فایل اصلی به سطل زباله منتقل می‌شود و می‌توانید آن را بازیابی کنید. فقط زمانی که نتیجه فرمت متفاوتی داشته باشد (گزینه «جایگزینی فایل اصلی» برای همان فرمت است). هرگز برای پوشه‌های تحت‌نظر، فایل‌های دریافتی از مرورگر، خط فرمان، ادغام‌ها یا نتیجه‌های ZIP اعمال نمی‌شود. اگر انتقال فایل اصلی ممکن نباشد، همان‌جا باقی می‌ماند.", "presets.conflict": "در صورت وجود فایل هم‌نام", "presets.conflict.Rename": "افزودن شماره به انتهای نام", "presets.conflict.Overwrite": "جایگزین کردن فایل موجود", diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index b08536140..c1132740c 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Ce fichier est en CMJN, mais Ghostscript n'a pas pu le dessiner : il a été enregistré en RVB", "notice.original_kept": "L'original a été conservé, le résultat a été enregistré en copie", "notice.original_in_trash": "L'original est dans la Corbeille, le résultat a gardé son propre nom", + "notice.trash_original_kept": "L'original a été conservé, car il n'a pas pu être mis à la Corbeille", "notice.original_unchanged": "Impossible de le rendre plus petit : l'original a été laissé tel quel", "notice.move_original_kept": "Copié, mais l’original n’a pas pu être supprimé", "trash.no_recycle_bin": "ce lecteur n'a pas de Corbeille", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Les fichiers du résultat (les .shp, .shx, .dbf, .prj et .cpg d'un Shapefile) sont regroupés dans un seul ZIP à côté de l'original, au lieu de fichiers séparés.", "presets.replace_original": "Remplacer l'original", "presets.replace_original_hint": "Le résultat prend le nom et la place de l'original, et l'original va dans la Corbeille. Seulement quand le résultat a le même format, jamais pour les dossiers surveillés ni les fichiers venant d'un navigateur. Si l'original ne peut pas aller dans la Corbeille, il reste et le résultat est enregistré en copie. Le résultat est enregistré dans le dossier de l'original, quel que soit « Enregistrer dans ».", + "presets.trash_original": "Mettre l'original à la Corbeille après la conversion", + "presets.trash_original_hint": "Quand le résultat est terminé, l'original va dans la Corbeille, d'où vous pouvez le restaurer. Seulement quand le résultat a un autre format (« Remplacer l'original » sert pour le même format). Jamais pour les dossiers surveillés, les fichiers venant d'un navigateur, la ligne de commande, les fusions ni les résultats ZIP. Si l'original ne peut pas aller dans la Corbeille, il reste.", "presets.conflict": "Si le fichier existe", "presets.conflict.Rename": "Ajouter un numéro", "presets.conflict.Overwrite": "Le remplacer", diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 4a38f4f8c..9cee8d911 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "यह फ़ाइल CMYK है, लेकिन Ghostscript इसे नहीं बना सका, इसलिए यह RGB में सेव हुई", "notice.original_kept": "मूल फ़ाइल रखी गई, परिणाम कॉपी के रूप में सहेजा गया", "notice.original_in_trash": "मूल फ़ाइल रीसायकल बिन / ट्रैश में है, परिणाम ने अपना नाम रखा", + "notice.trash_original_kept": "मूल फ़ाइल रखी गई, उसे रीसायकल बिन / ट्रैश में नहीं भेजा जा सका", "notice.original_unchanged": "इसे छोटा नहीं किया जा सका, इसलिए मूल फ़ाइल जैसी थी वैसी छोड़ दी गई", "notice.move_original_kept": "कॉपी हो गया, लेकिन मूल फ़ाइल हटाई नहीं जा सकी", "trash.no_recycle_bin": "इस ड्राइव में रीसायकल बिन / ट्रैश नहीं है", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "नतीजे की फ़ाइलें (Shapefile की .shp, .shx, .dbf, .prj और .cpg) अलग-अलग रखने के बजाय स्रोत के बगल में एक ZIP में पैक की जाती हैं।", "presets.replace_original": "मूल फ़ाइल बदलें", "presets.replace_original_hint": "परिणाम मूल फ़ाइल का नाम और जगह ले लेता है, और मूल फ़ाइल रीसायकल बिन / ट्रैश में चली जाती है। केवल तब जब परिणाम का फ़ॉर्मैट वही हो, वॉच फ़ोल्डर या ब्राउज़र से आई फ़ाइलों के लिए कभी नहीं। अगर मूल फ़ाइल वहाँ नहीं जा सकती, तो वह रहती है और परिणाम एक कॉपी के रूप में सहेजा जाता है। परिणाम मूल फ़ाइल के फ़ोल्डर में सेव होता है, \"यहाँ सेव करें\" में चाहे जो हो।", + "presets.trash_original": "बदलने के बाद मूल फ़ाइल को रीसायकल बिन / ट्रैश में भेजें", + "presets.trash_original_hint": "परिणाम पूरा होने पर मूल फ़ाइल रीसायकल बिन / ट्रैश में चली जाती है, जहाँ से उसे वापस लाया जा सकता है। केवल तब जब परिणाम का फ़ॉर्मैट अलग हो (\"मूल फ़ाइल बदलें\" उसी फ़ॉर्मैट के लिए है)। वॉच फ़ोल्डर, ब्राउज़र से आई फ़ाइलों, कमांड लाइन, मर्ज या ZIP परिणामों के लिए कभी नहीं। अगर मूल फ़ाइल वहाँ नहीं जा सकती, तो वह रहती है।", "presets.conflict": "अगर फ़ाइल पहले से मौजूद हो", "presets.conflict.Rename": "नंबर जोड़ें", "presets.conflict.Overwrite": "बदल दें", diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index 96d8c0066..f83b1e46e 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "File ini CMYK, tetapi Ghostscript tidak bisa menggambarnya, jadi disimpan sebagai RGB", "notice.original_kept": "File asli dipertahankan, hasil konversi disimpan sebagai salinan", "notice.original_in_trash": "File asli ada di Tong Sampah, hasil konversi mempertahankan namanya sendiri", + "notice.trash_original_kept": "File asli dipertahankan karena tidak dapat dipindahkan ke Tong Sampah", "notice.original_unchanged": "Ukuran tidak dapat diperkecil lagi, sehingga file asli dibiarkan apa adanya", "notice.move_original_kept": "Tersalin, tetapi file asli tidak dapat dihapus", "trash.no_recycle_bin": "drive ini tidak memiliki Tong Sampah", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "File keluaran (seperti file .shp, .shx, .dbf, .prj, dan .cpg milik Shapefile) dikemas menjadi satu file ZIP di samping file sumber, menggantikan file-file yang terpisah.", "presets.replace_original": "Gantikan file asli", "presets.replace_original_hint": "Hasil konversi mengambil nama dan tempat file asli, lalu file asli dipindahkan ke Tong Sampah. Hanya berlaku bila hasilnya berformat sama, tidak pernah untuk folder pantau atau file dari peramban. Jika file asli tidak dapat dipindahkan, file asli dipertahankan dan hasilnya disimpan sebagai salinan. Hasil konversi selalu disimpan di folder file asli, apa pun isi setelan \"Simpan ke\".", + "presets.trash_original": "Pindahkan file asli ke Tong Sampah setelah konversi", + "presets.trash_original_hint": "Setelah hasil konversi selesai, file asli dipindahkan ke Tong Sampah dan bisa dipulihkan dari sana. Hanya berlaku bila hasilnya berformat lain (\"Gantikan file asli\" untuk format yang sama). Tidak pernah untuk folder pantau, file dari peramban, baris perintah, penggabungan, atau hasil ZIP. Jika file asli tidak dapat dipindahkan, file asli dipertahankan.", "presets.conflict": "Jika file tujuan sudah ada", "presets.conflict.Rename": "Tambahkan nomor", "presets.conflict.Overwrite": "Timpa file", diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index c3c54a568..601edf823 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -195,6 +195,7 @@ "notice.cmyk_render_failed": "Questo file è CMYK, ma Ghostscript non è riuscito a disegnarlo, quindi è stato salvato in RGB", "notice.original_kept": "L'originale è stato conservato, il risultato è stato salvato come copia", "notice.original_in_trash": "L'originale è nel Cestino, il risultato ha mantenuto il proprio nome", +"notice.trash_original_kept": "L'originale è stato conservato perché non è stato possibile spostarlo nel Cestino", "notice.original_unchanged": "Impossibile ridurlo, quindi l'originale è stato lasciato com'è", "notice.move_original_kept": "Copiato, ma non è stato possibile rimuovere l’originale", "trash.no_recycle_bin": "questa unità non ha un Cestino", @@ -1185,6 +1186,8 @@ "presets.zip_result_hint": "I file del risultato (i .shp, .shx, .dbf, .prj e .cpg di uno Shapefile) vengono raccolti in un unico ZIP accanto all'origine, al posto dei file sciolti.", "presets.replace_original": "Sostituisci l'originale", "presets.replace_original_hint": "Il risultato prende il nome e il posto dell'originale, e l'originale va nel Cestino. Solo quando il risultato ha lo stesso formato, mai per le cartelle monitorate o i file da un browser. Quando l'originale non può andarci, resta dov'è e il risultato viene salvato come copia. Il risultato viene salvato nella cartella dell'originale, qualunque cosa dica “Salva in”.", +"presets.trash_original": "Sposta l'originale nel Cestino dopo la conversione", +"presets.trash_original_hint": "Quando il risultato è completo, l'originale va nel Cestino, da dove puoi ripristinarlo. Solo quando il risultato ha un formato diverso («Sostituisci l'originale» vale per lo stesso formato). Mai per le cartelle monitorate, i file da un browser, la riga di comando, le unioni o i risultati ZIP. Quando l'originale non può andare nel Cestino, resta dov'è.", "presets.conflict": "Se il file esiste", "presets.conflict.Rename": "Aggiungi un numero", "presets.conflict.Overwrite": "Sostituiscilo", diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index b4dfcfc96..18f8f1090 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "CMYK のファイルですが、Ghostscript で描画できなかったため RGB で保存しました", "notice.original_kept": "元のファイルを残し、結果をコピーとして保存しました", "notice.original_in_trash": "元のファイルはごみ箱にあります。結果は別の名前のままです", + "notice.trash_original_kept": "元のファイルをごみ箱に移動できなかったため、残しました", "notice.original_unchanged": "小さくできなかったため、元のファイルはそのままにしました", "notice.move_original_kept": "コピーしましたが、元のファイルを削除できませんでした", "trash.no_recycle_bin": "このドライブにはごみ箱がありません", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "変換結果のファイル(Shapefileの.shp、.shx、.dbf、.prj、.cpg)を、ばらばらに置く代わりに元ファイルの隣の1つのZIPにまとめます。", "presets.replace_original": "元のファイルを置き換える", "presets.replace_original_hint": "変換結果が元のファイルの名前と場所を引き継ぎ、元のファイルはごみ箱に移動します。結果が同じ形式のときだけで、監視フォルダーやブラウザーからのファイルには使われません。元のファイルをごみ箱に移動できないときは残し、結果はコピーとして保存します。 結果は「保存先」の設定にかかわらず、元のファイルのフォルダーに保存されます。", + "presets.trash_original": "変換後に元のファイルをごみ箱に移動する", + "presets.trash_original_hint": "変換結果が完成すると、元のファイルをごみ箱に移動します。ごみ箱から元に戻せます。結果が別の形式のときだけで(同じ形式の場合は「元のファイルを置き換える」を使います)、監視フォルダー、ブラウザーからのファイル、コマンドライン、結合、ZIP の結果には使われません。元のファイルをごみ箱に移動できないときは残します。", "presets.conflict": "同名ファイルがある場合", "presets.conflict.Rename": "連番を付ける", "presets.conflict.Overwrite": "上書き", diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index c1fb69441..5307a8df5 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "CMYK 파일인데 Ghostscript가 그리지 못해서 RGB로 저장했어요", "notice.original_kept": "원본은 그대로 두고 결과를 사본으로 저장했어요", "notice.original_in_trash": "원본은 휴지통으로 옮겼고, 결과는 저장된 이름 그대로예요", + "notice.trash_original_kept": "원본을 휴지통으로 옮길 수 없어서 그대로 두었어요", "notice.original_unchanged": "더 작게 만들지 못해서 원본을 그대로 두었어요", "notice.move_original_kept": "복사했지만 원본을 지우지 못했어요", "trash.no_recycle_bin": "이 드라이브에는 휴지통이 없어요", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "결과 파일들(Shapefile의 .shp, .shx, .dbf, .prj, .cpg)을 낱개로 두지 않고 원본 옆에 ZIP 하나로 묶어요.", "presets.replace_original": "원본 바꾸기", "presets.replace_original_hint": "결과가 원본의 이름과 자리를 이어받고, 원본은 휴지통으로 옮겨요. 결과가 같은 형식일 때만 바꾸고, 감시 폴더나 브라우저에서 가져온 파일은 바꾸지 않아요. 원본을 휴지통으로 옮길 수 없으면 원본은 그대로 두고 결과를 사본으로 저장해요. 결과는 '저장 위치'와 상관없이 원본 폴더에 저장돼요.", + "presets.trash_original": "변환 후 원본을 휴지통으로 옮기기", + "presets.trash_original_hint": "결과가 완성되면 원본을 휴지통으로 옮겨요. 휴지통에서 복원할 수 있어요. 결과가 다른 형식일 때만 옮기고(같은 형식은 '원본 바꾸기'가 맡아요), 감시 폴더, 브라우저에서 가져온 파일, 명령줄, 병합, ZIP 결과에는 쓰지 않아요. 원본을 휴지통으로 옮길 수 없으면 그대로 둬요.", "presets.conflict": "같은 파일이 있으면", "presets.conflict.Rename": "번호 붙이기", "presets.conflict.Overwrite": "덮어쓰기", diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index fa528de85..d5abe2197 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -190,6 +190,7 @@ "notice.cmyk_render_failed": "Энэ файл CMYK боловч Ghostscript зурж чадсангүй тул RGB хэлбэрээр хадгаллаа", "notice.original_kept": "Эх файлыг хэвээр үлдээж, үр дүнг хуулбар болгон хадгаллаа", "notice.original_in_trash": "Эх файл Хогийн саванд орж, үр дүнгийн файл нэрийг нь авлаа", + "notice.trash_original_kept": "Эх файлыг Хогийн сав руу зөөж чадаагүй тул хэвээр үлдээлээ", "notice.original_unchanged": "Жижигрүүлж чадсангүй тул эх файлыг хэвээр үлдээлээ", "notice.move_original_kept": "Хуулагдсан боловч эх файлыг устгаж чадсангүй", "trash.no_recycle_bin": "энэ дискэнд Хогийн сав байхгүй", @@ -1173,6 +1174,8 @@ "presets.zip_result_hint": "Үр дүнгийн файлууд (Shapefile-ийн .shp, .shx, .dbf, .prj болон .cpg) задгай файлуудын оронд эх файлын хажууд нэг ZIP болж багцлагдана.", "presets.replace_original": "Эх файлыг орлуулах", "presets.replace_original_hint": "Үр дүнгийн файл эх файлын нэр болон байршлыг авч, эх файл Хогийн сав руу орно. Зөвхөн үр дүн нь ижил форматтай үед ажиллах ба хянах хавтас эсвэл хөтчөөс чирсэн файлд хэзээ ч ажиллахгүй. Эх файл Хогийн сав руу орох боломжгүй үед хэвээр үлдэж үр дүнг хуулбар болгон хадгална. \"Хадгалах газар\" дээр юу гэж зааснаас үл хамааран эх файлын хавтаст хадгалагдана.", + "presets.trash_original": "Хөрвүүлсний дараа эх файлыг Хогийн сав руу зөөх", + "presets.trash_original_hint": "Үр дүн бүрэн болмогц эх файл Хогийн сав руу орох ба тэндээс сэргээж болно. Зөвхөн үр дүн нь өөр форматтай үед ажиллана (ижил формат бол \"Эх файлыг орлуулах\"). Хянах хавтас, хөтчөөс чирсэн файл, тушаалын мөр, нэгтгэл, ZIP үр дүнд хэзээ ч ажиллахгүй. Эх файл Хогийн сав руу орох боломжгүй үед хэвээр үлдэнэ.", "presets.conflict": "Хэрэв файл аль хэдийн байвал", "presets.conflict.Rename": "Дугаар нэмэх", "presets.conflict.Overwrite": "Дарж бичих", diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index 1037c1caf..a10736626 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "यो फाइल CMYK हो, तर Ghostscript ले यसलाई कोर्न सकेन, त्यसैले RGB मा सेभ भयो", "notice.original_kept": "मूल फाइल राखियो, नतिजा प्रतिलिपिको रूपमा सुरक्षित भयो", "notice.original_in_trash": "मूल फाइल रिसाइकल बिन / ट्र्यासमा छ, नतिजाले आफ्नै नाम राख्यो", + "notice.trash_original_kept": "मूल फाइललाई रिसाइकल बिन / ट्र्यासमा सार्न सकिएन, त्यसैले राखियो", "notice.original_unchanged": "यसलाई सानो बनाउन सकिएन, त्यसैले मूल फाइल जस्ताको तस्तै छोडियो", "notice.move_original_kept": "प्रतिलिपि भयो, तर मूल फाइल हटाउन सकिएन", "trash.no_recycle_bin": "यो ड्राइभमा रिसाइकल बिन / ट्र्यास छैन", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "परिणामका फाइलहरू (Shapefile को .shp, .shx, .dbf, .prj र .cpg) छुट्टाछुट्टै राख्नुको सट्टा स्रोतको छेउमा एउटै ZIP मा प्याक गरिन्छ।", "presets.replace_original": "मूल फाइल बदल्नुहोस्", "presets.replace_original_hint": "नतिजाले मूल फाइलको नाम र ठाउँ लिन्छ, र मूल फाइल रिसाइकल बिन / ट्र्यासमा जान्छ। नतिजाको ढाँचा उही हुँदा मात्र, वाच फोल्डर वा ब्राउजरबाट आएका फाइलका लागि कहिल्यै होइन। मूल फाइल त्यहाँ जान नसके, त्यो रहन्छ र नतिजा प्रतिलिपिको रूपमा सुरक्षित हुन्छ। \"यहाँ सेभ गर्नुहोस्\" मा जे भए पनि नतिजा मूल फाइलको फोल्डरमा सेभ हुन्छ।", + "presets.trash_original": "रूपान्तरण पछि मूल फाइललाई रिसाइकल बिन / ट्र्यासमा सार्नुहोस्", + "presets.trash_original_hint": "नतिजा पूरा भएपछि मूल फाइल रिसाइकल बिन / ट्र्यासमा जान्छ, जहाँबाट फिर्ता ल्याउन सकिन्छ। नतिजाको ढाँचा फरक हुँदा मात्र (उही ढाँचाका लागि \"मूल फाइल बदल्नुहोस्\" छ)। वाच फोल्डर, ब्राउजरबाट आएका फाइल, कमान्ड लाइन, मर्ज वा ZIP नतिजाका लागि कहिल्यै होइन। मूल फाइल त्यहाँ जान नसके, त्यो रहन्छ।", "presets.conflict": "यदि फाइल पहिले नै अवस्थित छ भने", "presets.conflict.Rename": "नम्बर थप्नुहोस्", "presets.conflict.Overwrite": "बदल्नुहोस् (अधिलेखन)", diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index bb64aceae..44c25371b 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Ten plik jest w CMYK, ale Ghostscript nie mógł go narysować, więc zapisano go w RGB", "notice.original_kept": "Oryginał został zachowany, wynik zapisano jako kopię", "notice.original_in_trash": "Oryginał jest w Koszu, wynik zachował własną nazwę", + "notice.trash_original_kept": "Oryginał został zachowany, bo nie udało się przenieść go do Kosza", "notice.original_unchanged": "Nie udało się go zmniejszyć, więc oryginał pozostał bez zmian", "notice.move_original_kept": "Skopiowano, ale nie udało się usunąć oryginału", "trash.no_recycle_bin": "ten dysk nie ma Kosza", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Pliki wyniku (.shp, .shx, .dbf, .prj i .cpg Shapefile) są pakowane do jednego ZIP obok źródła zamiast luźnych plików.", "presets.replace_original": "Zastąp oryginał", "presets.replace_original_hint": "Wynik przejmuje nazwę i miejsce oryginału, a oryginał trafia do Kosza. Tylko gdy wynik ma ten sam format, nigdy dla obserwowanych folderów ani plików z przeglądarki. Jeśli oryginał nie może trafić do Kosza, zostaje, a wynik jest zapisywany jako kopia. Wynik jest zapisywany w folderze oryginału, niezależnie od ustawienia „Zapisz w”.", + "presets.trash_original": "Przenieś oryginał do Kosza po konwersji", + "presets.trash_original_hint": "Gdy wynik jest gotowy, oryginał trafia do Kosza, skąd można go przywrócić. Tylko gdy wynik ma inny format („Zastąp oryginał” dotyczy tego samego formatu). Nigdy dla obserwowanych folderów, plików z przeglądarki, wiersza poleceń, scalania ani wyników ZIP. Jeśli oryginał nie może trafić do Kosza, zostaje.", "presets.conflict": "Jeśli plik istnieje", "presets.conflict.Rename": "Dodaj numer", "presets.conflict.Overwrite": "Zastąp", diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index cbec29537..3dc2db3f5 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Este arquivo é CMYK, mas o Ghostscript não conseguiu desenhá-lo, então foi salvo em RGB", "notice.original_kept": "O original foi mantido, o resultado foi salvo como cópia", "notice.original_in_trash": "O original está na Lixeira, o resultado manteve o próprio nome", + "notice.trash_original_kept": "O original foi mantido porque não foi possível movê-lo para a Lixeira", "notice.original_unchanged": "Não foi possível deixá-lo menor, então o original ficou como estava", "notice.move_original_kept": "Copiado, mas não foi possível remover o original", "trash.no_recycle_bin": "esta unidade não tem Lixeira", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Os arquivos do resultado (os .shp, .shx, .dbf, .prj e .cpg de um Shapefile) são compactados num ZIP ao lado da origem, no lugar de arquivos soltos.", "presets.replace_original": "Substituir o original", "presets.replace_original_hint": "O resultado assume o nome e o lugar do original, e o original vai para a Lixeira. Só quando o resultado tem o mesmo formato, nunca para pastas monitoradas ou arquivos vindos de um navegador. Se o original não puder ir para a Lixeira, ele fica e o resultado é salvo como cópia. O resultado é salvo na pasta do original, seja qual for o \"Salvar em\".", + "presets.trash_original": "Mover o original para a Lixeira após converter", + "presets.trash_original_hint": "Quando o resultado está pronto, o original vai para a Lixeira, de onde você pode restaurá-lo. Só quando o resultado tem outro formato (\"Substituir o original\" é para o mesmo formato). Nunca para pastas monitoradas, arquivos vindos de um navegador, a linha de comando, mesclagens ou resultados ZIP. Se o original não puder ir para a Lixeira, ele fica.", "presets.conflict": "Se o arquivo existir", "presets.conflict.Rename": "Adicionar um número", "presets.conflict.Overwrite": "Substituir", diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index a7c27a580..0e4e157f9 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Este ficheiro é CMYK, mas o Ghostscript não o conseguiu desenhar, por isso foi guardado em RGB", "notice.original_kept": "O original foi mantido e o resultado foi guardado como cópia", "notice.original_in_trash": "O original está na Reciclagem ou no Lixo; o resultado manteve o seu próprio nome", + "notice.trash_original_kept": "O original foi mantido porque não foi possível movê-lo para a Reciclagem ou para o Lixo", "notice.original_unchanged": "Não foi possível reduzir o tamanho, pelo que o original foi mantido sem alterações", "notice.move_original_kept": "Copiado, mas não foi possível remover o original", "trash.no_recycle_bin": "esta unidade não tem Reciclagem nem Lixo", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Os ficheiros do resultado (.shp, .shx, .dbf, .prj e .cpg de um Shapefile) são comprimidos num ZIP junto à origem, em vez de ficarem separados.", "presets.replace_original": "Substituir o original", "presets.replace_original_hint": "O resultado fica com o nome e no local do original, e o original é movido para a Reciclagem ou para o Lixo. Só se aplica quando o resultado tem o mesmo formato, e nunca a pastas monitorizadas nem a ficheiros de um navegador. Se não for possível mover o original, este é mantido e o resultado é guardado como cópia. O resultado é guardado na pasta do original, independentemente da opção «Guardar em».", + "presets.trash_original": "Mover o original para a Reciclagem ou para o Lixo após converter", + "presets.trash_original_hint": "Quando o resultado está concluído, o original é movido para a Reciclagem ou para o Lixo, de onde o pode restaurar. Só se aplica quando o resultado tem outro formato («Substituir o original» serve para o mesmo formato), e nunca a pastas monitorizadas, ficheiros de um navegador, à linha de comandos, a junções ou a resultados ZIP. Se não for possível mover o original, este é mantido.", "presets.conflict": "Se o ficheiro existir", "presets.conflict.Rename": "Adicionar um número", "presets.conflict.Overwrite": "Substituir", diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 7fb769f62..353ad6307 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Это файл CMYK, но Ghostscript не смог его отрисовать, поэтому он сохранён в RGB", "notice.original_kept": "Оригинал оставлен, результат сохранён как копия", "notice.original_in_trash": "Оригинал в Корзине, результат сохранил своё имя", + "notice.trash_original_kept": "Оригинал оставлен: его не удалось отправить в Корзину", "notice.original_unchanged": "Не удалось сделать его меньше, поэтому оригинал оставлен как есть", "notice.move_original_kept": "Скопировано, но оригинал не удалось удалить", "trash.no_recycle_bin": "на этом диске нет Корзины", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Файлы результата (у Shapefile это .shp, .shx, .dbf, .prj и .cpg) упаковываются в один ZIP рядом с исходником вместо отдельных файлов.", "presets.replace_original": "Заменить оригинал", "presets.replace_original_hint": "Результат получает имя и место оригинала, а оригинал отправляется в Корзину. Только если у результата тот же формат, никогда для отслеживаемых папок и файлов из браузера. Если оригинал нельзя отправить в Корзину, он остаётся, а результат сохраняется как копия. Результат сохраняется в папке оригинала, что бы ни было указано в «Сохранять в».", + "presets.trash_original": "Перемещать оригинал в Корзину после конвертации", + "presets.trash_original_hint": "Когда результат готов, оригинал отправляется в Корзину, откуда его можно восстановить. Только если у результата другой формат (для того же формата есть «Заменить оригинал»). Никогда для отслеживаемых папок, файлов из браузера, командной строки, объединений и результатов ZIP. Если оригинал нельзя отправить в Корзину, он остаётся.", "presets.conflict": "Если файл уже есть", "presets.conflict.Rename": "Добавить номер", "presets.conflict.Overwrite": "Заменить", diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index 4ee2f8993..7d227ab92 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "ไฟล์นี้เป็น CMYK แต่ Ghostscript วาดไม่ได้ จึงบันทึกเป็น RGB", "notice.original_kept": "เก็บไฟล์ต้นฉบับไว้ และบันทึกผลลัพธ์เป็นสำเนา", "notice.original_in_trash": "ไฟล์ต้นฉบับอยู่ในถังขยะ ผลลัพธ์ยังใช้ชื่อของตัวเอง", + "notice.trash_original_kept": "เก็บไฟล์ต้นฉบับไว้ เพราะย้ายไปที่ถังขยะไม่ได้", "notice.original_unchanged": "ทำให้เล็กลงไม่ได้ จึงปล่อยไฟล์ต้นฉบับไว้ตามเดิม", "notice.move_original_kept": "คัดลอกแล้ว แต่ลบต้นฉบับไม่ได้", "trash.no_recycle_bin": "ไดรฟ์นี้ไม่มีถังรีไซเคิล / ถังขยะ", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "ไฟล์ผลลัพธ์ทั้งหมด (เช่น .shp, .shx, .dbf, .prj และ .cpg ของ Shapefile) จะถูกรวมเป็น ZIP เดียวไว้ข้างไฟล์ต้นฉบับ แทนที่จะเป็นไฟล์แยกเดี่ยวๆ", "presets.replace_original": "แทนที่ไฟล์ต้นฉบับ", "presets.replace_original_hint": "ผลลัพธ์จะใช้ชื่อและตำแหน่งของไฟล์ต้นฉบับ และไฟล์ต้นฉบับจะถูกย้ายไปที่ถังขยะ เฉพาะเมื่อผลลัพธ์มีรูปแบบเดียวกัน และไม่ใช้กับโฟลเดอร์เฝ้าดูหรือไฟล์จากเบราว์เซอร์ หากย้ายไฟล์ต้นฉบับไปถังขยะไม่ได้ ไฟล์จะยังอยู่ และผลลัพธ์จะถูกบันทึกเป็นสำเนา ผลลัพธ์จะถูกบันทึกในโฟลเดอร์ของไฟล์ต้นฉบับ ไม่ว่า \"บันทึกไปที่\" จะตั้งไว้อย่างไร", + "presets.trash_original": "ย้ายไฟล์ต้นฉบับไปที่ถังขยะหลังแปลง", + "presets.trash_original_hint": "เมื่อผลลัพธ์เสร็จสมบูรณ์ ไฟล์ต้นฉบับจะถูกย้ายไปที่ถังขยะ และกู้คืนได้จากที่นั่น เฉพาะเมื่อผลลัพธ์มีรูปแบบต่างจากต้นฉบับ (รูปแบบเดียวกันให้ใช้ \"แทนที่ไฟล์ต้นฉบับ\") และไม่ใช้กับโฟลเดอร์เฝ้าดู ไฟล์จากเบราว์เซอร์ บรรทัดคำสั่ง การรวมไฟล์ หรือผลลัพธ์ ZIP หากย้ายไฟล์ต้นฉบับไปถังขยะไม่ได้ ไฟล์จะยังอยู่", "presets.conflict": "หากมีไฟล์ชื่อนี้อยู่แล้ว", "presets.conflict.Rename": "เติมตัวเลขต่อท้าย", "presets.conflict.Overwrite": "เขียนทับ", diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 39612b88b..2f25bb001 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -196,6 +196,7 @@ "notice.cmyk_render_failed": "Bu dosya CMYK ama Ghostscript onu çizemedi, bu yüzden RGB olarak kaydedildi", "notice.original_kept": "Özgün dosya korundu, sonuç kopya olarak kaydedildi", "notice.original_in_trash": "Özgün dosya Geri Dönüşüm Kutusu'nda / Çöp Sepeti'nde; sonuç kendi adını korudu", + "notice.trash_original_kept": "Özgün dosya Geri Dönüşüm Kutusu'na taşınamadığı için korundu", "notice.original_unchanged": "Küçültülemediği için özgün dosya olduğu gibi bırakıldı", "notice.move_original_kept": "Kopyalandı, ancak orijinal kaldırılamadı", "trash.no_recycle_bin": "bu sürücüde Geri Dönüşüm Kutusu / Çöp Sepeti yok", @@ -1186,6 +1187,8 @@ "presets.zip_result_hint": "Sonuç dosyaları (Shapefile'ın .shp, .shx, .dbf, .prj ve .cpg dosyaları), ayrı dosyalar yerine kaynağın yanında tek ZIP'e paketlenir.", "presets.replace_original": "Özgün dosyanın yerine koy", "presets.replace_original_hint": "Sonuç özgün dosyanın adını ve konumunu alır; özgün dosya Geri Dönüşüm Kutusu'na / Çöp Sepeti'ne gider. Yalnızca sonuç aynı biçimdeyse uygulanır; izlenen klasörler veya tarayıcıdan gelen dosyalarda uygulanmaz. Özgün dosya kutuya taşınamazsa korunur ve sonuç kopya olarak kaydedilir. “Kayıt yeri” ne olursa olsun sonuç özgün dosyanın klasörüne kaydedilir.", + "presets.trash_original": "Dönüştürdükten sonra özgün dosyayı Geri Dönüşüm Kutusu'na taşı", + "presets.trash_original_hint": "Sonuç tamamlandığında özgün dosya Geri Dönüşüm Kutusu'na / Çöp Sepeti'ne gider ve oradan geri yüklenebilir. Yalnızca sonuç farklı bir biçimdeyse uygulanır (aynı biçim için “Özgün dosyanın yerine koy” vardır). İzlenen klasörlerde, tarayıcıdan gelen dosyalarda, komut satırında, birleştirmelerde ve ZIP sonuçlarında asla uygulanmaz. Özgün dosya kutuya taşınamazsa korunur.", "presets.conflict": "Dosya mevcutsa", "presets.conflict.Rename": "Numara ekle", "presets.conflict.Overwrite": "Üzerine yaz", diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 79ed7ebbe..560ac1415 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "Tệp này là CMYK, nhưng Ghostscript không vẽ được nên đã lưu dưới dạng RGB", "notice.original_kept": "Bản gốc được giữ lại, kết quả được lưu thành bản sao", "notice.original_in_trash": "Bản gốc đã ở trong Thùng rác, kết quả giữ tên riêng của nó", + "notice.trash_original_kept": "Bản gốc được giữ lại vì không thể chuyển vào Thùng rác", "notice.original_unchanged": "Không thể làm nhỏ hơn nên bản gốc được giữ nguyên", "notice.move_original_kept": "Đã sao chép, nhưng không thể gỡ bỏ bản gốc", "trash.no_recycle_bin": "ổ đĩa này không có Thùng rác", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "Các tệp của kết quả (.shp, .shx, .dbf, .prj và .cpg của Shapefile) được đóng gói thành một tệp ZIP cạnh tệp nguồn, thay vì để các tệp rời.", "presets.replace_original": "Thay thế bản gốc", "presets.replace_original_hint": "Kết quả nhận tên và vị trí của bản gốc, còn bản gốc được chuyển vào Thùng rác. Chỉ khi kết quả có cùng định dạng, không bao giờ áp dụng cho thư mục theo dõi hoặc tệp từ trình duyệt. Khi không thể chuyển bản gốc vào đó, bản gốc được giữ lại và kết quả được lưu thành bản sao. Kết quả được lưu trong thư mục của bản gốc, bất kể “Lưu vào” đặt là gì.", + "presets.trash_original": "Chuyển bản gốc vào Thùng rác sau khi chuyển đổi", + "presets.trash_original_hint": "Khi kết quả hoàn tất, bản gốc được chuyển vào Thùng rác và bạn có thể khôi phục từ đó. Chỉ khi kết quả có định dạng khác (cùng định dạng thì dùng “Thay thế bản gốc”). Không bao giờ áp dụng cho thư mục theo dõi, tệp từ trình duyệt, dòng lệnh, gộp tệp hoặc kết quả ZIP. Khi không thể chuyển bản gốc vào đó, bản gốc được giữ lại.", "presets.conflict": "Nếu tệp đã tồn tại", "presets.conflict.Rename": "Thêm số", "presets.conflict.Overwrite": "Thay thế", diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index e3b1176ef..e7f16c117 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "这是 CMYK 文件,但 Ghostscript 无法绘制,所以保存成了 RGB", "notice.original_kept": "已保留原文件,结果另存为副本", "notice.original_in_trash": "原文件已在回收站/废纸篓中,结果保留了自己的名称", + "notice.trash_original_kept": "已保留原文件,因为无法将其移到回收站/废纸篓", "notice.original_unchanged": "无法变小,因此保留原文件不变", "notice.move_original_kept": "已复制,但无法删除原文件", "trash.no_recycle_bin": "此驱动器没有回收站/废纸篓", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "结果文件(Shapefile 的 .shp、.shx、.dbf、.prj 和 .cpg)会打包成原文件旁的一个 ZIP,而不是零散的文件。", "presets.replace_original": "替换原文件", "presets.replace_original_hint": "结果会使用原文件的名称和位置,原文件移到回收站/废纸篓。仅在结果格式相同时生效,监视文件夹和来自浏览器的文件不会替换。若原文件无法移到回收站/废纸篓,则保留原文件,结果另存为副本。无论“保存到”如何设置,结果都会保存在原文件所在的文件夹。", + "presets.trash_original": "转换后将原文件移到回收站/废纸篓", + "presets.trash_original_hint": "结果完成后,原文件会移到回收站/废纸篓,可以从那里还原。仅在结果格式不同时生效(格式相同请用“替换原文件”),监视文件夹、来自浏览器的文件、命令行、合并和 ZIP 结果不会移动原文件。若原文件无法移到回收站/废纸篓,则保留原文件。", "presets.conflict": "文件已存在时", "presets.conflict.Rename": "添加编号", "presets.conflict.Overwrite": "覆盖", diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index c7b54bec2..483a6b2db 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -202,6 +202,7 @@ "notice.cmyk_render_failed": "這是 CMYK 檔案,但 Ghostscript 無法繪製,所以儲存成了 RGB", "notice.original_kept": "已保留原始檔案,結果另存為副本", "notice.original_in_trash": "原始檔案已在資源回收筒/垃圾桶中,結果保留了自己的名稱", + "notice.trash_original_kept": "已保留原始檔案,因為無法將其移到資源回收筒/垃圾桶", "notice.original_unchanged": "無法變小,因此保留原始檔案不變", "notice.move_original_kept": "已複製,但無法刪除原始檔案", "trash.no_recycle_bin": "此磁碟機沒有資源回收筒/垃圾桶", @@ -1201,6 +1202,8 @@ "presets.zip_result_hint": "結果檔案(Shapefile 的 .shp、.shx、.dbf、.prj 和 .cpg)會打包成原始檔案旁的一個 ZIP,而不是零散的檔案。", "presets.replace_original": "取代原始檔案", "presets.replace_original_hint": "結果會使用原始檔案的名稱和位置,原始檔案移到資源回收筒/垃圾桶。僅在結果格式相同時生效,監看資料夾和來自瀏覽器的檔案不會取代。若原始檔案無法移到資源回收筒/垃圾桶,則保留原始檔案,結果另存為副本。無論「儲存到」如何設定,結果都會儲存在原始檔案所在的資料夾。", + "presets.trash_original": "轉換後將原始檔案移到資源回收筒/垃圾桶", + "presets.trash_original_hint": "結果完成後,原始檔案會移到資源回收筒/垃圾桶,可以從那裡還原。僅在結果格式不同時生效(格式相同請用「取代原始檔案」),監看資料夾、來自瀏覽器的檔案、命令列、合併和 ZIP 結果不會移動原始檔案。若原始檔案無法移到資源回收筒/垃圾桶,則保留原始檔案。", "presets.conflict": "檔案已存在時", "presets.conflict.Rename": "新增編號", "presets.conflict.Overwrite": "覆蓋", From e0aee201d5e5414042f245254d48e1df1692b241 Mon Sep 17 00:00:00 2001 From: adnan-bhaldar Date: Sat, 14 Nov 2026 12:24:40 +0530 Subject: [PATCH 21/95] test: fix null-conditional on method group in TrashOriginalTests trash?.Move does not compile (CS8978). Use trash is null ? null : trash.Move instead. Refs #1387 --- tests/Filee.Core.Tests/TrashOriginalTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Filee.Core.Tests/TrashOriginalTests.cs b/tests/Filee.Core.Tests/TrashOriginalTests.cs index a2b3f88ca..853fa36b9 100644 --- a/tests/Filee.Core.Tests/TrashOriginalTests.cs +++ b/tests/Filee.Core.Tests/TrashOriginalTests.cs @@ -33,7 +33,7 @@ private sealed class FakeTrash(string folder, TrashRefusal? refuse = null) private static async Task Run(FakeTrash? trash, string source, Preset preset, ISourceFetcher? fetcher = null) { - await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("fake", Edges)]), moveToTrash: trash?.Move); + await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("fake", Edges)]), moveToTrash: trash is null ? null : trash.Move); var job = new ConversionJob([source], preset, "Test", fetcher); await queue.RunAsync(job); return job; From 240c65777e732651c5635ff24cc7ab9f6c0c1d39 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sun, 15 Nov 2026 03:23:55 +0900 Subject: [PATCH 22/95] i18n(mn): the keys #1420, #1451 and #1503 added; drop a removed key Mongolian landed while those PRs were open, so main's LocalizationTests failed on mn. Adds the 23 missing strings in Mongolian and removes engines.state.system_copy, which en.json no longer has. Co-Authored-By: Claude Opus 5.5 --- src/Filee.App/Assets/i18n/mn.json | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index fa528de85..5119bf5d0 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -73,6 +73,9 @@ "donut.files_same": "{0} × {1}", "donut.files_mixed": "{0} файл", "donut.drop_to": "Тавих → {0}", + "donut.ordinary_conversion.single": "Энэ файлыг энгийн хөрвүүлэлтээр боловсруулна", + "donut.ordinary_conversion.all": "Хөрвүүлэх боломжтой бүх файлыг энгийн хөрвүүлэлтээр боловсруулна", + "donut.ordinary_conversion.some": "Зарим файлыг энгийн хөрвүүлэлтээр боловсруулна", "donut.pick_in_group": "Сонгохын тулд гадагш чиглүүлнэ үү", "donut.group_empty": "Энэ бүлэгт урьдчилсан тохиргоо үлдсэнгүй. Тохиргоо → Цагираг самбар хэсгээс засна уу", "donut.click_to": "Товших → {0}", @@ -126,6 +129,8 @@ "error.split_unknown_length": "Энэ видеоны урт тодорхойгүй байгаа тул тэнцүү хэсгүүдэд хуваах боломжгүй", "error.split_needs_copy": "Хуваах үйлдэл нь видеог байгаагаар нь хуулдаг бөгөөд энэ формат түүнийг агуулж чадахгүй. Видеоны өөрийнх нь формат эсвэл MKV сонгоно уу", "error.merged_image_too_large": "Нэгтгэсэн зураг хэт том болох тул цөөн эсвэл жижиг зураг нэгтгэнэ үү", + "error.merge_paper_geometry": "Нэг хуудасны хэмжээ, эргэлт эсвэл нэгж буруу тул сонгосон цаасанд багтааж чадахгүй", + "error.merge_paper_limit": "Энэ PDF хэт нарийн бүтэцтэй тул нэг цаасны хэмжээнд багтааж чадахгүй", "error.over_size_limit": "Хэмжээний хязгаарт багтаахаар жижигрүүлэх боломжгүй байна", "error.not_enough_space": "Зургуудыг хадгалахад дискний сул зай хүрэлцэхгүй байна", "error.no_motion_photo": "Энэ зурагт Filee унших боломжтой видео алга (Android Motion Photo, эсвэл хажуудаа MOV файлтай iPhone Live Photo байх шаардлагатай)", @@ -847,6 +852,9 @@ "toolbar.mixed_others": "Бусад холимог файлууд “{0}”-ийг нээнэ.", "toolbar.mixed_others_self": "Юу ч тэмдэглээгүй өөр холимог профайл үлдээгүй тул энэ профайл бусад бүх холимогт мөн ашиглагдана.", "toolbar.chip_tip.makes": "→ {0} · {1}", + "toolbar.chip_tip.ordinary_conversion.single": "Энэ оролтын форматыг энгийн хөрвүүлэлтээр боловсруулна", + "toolbar.chip_tip.ordinary_conversion.all": "Хөрвүүлэх боломжтой бүх оролтын форматыг энгийн хөрвүүлэлтээр боловсруулна", + "toolbar.chip_tip.ordinary_conversion.some": "Зарим оролтын форматыг энгийн хөрвүүлэлтээр боловсруулна", "toolbar.chip_tip.makes_same": "→ Ижил формат", "toolbar.chip_tip.makes_name": "→ {0}", "toolbar.chip_tip.works_with": "Зөвшөөрөгдөх форматууд: {0}", @@ -987,6 +995,10 @@ "presets.group.pdf": "PDF", "presets.merge": "Бүх файлыг нэг PDF болгож нэгтгэх", "presets.source_bookmarks": "Эх файл бүрт хавчуурга (bookmark) нэмэх", + "presets.normalize_merge_paper": "Нэгтгэсэн бүх хуудсанд нэг цаасны хэмжээ ашиглах", + "presets.merge_paper": "Нэгтгэсэн PDF-ийн цаас", + "presets.merge_paper_hint": "Хуудас бүрийг сонгосон цаасанд багтааж, тайрахгүйгээр голлуулна. Зургийн хуудасны тохиргоог нэгтгэхээс өмнө хэрэглэнэ.", + "presets.merge_paper_auto_hint": "Автомат чиглэлийг эхний хуудаснаас нэг удаа сонгоно. Жижиг хуудсыг багтахаар томруулна.", "presets.page_size": "Хуудасны хэмжээ", "presets.page_size.FitImage": "Зурагт тааруулах", "presets.page_size.A4": "A4", @@ -1396,7 +1408,17 @@ "engines.remove": "Устгах", "engines.remove_confirm": "{0}-г устгах уу? Та дараа нь дахин татаж авах боломжтой.", "engines.state.own_copy": "Таны хувилбар", - "engines.state.system_copy": "Энэ компьютер дээр олдсон", + "engines.source.download": "Filee-ийн татсан", + "engines.source.system": "Энэ компьютер дээр", + "engines.source.version": "хувилбар {0}", + "engines.source.on_disk": "дискэн дээр: {0}", + "engines.other_copy_title": "Энэ компьютер дээр бас байна", + "engines.other_copy_detail": "{0} (Filee-ийн татсан хуулбарыг устгана)", + "engines.use_other_copy": "Үүнийг ашиглах", + "engines.use_other_copy_confirm": "{0} доторх хуулбарыг ашиглаж, Filee-ийн татсан {1}-г устгах уу? Дараа нь дахин татаж болно.", + "engines.other_copy_gone": "Тэр хуулбар олдохгүй байна эсвэл ажиллахгүй байна. Filee-ийн татсан хуулбарыг үлдээлээ.", + "engines.install_filee_copy": "Filee-ийн хуулбарыг суулгах", + "engines.use_another": "Өөр хуулбар ашиглах…", "engines.update_recommended": "Шинэчлэхийг зөвлөж байна: энэ хувилбар нь {0}, Filee нь {1} хувилбартай шалгагдсан.\nИхэнх хөрвүүлэлт ажилласан хэвээр байна.", "engines.use_own": "Миний хувилбарыг ашиглах…", "engines.use_own_hint": "Танд аль хэдийн байгаа юу? Програмыг нь зааж өгвөл Filee өөрөө татахын оронд түүнийг ашиглана.", From e59affcfcb5bc6f362ea59202409485455659f10 Mon Sep 17 00:00:00 2001 From: KnifeLemon Date: Sun, 15 Nov 2026 04:50:25 +0900 Subject: [PATCH 23/95] feat(presets): preset gallery window and 'filee presets check' Part B of the preset gallery (#1530). - Filee.Core/Gallery: an explicit allow-list of the fields a shared preset.json may have (unknown fields fail, fields that carry the sharer's folders, passwords, picture paths, clip music, metadata edits or the AI model may only be empty), the bundle and folder checks (pictures by header, sizes, no animation), index.json reading with relative paths and the counted download link, and an installer that verifies SHA-256 and the rules, then adds new presets and a donut under new ids without replacing anything. - filee presets check [--json]: what the gallery's CI runs, with SkiaSharp decoding every picture; codes, messages and derived meta fields. - App: "Preset gallery" window from the Presets page (Hot/Best/New, filters, search, details, Install, Comments), contacting filee.sh only while open, through the proxy setting with time and size limits and a picture cache. Texts in all 23 languages, labels matching filee.sh. - Export writes settingsSchema into bundles. Refs #1530 Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 21 + src/Filee.App/Assets/i18n/ar.json | 64 +- src/Filee.App/Assets/i18n/bn-BD.json | 64 +- src/Filee.App/Assets/i18n/de.json | 64 +- src/Filee.App/Assets/i18n/en.json | 64 +- src/Filee.App/Assets/i18n/es.json | 64 +- src/Filee.App/Assets/i18n/fa.json | 64 +- src/Filee.App/Assets/i18n/fr.json | 64 +- src/Filee.App/Assets/i18n/hi.json | 64 +- src/Filee.App/Assets/i18n/id.json | 64 +- src/Filee.App/Assets/i18n/it.json | 64 +- src/Filee.App/Assets/i18n/ja.json | 64 +- src/Filee.App/Assets/i18n/ko.json | 64 +- src/Filee.App/Assets/i18n/mn.json | 64 +- src/Filee.App/Assets/i18n/ne.json | 64 +- src/Filee.App/Assets/i18n/pl.json | 64 +- src/Filee.App/Assets/i18n/pt-BR.json | 64 +- src/Filee.App/Assets/i18n/pt-PT.json | 64 +- src/Filee.App/Assets/i18n/ru.json | 64 +- src/Filee.App/Assets/i18n/th.json | 64 +- src/Filee.App/Assets/i18n/tr.json | 64 +- src/Filee.App/Assets/i18n/vi.json | 64 +- src/Filee.App/Assets/i18n/zh-CN.json | 64 +- src/Filee.App/Assets/i18n/zh-TW.json | 64 +- src/Filee.App/Services/PresetGalleryClient.cs | 203 ++++++ src/Filee.App/Services/WindowService.cs | 46 ++ src/Filee.App/ViewModels/GallerySummaries.cs | 129 ++++ .../ViewModels/Pages/PresetsPageViewModel.cs | 8 + .../ViewModels/PresetGalleryViewModel.cs | 594 ++++++++++++++++++ src/Filee.App/Views/Pages/PresetsPage.axaml | 8 + src/Filee.App/Views/PresetGalleryWindow.axaml | 251 ++++++++ .../Views/PresetGalleryWindow.axaml.cs | 31 + src/Filee.Cli/Cli.cs | 12 +- src/Filee.Cli/CliOptions.cs | 4 + src/Filee.Cli/Help.cs | 27 +- src/Filee.Cli/PresetsCheckCommand.cs | 111 ++++ src/Filee.Core/Gallery/GalleryImageHeader.cs | 151 +++++ src/Filee.Core/Gallery/GalleryIndex.cs | 221 +++++++ src/Filee.Core/Gallery/GalleryInstaller.cs | 113 ++++ src/Filee.Core/Gallery/PresetCheckResult.cs | 71 +++ src/Filee.Core/Gallery/SharedBundleCheck.cs | 310 +++++++++ .../Gallery/SharedPresetFolderCheck.cs | 281 +++++++++ src/Filee.Core/Gallery/SharedPresetRules.cs | 331 ++++++++++ src/Filee.Core/Gallery/SharedText.cs | 149 +++++ src/Filee.Core/Settings/FileeJsonContext.cs | 7 + src/Filee.Core/Settings/UserDataStore.cs | 8 +- tests/Filee.App.Tests/PresetGalleryTests.cs | 529 ++++++++++++++++ tests/Filee.Cli.Tests/PresetsCheckTests.cs | 156 +++++ tests/Filee.Core.Tests/GalleryFiles.cs | 131 ++++ .../PresetGalleryCheckTests.cs | 427 +++++++++++++ .../PresetGalleryFolderTests.cs | 233 +++++++ .../PresetGalleryIndexTests.cs | 188 ++++++ .../PresetGalleryInstallTests.cs | 165 +++++ 53 files changed, 6357 insertions(+), 31 deletions(-) create mode 100644 src/Filee.App/Services/PresetGalleryClient.cs create mode 100644 src/Filee.App/ViewModels/GallerySummaries.cs create mode 100644 src/Filee.App/ViewModels/PresetGalleryViewModel.cs create mode 100644 src/Filee.App/Views/PresetGalleryWindow.axaml create mode 100644 src/Filee.App/Views/PresetGalleryWindow.axaml.cs create mode 100644 src/Filee.Cli/PresetsCheckCommand.cs create mode 100644 src/Filee.Core/Gallery/GalleryImageHeader.cs create mode 100644 src/Filee.Core/Gallery/GalleryIndex.cs create mode 100644 src/Filee.Core/Gallery/GalleryInstaller.cs create mode 100644 src/Filee.Core/Gallery/PresetCheckResult.cs create mode 100644 src/Filee.Core/Gallery/SharedBundleCheck.cs create mode 100644 src/Filee.Core/Gallery/SharedPresetFolderCheck.cs create mode 100644 src/Filee.Core/Gallery/SharedPresetRules.cs create mode 100644 src/Filee.Core/Gallery/SharedText.cs create mode 100644 tests/Filee.App.Tests/PresetGalleryTests.cs create mode 100644 tests/Filee.Cli.Tests/PresetsCheckTests.cs create mode 100644 tests/Filee.Core.Tests/GalleryFiles.cs create mode 100644 tests/Filee.Core.Tests/PresetGalleryCheckTests.cs create mode 100644 tests/Filee.Core.Tests/PresetGalleryFolderTests.cs create mode 100644 tests/Filee.Core.Tests/PresetGalleryIndexTests.cs create mode 100644 tests/Filee.Core.Tests/PresetGalleryInstallTests.cs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0412d726b..68fd8e500 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -613,6 +613,27 @@ installed yet; the slides introduce the installed one. The demo animations are r The tray app runs one per rule (`WatchFolderService`, Settings → Watch folders, conversions in the toast and history); `filee watch` runs one on its own, with a stable `cli` rule identity across command restarts. +## Preset gallery + +Presets shared by users live in the `KnifeLemon/Filee-Presets` repository and on filee.sh (#1530); the app reads +them, it never uploads. + +- `Filee.Core/Gallery/SharedPresetRules` is the allow-list: every field a shared preset.json (a `PresetBundle`) may + have, with its range, and the fields left out (folders, passwords, a picture's path, a clip's music, metadata edits, + the AI model), which may only be empty. A field added to `Preset` fails the check until it is listed there + (`PresetGalleryCheckTests` compares the list with the model). +- `SharedBundleCheck` checks a preset.json against it, as JSON first (unknown fields, types, ranges, links, personal + paths) and then as presets (kinds, tools, targets, references), and derives what meta.json needs. + `SharedPresetFolderCheck` checks a whole submission folder, pictures included (`GalleryImageHeader` reads their + header before anything decodes them). `filee presets check [--json]` runs it, with SkiaSharp decoding each + picture; the gallery's CI calls it. +- `GalleryInstaller` checks the downloaded file's SHA-256 and the rules again, then adds its presets and donut under + new ids (" (2)" on a name the library has); nothing is ever replaced, unlike Settings → General → Import. +- The app's `PresetGalleryWindow` (from the Presets page) reads `index.json` through `PresetGalleryClient`, only while + it is open, with the proxy setting, time and size limits, and falls back to the repository on GitHub when filee.sh + can't be reached. Paths in the index are relative to the URL it came from; Install uses the entry's counted + `download` link. Pictures are cached in the work folder's `gallery/` (64 MB, 30 days). + ## Platform code Everything OS-specific goes through `IPlatformServices` (`Filee.Core/Platform`). Windows lives in diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json index 5df39016d..1780a541a 100644 --- a/src/Filee.App/Assets/i18n/ar.json +++ b/src/Filee.App/Assets/i18n/ar.json @@ -1850,5 +1850,67 @@ "connect.pin_label": "رمز PIN:", "connect.firewall_hint_generic": "ملاحظة: إذا لم يتمكن هاتفك من الاتصال، اسمح لـ Filee في جدار الحماية الخاص بالنظام.", "connect.no_network_message": "تعذر بدء Filee Connect. يرجى التأكد من اتصال هذا الجهاز بشبكة Wi-Fi أو شبكة إيثرنت محلية.", - "connect.save_as": "حفظ باسم…" + "connect.save_as": "حفظ باسم…", + "gallery.title": "معرض الإعدادات المسبقة", + "gallery.open": "معرض الإعدادات المسبقة", + "gallery.open_tip": "إعدادات مسبقة شاركها آخرون على filee.sh", + "gallery.lead": "إعدادات مسبقة شاركها آخرون على filee.sh. عند تثبيتها تُضاف كإعدادات مسبقة جديدة وتبقى إعداداتك كما هي. لا يتصل Filee بـ filee.sh إلا أثناء فتح هذه النافذة.", + "gallery.sort": "الترتيب", + "gallery.sort.Hot": "الرائج", + "gallery.sort.Best": "الأفضل", + "gallery.sort.New": "الأحدث", + "gallery.period": "الفترة", + "gallery.period.day": "اليوم", + "gallery.period.week": "هذا الأسبوع", + "gallery.period.month": "هذا الشهر", + "gallery.period.year": "هذا العام", + "gallery.period.all": "كل الأوقات", + "gallery.filter.kind": "النوع", + "gallery.kind.all": "كل الأنواع", + "gallery.kind.convert": "التحويلات", + "gallery.kind.tool": "الأدوات", + "gallery.kind.toolbar": "الأشرطة الدائرية", + "gallery.filter.format": "الصيغة", + "gallery.format.all": "كل الصيغ", + "gallery.filter.tag": "الوسم", + "gallery.tag.all": "كل الوسوم", + "gallery.filter.language": "اللغة", + "gallery.language.all": "كل اللغات", + "gallery.loading": "جارٍ تحميل الإعدادات المسبقة من filee.sh…", + "gallery.failed": "تعذّر الوصول إلى filee.sh. تحقّق من الاتصال بالإنترنت ومن الوكيل في الإعدادات ← عام، ثم أعد المحاولة.", + "gallery.empty": "لا يوجد إعداد مسبق يطابق البحث وعوامل التصفية.", + "gallery.none": "لم يشارك أحد إعدادات مسبقة بعد.", + "gallery.newer": "{0} أخرى تحتاج إلى إصدار أحدث من Filee.", + "gallery.by": "من {0}", + "gallery.likes": "{0} إعجاب", + "gallery.downloads": "{0} تنزيل", + "gallery.select": "اختر إعدادًا مسبقًا لترى صوره وما يفعله.", + "gallery.image": "الصورة {0} من {1}", + "gallery.what": "ما سيُضاف", + "gallery.what_group": "مجموعة: {0}", + "gallery.loading_details": "جارٍ التحميل…", + "gallery.donut_new": "يضيف الشريط الدائري «{0}» لـ {1}. لا يُفتح إلا للملفات التي لا يتولاها أي من أشرطتك الدائرية؛ يمكنك تغيير ذلك من الإعدادات ← شريط الأدوات الدائري.", + "gallery.donut_mixed": "الملفات المختلطة", + "gallery.donut_none": "لا يوضع على أي شريط دائري: أضفه إلى أحدها من الإعدادات ← شريط الأدوات الدائري.", + "gallery.license": "شاركه {0} بموجب CC0: حرّ الاستخدام والتعديل والمشاركة.", + "gallery.comments": "التعليقات", + "gallery.install": "تثبيت", + "gallery.installing": "جارٍ التثبيت…", + "gallery.installed": "أُضيف {0} من الإعدادات المسبقة. تجدها في قائمة الإعدادات المسبقة.", + "gallery.installed_donut": "أُضيف {0} من الإعدادات المسبقة والشريط الدائري «{1}».", + "gallery.install_failed": "تعذّر التثبيت: {0}", + "gallery.not_installable": "لا يمكن تثبيت هذا الإعداد المسبق: {0}", + "gallery.download_failed": "تعذّر تنزيل الإعداد المسبق. تحقّق من الاتصال وأعد المحاولة.", + "gallery.mismatch": "الملف الذي نُزّل ليس الملف الذي يذكره المعرض، لذا لم يُثبَّت شيء.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "{0} ميغابايت كحد أقصى", + "gallery.option.no_metadata": "يزيل البيانات الوصفية", + "gallery.option.merge": "يدمج في ملف واحد", + "gallery.option.pages": "الصفحات {0}", + "gallery.option.max_height": "حتى {0}p", + "gallery.option.translate": "يترجم إلى {0}", + "gallery.option.ask_compression": "يسأل عن درجة الضغط في كل مرة", + "gallery.option.subfolder": "يحفظ في المجلد «{0}»", + "gallery.option.file_name": "اسم الملف: {0}" } diff --git a/src/Filee.App/Assets/i18n/bn-BD.json b/src/Filee.App/Assets/i18n/bn-BD.json index d99bc260f..a18c41f11 100644 --- a/src/Filee.App/Assets/i18n/bn-BD.json +++ b/src/Filee.App/Assets/i18n/bn-BD.json @@ -1847,5 +1847,67 @@ "connect.pin_label": "পিন:", "connect.firewall_hint_generic": "নোট: আপনার ফোন সংযোগ করতে না পারলে, সিস্টেম ফায়ারওয়ালে Filee অনুমতি দিন।", "connect.no_network_message": "Filee Connect শুরু করা যায়নি। অনুগ্রহ করে নিশ্চিত করুন যে এই ডিভাইসটি একটি স্থানীয় Wi-Fi বা ইথারনেট নেটওয়ার্কের সাথে সংযুক্ত রয়েছে।", - "connect.save_as": "সংরক্ষণ করুন…" + "connect.save_as": "সংরক্ষণ করুন…", + "gallery.title": "প্রিসেট গ্যালারি", + "gallery.open": "প্রিসেট গ্যালারি", + "gallery.open_tip": "অন্যরা filee.sh-এ যে প্রিসেট শেয়ার করেছেন", + "gallery.lead": "অন্যরা filee.sh-এ যে প্রিসেট শেয়ার করেছেন। ইনস্টল করলে এগুলো নতুন প্রিসেট হিসেবে যোগ হয়, আপনার প্রিসেটগুলো যেমন আছে তেমনই থাকে। এই উইন্ডো খোলা থাকলেই কেবল Filee filee.sh-এর সঙ্গে যোগাযোগ করে।", + "gallery.sort": "সাজান", + "gallery.sort.Hot": "জনপ্রিয়", + "gallery.sort.Best": "সেরা", + "gallery.sort.New": "নতুন", + "gallery.period": "সময়কাল", + "gallery.period.day": "আজ", + "gallery.period.week": "এই সপ্তাহ", + "gallery.period.month": "এই মাস", + "gallery.period.year": "এই বছর", + "gallery.period.all": "সব সময়", + "gallery.filter.kind": "ধরন", + "gallery.kind.all": "সব ধরন", + "gallery.kind.convert": "রূপান্তর", + "gallery.kind.tool": "টুল", + "gallery.kind.toolbar": "ডোনাট টুলবার", + "gallery.filter.format": "ফরম্যাট", + "gallery.format.all": "সব ফরম্যাট", + "gallery.filter.tag": "ট্যাগ", + "gallery.tag.all": "সব ট্যাগ", + "gallery.filter.language": "ভাষা", + "gallery.language.all": "সব ভাষা", + "gallery.loading": "filee.sh থেকে প্রিসেট লোড হচ্ছে…", + "gallery.failed": "filee.sh-এ সংযোগ করা যায়নি। ইন্টারনেট সংযোগ এবং সেটিংস → সাধারণ-এর প্রক্সি পরীক্ষা করে আবার চেষ্টা করুন।", + "gallery.empty": "অনুসন্ধান ও ফিল্টারের সঙ্গে মেলে এমন কোনো প্রিসেট নেই।", + "gallery.none": "এখনো কোনো প্রিসেট শেয়ার করা হয়নি।", + "gallery.newer": "আরও {0}টির জন্য Filee-এর নতুন সংস্করণ লাগবে।", + "gallery.by": "{0}-এর", + "gallery.likes": "{0} লাইক", + "gallery.downloads": "{0} ডাউনলোড", + "gallery.select": "একটি প্রিসেট বেছে নিন, তার ছবি আর সেটি কী করে তা দেখতে।", + "gallery.image": "ছবি {0} / {1}", + "gallery.what": "যা যোগ হবে", + "gallery.what_group": "গ্রুপ: {0}", + "gallery.loading_details": "লোড হচ্ছে…", + "gallery.donut_new": "{1}-এর জন্য ডোনাট টুলবার “{0}” যোগ করে। আপনার কোনো ডোনাট যে ফাইল নেয় না, কেবল সেগুলোর জন্যই এটি খোলে; সেটিংস → ডোনাট টুলবারে এটি বদলাতে পারেন।", + "gallery.donut_mixed": "মিশ্র ফাইল", + "gallery.donut_none": "কোনো ডোনাটে নেই: সেটিংস → ডোনাট টুলবারে কোনো একটিতে যোগ করুন।", + "gallery.license": "{0} CC0-এর অধীনে শেয়ার করেছেন: ব্যবহার, পরিবর্তন ও শেয়ার করা সম্পূর্ণ মুক্ত।", + "gallery.comments": "মন্তব্য", + "gallery.install": "ইনস্টল করুন", + "gallery.installing": "ইনস্টল হচ্ছে…", + "gallery.installed": "{0}টি প্রিসেট যোগ হয়েছে। প্রিসেট তালিকায় সেগুলো পাবেন।", + "gallery.installed_donut": "{0}টি প্রিসেট ও ডোনাট টুলবার “{1}” যোগ হয়েছে।", + "gallery.install_failed": "ইনস্টল করা যায়নি: {0}", + "gallery.not_installable": "এই প্রিসেট ইনস্টল করা যাবে না: {0}", + "gallery.download_failed": "প্রিসেট ডাউনলোড করা যায়নি। সংযোগ পরীক্ষা করে আবার চেষ্টা করুন।", + "gallery.mismatch": "ডাউনলোড করা ফাইলটি গ্যালারির তালিকার ফাইল নয়, তাই কিছুই ইনস্টল করা হয়নি।", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "সর্বোচ্চ {0} MB", + "gallery.option.no_metadata": "মেটাডেটা সরায়", + "gallery.option.merge": "একটি ফাইলে জোড়া লাগায়", + "gallery.option.pages": "পৃষ্ঠা {0}", + "gallery.option.max_height": "সর্বোচ্চ {0}p", + "gallery.option.translate": "{0}-এ অনুবাদ করে", + "gallery.option.ask_compression": "প্রতিবার কমপ্রেশন জিজ্ঞেস করে", + "gallery.option.subfolder": "“{0}” ফোল্ডারে সেভ করে", + "gallery.option.file_name": "ফাইলের নাম: {0}" } diff --git a/src/Filee.App/Assets/i18n/de.json b/src/Filee.App/Assets/i18n/de.json index ab9cf21bf..3e9d72197 100644 --- a/src/Filee.App/Assets/i18n/de.json +++ b/src/Filee.App/Assets/i18n/de.json @@ -1849,5 +1849,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Hinweis: Wenn dein Smartphone keine Verbindung herstellen kann, erlaube Filee in der System-Firewall.", "connect.no_network_message": "Filee Connect konnte nicht gestartet werden. Bitte stelle sicher, dass dieses Gerät mit einem lokalen WLAN- oder Ethernet-Netzwerk verbunden ist.", - "connect.save_as": "Speichern unter…" + "connect.save_as": "Speichern unter…", + "gallery.title": "Vorlagengalerie", + "gallery.open": "Vorlagengalerie", + "gallery.open_tip": "Vorlagen, die andere auf filee.sh geteilt haben", + "gallery.lead": "Vorlagen, die andere auf filee.sh geteilt haben. Beim Installieren kommen sie als neue Vorlagen hinzu, deine eigenen bleiben, wie sie sind. Filee verbindet sich nur mit filee.sh, solange dieses Fenster offen ist.", + "gallery.sort": "Sortieren", + "gallery.sort.Hot": "Angesagt", + "gallery.sort.Best": "Beste", + "gallery.sort.New": "Neu", + "gallery.period": "Zeitraum", + "gallery.period.day": "Heute", + "gallery.period.week": "Diese Woche", + "gallery.period.month": "Diesen Monat", + "gallery.period.year": "Dieses Jahr", + "gallery.period.all": "Gesamt", + "gallery.filter.kind": "Art", + "gallery.kind.all": "Alle Arten", + "gallery.kind.convert": "Umwandlungen", + "gallery.kind.tool": "Werkzeuge", + "gallery.kind.toolbar": "Ringmenüs", + "gallery.filter.format": "Format", + "gallery.format.all": "Alle Formate", + "gallery.filter.tag": "Schlagwort", + "gallery.tag.all": "Alle Schlagwörter", + "gallery.filter.language": "Sprache", + "gallery.language.all": "Alle Sprachen", + "gallery.loading": "Vorlagen werden von filee.sh geladen …", + "gallery.failed": "filee.sh ist nicht erreichbar. Prüfe die Internetverbindung und den Proxy unter Einstellungen → Allgemein und versuche es dann erneut.", + "gallery.empty": "Keine Vorlage passt zur Suche und zu den Filtern.", + "gallery.none": "Bisher wurden keine Vorlagen geteilt.", + "gallery.newer": "{0} weitere brauchen eine neuere Version von Filee.", + "gallery.by": "von {0}", + "gallery.likes": "{0} Likes", + "gallery.downloads": "{0} Downloads", + "gallery.select": "Wähle eine Vorlage, um ihre Bilder zu sehen und was sie tut.", + "gallery.image": "Bild {0} von {1}", + "gallery.what": "Was hinzukommt", + "gallery.what_group": "Gruppe: {0}", + "gallery.loading_details": "Wird geladen …", + "gallery.donut_new": "Fügt das Ringmenü „{0}“ für {1} hinzu. Es öffnet sich nur für Dateien, die keines deiner Ringmenüs übernimmt; ändern kannst du das unter Einstellungen → Ringmenü.", + "gallery.donut_mixed": "gemischte Dateien", + "gallery.donut_none": "Kommt in kein Ringmenü: Füge sie unter Einstellungen → Ringmenü einem hinzu.", + "gallery.license": "Von {0} unter CC0 geteilt: frei zu nutzen, zu ändern und weiterzugeben.", + "gallery.comments": "Kommentare", + "gallery.install": "Installieren", + "gallery.installing": "Wird installiert …", + "gallery.installed": "{0} Vorlage(n) hinzugefügt. Du findest sie in der Liste der Vorlagen.", + "gallery.installed_donut": "{0} Vorlage(n) und das Ringmenü „{1}“ hinzugefügt.", + "gallery.install_failed": "Installieren fehlgeschlagen: {0}", + "gallery.not_installable": "Diese Vorlage kann nicht installiert werden: {0}", + "gallery.download_failed": "Die Vorlage konnte nicht heruntergeladen werden. Prüfe die Verbindung und versuche es erneut.", + "gallery.mismatch": "Die heruntergeladene Datei ist nicht die, die die Galerie angibt; es wurde nichts installiert.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Höchstens {0} MB", + "gallery.option.no_metadata": "Entfernt Metadaten", + "gallery.option.merge": "Fügt zu einer Datei zusammen", + "gallery.option.pages": "Seiten {0}", + "gallery.option.max_height": "Bis {0}p", + "gallery.option.translate": "Übersetzt in: {0}", + "gallery.option.ask_compression": "Fragt jedes Mal nach der Komprimierung", + "gallery.option.subfolder": "Speichert im Ordner „{0}“", + "gallery.option.file_name": "Dateiname: {0}" } diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json index b9eebb3f2..4ab829fe4 100644 --- a/src/Filee.App/Assets/i18n/en.json +++ b/src/Filee.App/Assets/i18n/en.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Note: If your phone cannot connect, allow Filee in your system firewall.", "connect.no_network_message": "Could not start Filee Connect. Please ensure this device is connected to a local Wi-Fi or Ethernet network.", - "connect.save_as": "Save as…" + "connect.save_as": "Save as…", + "gallery.title": "Preset gallery", + "gallery.open": "Preset gallery", + "gallery.open_tip": "Presets other people shared on filee.sh", + "gallery.lead": "Presets other people shared on filee.sh. Installing adds them as new presets and leaves yours as they are. Filee contacts filee.sh only while this window is open.", + "gallery.sort": "Sort", + "gallery.sort.Hot": "Hot", + "gallery.sort.Best": "Best", + "gallery.sort.New": "New", + "gallery.period": "Period", + "gallery.period.day": "Today", + "gallery.period.week": "This week", + "gallery.period.month": "This month", + "gallery.period.year": "This year", + "gallery.period.all": "All time", + "gallery.filter.kind": "Kind", + "gallery.kind.all": "All kinds", + "gallery.kind.convert": "Conversions", + "gallery.kind.tool": "Tools", + "gallery.kind.toolbar": "Donuts", + "gallery.filter.format": "Format", + "gallery.format.all": "All formats", + "gallery.filter.tag": "Tag", + "gallery.tag.all": "All tags", + "gallery.filter.language": "Language", + "gallery.language.all": "All languages", + "gallery.loading": "Loading presets from filee.sh…", + "gallery.failed": "Couldn't reach filee.sh. Check the internet connection and the proxy in Settings → General, then try again.", + "gallery.empty": "No preset matches the search and filters.", + "gallery.none": "No presets have been shared yet.", + "gallery.newer": "{0} more need a newer version of Filee.", + "gallery.by": "by {0}", + "gallery.likes": "{0} likes", + "gallery.downloads": "{0} downloads", + "gallery.select": "Choose a preset to see its pictures and what it does.", + "gallery.image": "Picture {0} of {1}", + "gallery.what": "What it adds", + "gallery.what_group": "Group: {0}", + "gallery.loading_details": "Loading…", + "gallery.donut_new": "Adds the donut “{0}” for {1}. It opens only for files none of your donuts takes; change that in Settings → Donut toolbar.", + "gallery.donut_mixed": "mixed files", + "gallery.donut_none": "Goes on no donut: add it to one in Settings → Donut toolbar.", + "gallery.license": "Shared by {0} under CC0: free to use, change and share.", + "gallery.comments": "Comments", + "gallery.install": "Install", + "gallery.installing": "Installing…", + "gallery.installed": "Added {0} preset(s). Find them in the Presets list.", + "gallery.installed_donut": "Added {0} preset(s) and the donut “{1}”.", + "gallery.install_failed": "Couldn't install it: {0}", + "gallery.not_installable": "This preset can't be installed: {0}", + "gallery.download_failed": "Couldn't download the preset. Check the connection and try again.", + "gallery.mismatch": "The downloaded file isn't the one the gallery lists, so nothing was installed.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "At most {0} MB", + "gallery.option.no_metadata": "Removes metadata", + "gallery.option.merge": "Merges into one file", + "gallery.option.pages": "Pages {0}", + "gallery.option.max_height": "Up to {0}p", + "gallery.option.translate": "Translates into {0}", + "gallery.option.ask_compression": "Asks for the compression each time", + "gallery.option.subfolder": "Saves in the folder “{0}”", + "gallery.option.file_name": "File name: {0}" } diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json index f496216e4..ff079c039 100644 --- a/src/Filee.App/Assets/i18n/es.json +++ b/src/Filee.App/Assets/i18n/es.json @@ -1851,5 +1851,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Nota: Si tu teléfono no puede conectarse, permite Filee en el cortafuegos del sistema.", "connect.no_network_message": "No se pudo iniciar Filee Connect. Asegúrate de que este dispositivo esté conectado a una red Wi-Fi o Ethernet local.", - "connect.save_as": "Guardar como…" + "connect.save_as": "Guardar como…", + "gallery.title": "Galería de ajustes preestablecidos", + "gallery.open": "Galería de ajustes preestablecidos", + "gallery.open_tip": "Ajustes preestablecidos que otras personas compartieron en filee.sh", + "gallery.lead": "Ajustes preestablecidos que otras personas compartieron en filee.sh. Al instalarlos se añaden como ajustes nuevos y los tuyos quedan como están. Filee solo se conecta a filee.sh mientras esta ventana está abierta.", + "gallery.sort": "Ordenar", + "gallery.sort.Hot": "Populares", + "gallery.sort.Best": "Mejores", + "gallery.sort.New": "Nuevos", + "gallery.period": "Período", + "gallery.period.day": "Hoy", + "gallery.period.week": "Esta semana", + "gallery.period.month": "Este mes", + "gallery.period.year": "Este año", + "gallery.period.all": "Desde siempre", + "gallery.filter.kind": "Tipo", + "gallery.kind.all": "Todos los tipos", + "gallery.kind.convert": "Conversiones", + "gallery.kind.tool": "Herramientas", + "gallery.kind.toolbar": "Menús circulares", + "gallery.filter.format": "Formato", + "gallery.format.all": "Todos los formatos", + "gallery.filter.tag": "Etiqueta", + "gallery.tag.all": "Todas las etiquetas", + "gallery.filter.language": "Idioma", + "gallery.language.all": "Todos los idiomas", + "gallery.loading": "Cargando ajustes desde filee.sh…", + "gallery.failed": "No se pudo conectar con filee.sh. Revisa la conexión a internet y el proxy en Ajustes → General, y vuelve a intentarlo.", + "gallery.empty": "Ningún ajuste coincide con la búsqueda y los filtros.", + "gallery.none": "Todavía no se ha compartido ningún ajuste.", + "gallery.newer": "{0} más necesitan una versión más nueva de Filee.", + "gallery.by": "de {0}", + "gallery.likes": "{0} me gusta", + "gallery.downloads": "{0} descargas", + "gallery.select": "Elige un ajuste para ver sus imágenes y lo que hace.", + "gallery.image": "Imagen {0} de {1}", + "gallery.what": "Lo que se añade", + "gallery.what_group": "Grupo: {0}", + "gallery.loading_details": "Cargando…", + "gallery.donut_new": "Añade el menú circular «{0}» para {1}. Solo se abre con archivos que ninguno de tus menús circulares toma; puedes cambiarlo en Ajustes → Menú circular.", + "gallery.donut_mixed": "archivos mezclados", + "gallery.donut_none": "No va en ningún menú circular: añádelo a uno en Ajustes → Menú circular.", + "gallery.license": "Compartido por {0} bajo CC0: libre para usar, modificar y compartir.", + "gallery.comments": "Comentarios", + "gallery.install": "Instalar", + "gallery.installing": "Instalando…", + "gallery.installed": "Se añadieron {0} ajuste(s). Están en la lista de ajustes preestablecidos.", + "gallery.installed_donut": "Se añadieron {0} ajuste(s) y el menú circular «{1}».", + "gallery.install_failed": "No se pudo instalar: {0}", + "gallery.not_installable": "Este ajuste no se puede instalar: {0}", + "gallery.download_failed": "No se pudo descargar el ajuste. Revisa la conexión y vuelve a intentarlo.", + "gallery.mismatch": "El archivo descargado no es el que indica la galería, así que no se instaló nada.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Como máximo {0} MB", + "gallery.option.no_metadata": "Quita los metadatos", + "gallery.option.merge": "Une en un solo archivo", + "gallery.option.pages": "Páginas {0}", + "gallery.option.max_height": "Hasta {0}p", + "gallery.option.translate": "Traduce a {0}", + "gallery.option.ask_compression": "Pregunta la compresión cada vez", + "gallery.option.subfolder": "Guarda en la carpeta «{0}»", + "gallery.option.file_name": "Nombre de archivo: {0}" } diff --git a/src/Filee.App/Assets/i18n/fa.json b/src/Filee.App/Assets/i18n/fa.json index ddf929c3d..67246df9d 100644 --- a/src/Filee.App/Assets/i18n/fa.json +++ b/src/Filee.App/Assets/i18n/fa.json @@ -1847,5 +1847,67 @@ "connect.pin_label": "پین:", "connect.firewall_hint_generic": "توجه: اگر تلفن شما متصل نمی‌شود، به Filee در فایروال سیستم اجازه دسترسی دهید.", "connect.no_network_message": "Filee Connect راه‌اندازی نشد. لطفاً مطمئن شوید این دستگاه به شبکه Wi-Fi یا اترنت محلی متصل است.", - "connect.save_as": "ذخیره به عنوان…" + "connect.save_as": "ذخیره به عنوان…", + "gallery.title": "گالری پیش‌تنظیم‌ها", + "gallery.open": "گالری پیش‌تنظیم‌ها", + "gallery.open_tip": "پیش‌تنظیم‌هایی که دیگران در filee.sh هم‌رسانی کرده‌اند", + "gallery.lead": "پیش‌تنظیم‌هایی که دیگران در filee.sh هم‌رسانی کرده‌اند. با نصب، به‌عنوان پیش‌تنظیم‌های جدید اضافه می‌شوند و پیش‌تنظیم‌های خودتان دست‌نخورده می‌مانند. Filee فقط وقتی این پنجره باز است به filee.sh وصل می‌شود.", + "gallery.sort": "مرتب‌سازی", + "gallery.sort.Hot": "داغ", + "gallery.sort.Best": "بهترین", + "gallery.sort.New": "جدید", + "gallery.period": "بازه", + "gallery.period.day": "امروز", + "gallery.period.week": "این هفته", + "gallery.period.month": "این ماه", + "gallery.period.year": "امسال", + "gallery.period.all": "همه زمان‌ها", + "gallery.filter.kind": "نوع", + "gallery.kind.all": "همه انواع", + "gallery.kind.convert": "تبدیل‌ها", + "gallery.kind.tool": "ابزارها", + "gallery.kind.toolbar": "نوارهای ابزار دونات", + "gallery.filter.format": "فرمت", + "gallery.format.all": "همه فرمت‌ها", + "gallery.filter.tag": "برچسب", + "gallery.tag.all": "همه برچسب‌ها", + "gallery.filter.language": "زبان", + "gallery.language.all": "همه زبان‌ها", + "gallery.loading": "در حال بارگیری پیش‌تنظیم‌ها از filee.sh…", + "gallery.failed": "اتصال به filee.sh ممکن نشد. اتصال اینترنت و پراکسی را در تنظیمات ← عمومی بررسی کنید و دوباره تلاش کنید.", + "gallery.empty": "هیچ پیش‌تنظیمی با جست‌وجو و فیلترها جور نیست.", + "gallery.none": "هنوز کسی پیش‌تنظیمی هم‌رسانی نکرده است.", + "gallery.newer": "{0} مورد دیگر به نسخه جدیدتری از Filee نیاز دارند.", + "gallery.by": "از {0}", + "gallery.likes": "{0} پسند", + "gallery.downloads": "{0} بارگیری", + "gallery.select": "یک پیش‌تنظیم انتخاب کنید تا تصاویر و کارش را ببینید.", + "gallery.image": "تصویر {0} از {1}", + "gallery.what": "آنچه اضافه می‌شود", + "gallery.what_group": "گروه: {0}", + "gallery.loading_details": "در حال بارگیری…", + "gallery.donut_new": "نوار ابزار دونات «{0}» را برای {1} اضافه می‌کند. فقط برای فایل‌هایی باز می‌شود که هیچ‌یک از دونات‌های شما آن‌ها را نمی‌گیرد؛ این را می‌توانید در تنظیمات ← نوار ابزار دونات تغییر دهید.", + "gallery.donut_mixed": "فایل‌های ترکیبی", + "gallery.donut_none": "روی هیچ دوناتی نیست: آن را در تنظیمات ← نوار ابزار دونات به یکی اضافه کنید.", + "gallery.license": "هم‌رسانی‌شده توسط {0} تحت CC0: استفاده، تغییر و هم‌رسانی آزاد است.", + "gallery.comments": "نظرها", + "gallery.install": "نصب", + "gallery.installing": "در حال نصب…", + "gallery.installed": "{0} پیش‌تنظیم اضافه شد. آن‌ها را در فهرست پیش‌تنظیم‌ها پیدا می‌کنید.", + "gallery.installed_donut": "{0} پیش‌تنظیم و نوار ابزار دونات «{1}» اضافه شد.", + "gallery.install_failed": "نصب ممکن نشد: {0}", + "gallery.not_installable": "این پیش‌تنظیم را نمی‌توان نصب کرد: {0}", + "gallery.download_failed": "بارگیری پیش‌تنظیم ممکن نشد. اتصال را بررسی کنید و دوباره تلاش کنید.", + "gallery.mismatch": "فایل بارگیری‌شده همان فایلی نیست که گالری فهرست کرده است، پس چیزی نصب نشد.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "حداکثر {0} MB", + "gallery.option.no_metadata": "فراداده را حذف می‌کند", + "gallery.option.merge": "در یک فایل ادغام می‌کند", + "gallery.option.pages": "صفحه‌های {0}", + "gallery.option.max_height": "تا {0}p", + "gallery.option.translate": "به {0} ترجمه می‌کند", + "gallery.option.ask_compression": "هر بار درباره فشرده‌سازی می‌پرسد", + "gallery.option.subfolder": "در پوشه «{0}» ذخیره می‌کند", + "gallery.option.file_name": "نام فایل: {0}" } diff --git a/src/Filee.App/Assets/i18n/fr.json b/src/Filee.App/Assets/i18n/fr.json index b08536140..1c6a47c72 100644 --- a/src/Filee.App/Assets/i18n/fr.json +++ b/src/Filee.App/Assets/i18n/fr.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "Code PIN :", "connect.firewall_hint_generic": "Remarque : Si votre téléphone ne peut pas se connecter, autorisez Filee dans le pare-feu du système.", "connect.no_network_message": "Impossible de démarrer Filee Connect. Veuillez vous assurer que cet appareil est connecté à un réseau Wi-Fi ou Ethernet local.", - "connect.save_as": "Enregistrer sous…" + "connect.save_as": "Enregistrer sous…", + "gallery.title": "Galerie de préréglages", + "gallery.open": "Galerie de préréglages", + "gallery.open_tip": "Préréglages partagés par d'autres sur filee.sh", + "gallery.lead": "Des préréglages partagés par d'autres sur filee.sh. Les installer les ajoute comme nouveaux préréglages, sans toucher aux vôtres. Filee ne contacte filee.sh que tant que cette fenêtre est ouverte.", + "gallery.sort": "Trier", + "gallery.sort.Hot": "Tendances", + "gallery.sort.Best": "Meilleurs", + "gallery.sort.New": "Nouveaux", + "gallery.period": "Période", + "gallery.period.day": "Aujourd'hui", + "gallery.period.week": "Cette semaine", + "gallery.period.month": "Ce mois-ci", + "gallery.period.year": "Cette année", + "gallery.period.all": "Depuis toujours", + "gallery.filter.kind": "Type", + "gallery.kind.all": "Tous les types", + "gallery.kind.convert": "Conversions", + "gallery.kind.tool": "Outils", + "gallery.kind.toolbar": "Menus circulaires", + "gallery.filter.format": "Format", + "gallery.format.all": "Tous les formats", + "gallery.filter.tag": "Étiquette", + "gallery.tag.all": "Toutes les étiquettes", + "gallery.filter.language": "Langue", + "gallery.language.all": "Toutes les langues", + "gallery.loading": "Chargement des préréglages depuis filee.sh…", + "gallery.failed": "Impossible de joindre filee.sh. Vérifiez la connexion Internet et le proxy dans Paramètres → Général, puis réessayez.", + "gallery.empty": "Aucun préréglage ne correspond à la recherche et aux filtres.", + "gallery.none": "Aucun préréglage n'a encore été partagé.", + "gallery.newer": "{0} autres demandent une version plus récente de Filee.", + "gallery.by": "par {0}", + "gallery.likes": "{0} j'aime", + "gallery.downloads": "{0} téléchargements", + "gallery.select": "Choisissez un préréglage pour voir ses images et ce qu'il fait.", + "gallery.image": "Image {0} sur {1}", + "gallery.what": "Ce qui est ajouté", + "gallery.what_group": "Groupe : {0}", + "gallery.loading_details": "Chargement…", + "gallery.donut_new": "Ajoute le menu circulaire « {0} » pour {1}. Il ne s'ouvre que pour les fichiers qu'aucun de vos menus ne prend ; vous pouvez changer cela dans Paramètres → Menu circulaire.", + "gallery.donut_mixed": "les fichiers mélangés", + "gallery.donut_none": "N'est sur aucun menu circulaire : ajoutez-le à l'un d'eux dans Paramètres → Menu circulaire.", + "gallery.license": "Partagé par {0} sous CC0 : libre d'utilisation, de modification et de partage.", + "gallery.comments": "Commentaires", + "gallery.install": "Installer", + "gallery.installing": "Installation…", + "gallery.installed": "{0} préréglage(s) ajouté(s). Ils sont dans la liste des préréglages.", + "gallery.installed_donut": "{0} préréglage(s) et le menu circulaire « {1} » ajoutés.", + "gallery.install_failed": "Installation impossible : {0}", + "gallery.not_installable": "Ce préréglage ne peut pas être installé : {0}", + "gallery.download_failed": "Impossible de télécharger le préréglage. Vérifiez la connexion et réessayez.", + "gallery.mismatch": "Le fichier téléchargé n'est pas celui indiqué par la galerie : rien n'a été installé.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "{0} Mo au plus", + "gallery.option.no_metadata": "Supprime les métadonnées", + "gallery.option.merge": "Fusionne en un seul fichier", + "gallery.option.pages": "Pages {0}", + "gallery.option.max_height": "Jusqu'à {0}p", + "gallery.option.translate": "Traduit en {0}", + "gallery.option.ask_compression": "Demande la compression à chaque fois", + "gallery.option.subfolder": "Enregistre dans le dossier « {0} »", + "gallery.option.file_name": "Nom de fichier : {0}" } diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json index 4a38f4f8c..d83d42a9e 100644 --- a/src/Filee.App/Assets/i18n/hi.json +++ b/src/Filee.App/Assets/i18n/hi.json @@ -1851,5 +1851,67 @@ "connect.pin_label": "पिन:", "connect.firewall_hint_generic": "नोट: यदि आपका फ़ोन कनेक्ट नहीं हो पा रहा है, तो सिस्टम फ़ायरवॉल में Filee को अनुमति दें।", "connect.no_network_message": "Filee Connect प्रारंभ नहीं किया जा सका। कृपया सुनिश्चित करें कि यह डिवाइस स्थानीय वाई-फ़ाई या ईथरनेट नेटवर्क से कनेक्ट है।", - "connect.save_as": "इस रूप में सहेजें…" + "connect.save_as": "इस रूप में सहेजें…", + "gallery.title": "प्रीसेट गैलरी", + "gallery.open": "प्रीसेट गैलरी", + "gallery.open_tip": "दूसरों द्वारा filee.sh पर साझा किए गए प्रीसेट", + "gallery.lead": "दूसरों द्वारा filee.sh पर साझा किए गए प्रीसेट। इंस्टॉल करने पर ये नए प्रीसेट के रूप में जुड़ते हैं और आपके प्रीसेट जैसे हैं वैसे ही रहते हैं। Filee केवल तभी filee.sh से जुड़ता है जब यह विंडो खुली हो।", + "gallery.sort": "क्रम", + "gallery.sort.Hot": "लोकप्रिय", + "gallery.sort.Best": "सर्वश्रेष्ठ", + "gallery.sort.New": "नए", + "gallery.period": "अवधि", + "gallery.period.day": "आज", + "gallery.period.week": "इस सप्ताह", + "gallery.period.month": "इस महीने", + "gallery.period.year": "इस साल", + "gallery.period.all": "अब तक", + "gallery.filter.kind": "प्रकार", + "gallery.kind.all": "सभी प्रकार", + "gallery.kind.convert": "रूपांतरण", + "gallery.kind.tool": "टूल", + "gallery.kind.toolbar": "डोनट टूलबार", + "gallery.filter.format": "फ़ॉर्मैट", + "gallery.format.all": "सभी फ़ॉर्मैट", + "gallery.filter.tag": "टैग", + "gallery.tag.all": "सभी टैग", + "gallery.filter.language": "भाषा", + "gallery.language.all": "सभी भाषाएँ", + "gallery.loading": "filee.sh से प्रीसेट लोड हो रहे हैं…", + "gallery.failed": "filee.sh से कनेक्ट नहीं हो सका। इंटरनेट कनेक्शन और सेटिंग्स → सामान्य में प्रॉक्सी जाँचें, फिर दोबारा कोशिश करें।", + "gallery.empty": "खोज और फ़िल्टर से मेल खाने वाला कोई प्रीसेट नहीं है।", + "gallery.none": "अभी तक कोई प्रीसेट साझा नहीं किया गया है।", + "gallery.newer": "{0} और प्रीसेट के लिए Filee का नया संस्करण चाहिए।", + "gallery.by": "{0} द्वारा", + "gallery.likes": "{0} पसंद", + "gallery.downloads": "{0} डाउनलोड", + "gallery.select": "प्रीसेट चुनें, ताकि उसकी तस्वीरें और वह क्या करता है, दिख सके।", + "gallery.image": "तस्वीर {0} / {1}", + "gallery.what": "क्या जुड़ेगा", + "gallery.what_group": "समूह: {0}", + "gallery.loading_details": "लोड हो रहा है…", + "gallery.donut_new": "{1} के लिए डोनट टूलबार “{0}” जोड़ता है। यह केवल उन फ़ाइलों के लिए खुलता है जिन्हें आपका कोई डोनट नहीं लेता; इसे सेटिंग्स → डोनट टूलबार में बदलें।", + "gallery.donut_mixed": "मिश्रित फ़ाइलों", + "gallery.donut_none": "किसी डोनट पर नहीं है: इसे सेटिंग्स → डोनट टूलबार में किसी एक में जोड़ें।", + "gallery.license": "{0} द्वारा CC0 के तहत साझा किया गया: उपयोग, बदलाव और साझा करने के लिए मुक्त।", + "gallery.comments": "टिप्पणियाँ", + "gallery.install": "इंस्टॉल करें", + "gallery.installing": "इंस्टॉल हो रहा है…", + "gallery.installed": "{0} प्रीसेट जोड़े गए। ये प्रीसेट सूची में हैं।", + "gallery.installed_donut": "{0} प्रीसेट और डोनट टूलबार “{1}” जोड़े गए।", + "gallery.install_failed": "इंस्टॉल नहीं हो सका: {0}", + "gallery.not_installable": "यह प्रीसेट इंस्टॉल नहीं किया जा सकता: {0}", + "gallery.download_failed": "प्रीसेट डाउनलोड नहीं हो सका। कनेक्शन जाँचकर दोबारा कोशिश करें।", + "gallery.mismatch": "डाउनलोड की गई फ़ाइल वह नहीं है जो गैलरी में दी गई है, इसलिए कुछ भी इंस्टॉल नहीं किया गया।", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "अधिकतम {0} MB", + "gallery.option.no_metadata": "मेटाडेटा हटाता है", + "gallery.option.merge": "एक फ़ाइल में जोड़ता है", + "gallery.option.pages": "पेज {0}", + "gallery.option.max_height": "{0}p तक", + "gallery.option.translate": "{0} में अनुवाद करता है", + "gallery.option.ask_compression": "हर बार कंप्रेशन पूछता है", + "gallery.option.subfolder": "फ़ोल्डर “{0}” में सहेजता है", + "gallery.option.file_name": "फ़ाइल नाम: {0}" } diff --git a/src/Filee.App/Assets/i18n/id.json b/src/Filee.App/Assets/i18n/id.json index 96d8c0066..ec9c2a872 100644 --- a/src/Filee.App/Assets/i18n/id.json +++ b/src/Filee.App/Assets/i18n/id.json @@ -1849,5 +1849,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Catatan: Jika ponsel Anda tidak dapat terhubung, izinkan Filee di firewall sistem.", "connect.no_network_message": "Tidak dapat memulai Filee Connect. Pastikan perangkat ini terhubung ke jaringan Wi-Fi atau Ethernet lokal.", - "connect.save_as": "Simpan sebagai…" + "connect.save_as": "Simpan sebagai…", + "gallery.title": "Galeri preset", + "gallery.open": "Galeri preset", + "gallery.open_tip": "Preset yang dibagikan orang lain di filee.sh", + "gallery.lead": "Preset yang dibagikan orang lain di filee.sh. Saat dipasang, preset ditambahkan sebagai preset baru dan milik Anda tetap seperti semula. Filee hanya terhubung ke filee.sh selama jendela ini terbuka.", + "gallery.sort": "Urutkan", + "gallery.sort.Hot": "Populer", + "gallery.sort.Best": "Terbaik", + "gallery.sort.New": "Terbaru", + "gallery.period": "Periode", + "gallery.period.day": "Hari ini", + "gallery.period.week": "Minggu ini", + "gallery.period.month": "Bulan ini", + "gallery.period.year": "Tahun ini", + "gallery.period.all": "Sepanjang waktu", + "gallery.filter.kind": "Jenis", + "gallery.kind.all": "Semua jenis", + "gallery.kind.convert": "Konversi", + "gallery.kind.tool": "Alat", + "gallery.kind.toolbar": "Toolbar donut", + "gallery.filter.format": "Format", + "gallery.format.all": "Semua format", + "gallery.filter.tag": "Tag", + "gallery.tag.all": "Semua tag", + "gallery.filter.language": "Bahasa", + "gallery.language.all": "Semua bahasa", + "gallery.loading": "Memuat preset dari filee.sh…", + "gallery.failed": "Tidak dapat menghubungi filee.sh. Periksa koneksi internet dan proxy di Pengaturan → Umum, lalu coba lagi.", + "gallery.empty": "Tidak ada preset yang cocok dengan pencarian dan filter.", + "gallery.none": "Belum ada preset yang dibagikan.", + "gallery.newer": "{0} lainnya memerlukan versi Filee yang lebih baru.", + "gallery.by": "oleh {0}", + "gallery.likes": "{0} suka", + "gallery.downloads": "{0} unduhan", + "gallery.select": "Pilih preset untuk melihat gambar dan fungsinya.", + "gallery.image": "Gambar {0} dari {1}", + "gallery.what": "Yang ditambahkan", + "gallery.what_group": "Grup: {0}", + "gallery.loading_details": "Memuat…", + "gallery.donut_new": "Menambahkan toolbar donut “{0}” untuk {1}. Toolbar ini hanya terbuka untuk file yang tidak ditangani toolbar donut Anda yang lain; ubah di Pengaturan → Toolbar donut.", + "gallery.donut_mixed": "file campuran", + "gallery.donut_none": "Tidak ada di toolbar donut mana pun: tambahkan ke salah satunya di Pengaturan → Toolbar donut.", + "gallery.license": "Dibagikan oleh {0} dengan CC0: bebas digunakan, diubah, dan dibagikan.", + "gallery.comments": "Komentar", + "gallery.install": "Pasang", + "gallery.installing": "Memasang…", + "gallery.installed": "{0} preset ditambahkan. Anda dapat menemukannya di daftar Preset.", + "gallery.installed_donut": "{0} preset dan toolbar donut “{1}” ditambahkan.", + "gallery.install_failed": "Tidak dapat memasang: {0}", + "gallery.not_installable": "Preset ini tidak dapat dipasang: {0}", + "gallery.download_failed": "Tidak dapat mengunduh preset. Periksa koneksi lalu coba lagi.", + "gallery.mismatch": "File yang diunduh bukan file yang tercantum di galeri, jadi tidak ada yang dipasang.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Paling besar {0} MB", + "gallery.option.no_metadata": "Menghapus metadata", + "gallery.option.merge": "Menggabungkan menjadi satu file", + "gallery.option.pages": "Halaman {0}", + "gallery.option.max_height": "Hingga {0}p", + "gallery.option.translate": "Menerjemahkan ke {0}", + "gallery.option.ask_compression": "Menanyakan kompresi setiap kali", + "gallery.option.subfolder": "Menyimpan di folder “{0}”", + "gallery.option.file_name": "Nama file: {0}" } diff --git a/src/Filee.App/Assets/i18n/it.json b/src/Filee.App/Assets/i18n/it.json index c3c54a568..7f1b26363 100644 --- a/src/Filee.App/Assets/i18n/it.json +++ b/src/Filee.App/Assets/i18n/it.json @@ -1848,5 +1848,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Nota: se il telefono non si connette, autorizza Filee nel firewall di sistema.", "connect.no_network_message": "Impossibile avviare Filee Connect. Assicurati che questo dispositivo sia connesso a una rete Wi-Fi o Ethernet locale.", - "connect.save_as": "Salva con nome…" + "connect.save_as": "Salva con nome…", + "gallery.title": "Galleria dei preset", + "gallery.open": "Galleria dei preset", + "gallery.open_tip": "Preset condivisi da altri su filee.sh", + "gallery.lead": "Preset condivisi da altre persone su filee.sh. Installandoli si aggiungono come nuovi preset e i tuoi restano come sono. Filee si collega a filee.sh solo mentre questa finestra è aperta.", + "gallery.sort": "Ordina", + "gallery.sort.Hot": "Di tendenza", + "gallery.sort.Best": "Migliori", + "gallery.sort.New": "Nuovi", + "gallery.period": "Periodo", + "gallery.period.day": "Oggi", + "gallery.period.week": "Questa settimana", + "gallery.period.month": "Questo mese", + "gallery.period.year": "Quest'anno", + "gallery.period.all": "Di sempre", + "gallery.filter.kind": "Tipo", + "gallery.kind.all": "Tutti i tipi", + "gallery.kind.convert": "Conversioni", + "gallery.kind.tool": "Strumenti", + "gallery.kind.toolbar": "Barre donut", + "gallery.filter.format": "Formato", + "gallery.format.all": "Tutti i formati", + "gallery.filter.tag": "Tag", + "gallery.tag.all": "Tutti i tag", + "gallery.filter.language": "Lingua", + "gallery.language.all": "Tutte le lingue", + "gallery.loading": "Caricamento dei preset da filee.sh…", + "gallery.failed": "Impossibile raggiungere filee.sh. Controlla la connessione a Internet e il proxy in Impostazioni → Generali, poi riprova.", + "gallery.empty": "Nessun preset corrisponde alla ricerca e ai filtri.", + "gallery.none": "Non è stato ancora condiviso nessun preset.", + "gallery.newer": "Altri {0} richiedono una versione più recente di Filee.", + "gallery.by": "di {0}", + "gallery.likes": "{0} Mi piace", + "gallery.downloads": "{0} download", + "gallery.select": "Scegli un preset per vederne le immagini e cosa fa.", + "gallery.image": "Immagine {0} di {1}", + "gallery.what": "Cosa aggiunge", + "gallery.what_group": "Gruppo: {0}", + "gallery.loading_details": "Caricamento…", + "gallery.donut_new": "Aggiunge la barra donut «{0}» per {1}. Si apre solo per i file che nessuna delle tue barre prende; puoi cambiarlo in Impostazioni → Barra donut.", + "gallery.donut_mixed": "file misti", + "gallery.donut_none": "Non va su nessuna barra donut: aggiungilo a una in Impostazioni → Barra donut.", + "gallery.license": "Condiviso da {0} con licenza CC0: libero da usare, modificare e condividere.", + "gallery.comments": "Commenti", + "gallery.install": "Installa", + "gallery.installing": "Installazione…", + "gallery.installed": "Aggiunti {0} preset. Li trovi nell'elenco dei preset.", + "gallery.installed_donut": "Aggiunti {0} preset e la barra donut «{1}».", + "gallery.install_failed": "Impossibile installare: {0}", + "gallery.not_installable": "Questo preset non può essere installato: {0}", + "gallery.download_failed": "Impossibile scaricare il preset. Controlla la connessione e riprova.", + "gallery.mismatch": "Il file scaricato non è quello indicato dalla galleria, quindi non è stato installato nulla.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Al massimo {0} MB", + "gallery.option.no_metadata": "Rimuove i metadati", + "gallery.option.merge": "Unisce in un solo file", + "gallery.option.pages": "Pagine {0}", + "gallery.option.max_height": "Fino a {0}p", + "gallery.option.translate": "Traduce in {0}", + "gallery.option.ask_compression": "Chiede ogni volta la compressione", + "gallery.option.subfolder": "Salva nella cartella «{0}»", + "gallery.option.file_name": "Nome file: {0}" } diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json index b4dfcfc96..dfcfd36c0 100644 --- a/src/Filee.App/Assets/i18n/ja.json +++ b/src/Filee.App/Assets/i18n/ja.json @@ -1851,5 +1851,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "注: スマートフォンが接続できない場合は、システムファイアウォールでFileeを許可してください。", "connect.no_network_message": "Filee Connectを開始できませんでした。このデバイスがローカルのWi-Fiまたは有線LANネットワークに接続されていることを確認してください。", - "connect.save_as": "名前を付けて保存…" + "connect.save_as": "名前を付けて保存…", + "gallery.title": "プリセットギャラリー", + "gallery.open": "プリセットギャラリー", + "gallery.open_tip": "ほかの人が filee.sh で共有したプリセット", + "gallery.lead": "ほかの人が filee.sh で共有したプリセットです。インストールすると新しいプリセットとして追加され、自分のプリセットはそのまま残ります。filee.sh に接続するのは、このウィンドウを開いている間だけです。", + "gallery.sort": "並べ替え", + "gallery.sort.Hot": "人気", + "gallery.sort.Best": "ベスト", + "gallery.sort.New": "新着", + "gallery.period": "期間", + "gallery.period.day": "今日", + "gallery.period.week": "今週", + "gallery.period.month": "今月", + "gallery.period.year": "今年", + "gallery.period.all": "全期間", + "gallery.filter.kind": "種類", + "gallery.kind.all": "すべての種類", + "gallery.kind.convert": "変換", + "gallery.kind.tool": "ツール", + "gallery.kind.toolbar": "ドーナツメニュー", + "gallery.filter.format": "形式", + "gallery.format.all": "すべての形式", + "gallery.filter.tag": "タグ", + "gallery.tag.all": "すべてのタグ", + "gallery.filter.language": "言語", + "gallery.language.all": "すべての言語", + "gallery.loading": "filee.sh からプリセットを読み込んでいます…", + "gallery.failed": "filee.sh に接続できません。インターネット接続と「設定」→「一般」のプロキシを確認してから、もう一度お試しください。", + "gallery.empty": "検索とフィルターに合うプリセットはありません。", + "gallery.none": "共有されたプリセットはまだありません。", + "gallery.newer": "ほかに {0} 件は、より新しい Filee が必要です。", + "gallery.by": "{0} さん", + "gallery.likes": "いいね {0}", + "gallery.downloads": "ダウンロード {0}", + "gallery.select": "プリセットを選ぶと、画像と内容が表示されます。", + "gallery.image": "画像 {0}/{1}", + "gallery.what": "追加されるもの", + "gallery.what_group": "グループ: {0}", + "gallery.loading_details": "読み込み中…", + "gallery.donut_new": "ドーナツメニュー「{0}」を {1} 用に追加します。自分のどのドーナツメニューも扱わないファイルでだけ開きます。「設定」→「ドーナツメニュー」で変更できます。", + "gallery.donut_mixed": "複数の種類のファイル", + "gallery.donut_none": "どのドーナツメニューにも入りません。「設定」→「ドーナツメニュー」で追加できます。", + "gallery.license": "{0} さんが CC0 で共有しました。自由に使用、変更、共有できます。", + "gallery.comments": "コメント", + "gallery.install": "インストール", + "gallery.installing": "インストールしています…", + "gallery.installed": "{0} 個のプリセットを追加しました。プリセットの一覧にあります。", + "gallery.installed_donut": "{0} 個のプリセットとドーナツメニュー「{1}」を追加しました。", + "gallery.install_failed": "インストールできませんでした: {0}", + "gallery.not_installable": "このプリセットはインストールできません: {0}", + "gallery.download_failed": "プリセットをダウンロードできませんでした。接続を確認して、もう一度お試しください。", + "gallery.mismatch": "ダウンロードしたファイルがギャラリーに載っているものと違うため、何もインストールしませんでした。", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "最大 {0} MB", + "gallery.option.no_metadata": "メタデータを削除", + "gallery.option.merge": "1 つのファイルに結合", + "gallery.option.pages": "ページ {0}", + "gallery.option.max_height": "最大 {0}p", + "gallery.option.translate": "{0}に翻訳", + "gallery.option.ask_compression": "毎回圧縮率を確認", + "gallery.option.subfolder": "フォルダー「{0}」に保存", + "gallery.option.file_name": "ファイル名: {0}" } diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json index c1fb69441..0cbdc3368 100644 --- a/src/Filee.App/Assets/i18n/ko.json +++ b/src/Filee.App/Assets/i18n/ko.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "참고: 휴대폰이 연결되지 않으면 시스템 방화벽에서 Filee를 허용하세요.", "connect.no_network_message": "Filee Connect를 시작할 수 없습니다. 이 기기가 로컬 Wi-Fi 또는 이더넷 네트워크에 연결되어 있는지 확인하세요.", - "connect.save_as": "다른 이름으로 저장…" + "connect.save_as": "다른 이름으로 저장…", + "gallery.title": "프리셋 갤러리", + "gallery.open": "프리셋 갤러리", + "gallery.open_tip": "다른 사람들이 filee.sh에 공유한 프리셋", + "gallery.lead": "다른 사람들이 filee.sh에 공유한 프리셋이에요. 설치하면 새 프리셋으로 추가되고, 내 프리셋은 그대로 남아요. 이 창이 열려 있는 동안에만 filee.sh에 연결해요.", + "gallery.sort": "정렬", + "gallery.sort.Hot": "인기", + "gallery.sort.Best": "베스트", + "gallery.sort.New": "최신", + "gallery.period": "기간", + "gallery.period.day": "오늘", + "gallery.period.week": "이번 주", + "gallery.period.month": "이번 달", + "gallery.period.year": "올해", + "gallery.period.all": "전체 기간", + "gallery.filter.kind": "종류", + "gallery.kind.all": "모든 종류", + "gallery.kind.convert": "변환", + "gallery.kind.tool": "도구", + "gallery.kind.toolbar": "원형 툴바", + "gallery.filter.format": "형식", + "gallery.format.all": "모든 형식", + "gallery.filter.tag": "태그", + "gallery.tag.all": "모든 태그", + "gallery.filter.language": "언어", + "gallery.language.all": "모든 언어", + "gallery.loading": "filee.sh에서 프리셋을 불러오는 중…", + "gallery.failed": "filee.sh에 연결할 수 없어요. 인터넷 연결과 설정 → 일반의 프록시를 확인한 뒤 다시 시도해 주세요.", + "gallery.empty": "검색어와 필터에 맞는 프리셋이 없어요.", + "gallery.none": "아직 공유된 프리셋이 없어요.", + "gallery.newer": "{0}개는 더 새로운 Filee가 필요해요.", + "gallery.by": "{0} 님", + "gallery.likes": "좋아요 {0}", + "gallery.downloads": "다운로드 {0}", + "gallery.select": "프리셋을 고르면 그림과 하는 일을 볼 수 있어요.", + "gallery.image": "그림 {0}/{1}", + "gallery.what": "추가되는 것", + "gallery.what_group": "묶음: {0}", + "gallery.loading_details": "불러오는 중…", + "gallery.donut_new": "원형 툴바 “{0}”를 {1}용으로 추가해요. 내 원형 툴바가 맡지 않는 파일에서만 열리고, 설정 → 원형 툴바에서 바꿀 수 있어요.", + "gallery.donut_mixed": "여러 종류의 파일", + "gallery.donut_none": "원형 툴바에는 올라가지 않아요. 설정 → 원형 툴바에서 넣을 수 있어요.", + "gallery.license": "{0} 님이 CC0로 공유했어요. 누구나 자유롭게 쓰고 고치고 나눌 수 있어요.", + "gallery.comments": "댓글", + "gallery.install": "설치", + "gallery.installing": "설치하는 중…", + "gallery.installed": "프리셋 {0}개를 추가했어요. 프리셋 목록에서 찾을 수 있어요.", + "gallery.installed_donut": "프리셋 {0}개와 원형 툴바 “{1}”를 추가했어요.", + "gallery.install_failed": "설치하지 못했어요: {0}", + "gallery.not_installable": "이 프리셋은 설치할 수 없어요: {0}", + "gallery.download_failed": "프리셋을 내려받지 못했어요. 연결을 확인하고 다시 시도해 주세요.", + "gallery.mismatch": "내려받은 파일이 갤러리에 올라온 파일과 달라서 아무것도 설치하지 않았어요.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "최대 {0} MB", + "gallery.option.no_metadata": "메타데이터 제거", + "gallery.option.merge": "파일 하나로 합치기", + "gallery.option.pages": "{0} 페이지", + "gallery.option.max_height": "최대 {0}p", + "gallery.option.translate": "{0}(으)로 번역", + "gallery.option.ask_compression": "매번 압축 정도를 물어봄", + "gallery.option.subfolder": "“{0}” 폴더에 저장", + "gallery.option.file_name": "파일 이름: {0}" } diff --git a/src/Filee.App/Assets/i18n/mn.json b/src/Filee.App/Assets/i18n/mn.json index fa528de85..44329b032 100644 --- a/src/Filee.App/Assets/i18n/mn.json +++ b/src/Filee.App/Assets/i18n/mn.json @@ -1825,5 +1825,67 @@ "connect.pin_label": "ПИН:", "connect.firewall_hint_generic": "Тэмдэглэл: Хэрэв таны утас холбогдохгүй бол системийн галт хана (firewall) дотор Filee-г зөвшөөрнө үү.", "connect.no_network_message": "Filee Connect-ийг эхлүүлж чадсангүй. Энэ төхөөрөмж дотоод Wi-Fi эсвэл Ethernet сүлжээнд холбогдсон эсэхийг шалгана уу.", - "connect.save_as": "Өөрөөр хадгалах…" + "connect.save_as": "Өөрөөр хадгалах…", + "gallery.title": "Урьдчилсан тохиргооны цомог", + "gallery.open": "Урьдчилсан тохиргооны цомог", + "gallery.open_tip": "Бусдын filee.sh дээр хуваалцсан урьдчилсан тохиргоонууд", + "gallery.lead": "Бусдын filee.sh дээр хуваалцсан урьдчилсан тохиргоонууд. Суулгахад шинэ урьдчилсан тохиргоо болж нэмэгдэх бөгөөд таны өөрийнх хэвээрээ үлдэнэ. Filee зөвхөн энэ цонх нээлттэй байх үед filee.sh-тэй холбогдоно.", + "gallery.sort": "Эрэмбэлэх", + "gallery.sort.Hot": "Эрэлттэй", + "gallery.sort.Best": "Шилдэг", + "gallery.sort.New": "Шинэ", + "gallery.period": "Хугацаа", + "gallery.period.day": "Өнөөдөр", + "gallery.period.week": "Энэ долоо хоног", + "gallery.period.month": "Энэ сар", + "gallery.period.year": "Энэ жил", + "gallery.period.all": "Бүх цаг үе", + "gallery.filter.kind": "Төрөл", + "gallery.kind.all": "Бүх төрөл", + "gallery.kind.convert": "Хөрвүүлэлт", + "gallery.kind.tool": "Хэрэгсэл", + "gallery.kind.toolbar": "Цагираг самбар", + "gallery.filter.format": "Формат", + "gallery.format.all": "Бүх формат", + "gallery.filter.tag": "Шошго", + "gallery.tag.all": "Бүх шошго", + "gallery.filter.language": "Хэл", + "gallery.language.all": "Бүх хэл", + "gallery.loading": "filee.sh-ээс урьдчилсан тохиргоонуудыг ачаалж байна…", + "gallery.failed": "filee.sh-тэй холбогдож чадсангүй. Интернэт холболт болон Тохиргоо → Ерөнхий хэсгийн проксиг шалгаад дахин оролдоно уу.", + "gallery.empty": "Хайлт болон шүүлтүүрт тохирох урьдчилсан тохиргоо алга.", + "gallery.none": "Одоогоор хуваалцсан урьдчилсан тохиргоо алга.", + "gallery.newer": "Өөр {0} нь Filee-гийн шинэ хувилбар шаардана.", + "gallery.by": "Нийтэлсэн: {0}", + "gallery.likes": "{0} таалагдсан", + "gallery.downloads": "{0} татсан", + "gallery.select": "Зураг болон юу хийдгийг нь харахын тулд урьдчилсан тохиргоо сонгоно уу.", + "gallery.image": "Зураг {0}/{1}", + "gallery.what": "Нэмэгдэх зүйл", + "gallery.what_group": "Бүлэг: {0}", + "gallery.loading_details": "Ачаалж байна…", + "gallery.donut_new": "{1}-д зориулсан “{0}” цагираг самбарыг нэмнэ. Таны аль ч цагираг самбар авдаггүй файлд л нээгдэнэ; үүнийг Тохиргоо → Цагираг самбар хэсгээс өөрчилж болно.", + "gallery.donut_mixed": "холимог файл", + "gallery.donut_none": "Аль ч цагираг самбарт ороогүй: Тохиргоо → Цагираг самбар хэсгээс аль нэгэнд нь нэмнэ үү.", + "gallery.license": "{0} CC0 лицензээр хуваалцсан: чөлөөтэй ашиглаж, өөрчилж, түгээж болно.", + "gallery.comments": "Сэтгэгдэл", + "gallery.install": "Суулгах", + "gallery.installing": "Суулгаж байна…", + "gallery.installed": "{0} урьдчилсан тохиргоо нэмэгдлээ. Урьдчилсан тохиргооны жагсаалтаас олно уу.", + "gallery.installed_donut": "{0} урьдчилсан тохиргоо болон “{1}” цагираг самбар нэмэгдлээ.", + "gallery.install_failed": "Суулгаж чадсангүй: {0}", + "gallery.not_installable": "Энэ урьдчилсан тохиргоог суулгах боломжгүй: {0}", + "gallery.download_failed": "Урьдчилсан тохиргоог татаж чадсангүй. Холболтоо шалгаад дахин оролдоно уу.", + "gallery.mismatch": "Татсан файл нь цомогт заасан файл биш тул юу ч суулгаагүй.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Дээд тал нь {0} MB", + "gallery.option.no_metadata": "Мета өгөгдлийг устгана", + "gallery.option.merge": "Нэг файл болгон нэгтгэнэ", + "gallery.option.pages": "Хуудас {0}", + "gallery.option.max_height": "{0}p хүртэл", + "gallery.option.translate": "{0} хэл рүү орчуулна", + "gallery.option.ask_compression": "Шахалтыг тухай бүр асууна", + "gallery.option.subfolder": "“{0}” хавтаст хадгална", + "gallery.option.file_name": "Файлын нэр: {0}" } diff --git a/src/Filee.App/Assets/i18n/ne.json b/src/Filee.App/Assets/i18n/ne.json index 1037c1caf..dd6b1899a 100644 --- a/src/Filee.App/Assets/i18n/ne.json +++ b/src/Filee.App/Assets/i18n/ne.json @@ -1851,5 +1851,67 @@ "connect.pin_label": "पिन:", "connect.firewall_hint_generic": "नोट: यदि तपाईंको फोन जडान हुन सकेन भने, प्रणाली फायरवालमा Filee लाई अनुमति दिनुहोस्।", "connect.no_network_message": "Filee Connect सुरु गर्न सकिएन। कृपया यो यन्त्र स्थानीय Wi-Fi वा इथरनेट नेटवर्कमा जडान भएको निश्चित गर्नुहोस्।", - "connect.save_as": "यस रूपमा बचत गर्नुहोस्…" + "connect.save_as": "यस रूपमा बचत गर्नुहोस्…", + "gallery.title": "प्रिसेट ग्यालरी", + "gallery.open": "प्रिसेट ग्यालरी", + "gallery.open_tip": "अरूले filee.sh मा साझा गरेका प्रिसेटहरू", + "gallery.lead": "अरूले filee.sh मा साझा गरेका प्रिसेटहरू। स्थापना गर्दा यी नयाँ प्रिसेटका रूपमा थपिन्छन् र तपाईंका प्रिसेटहरू जस्ताको तस्तै रहन्छन्। यो विन्डो खुला हुँदा मात्र Filee ले filee.sh सँग जडान गर्छ।", + "gallery.sort": "क्रम", + "gallery.sort.Hot": "लोकप्रिय", + "gallery.sort.Best": "उत्कृष्ट", + "gallery.sort.New": "नयाँ", + "gallery.period": "अवधि", + "gallery.period.day": "आज", + "gallery.period.week": "यो हप्ता", + "gallery.period.month": "यो महिना", + "gallery.period.year": "यो वर्ष", + "gallery.period.all": "सबै समय", + "gallery.filter.kind": "प्रकार", + "gallery.kind.all": "सबै प्रकार", + "gallery.kind.convert": "रूपान्तरणहरू", + "gallery.kind.tool": "उपकरणहरू", + "gallery.kind.toolbar": "डोनट टुलबारहरू", + "gallery.filter.format": "ढाँचा", + "gallery.format.all": "सबै ढाँचा", + "gallery.filter.tag": "ट्याग", + "gallery.tag.all": "सबै ट्याग", + "gallery.filter.language": "भाषा", + "gallery.language.all": "सबै भाषा", + "gallery.loading": "filee.sh बाट प्रिसेटहरू लोड हुँदैछन्…", + "gallery.failed": "filee.sh सँग जडान हुन सकेन। इन्टरनेट जडान र सेटिङहरू → सामान्यमा प्रोक्सी जाँच गरेर फेरि प्रयास गर्नुहोस्।", + "gallery.empty": "खोज र फिल्टरसँग मिल्ने कुनै प्रिसेट छैन।", + "gallery.none": "अहिलेसम्म कुनै प्रिसेट साझा गरिएको छैन।", + "gallery.newer": "थप {0} लाई Filee को नयाँ संस्करण चाहिन्छ।", + "gallery.by": "{0} द्वारा", + "gallery.likes": "{0} मन पराइएको", + "gallery.downloads": "{0} डाउनलोड", + "gallery.select": "प्रिसेट छान्नुहोस्; त्यसका तस्बिर र त्यसले के गर्छ भन्ने देखिन्छ।", + "gallery.image": "तस्बिर {0} / {1}", + "gallery.what": "के थपिन्छ", + "gallery.what_group": "समूह: {0}", + "gallery.loading_details": "लोड हुँदैछ…", + "gallery.donut_new": "{1} का लागि डोनट टुलबार “{0}” थप्छ। यो तपाईंको कुनै पनि डोनटले नलिने फाइलहरूमा मात्र खुल्छ; यसलाई सेटिङहरू → डोनट टुलबारमा परिवर्तन गर्नुहोस्।", + "gallery.donut_mixed": "मिश्रित फाइलहरू", + "gallery.donut_none": "कुनै डोनटमा छैन: सेटिङहरू → डोनट टुलबारमा कुनै एकमा थप्नुहोस्।", + "gallery.license": "{0} ले CC0 अन्तर्गत साझा गर्नुभएको: प्रयोग, परिवर्तन र साझा गर्न स्वतन्त्र।", + "gallery.comments": "टिप्पणीहरू", + "gallery.install": "स्थापना गर्नुहोस्", + "gallery.installing": "स्थापना हुँदैछ…", + "gallery.installed": "{0} प्रिसेट थपियो। तिनीहरू प्रिसेटहरूको सूचीमा छन्।", + "gallery.installed_donut": "{0} प्रिसेट र डोनट टुलबार “{1}” थपियो।", + "gallery.install_failed": "स्थापना गर्न सकिएन: {0}", + "gallery.not_installable": "यो प्रिसेट स्थापना गर्न सकिँदैन: {0}", + "gallery.download_failed": "प्रिसेट डाउनलोड गर्न सकिएन। जडान जाँचेर फेरि प्रयास गर्नुहोस्।", + "gallery.mismatch": "डाउनलोड गरिएको फाइल ग्यालरीले देखाएको फाइल होइन, त्यसैले केही पनि स्थापना गरिएन।", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "बढीमा {0} MB", + "gallery.option.no_metadata": "मेटाडाटा हटाउँछ", + "gallery.option.merge": "एउटै फाइलमा जोड्छ", + "gallery.option.pages": "पृष्ठ {0}", + "gallery.option.max_height": "{0}p सम्म", + "gallery.option.translate": "{0} मा अनुवाद गर्छ", + "gallery.option.ask_compression": "हरेक पटक कम्प्रेसन सोध्छ", + "gallery.option.subfolder": "“{0}” फोल्डरमा सेभ गर्छ", + "gallery.option.file_name": "फाइल नाम: {0}" } diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json index bb64aceae..49b0cdb7c 100644 --- a/src/Filee.App/Assets/i18n/pl.json +++ b/src/Filee.App/Assets/i18n/pl.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Uwaga: jeśli telefon nie może się połączyć, zezwól na Filee w zaporze systemowej.", "connect.no_network_message": "Nie można uruchomić Filee Connect. Upewnij się, że to urządzenie jest połączone z lokalną siecią Wi-Fi lub Ethernet.", - "connect.save_as": "Zapisz jako…" + "connect.save_as": "Zapisz jako…", + "gallery.title": "Galeria ustawień wstępnych", + "gallery.open": "Galeria ustawień wstępnych", + "gallery.open_tip": "Ustawienia wstępne udostępnione przez innych na filee.sh", + "gallery.lead": "Ustawienia wstępne, które inni udostępnili na filee.sh. Instalacja dodaje je jako nowe ustawienia, a Twoje zostają bez zmian. Filee łączy się z filee.sh tylko wtedy, gdy to okno jest otwarte.", + "gallery.sort": "Sortuj", + "gallery.sort.Hot": "Popularne", + "gallery.sort.Best": "Najlepsze", + "gallery.sort.New": "Nowe", + "gallery.period": "Okres", + "gallery.period.day": "Dziś", + "gallery.period.week": "Ten tydzień", + "gallery.period.month": "Ten miesiąc", + "gallery.period.year": "Ten rok", + "gallery.period.all": "Cały czas", + "gallery.filter.kind": "Rodzaj", + "gallery.kind.all": "Wszystkie rodzaje", + "gallery.kind.convert": "Konwersje", + "gallery.kind.tool": "Narzędzia", + "gallery.kind.toolbar": "Paski-pierścienie", + "gallery.filter.format": "Format", + "gallery.format.all": "Wszystkie formaty", + "gallery.filter.tag": "Tag", + "gallery.tag.all": "Wszystkie tagi", + "gallery.filter.language": "Język", + "gallery.language.all": "Wszystkie języki", + "gallery.loading": "Wczytywanie ustawień z filee.sh…", + "gallery.failed": "Nie można połączyć się z filee.sh. Sprawdź połączenie z internetem i serwer proxy w Ustawienia → Ogólne, a potem spróbuj ponownie.", + "gallery.empty": "Żadne ustawienie nie pasuje do wyszukiwania i filtrów.", + "gallery.none": "Nikt jeszcze nie udostępnił ustawień.", + "gallery.newer": "Jeszcze {0} wymaga nowszej wersji Filee.", + "gallery.by": "autor: {0}", + "gallery.likes": "Polubienia: {0}", + "gallery.downloads": "Pobrania: {0}", + "gallery.select": "Wybierz ustawienie, aby zobaczyć jego obrazy i to, co robi.", + "gallery.image": "Obraz {0} z {1}", + "gallery.what": "Co zostanie dodane", + "gallery.what_group": "Grupa: {0}", + "gallery.loading_details": "Wczytywanie…", + "gallery.donut_new": "Dodaje pasek-pierścień „{0}” dla {1}. Otwiera się tylko dla plików, których nie obsługuje żaden z Twoich pasków; zmienisz to w Ustawienia → Pasek-pierścień.", + "gallery.donut_mixed": "plików mieszanych", + "gallery.donut_none": "Nie trafia na żaden pasek-pierścień: dodaj je do któregoś w Ustawienia → Pasek-pierścień.", + "gallery.license": "Udostępnione przez {0} na licencji CC0: można swobodnie używać, zmieniać i udostępniać.", + "gallery.comments": "Komentarze", + "gallery.install": "Zainstaluj", + "gallery.installing": "Instalowanie…", + "gallery.installed": "Dodano ustawienia: {0}. Znajdziesz je na liście ustawień.", + "gallery.installed_donut": "Dodano ustawienia: {0} oraz pasek-pierścień „{1}”.", + "gallery.install_failed": "Nie udało się zainstalować: {0}", + "gallery.not_installable": "Tego ustawienia nie można zainstalować: {0}", + "gallery.download_failed": "Nie udało się pobrać ustawienia. Sprawdź połączenie i spróbuj ponownie.", + "gallery.mismatch": "Pobrany plik nie jest tym, który podaje galeria, więc nic nie zainstalowano.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Najwyżej {0} MB", + "gallery.option.no_metadata": "Usuwa metadane", + "gallery.option.merge": "Łączy w jeden plik", + "gallery.option.pages": "Strony {0}", + "gallery.option.max_height": "Do {0}p", + "gallery.option.translate": "Tłumaczy na: {0}", + "gallery.option.ask_compression": "Za każdym razem pyta o kompresję", + "gallery.option.subfolder": "Zapisuje w folderze „{0}”", + "gallery.option.file_name": "Nazwa pliku: {0}" } diff --git a/src/Filee.App/Assets/i18n/pt-BR.json b/src/Filee.App/Assets/i18n/pt-BR.json index cbec29537..7dddc080a 100644 --- a/src/Filee.App/Assets/i18n/pt-BR.json +++ b/src/Filee.App/Assets/i18n/pt-BR.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Observação: se o seu celular não conseguir se conectar, permita o Filee no firewall do sistema.", "connect.no_network_message": "Não foi possível iniciar o Filee Connect. Certifique-se de que este dispositivo esteja conectado a uma rede Wi-Fi ou Ethernet local.", - "connect.save_as": "Salvar como…" + "connect.save_as": "Salvar como…", + "gallery.title": "Galeria de predefinições", + "gallery.open": "Galeria de predefinições", + "gallery.open_tip": "Predefinições que outras pessoas compartilharam no filee.sh", + "gallery.lead": "Predefinições que outras pessoas compartilharam no filee.sh. Ao instalar, elas entram como novas predefinições e as suas ficam como estão. O Filee só se conecta ao filee.sh enquanto esta janela está aberta.", + "gallery.sort": "Ordenar", + "gallery.sort.Hot": "Em alta", + "gallery.sort.Best": "Melhores", + "gallery.sort.New": "Novas", + "gallery.period": "Período", + "gallery.period.day": "Hoje", + "gallery.period.week": "Esta semana", + "gallery.period.month": "Este mês", + "gallery.period.year": "Este ano", + "gallery.period.all": "Desde sempre", + "gallery.filter.kind": "Tipo", + "gallery.kind.all": "Todos os tipos", + "gallery.kind.convert": "Conversões", + "gallery.kind.tool": "Ferramentas", + "gallery.kind.toolbar": "Menus circulares", + "gallery.filter.format": "Formato", + "gallery.format.all": "Todos os formatos", + "gallery.filter.tag": "Tag", + "gallery.tag.all": "Todas as tags", + "gallery.filter.language": "Idioma", + "gallery.language.all": "Todos os idiomas", + "gallery.loading": "Carregando predefinições do filee.sh…", + "gallery.failed": "Não foi possível acessar o filee.sh. Verifique a conexão com a internet e o proxy em Configurações → Geral e tente de novo.", + "gallery.empty": "Nenhuma predefinição corresponde à busca e aos filtros.", + "gallery.none": "Ninguém compartilhou predefinições ainda.", + "gallery.newer": "Mais {0} precisam de uma versão mais nova do Filee.", + "gallery.by": "por {0}", + "gallery.likes": "{0} curtidas", + "gallery.downloads": "{0} downloads", + "gallery.select": "Escolha uma predefinição para ver as imagens e o que ela faz.", + "gallery.image": "Imagem {0} de {1}", + "gallery.what": "O que é adicionado", + "gallery.what_group": "Grupo: {0}", + "gallery.loading_details": "Carregando…", + "gallery.donut_new": "Adiciona o menu circular “{0}” para {1}. Ele só abre para arquivos que nenhum dos seus menus pega; mude isso em Configurações → Menu circular.", + "gallery.donut_mixed": "arquivos mistos", + "gallery.donut_none": "Não fica em nenhum menu circular: adicione a um em Configurações → Menu circular.", + "gallery.license": "Compartilhado por {0} sob CC0: livre para usar, alterar e compartilhar.", + "gallery.comments": "Comentários", + "gallery.install": "Instalar", + "gallery.installing": "Instalando…", + "gallery.installed": "{0} predefinição(ões) adicionada(s). Estão na lista de predefinições.", + "gallery.installed_donut": "{0} predefinição(ões) e o menu circular “{1}” adicionados.", + "gallery.install_failed": "Não foi possível instalar: {0}", + "gallery.not_installable": "Esta predefinição não pode ser instalada: {0}", + "gallery.download_failed": "Não foi possível baixar a predefinição. Verifique a conexão e tente de novo.", + "gallery.mismatch": "O arquivo baixado não é o que a galeria indica, então nada foi instalado.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "No máximo {0} MB", + "gallery.option.no_metadata": "Remove os metadados", + "gallery.option.merge": "Junta em um só arquivo", + "gallery.option.pages": "Páginas {0}", + "gallery.option.max_height": "Até {0}p", + "gallery.option.translate": "Traduz para {0}", + "gallery.option.ask_compression": "Pergunta a compressão toda vez", + "gallery.option.subfolder": "Salva na pasta “{0}”", + "gallery.option.file_name": "Nome do arquivo: {0}" } diff --git a/src/Filee.App/Assets/i18n/pt-PT.json b/src/Filee.App/Assets/i18n/pt-PT.json index a7c27a580..d026a919e 100644 --- a/src/Filee.App/Assets/i18n/pt-PT.json +++ b/src/Filee.App/Assets/i18n/pt-PT.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Nota: se o seu telemóvel não conseguir ligar-se, permita o Filee na firewall do sistema.", "connect.no_network_message": "Não foi possível iniciar o Filee Connect. Certifique-se de que este dispositivo está ligado a uma rede Wi-Fi ou Ethernet local.", - "connect.save_as": "Guardar como…" + "connect.save_as": "Guardar como…", + "gallery.title": "Galeria de predefinições", + "gallery.open": "Galeria de predefinições", + "gallery.open_tip": "Predefinições que outras pessoas partilharam no filee.sh", + "gallery.lead": "Predefinições que outras pessoas partilharam no filee.sh. Ao instalar, são adicionadas como novas predefinições e as tuas ficam como estão. O Filee só contacta o filee.sh enquanto esta janela está aberta.", + "gallery.sort": "Ordenar", + "gallery.sort.Hot": "Em destaque", + "gallery.sort.Best": "Melhores", + "gallery.sort.New": "Novas", + "gallery.period": "Período", + "gallery.period.day": "Hoje", + "gallery.period.week": "Esta semana", + "gallery.period.month": "Este mês", + "gallery.period.year": "Este ano", + "gallery.period.all": "Desde sempre", + "gallery.filter.kind": "Tipo", + "gallery.kind.all": "Todos os tipos", + "gallery.kind.convert": "Conversões", + "gallery.kind.tool": "Ferramentas", + "gallery.kind.toolbar": "Barras circulares", + "gallery.filter.format": "Formato", + "gallery.format.all": "Todos os formatos", + "gallery.filter.tag": "Etiqueta", + "gallery.tag.all": "Todas as etiquetas", + "gallery.filter.language": "Idioma", + "gallery.language.all": "Todos os idiomas", + "gallery.loading": "A carregar predefinições do filee.sh…", + "gallery.failed": "Não foi possível contactar o filee.sh. Verifica a ligação à Internet e o proxy em Definições → Geral e tenta novamente.", + "gallery.empty": "Nenhuma predefinição corresponde à pesquisa e aos filtros.", + "gallery.none": "Ainda ninguém partilhou predefinições.", + "gallery.newer": "Mais {0} precisam de uma versão mais recente do Filee.", + "gallery.by": "por {0}", + "gallery.likes": "{0} gostos", + "gallery.downloads": "{0} transferências", + "gallery.select": "Escolhe uma predefinição para veres as imagens e o que faz.", + "gallery.image": "Imagem {0} de {1}", + "gallery.what": "O que é adicionado", + "gallery.what_group": "Grupo: {0}", + "gallery.loading_details": "A carregar…", + "gallery.donut_new": "Adiciona a barra circular “{0}” para {1}. Só abre para ficheiros que nenhuma das tuas barras trata; podes mudar isso em Definições → Barra circular.", + "gallery.donut_mixed": "ficheiros mistos", + "gallery.donut_none": "Não fica em nenhuma barra circular: adiciona-a a uma em Definições → Barra circular.", + "gallery.license": "Partilhado por {0} sob CC0: livre para usar, alterar e partilhar.", + "gallery.comments": "Comentários", + "gallery.install": "Instalar", + "gallery.installing": "A instalar…", + "gallery.installed": "{0} predefinição(ões) adicionada(s). Estão na lista de predefinições.", + "gallery.installed_donut": "{0} predefinição(ões) e a barra circular “{1}” adicionadas.", + "gallery.install_failed": "Não foi possível instalar: {0}", + "gallery.not_installable": "Esta predefinição não pode ser instalada: {0}", + "gallery.download_failed": "Não foi possível transferir a predefinição. Verifica a ligação e tenta novamente.", + "gallery.mismatch": "O ficheiro transferido não é o que a galeria indica, por isso nada foi instalado.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "No máximo {0} MB", + "gallery.option.no_metadata": "Remove os metadados", + "gallery.option.merge": "Junta num só ficheiro", + "gallery.option.pages": "Páginas {0}", + "gallery.option.max_height": "Até {0}p", + "gallery.option.translate": "Traduz para {0}", + "gallery.option.ask_compression": "Pergunta a compressão de cada vez", + "gallery.option.subfolder": "Guarda na pasta “{0}”", + "gallery.option.file_name": "Nome do ficheiro: {0}" } diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json index 7fb769f62..014ed00f4 100644 --- a/src/Filee.App/Assets/i18n/ru.json +++ b/src/Filee.App/Assets/i18n/ru.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Примечание: если телефон не подключается, разрешите Filee в системном брандмауэре.", "connect.no_network_message": "Не удалось запустить Filee Connect. Убедитесь, что это устройство подключено к локальной сети Wi-Fi или Ethernet.", - "connect.save_as": "Сохранить как…" + "connect.save_as": "Сохранить как…", + "gallery.title": "Галерея пресетов", + "gallery.open": "Галерея пресетов", + "gallery.open_tip": "Пресеты, которыми другие поделились на filee.sh", + "gallery.lead": "Пресеты, которыми другие поделились на filee.sh. При установке они добавляются как новые пресеты, а ваши остаются как есть. Filee обращается к filee.sh, только пока открыто это окно.", + "gallery.sort": "Сортировка", + "gallery.sort.Hot": "Популярные", + "gallery.sort.Best": "Лучшие", + "gallery.sort.New": "Новые", + "gallery.period": "Период", + "gallery.period.day": "Сегодня", + "gallery.period.week": "За неделю", + "gallery.period.month": "За месяц", + "gallery.period.year": "За год", + "gallery.period.all": "За всё время", + "gallery.filter.kind": "Тип", + "gallery.kind.all": "Все типы", + "gallery.kind.convert": "Преобразования", + "gallery.kind.tool": "Инструменты", + "gallery.kind.toolbar": "Круговые меню", + "gallery.filter.format": "Формат", + "gallery.format.all": "Все форматы", + "gallery.filter.tag": "Тег", + "gallery.tag.all": "Все теги", + "gallery.filter.language": "Язык", + "gallery.language.all": "Все языки", + "gallery.loading": "Загрузка пресетов с filee.sh…", + "gallery.failed": "Не удалось подключиться к filee.sh. Проверьте подключение к интернету и прокси в разделе «Настройки → Общие» и повторите попытку.", + "gallery.empty": "Нет пресетов, подходящих под поиск и фильтры.", + "gallery.none": "Пока никто не поделился пресетами.", + "gallery.newer": "Ещё {0} требуют более новой версии Filee.", + "gallery.by": "автор: {0}", + "gallery.likes": "Нравится: {0}", + "gallery.downloads": "Загрузок: {0}", + "gallery.select": "Выберите пресет, чтобы увидеть его изображения и что он делает.", + "gallery.image": "Изображение {0} из {1}", + "gallery.what": "Что добавится", + "gallery.what_group": "Группа: {0}", + "gallery.loading_details": "Загрузка…", + "gallery.donut_new": "Добавляет круговое меню «{0}» для {1}. Оно открывается только для файлов, которые не берёт ни одно из ваших меню; изменить это можно в разделе «Настройки → Круговое меню».", + "gallery.donut_mixed": "смешанных файлов", + "gallery.donut_none": "Не входит ни в одно круговое меню: добавьте его в разделе «Настройки → Круговое меню».", + "gallery.license": "Опубликовал {0} под CC0: можно свободно использовать, изменять и распространять.", + "gallery.comments": "Комментарии", + "gallery.install": "Установить", + "gallery.installing": "Установка…", + "gallery.installed": "Добавлено пресетов: {0}. Они в списке пресетов.", + "gallery.installed_donut": "Добавлено пресетов: {0} и круговое меню «{1}».", + "gallery.install_failed": "Не удалось установить: {0}", + "gallery.not_installable": "Этот пресет нельзя установить: {0}", + "gallery.download_failed": "Не удалось скачать пресет. Проверьте подключение и повторите попытку.", + "gallery.mismatch": "Скачанный файл не совпадает с указанным в галерее, поэтому ничего не установлено.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Не больше {0} МБ", + "gallery.option.no_metadata": "Удаляет метаданные", + "gallery.option.merge": "Объединяет в один файл", + "gallery.option.pages": "Страницы {0}", + "gallery.option.max_height": "До {0}p", + "gallery.option.translate": "Переводит на язык: {0}", + "gallery.option.ask_compression": "Каждый раз спрашивает степень сжатия", + "gallery.option.subfolder": "Сохраняет в папку «{0}»", + "gallery.option.file_name": "Имя файла: {0}" } diff --git a/src/Filee.App/Assets/i18n/th.json b/src/Filee.App/Assets/i18n/th.json index 4ee2f8993..f105ff768 100644 --- a/src/Filee.App/Assets/i18n/th.json +++ b/src/Filee.App/Assets/i18n/th.json @@ -1851,5 +1851,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "หมายเหตุ: หากโทรศัพท์ของคุณไม่สามารถเชื่อมต่อได้ ให้เปิดการอนุญาต Filee ในไฟร์วอลล์ของระบบ", "connect.no_network_message": "ไม่สามารถเริ่ม Filee Connect ได้ โปรดตรวจสอบให้แน่ใจว่าอุปกรณ์นี้เชื่อมต่อกับเครือข่าย Wi-Fi หรืออีเทอร์เน็ตในเครื่อง", - "connect.save_as": "บันทึกเป็น…" + "connect.save_as": "บันทึกเป็น…", + "gallery.title": "แกลเลอรีพรีเซ็ต", + "gallery.open": "แกลเลอรีพรีเซ็ต", + "gallery.open_tip": "พรีเซ็ตที่ผู้อื่นแชร์ไว้บน filee.sh", + "gallery.lead": "พรีเซ็ตที่ผู้อื่นแชร์ไว้บน filee.sh เมื่อติดตั้ง พรีเซ็ตจะถูกเพิ่มเป็นพรีเซ็ตใหม่ และพรีเซ็ตของคุณยังคงเหมือนเดิม Filee จะเชื่อมต่อกับ filee.sh เฉพาะขณะที่หน้าต่างนี้เปิดอยู่", + "gallery.sort": "เรียงตาม", + "gallery.sort.Hot": "มาแรง", + "gallery.sort.Best": "ยอดนิยม", + "gallery.sort.New": "ใหม่ล่าสุด", + "gallery.period": "ช่วงเวลา", + "gallery.period.day": "วันนี้", + "gallery.period.week": "สัปดาห์นี้", + "gallery.period.month": "เดือนนี้", + "gallery.period.year": "ปีนี้", + "gallery.period.all": "ตลอดเวลา", + "gallery.filter.kind": "ชนิด", + "gallery.kind.all": "ทุกชนิด", + "gallery.kind.convert": "การแปลง", + "gallery.kind.tool": "เครื่องมือ", + "gallery.kind.toolbar": "แถบโดนัท", + "gallery.filter.format": "ฟอร์แมต", + "gallery.format.all": "ทุกฟอร์แมต", + "gallery.filter.tag": "แท็ก", + "gallery.tag.all": "ทุกแท็ก", + "gallery.filter.language": "ภาษา", + "gallery.language.all": "ทุกภาษา", + "gallery.loading": "กำลังโหลดพรีเซ็ตจาก filee.sh…", + "gallery.failed": "เชื่อมต่อ filee.sh ไม่ได้ ตรวจสอบการเชื่อมต่ออินเทอร์เน็ตและพร็อกซีใน การตั้งค่า → ทั่วไป แล้วลองอีกครั้ง", + "gallery.empty": "ไม่มีพรีเซ็ตที่ตรงกับการค้นหาและตัวกรอง", + "gallery.none": "ยังไม่มีใครแชร์พรีเซ็ต", + "gallery.newer": "อีก {0} รายการต้องใช้ Filee เวอร์ชันใหม่กว่านี้", + "gallery.by": "โดย {0}", + "gallery.likes": "ถูกใจ {0}", + "gallery.downloads": "ดาวน์โหลด {0}", + "gallery.select": "เลือกพรีเซ็ตเพื่อดูรูปภาพและสิ่งที่พรีเซ็ตทำ", + "gallery.image": "รูปที่ {0} จาก {1}", + "gallery.what": "สิ่งที่จะเพิ่ม", + "gallery.what_group": "กลุ่ม: {0}", + "gallery.loading_details": "กำลังโหลด…", + "gallery.donut_new": "เพิ่มแถบโดนัท “{0}” สำหรับ {1} ซึ่งจะเปิดเฉพาะกับไฟล์ที่ไม่มีแถบโดนัทของคุณรับอยู่ เปลี่ยนได้ใน การตั้งค่า → แถบโดนัท", + "gallery.donut_mixed": "ไฟล์หลายชนิด", + "gallery.donut_none": "ไม่ได้อยู่บนแถบโดนัทใด เพิ่มลงในแถบใดแถบหนึ่งได้ใน การตั้งค่า → แถบโดนัท", + "gallery.license": "{0} แชร์ไว้ภายใต้ CC0: ใช้ แก้ไข และแชร์ต่อได้อย่างอิสระ", + "gallery.comments": "ความคิดเห็น", + "gallery.install": "ติดตั้ง", + "gallery.installing": "กำลังติดตั้ง…", + "gallery.installed": "เพิ่มพรีเซ็ต {0} รายการแล้ว ดูได้ในรายการพรีเซ็ต", + "gallery.installed_donut": "เพิ่มพรีเซ็ต {0} รายการและแถบโดนัท “{1}” แล้ว", + "gallery.install_failed": "ติดตั้งไม่ได้: {0}", + "gallery.not_installable": "ติดตั้งพรีเซ็ตนี้ไม่ได้: {0}", + "gallery.download_failed": "ดาวน์โหลดพรีเซ็ตไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง", + "gallery.mismatch": "ไฟล์ที่ดาวน์โหลดไม่ใช่ไฟล์ที่แกลเลอรีระบุไว้ จึงไม่ได้ติดตั้งอะไรเลย", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "ไม่เกิน {0} MB", + "gallery.option.no_metadata": "ลบข้อมูลเมตา", + "gallery.option.merge": "รวมเป็นไฟล์เดียว", + "gallery.option.pages": "หน้า {0}", + "gallery.option.max_height": "สูงสุด {0}p", + "gallery.option.translate": "แปลเป็น{0}", + "gallery.option.ask_compression": "ถามระดับการบีบอัดทุกครั้ง", + "gallery.option.subfolder": "บันทึกในโฟลเดอร์ “{0}”", + "gallery.option.file_name": "ชื่อไฟล์: {0}" } diff --git a/src/Filee.App/Assets/i18n/tr.json b/src/Filee.App/Assets/i18n/tr.json index 39612b88b..fefb7a08c 100644 --- a/src/Filee.App/Assets/i18n/tr.json +++ b/src/Filee.App/Assets/i18n/tr.json @@ -1849,5 +1849,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Not: Telefonunuz bağlanamıyorsa, sistem güvenlik duvarında Filee'ye izin verin.", "connect.no_network_message": "Filee Connect başlatılamadı. Lütfen bu cihazın yerel bir Wi-Fi veya Ethernet ağına bağlı olduğundan emin olun.", - "connect.save_as": "Farklı kaydet…" + "connect.save_as": "Farklı kaydet…", + "gallery.title": "Ön ayar galerisi", + "gallery.open": "Ön ayar galerisi", + "gallery.open_tip": "Başkalarının filee.sh'de paylaştığı ön ayarlar", + "gallery.lead": "Başkalarının filee.sh'de paylaştığı ön ayarlar. Kurduğunuzda yeni ön ayarlar olarak eklenir, sizinkiler olduğu gibi kalır. Filee, filee.sh'ye yalnızca bu pencere açıkken bağlanır.", + "gallery.sort": "Sırala", + "gallery.sort.Hot": "Popüler", + "gallery.sort.Best": "En iyi", + "gallery.sort.New": "Yeni", + "gallery.period": "Dönem", + "gallery.period.day": "Bugün", + "gallery.period.week": "Bu hafta", + "gallery.period.month": "Bu ay", + "gallery.period.year": "Bu yıl", + "gallery.period.all": "Tüm zamanlar", + "gallery.filter.kind": "Tür", + "gallery.kind.all": "Tüm türler", + "gallery.kind.convert": "Dönüştürmeler", + "gallery.kind.tool": "Araçlar", + "gallery.kind.toolbar": "Halka araç çubukları", + "gallery.filter.format": "Biçim", + "gallery.format.all": "Tüm biçimler", + "gallery.filter.tag": "Etiket", + "gallery.tag.all": "Tüm etiketler", + "gallery.filter.language": "Dil", + "gallery.language.all": "Tüm diller", + "gallery.loading": "Ön ayarlar filee.sh'den yükleniyor…", + "gallery.failed": "filee.sh'ye ulaşılamadı. İnternet bağlantısını ve Ayarlar → Genel'deki proxy'yi kontrol edip yeniden deneyin.", + "gallery.empty": "Aramaya ve filtrelere uyan ön ayar yok.", + "gallery.none": "Henüz paylaşılmış ön ayar yok.", + "gallery.newer": "{0} tanesi daha Filee'nin daha yeni bir sürümünü gerektiriyor.", + "gallery.by": "{0} tarafından", + "gallery.likes": "{0} beğeni", + "gallery.downloads": "{0} indirme", + "gallery.select": "Görsellerini ve ne yaptığını görmek için bir ön ayar seçin.", + "gallery.image": "Görsel {0}/{1}", + "gallery.what": "Eklenecekler", + "gallery.what_group": "Grup: {0}", + "gallery.loading_details": "Yükleniyor…", + "gallery.donut_new": "{1} için “{0}” halka araç çubuğunu ekler. Yalnızca hiçbir halka araç çubuğunuzun almadığı dosyalarda açılır; bunu Ayarlar → Halka araç çubuğu bölümünden değiştirebilirsiniz.", + "gallery.donut_mixed": "karışık dosyalar", + "gallery.donut_none": "Hiçbir halka araç çubuğunda yer almaz: Ayarlar → Halka araç çubuğu bölümünden birine ekleyin.", + "gallery.license": "{0} tarafından CC0 ile paylaşıldı: özgürce kullanılabilir, değiştirilebilir ve paylaşılabilir.", + "gallery.comments": "Yorumlar", + "gallery.install": "Kur", + "gallery.installing": "Kuruluyor…", + "gallery.installed": "{0} ön ayar eklendi. Ön ayarlar listesinde bulabilirsiniz.", + "gallery.installed_donut": "{0} ön ayar ve “{1}” halka araç çubuğu eklendi.", + "gallery.install_failed": "Kurulamadı: {0}", + "gallery.not_installable": "Bu ön ayar kurulamaz: {0}", + "gallery.download_failed": "Ön ayar indirilemedi. Bağlantıyı kontrol edip yeniden deneyin.", + "gallery.mismatch": "İndirilen dosya galerinin listelediği dosya değil, bu yüzden hiçbir şey kurulmadı.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "En fazla {0} MB", + "gallery.option.no_metadata": "Meta verileri kaldırır", + "gallery.option.merge": "Tek dosyada birleştirir", + "gallery.option.pages": "Sayfalar {0}", + "gallery.option.max_height": "{0}p'ye kadar", + "gallery.option.translate": "Çevirir: {0}", + "gallery.option.ask_compression": "Sıkıştırmayı her seferinde sorar", + "gallery.option.subfolder": "“{0}” klasörüne kaydeder", + "gallery.option.file_name": "Dosya adı: {0}" } diff --git a/src/Filee.App/Assets/i18n/vi.json b/src/Filee.App/Assets/i18n/vi.json index 79ed7ebbe..e1ed763d6 100644 --- a/src/Filee.App/Assets/i18n/vi.json +++ b/src/Filee.App/Assets/i18n/vi.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN:", "connect.firewall_hint_generic": "Lưu ý: Nếu điện thoại không thể kết nối, hãy cho phép Filee trong tường lửa hệ thống.", "connect.no_network_message": "Không thể khởi động Filee Connect. Vui lòng đảm bảo thiết bị này được kết nối với mạng Wi-Fi hoặc Ethernet cục bộ.", - "connect.save_as": "Lưu dưới dạng…" + "connect.save_as": "Lưu dưới dạng…", + "gallery.title": "Thư viện cấu hình sẵn", + "gallery.open": "Thư viện cấu hình sẵn", + "gallery.open_tip": "Cấu hình sẵn do người khác chia sẻ trên filee.sh", + "gallery.lead": "Cấu hình sẵn do người khác chia sẻ trên filee.sh. Khi cài đặt, chúng được thêm thành cấu hình sẵn mới, còn của bạn vẫn giữ nguyên. Filee chỉ kết nối với filee.sh khi cửa sổ này đang mở.", + "gallery.sort": "Sắp xếp", + "gallery.sort.Hot": "Thịnh hành", + "gallery.sort.Best": "Hay nhất", + "gallery.sort.New": "Mới", + "gallery.period": "Khoảng thời gian", + "gallery.period.day": "Hôm nay", + "gallery.period.week": "Tuần này", + "gallery.period.month": "Tháng này", + "gallery.period.year": "Năm nay", + "gallery.period.all": "Mọi lúc", + "gallery.filter.kind": "Loại", + "gallery.kind.all": "Tất cả các loại", + "gallery.kind.convert": "Chuyển đổi", + "gallery.kind.tool": "Công cụ", + "gallery.kind.toolbar": "Thanh công cụ vòng tròn", + "gallery.filter.format": "Định dạng", + "gallery.format.all": "Tất cả định dạng", + "gallery.filter.tag": "Thẻ", + "gallery.tag.all": "Tất cả thẻ", + "gallery.filter.language": "Ngôn ngữ", + "gallery.language.all": "Tất cả ngôn ngữ", + "gallery.loading": "Đang tải cấu hình sẵn từ filee.sh…", + "gallery.failed": "Không thể kết nối với filee.sh. Hãy kiểm tra kết nối Internet và proxy trong Cài đặt → Chung, rồi thử lại.", + "gallery.empty": "Không có cấu hình sẵn nào khớp với tìm kiếm và bộ lọc.", + "gallery.none": "Chưa có ai chia sẻ cấu hình sẵn.", + "gallery.newer": "Còn {0} mục cần phiên bản Filee mới hơn.", + "gallery.by": "của {0}", + "gallery.likes": "{0} lượt thích", + "gallery.downloads": "{0} lượt tải", + "gallery.select": "Chọn một cấu hình sẵn để xem hình ảnh và chức năng của nó.", + "gallery.image": "Hình {0} / {1}", + "gallery.what": "Những gì được thêm", + "gallery.what_group": "Nhóm: {0}", + "gallery.loading_details": "Đang tải…", + "gallery.donut_new": "Thêm thanh công cụ vòng tròn “{0}” cho {1}. Nó chỉ mở với các tệp mà không thanh nào của bạn đảm nhận; bạn có thể đổi điều này trong Cài đặt → Thanh công cụ vòng tròn.", + "gallery.donut_mixed": "tệp hỗn hợp", + "gallery.donut_none": "Không nằm trên thanh công cụ vòng tròn nào: hãy thêm vào một thanh trong Cài đặt → Thanh công cụ vòng tròn.", + "gallery.license": "Được {0} chia sẻ theo CC0: tự do sử dụng, chỉnh sửa và chia sẻ.", + "gallery.comments": "Bình luận", + "gallery.install": "Cài đặt", + "gallery.installing": "Đang cài đặt…", + "gallery.installed": "Đã thêm {0} cấu hình sẵn. Bạn có thể tìm thấy chúng trong danh sách cấu hình sẵn.", + "gallery.installed_donut": "Đã thêm {0} cấu hình sẵn và thanh công cụ vòng tròn “{1}”.", + "gallery.install_failed": "Không thể cài đặt: {0}", + "gallery.not_installable": "Không thể cài đặt cấu hình sẵn này: {0}", + "gallery.download_failed": "Không thể tải cấu hình sẵn xuống. Hãy kiểm tra kết nối rồi thử lại.", + "gallery.mismatch": "Tệp đã tải không phải tệp mà thư viện liệt kê, nên không có gì được cài đặt.", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "Tối đa {0} MB", + "gallery.option.no_metadata": "Xóa siêu dữ liệu", + "gallery.option.merge": "Gộp thành một tệp", + "gallery.option.pages": "Trang {0}", + "gallery.option.max_height": "Tối đa {0}p", + "gallery.option.translate": "Dịch sang {0}", + "gallery.option.ask_compression": "Hỏi mức nén mỗi lần", + "gallery.option.subfolder": "Lưu vào thư mục “{0}”", + "gallery.option.file_name": "Tên tệp: {0}" } diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json index e3b1176ef..32d7c8bda 100644 --- a/src/Filee.App/Assets/i18n/zh-CN.json +++ b/src/Filee.App/Assets/i18n/zh-CN.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN 码:", "connect.firewall_hint_generic": "注意:如果您的手机无法连接,请在系统防火墙中允许 Filee。", "connect.no_network_message": "无法启动 Filee Connect。请确保此设备已连接到本地 Wi-Fi 或有线以太网。", - "connect.save_as": "另存为…" + "connect.save_as": "另存为…", + "gallery.title": "预设广场", + "gallery.open": "预设广场", + "gallery.open_tip": "其他人在 filee.sh 上分享的预设", + "gallery.lead": "其他人在 filee.sh 上分享的预设。安装后会作为新预设添加,你自己的预设保持不变。只有在此窗口打开时,Filee 才会连接 filee.sh。", + "gallery.sort": "排序", + "gallery.sort.Hot": "热门", + "gallery.sort.Best": "最佳", + "gallery.sort.New": "最新", + "gallery.period": "时间段", + "gallery.period.day": "今天", + "gallery.period.week": "本周", + "gallery.period.month": "本月", + "gallery.period.year": "今年", + "gallery.period.all": "全部时间", + "gallery.filter.kind": "类型", + "gallery.kind.all": "所有类型", + "gallery.kind.convert": "转换", + "gallery.kind.tool": "工具", + "gallery.kind.toolbar": "环形工具栏", + "gallery.filter.format": "格式", + "gallery.format.all": "所有格式", + "gallery.filter.tag": "标签", + "gallery.tag.all": "所有标签", + "gallery.filter.language": "语言", + "gallery.language.all": "所有语言", + "gallery.loading": "正在从 filee.sh 加载预设…", + "gallery.failed": "无法连接 filee.sh。请检查网络连接以及 设置 → 常规 中的代理,然后重试。", + "gallery.empty": "没有符合搜索和筛选条件的预设。", + "gallery.none": "还没有人分享预设。", + "gallery.newer": "另有 {0} 个需要更新版本的 Filee。", + "gallery.by": "作者:{0}", + "gallery.likes": "{0} 个赞", + "gallery.downloads": "{0} 次下载", + "gallery.select": "选择一个预设,查看它的图片和作用。", + "gallery.image": "第 {0} 张,共 {1} 张", + "gallery.what": "将添加的内容", + "gallery.what_group": "组:{0}", + "gallery.loading_details": "正在加载…", + "gallery.donut_new": "添加用于 {1} 的环形工具栏“{0}”。它只会在你的环形工具栏都不处理的文件上打开;可在“设置 → 环形工具栏”中更改。", + "gallery.donut_mixed": "混合文件", + "gallery.donut_none": "不在任何环形工具栏上:可在“设置 → 环形工具栏”中添加。", + "gallery.license": "由 {0} 以 CC0 分享:可自由使用、修改和分享。", + "gallery.comments": "评论", + "gallery.install": "安装", + "gallery.installing": "正在安装…", + "gallery.installed": "已添加 {0} 个预设,可在预设列表中找到。", + "gallery.installed_donut": "已添加 {0} 个预设和环形工具栏“{1}”。", + "gallery.install_failed": "无法安装:{0}", + "gallery.not_installable": "无法安装此预设:{0}", + "gallery.download_failed": "无法下载预设。请检查网络连接后重试。", + "gallery.mismatch": "下载的文件与预设广场列出的不一致,因此没有安装任何内容。", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "最大 {0} MB", + "gallery.option.no_metadata": "删除元数据", + "gallery.option.merge": "合并为一个文件", + "gallery.option.pages": "页面 {0}", + "gallery.option.max_height": "最高 {0}p", + "gallery.option.translate": "翻译为{0}", + "gallery.option.ask_compression": "每次询问压缩程度", + "gallery.option.subfolder": "保存到文件夹“{0}”", + "gallery.option.file_name": "文件名:{0}" } diff --git a/src/Filee.App/Assets/i18n/zh-TW.json b/src/Filee.App/Assets/i18n/zh-TW.json index c7b54bec2..58c6fa2a5 100644 --- a/src/Filee.App/Assets/i18n/zh-TW.json +++ b/src/Filee.App/Assets/i18n/zh-TW.json @@ -1871,5 +1871,67 @@ "connect.pin_label": "PIN 碼:", "connect.firewall_hint_generic": "注意:如果您的手機無法連線,請在系統防火牆中允許 Filee。", "connect.no_network_message": "無法啟動 Filee Connect。請確認此裝置已連線至本機 Wi-Fi 或乙太網路。", - "connect.save_as": "另存為…" + "connect.save_as": "另存為…", + "gallery.title": "預設廣場", + "gallery.open": "預設廣場", + "gallery.open_tip": "其他人在 filee.sh 上分享的預設", + "gallery.lead": "其他人在 filee.sh 上分享的預設。安裝後會新增為新的預設,你自己的預設維持不變。只有在此視窗開啟時,Filee 才會連線到 filee.sh。", + "gallery.sort": "排序", + "gallery.sort.Hot": "熱門", + "gallery.sort.Best": "最佳", + "gallery.sort.New": "最新", + "gallery.period": "期間", + "gallery.period.day": "今天", + "gallery.period.week": "本週", + "gallery.period.month": "本月", + "gallery.period.year": "今年", + "gallery.period.all": "所有時間", + "gallery.filter.kind": "類型", + "gallery.kind.all": "所有類型", + "gallery.kind.convert": "轉換", + "gallery.kind.tool": "工具", + "gallery.kind.toolbar": "環形工具列", + "gallery.filter.format": "格式", + "gallery.format.all": "所有格式", + "gallery.filter.tag": "標籤", + "gallery.tag.all": "所有標籤", + "gallery.filter.language": "語言", + "gallery.language.all": "所有語言", + "gallery.loading": "正在從 filee.sh 載入預設…", + "gallery.failed": "無法連線到 filee.sh。請檢查網路連線以及 設定 → 一般 中的 Proxy,然後再試一次。", + "gallery.empty": "沒有符合搜尋與篩選條件的預設。", + "gallery.none": "還沒有人分享預設。", + "gallery.newer": "另有 {0} 個需要較新版本的 Filee。", + "gallery.by": "作者:{0}", + "gallery.likes": "{0} 個讚", + "gallery.downloads": "{0} 次下載", + "gallery.select": "選擇一個預設,即可查看它的圖片與用途。", + "gallery.image": "第 {0} 張,共 {1} 張", + "gallery.what": "會新增的項目", + "gallery.what_group": "群組:{0}", + "gallery.loading_details": "正在載入…", + "gallery.donut_new": "新增用於 {1} 的環形工具列「{0}」。只有在你的環形工具列都不處理的檔案上才會開啟;可在「設定 → 環形工具列」中變更。", + "gallery.donut_mixed": "混合檔案", + "gallery.donut_none": "不在任何環形工具列上:可在「設定 → 環形工具列」中加入。", + "gallery.license": "由 {0} 以 CC0 分享:可自由使用、修改與分享。", + "gallery.comments": "留言", + "gallery.install": "安裝", + "gallery.installing": "正在安裝…", + "gallery.installed": "已新增 {0} 個預設,可在預設清單中找到。", + "gallery.installed_donut": "已新增 {0} 個預設與環形工具列「{1}」。", + "gallery.install_failed": "無法安裝:{0}", + "gallery.not_installable": "無法安裝此預設:{0}", + "gallery.download_failed": "無法下載預設。請檢查網路連線後再試一次。", + "gallery.mismatch": "下載的檔案與預設廣場列出的不同,因此沒有安裝任何項目。", + "gallery.option.size": "{0} × {1} px", + "gallery.option.pixels": "{0} px", + "gallery.option.max_size": "最大 {0} MB", + "gallery.option.no_metadata": "移除中繼資料", + "gallery.option.merge": "合併成一個檔案", + "gallery.option.pages": "頁面 {0}", + "gallery.option.max_height": "最高 {0}p", + "gallery.option.translate": "翻譯成{0}", + "gallery.option.ask_compression": "每次詢問壓縮程度", + "gallery.option.subfolder": "儲存到資料夾「{0}」", + "gallery.option.file_name": "檔名:{0}" } diff --git a/src/Filee.App/Services/PresetGalleryClient.cs b/src/Filee.App/Services/PresetGalleryClient.cs new file mode 100644 index 000000000..836a85f00 --- /dev/null +++ b/src/Filee.App/Services/PresetGalleryClient.cs @@ -0,0 +1,203 @@ +// Talks to the preset gallery on filee.sh (#1530), and only while its window is open: index.json, the pictures, and a +// preset's preset.json (to show what it does, and through the download link to install it, which the site counts). +// Every path in index.json is relative to the address it came from, so the same code reads filee.sh's index and the +// repository's. +// Nothing else is sent. Requests go through the proxy of Settings → General (HttpClient's default proxy, see +// ProxySetting), each with a time limit and a size limit, and only to filee.sh or, when filee.sh can't be reached, +// to the gallery's repository on GitHub. Pictures are kept in the work folder (gallery/) up to a size, so the window +// opens quickly the next time. + +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using Filee.Core.Gallery; +using Filee.Core.Platform; + +namespace Filee.App.Services; + +public sealed class PresetGalleryClient : IDisposable +{ + /// The list the app and the site show. + public const string IndexUrl = "https://filee.sh/presets/index.json"; + + /// The gallery repository's own index.json, read when filee.sh can't be reached. + public const string RepositoryIndexUrl = "https://raw.githubusercontent.com/KnifeLemon/Filee-Presets/main/index.json"; + + /// A shared preset's comments and likes. + public const string DiscussionsUrl = "https://github.com/KnifeLemon/Filee-Presets/discussions/"; + + /// How long one request may take, from asking to the last byte. + public static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(20); + + /// Largest thumbnail and picture read. + public const int MaxThumbBytes = SharedPresetFolderCheck.MaxThumbBytes, MaxImageBytes = SharedPresetFolderCheck.MaxImageBytes; + + /// How much the picture cache may hold before the oldest pictures go, and how long one is kept. + public const long MaxCacheBytes = 64L * 1024 * 1024; + public static readonly TimeSpan MaxCacheAge = TimeSpan.FromDays(30); + + private readonly HttpClient _http; + private readonly string? _cache; + private readonly Lock _cacheGate = new(); + private Uri _index = new(IndexUrl); + private bool _fromRepository; + + /// The HTTP handler (tests pass one that answers in place of the network); the default + /// follows the proxy setting. + /// Where pictures are kept; the work folder's gallery/ when null, none when empty. + public PresetGalleryClient(HttpMessageHandler? handler = null, string? cacheFolder = null) + { + _http = new HttpClient(handler ?? new HttpClientHandler(), disposeHandler: true) { Timeout = RequestTimeout + TimeSpan.FromSeconds(5) }; + _http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Filee", UpdateService.CurrentVersion)); + _cache = cacheFolder ?? Path.Combine(WorkFolders.Root, "gallery"); + if (_cache.Length == 0) + _cache = null; + } + + /// The index came from the repository on GitHub: filee.sh couldn't be reached (no counts then). + public bool FromRepository => _fromRepository; + + /// The list of shared presets, from filee.sh or else from the repository. + public async Task GetIndexAsync(CancellationToken cancellationToken) + { + try + { + var index = GalleryIndex.Parse(await GetBytesAsync(new Uri(IndexUrl), GalleryIndex.MaxBytes, cancellationToken)); + (_index, _fromRepository) = (new Uri(IndexUrl), false); + return index; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or InvalidDataException or System.Text.Json.JsonException + && !cancellationToken.IsCancellationRequested) + { + var index = GalleryIndex.Parse(await GetBytesAsync(new Uri(RepositoryIndexUrl), GalleryIndex.MaxBytes, cancellationToken)); + (_index, _fromRepository) = (new Uri(RepositoryIndexUrl), true); + return index; + } + } + + /// + /// A picture of (one of its or its thumbnail), from the + /// cache when it has it for this version of the preset. + /// + public async Task GetImageAsync(GalleryEntry entry, string path, CancellationToken cancellationToken) + { + if (path != entry.Thumb && !entry.Images.Contains(path)) + throw new ArgumentException("Not one of the preset's pictures.", nameof(path)); + var max = path == entry.Thumb ? MaxThumbBytes : MaxImageBytes; + var key = CacheKey(entry, path); + if (ReadCache(key, max) is { } cached) + return cached; + var data = await GetBytesAsync(FileUri(path), max, cancellationToken); + WriteCache(key, data); + return data; + } + + /// The preset's preset.json as the gallery has it, to show what it does (not counted as a download). + public Task GetPresetAsync(GalleryEntry entry, CancellationToken cancellationToken) => + GetBytesAsync(FileUri(entry.Preset), SharedBundleCheck.MaxBytes, cancellationToken); + + /// + /// The preset's preset.json through its install link, which filee.sh counts; from the repository (which has none) + /// the file itself. Either way the installer checks it against the SHA-256 the index lists. + /// + public Task DownloadPresetAsync(GalleryEntry entry, CancellationToken cancellationToken) => + GetBytesAsync(entry.Download is { } link && OnIndexHost(new Uri(_index, link)) is { } download ? download : FileUri(entry.Preset), + SharedBundleCheck.MaxBytes, cancellationToken); + + /// The page of a shared preset's discussion. + public static Uri DiscussionUri(int number) => new(DiscussionsUrl + number.ToString(System.Globalization.CultureInfo.InvariantCulture)); + + // index.json's paths were checked to be plain relative paths into the preset's folder (GalleryIndex), so joining them + // to the index's address stays below it; the host is checked once more all the same. + private Uri FileUri(string path) => + OnIndexHost(new Uri(_index, path)) ?? throw new InvalidDataException("A gallery path leaves the gallery's address."); + + private Uri? OnIndexHost(Uri uri) => + uri.Scheme == Uri.UriSchemeHttps && string.Equals(uri.Host, _index.Host, StringComparison.OrdinalIgnoreCase) ? uri : null; + + private async Task GetBytesAsync(Uri uri, int maxBytes, CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(RequestTimeout); + using var response = await _http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + response.EnsureSuccessStatusCode(); + // A redirect (the download link's) must stay on HTTPS. + if (response.RequestMessage?.RequestUri is { Scheme: not "https" }) + throw new HttpRequestException("The gallery redirected to an address that isn't HTTPS."); + if (response.Content.Headers.ContentLength > maxBytes) + throw new InvalidDataException($"{uri.AbsolutePath} is larger than {maxBytes:N0} bytes."); + await using var stream = await response.Content.ReadAsStreamAsync(timeout.Token); + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await stream.ReadAsync(chunk, timeout.Token)) > 0) + { + if (buffer.Length + read > maxBytes) + throw new InvalidDataException($"{uri.AbsolutePath} is larger than {maxBytes:N0} bytes."); + buffer.Write(chunk, 0, read); + } + return buffer.ToArray(); + } + + /// One file per picture and version of the preset (its ). + private static string CacheKey(GalleryEntry entry, string path) => + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes($"{path}|{entry.Updated.ToUnixTimeSeconds()}")))[..32] + ".img"; + + private byte[]? ReadCache(string key, int maxBytes) + { + if (_cache is null) + return null; + try + { + var file = new FileInfo(Path.Combine(_cache, key)); + if (!file.Exists || file.Length > maxBytes || DateTime.UtcNow - file.LastWriteTimeUtc > MaxCacheAge) + return null; + var data = File.ReadAllBytes(file.FullName); + file.LastAccessTimeUtc = DateTime.UtcNow; + return data; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private void WriteCache(string key, byte[] data) + { + if (_cache is null) + return; + lock (_cacheGate) + { + try + { + Directory.CreateDirectory(_cache); + var path = Path.Combine(_cache, key); + var temp = path + ".tmp"; + File.WriteAllBytes(temp, data); + File.Move(temp, path, overwrite: true); + Trim(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A cache that can't be written only means the pictures are downloaded again. + } + } + } + + /// Deletes pictures older than , then the least recently used beyond the limit. + private void Trim() + { + var files = new DirectoryInfo(_cache!).GetFiles("*.img") + .OrderByDescending(f => f.LastAccessTimeUtc > f.LastWriteTimeUtc ? f.LastAccessTimeUtc : f.LastWriteTimeUtc) + .ToList(); + long total = 0; + foreach (var file in files) + { + total += file.Length; + if (total > MaxCacheBytes || DateTime.UtcNow - file.LastWriteTimeUtc > MaxCacheAge) + file.Delete(); + } + } + + public void Dispose() => _http.Dispose(); +} diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs index 8c02df794..c5aa29d0c 100644 --- a/src/Filee.App/Services/WindowService.cs +++ b/src/Filee.App/Services/WindowService.cs @@ -852,6 +852,52 @@ public void ShowWhatsNew(Controls.SlideDeck deck) internal WhatsNewWindow? WhatsNew => _whatsNew; + private PresetGalleryWindow? _gallery; + + internal PresetGalleryWindow? Gallery => _gallery; + + /// + /// Opens the preset gallery (#1530), centred on the main window; a second call brings the open one to the front. + /// filee.sh is contacted from now until it closes. is told after each install. + /// + public void ShowPresetGallery(Action? installed = null) + { + if (_gallery is not null) + { + _gallery.Activate(); + return; + } + var client = new PresetGalleryClient(); + PresetGalleryWindow? window = null; + var vm = new PresetGalleryViewModel(client, services.GetRequiredService(), loc, PresetGalleryViewModel.CurrentVersion, + async uri => + { + if (window is not null) + await window.Launcher.LaunchUriAsync(uri); + }, + installed); + window = new PresetGalleryWindow { DataContext = vm }; + PrepareWindow(window); + window.Closed += (_, _) => + { + if (_gallery == window) + _gallery = null; + vm.Dispose(); + client.Dispose(); + trimmer.Request(); + }; + _gallery = window; + if (_main is { IsVisible: true } main && main.WindowState != WindowState.Minimized) + window.Show(main); + else + { + window.WindowStartupLocation = WindowStartupLocation.CenterScreen; + window.Show(); + } + window.Activate(); + _ = vm.LoadAsync(); + } + /// Opens the optional-engine choice (first run); a second call brings the open window to front. /// /// Shows the engine choice. With (packages picked in the installer) the downloads start diff --git a/src/Filee.App/ViewModels/GallerySummaries.cs b/src/Filee.App/ViewModels/GallerySummaries.cs new file mode 100644 index 000000000..b683d2695 --- /dev/null +++ b/src/Filee.App/ViewModels/GallerySummaries.cs @@ -0,0 +1,129 @@ +// What a shared preset does, in a line or two for the preset gallery's detail view (#1530): its target or tool and the +// options it changes from the defaults, in the words of the preset editor where it has them. + +using System.Globalization; +using Filee.Core.Formats; +using Filee.Core.Localization; +using Filee.Core.Presets; + +namespace Filee.App.ViewModels; + +internal static class GallerySummaries +{ + /// Most options listed for one preset. + private const int MaxOptions = 8; + + private static readonly IReadOnlyDictionary ToolNames = new Dictionary + { + [Preset.CropTool] = "preset.crop", + [Preset.ClipTool] = "preset.clip", + [Preset.ImageEditTool] = "preset.image_edit", + [Preset.HideTool] = "preset.hide", + [Preset.AnnotateTool] = "preset.annotate", + [Preset.BackgroundTool] = "preset.background", + [Preset.UpscaleTool] = "preset.upscale", + }; + + private static readonly HashSet LossyPictures = ["jpg", "webp", "avif", "heic", "jxl"]; + + /// The name, what does and its main options; names a group's. + public static PresetGallerySummary Describe(Preset preset, IReadOnlyList all, ILocalizer loc) + { + var what = preset.Kind switch + { + PresetKind.Group => loc.Format("gallery.what_group", string.Join(", ", + preset.SubPresetIds.Select(id => all.FirstOrDefault(p => p.Id == id)).OfType().Select(loc.DisplayName))), + PresetKind.Tool => loc[ToolNames.GetValueOrDefault(preset.Tool ?? Preset.CropTool, "preset.crop")], + _ => preset.TargetFormat == BuiltInData.SameAsSource + ? loc["presets.same_as_source"] + : "→ " + (FormatLabels.NameOf(loc, preset.TargetFormat) ?? preset.TargetFormat.ToUpperInvariant()), + }; + var options = preset.IsGroup ? [] : Options(preset, loc).Take(MaxOptions); + return new PresetGallerySummary(loc.DisplayName(preset), what, string.Join(" · ", options)); + } + + private static IEnumerable Options(Preset preset, ILocalizer loc) + { + var category = FormatRegistry.FindById(preset.TargetFormat)?.Category; + var pictures = category == FormatCategory.Image || preset.TargetFormat == BuiltInData.SameAsSource || preset.IsTool; + var image = preset.Image; + if (pictures) + { + if (LossyPictures.Contains(preset.TargetFormat) && image.Quality != new ImageOptions().Quality) + yield return $"{loc["presets.quality"]} {image.Quality}"; + if (image.CustomSize is { } size) + yield return $"{loc["presets.resize.Custom"]} {loc.Format("gallery.option.size", size.ClampedWidth, size.ClampedHeight)}"; + else if (image.ClampedMinShortEdge is { } edge) + yield return $"{loc["presets.resize.MinShortEdge"]} {loc.Format("gallery.option.pixels", edge)}"; + else if (image.Resize == ResizeMode.Percent) + yield return $"{loc["presets.resize.Percent"]} {image.ResizePercent}%"; + else if (image.Resize == ResizeMode.LongEdge) + yield return $"{loc["presets.resize.LongEdge"]} {loc.Format("gallery.option.pixels", image.LongEdge)}"; + else if (image.Resize == ResizeMode.Width) + yield return $"{loc["presets.resize.Width"]} {loc.Format("gallery.option.pixels", image.Width)}"; + if (image.Rotation != ImageRotation.None) + yield return loc[$"presets.rotation.{image.Rotation}"]; + if (image.Flip != ImageFlip.None) + yield return loc[$"presets.flip.{image.Flip}"]; + if (image.Grayscale) + yield return loc["presets.grayscale"]; + if (image.RemoveBackground) + yield return loc["presets.remove_background"]; + if (image.MaxSizeMb > 0) + yield return loc.Format("gallery.option.max_size", image.MaxSizeMb.ToString("0.##", CultureInfo.CurrentCulture)); + if (!image.KeepMetadata) + yield return loc["gallery.option.no_metadata"]; + } + + var pdf = preset.Pdf; + if (pdf.MergeIntoSingle || image.JoinIntoOne || preset.Media.JoinIntoOne || preset.Archive.CombineIntoOne) + yield return loc["gallery.option.merge"]; + if (preset.TargetFormat == "pdf") + { + if (pdf.Compression != PdfCompression.None) + yield return loc[$"presets.pdf_compression.{pdf.Compression}"]; + if (pdf.MakesSheets) + yield return $"{loc["presets.pages_per_sheet"]} {pdf.PagesPerSheet}"; + if (pdf.SplitPages) + yield return loc["presets.split"]; + if (pdf.Ocr) + yield return loc["presets.ocr"]; + if (pdf.Watermark.Length > 0) + yield return $"{loc["presets.watermark"]}: “{pdf.Watermark}”"; + } + if (pdf.PageRange.Length > 0) + yield return loc.Format("gallery.option.pages", pdf.PageRange); + + if (category is FormatCategory.Video or FormatCategory.Audio) + { + var media = preset.Media; + if (media.Quality != MediaQuality.Balanced) + yield return $"{loc["presets.media_quality"]}: {loc[$"presets.media_quality.{media.Quality}"]}"; + if (media.MaxHeight > 0) + yield return loc.Format("gallery.option.max_height", media.MaxHeight); + if (media.RemoveAudio) + yield return loc["presets.remove_audio"]; + } + + if (preset.Translate.Enabled) + yield return loc.Format("gallery.option.translate", LanguageName(preset.Translate.TargetLanguage)); + if (preset.AskCompression) + yield return loc["gallery.option.ask_compression"]; + if (preset.Output.Location == OutputLocation.Subfolder) + yield return loc.Format("gallery.option.subfolder", preset.Output.SubfolderName); + if (preset.Output.FileNamePattern is { Length: > 0 } pattern && pattern != "{name}") + yield return loc.Format("gallery.option.file_name", pattern); + } + + private static string LanguageName(string code) + { + try + { + return CultureInfo.GetCultureInfo(code).NativeName; + } + catch (CultureNotFoundException) + { + return code; + } + } +} diff --git a/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs index 34435aa45..a5630b76a 100644 --- a/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs +++ b/src/Filee.App/ViewModels/Pages/PresetsPageViewModel.cs @@ -129,6 +129,14 @@ private async Task Delete() SelectedPreset = Presets.Count == 0 ? null : Presets[Math.Clamp(index, 0, Presets.Count - 1)]; } + /// Opens the preset gallery; what it installs joins the list. + [RelayCommand] + private void OpenGallery() => _windows.ShowPresetGallery(result => + { + foreach (var preset in result.Presets.Where(p => !p.IsGroup && (!p.IsTool || p.IsUpscaleTool))) + Presets.Add(new PresetListItem(preset, _loc)); + }); + private void AddPreset(Preset preset) { _store.Presets.Add(preset); diff --git a/src/Filee.App/ViewModels/PresetGalleryViewModel.cs b/src/Filee.App/ViewModels/PresetGalleryViewModel.cs new file mode 100644 index 000000000..e5fed571d --- /dev/null +++ b/src/Filee.App/ViewModels/PresetGalleryViewModel.cs @@ -0,0 +1,594 @@ +// The "Preset gallery" window (#1530): presets other people shared on filee.sh, as cards with their cover, sorted by +// Hot, Best (of a day, week, month, year or all time) or New and filtered by kind, format, tag, language and text. The +// one chosen shows its pictures, its description and what each of its presets does, and installs as new presets (see +// GalleryInstaller). Presets that need a newer Filee are left out and counted. filee.sh is contacted only while the +// window is open (PresetGalleryClient). + +using System.Collections.ObjectModel; +using System.Globalization; +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Filee.App.Services; +using Filee.Core.Gallery; +using Filee.Core.Localization; +using Filee.Core.Settings; + +namespace Filee.App.ViewModels; + +/// The orders the gallery offers. +public enum GallerySort +{ + /// Likes and downloads of late count most (the site's score). + Hot, + + /// The most liked and downloaded of a period. + Best, + + /// The newest first. + New, +} + +/// Where the list is: still loading, shown, or filee.sh couldn't be reached. +public enum GalleryState +{ + Loading, + Ready, + Failed, +} + +public sealed partial class PresetGalleryViewModel : ObservableObject, IDisposable +{ + /// The filter value meaning "any". + public const string Any = ""; + + /// Thumbnails loading at the same time. + private const int ThumbsAtOnce = 4; + + private readonly PresetGalleryClient _client; + private readonly UserDataStore _store; + private readonly ILocalizer _loc; + private readonly Version _appVersion; + private readonly Func _open; + private readonly Action? _installed; + private readonly CancellationTokenSource _closing = new(); + private readonly List _all = []; + private bool _refreshing; + + /// This Filee's version: presets that need a newer one are left out. + /// Opens a page in the browser (the comments). + /// Told after an install added presets, so the Presets page lists them. + public PresetGalleryViewModel(PresetGalleryClient client, UserDataStore store, ILocalizer loc, Version appVersion, + Func open, Action? installed = null) + { + _client = client; + _store = store; + _loc = loc; + _appVersion = appVersion; + _open = open; + _installed = installed; + Sorts = [.. Enum.GetValues().Select(s => new Choice(s, loc[$"gallery.sort.{s}"]))]; + _sort = Sorts[0]; + Periods = [.. GalleryStats.Periods.Select(p => new Choice(p, loc[$"gallery.period.{p}"]))]; + _period = Periods[1]; + Kinds = [new(Any, loc["gallery.kind.all"]), .. SharedPresetFolderCheck.Kinds.Select(k => new Choice(k, loc[$"gallery.kind.{k}"]))]; + _kind = Kinds[0]; + Formats = [new(Any, loc["gallery.format.all"])]; + _format = Formats[0]; + Tags = [new(Any, loc["gallery.tag.all"])]; + _tag = Tags[0]; + Languages = [new(Any, loc["gallery.language.all"])]; + _language = Languages[0]; + } + + /// This Filee's version, as the update check reads it (a pre-release counts as its release). + public static Version CurrentVersion => + Version.TryParse(UpdateService.CurrentVersion.Split('-')[0], out var version) ? version : new Version(0, 0, 0); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsLoading), nameof(IsFailed), nameof(IsReady), nameof(IsEmpty), nameof(EmptyText))] + private GalleryState _state = GalleryState.Loading; + + public bool IsLoading => State == GalleryState.Loading; + public bool IsFailed => State == GalleryState.Failed; + public bool IsReady => State == GalleryState.Ready; + + /// The list is shown but nothing is in it (none shared yet, or none matches the filters). + public bool IsEmpty => IsReady && Cards.Count == 0; + + public string EmptyText => _all.Count == 0 ? _loc["gallery.none"] : _loc["gallery.empty"]; + + /// The cards that pass the filters, in the chosen order. + public ObservableCollection Cards { get; } = []; + + public IReadOnlyList> Sorts { get; } + public IReadOnlyList> Periods { get; } + public IReadOnlyList> Kinds { get; } + public ObservableCollection> Formats { get; } + public ObservableCollection> Tags { get; } + public ObservableCollection> Languages { get; } + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ShowPeriods))] + private Choice _sort; + + /// The period of Best; the list only shows it with that order. + [ObservableProperty] private Choice _period; + + public bool ShowPeriods => Sort.Value == GallerySort.Best; + + [ObservableProperty] private Choice _kind; + [ObservableProperty] private Choice _format; + [ObservableProperty] private Choice _tag; + [ObservableProperty] private Choice _language; + [ObservableProperty] private string _search = ""; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasSelection))] + private PresetGalleryCardViewModel? _selected; + + /// What the chosen preset is and does, with Install and Comments. + [ObservableProperty] private PresetGalleryDetailViewModel? _detail; + + public bool HasSelection => Selected is not null; + + /// "3 more need a newer Filee", or null when none does. + [ObservableProperty] private string? _newerText; + + partial void OnSortChanged(Choice value) => Refresh(); + partial void OnPeriodChanged(Choice value) => Refresh(); + partial void OnKindChanged(Choice value) => Refresh(); + partial void OnFormatChanged(Choice value) => Refresh(); + partial void OnTagChanged(Choice value) => Refresh(); + partial void OnLanguageChanged(Choice value) => Refresh(); + partial void OnSearchChanged(string value) => Refresh(); + + partial void OnSelectedChanged(PresetGalleryCardViewModel? value) + { + // The list refills while it filters: the preset stays chosen when it is still in it. + if (_refreshing) + return; + Detail?.Dispose(); + Detail = value is null ? null : new PresetGalleryDetailViewModel(value.Entry, _client, _store, _loc, _open, Installed, _closing.Token); + _ = Detail?.LoadAsync(); + } + + private void Installed(GalleryInstallResult result) => _installed?.Invoke(result); + + /// Loads (or loads again) the list from filee.sh. + [RelayCommand] + public async Task LoadAsync() + { + State = GalleryState.Loading; + GalleryIndex index; + try + { + index = await _client.GetIndexAsync(_closing.Token); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or IOException or InvalidDataException or System.Text.Json.JsonException) + { + if (!_closing.IsCancellationRequested) + State = GalleryState.Failed; + return; + } + + foreach (var card in _all) + card.Dispose(); + _all.Clear(); + var newer = 0; + foreach (var entry in index.Entries) + { + if (entry.MinVersion > _appVersion) + newer++; + else + _all.Add(new PresetGalleryCardViewModel(entry, _loc)); + } + NewerText = newer == 0 ? null : _loc.Format("gallery.newer", newer); + Fill(Formats, _all.SelectMany(c => c.Entry.FormatsFrom.Concat(c.Entry.FormatsTo)), id => FormatLabels.NameOf(_loc, id) ?? id.ToUpperInvariant()); + Fill(Tags, _all.SelectMany(c => c.Entry.Tags), tag => tag); + Fill(Languages, _all.SelectMany(c => c.Entry.Languages), LanguageName); + State = GalleryState.Ready; + Refresh(); + _ = LoadThumbsAsync(); + } + + /// Fills a filter's list after its "any" item with the values the presets have, by their names. + private static void Fill(ObservableCollection> list, IEnumerable values, Func label) + { + while (list.Count > 1) + list.RemoveAt(list.Count - 1); + foreach (var value in values.Distinct(StringComparer.Ordinal).Select(v => new Choice(v, label(v))).OrderBy(c => c.Label, StringComparer.CurrentCultureIgnoreCase)) + list.Add(value); + } + + private static string LanguageName(string code) + { + try + { + var culture = CultureInfo.GetCultureInfo(code); + return culture.EnglishName == code || culture.NativeName.Length == 0 ? code : culture.NativeName; + } + catch (CultureNotFoundException) + { + return code; + } + } + + /// Applies the filters and the order to the list. + private void Refresh() + { + if (State != GalleryState.Ready) + return; + var query = Search.Trim(); + var cards = _all.Where(c => + (Kind.Value == Any || c.Entry.Kinds.Contains(Kind.Value)) + && (Format.Value == Any || c.Entry.FormatsFrom.Contains(Format.Value) || c.Entry.FormatsTo.Contains(Format.Value)) + && (Tag.Value == Any || c.Entry.Tags.Contains(Tag.Value)) + && (Language.Value == Any || c.Entry.Languages.Contains(Language.Value)) + && (query.Length == 0 || c.Matches(query))); + var sorted = Sort.Value switch + { + GallerySort.Hot => cards.OrderByDescending(c => c.Entry.Stats.Hot), + GallerySort.Best => cards.OrderByDescending(c => c.Entry.Stats.BestOf(Period.Value)).ThenByDescending(c => c.Entry.Stats.Likes), + _ => cards.OrderByDescending(c => c.Entry.Created), + }; + var ordered = sorted.ThenByDescending(c => c.Entry.Created).ThenBy(c => c.Title, StringComparer.CurrentCultureIgnoreCase).ToList(); + + var selected = Selected; + _refreshing = true; + try + { + Cards.Clear(); + foreach (var card in ordered) + Cards.Add(card); + Selected = selected is not null && ordered.Contains(selected) ? selected : null; + } + finally + { + _refreshing = false; + } + if (Selected != selected) + OnSelectedChanged(Selected); + OnPropertyChanged(nameof(IsEmpty)); + OnPropertyChanged(nameof(EmptyText)); + } + + /// Loads the cards' covers in the order they are listed, a few at a time. + private async Task LoadThumbsAsync() + { + using var gate = new SemaphoreSlim(ThumbsAtOnce); + var tasks = Cards.ToList().Concat(_all).Distinct().Select(async card => + { + await gate.WaitAsync(_closing.Token); + try + { + await card.LoadThumbAsync(_client, _closing.Token); + } + finally + { + gate.Release(); + } + }).ToList(); + try + { + await Task.WhenAll(tasks); + } + catch (OperationCanceledException) + { + } + } + + public void Dispose() + { + _closing.Cancel(); + Detail?.Dispose(); + foreach (var card in _all) + card.Dispose(); + _closing.Dispose(); + } +} + +/// One shared preset in the list: its cover, title, author, likes, downloads and tags. +public sealed partial class PresetGalleryCardViewModel : ObservableObject, IDisposable +{ + /// The cover's size in the list, in pixels of its long edge. + public const int ThumbEdge = 480; + + private bool _loading; + + public PresetGalleryCardViewModel(GalleryEntry entry, ILocalizer loc) + { + Entry = entry; + Byline = entry.Author.Length == 0 ? "" : loc.Format("gallery.by", entry.Author); + Likes = loc.Format("gallery.likes", entry.Stats.Likes.ToString("N0", CultureInfo.CurrentCulture)); + Downloads = loc.Format("gallery.downloads", entry.Stats.Downloads.ToString("N0", CultureInfo.CurrentCulture)); + AutomationName = string.Join(", ", new[] { entry.Title, Byline, entry.HasStats ? Likes : "", entry.HasStats ? Downloads : "" }.Where(s => s.Length > 0)); + } + + public GalleryEntry Entry { get; } + public string Title => Entry.Title; + public string Byline { get; } + public IReadOnlyList Tags => Entry.Tags; + public bool HasStats => Entry.HasStats; + public string Likes { get; } + public string Downloads { get; } + + /// What a screen reader says for the card. + public string AutomationName { get; } + + [ObservableProperty] private Bitmap? _thumb; + + /// True when the query is in the title, description, author or a tag. + public bool Matches(string query) => + Entry.Title.Contains(query, StringComparison.CurrentCultureIgnoreCase) + || Entry.Description.Contains(query, StringComparison.CurrentCultureIgnoreCase) + || Entry.Author.Contains(query, StringComparison.CurrentCultureIgnoreCase) + || Entry.Tags.Any(t => t.Contains(query, StringComparison.CurrentCultureIgnoreCase)); + + /// Loads the cover's thumbnail (the cover itself when there is none); a failure leaves the placeholder. + public async Task LoadThumbAsync(PresetGalleryClient client, CancellationToken cancellationToken) + { + if (Thumb is not null || _loading || (Entry.Thumb ?? Entry.Images.FirstOrDefault()) is not { } path) + return; + _loading = true; + try + { + var data = await client.GetImageAsync(Entry, path, cancellationToken); + var bitmap = await Task.Run(() => GalleryBitmaps.Decode(data, ThumbEdge), cancellationToken); + if (cancellationToken.IsCancellationRequested) + bitmap?.Dispose(); + else + Thumb = bitmap; + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or ArgumentException) + { + } + finally + { + _loading = false; + } + } + + public void Dispose() + { + Thumb?.Dispose(); + Thumb = null; + } +} + +/// A picture of the chosen preset, with what a screen reader says for it. +public sealed partial class PresetGalleryImageViewModel(string name) : ObservableObject +{ + public string Name { get; } = name; + + [ObservableProperty] private Bitmap? _bitmap; +} + +/// One preset of a shared preset.json: its name, what it does, its main options. +public sealed record PresetGallerySummary(string Name, string What, string Options) +{ + public bool HasOptions => Options.Length > 0; +} + +/// Whether the chosen preset is being installed, was, or couldn't be. +public enum GalleryInstallState +{ + Idle, + Installing, + Installed, + Failed, +} + +/// The chosen preset: its pictures, description, what it adds, Install and Comments. +public sealed partial class PresetGalleryDetailViewModel : ObservableObject, IDisposable +{ + /// The pictures' size in the window, in pixels of the long edge. + public const int ImageEdge = 1280; + + private readonly PresetGalleryClient _client; + private readonly UserDataStore _store; + private readonly ILocalizer _loc; + private readonly Func _open; + private readonly Action _installed; + private readonly CancellationTokenSource _cancel; + + internal PresetGalleryDetailViewModel(GalleryEntry entry, PresetGalleryClient client, UserDataStore store, ILocalizer loc, + Func open, Action installed, CancellationToken closing) + { + Entry = entry; + _client = client; + _store = store; + _loc = loc; + _open = open; + _installed = installed; + _cancel = CancellationTokenSource.CreateLinkedTokenSource(closing); + Byline = entry.Author.Length == 0 ? "" : loc.Format("gallery.by", entry.Author); + License = loc.Format("gallery.license", entry.Author.Length == 0 ? "?" : entry.Author); + Stats = entry.HasStats + ? string.Join(" · ", loc.Format("gallery.likes", entry.Stats.Likes.ToString("N0", CultureInfo.CurrentCulture)), + loc.Format("gallery.downloads", entry.Stats.Downloads.ToString("N0", CultureInfo.CurrentCulture))) + : ""; + for (var i = 0; i < entry.Images.Count; i++) + Images.Add(new PresetGalleryImageViewModel(loc.Format("gallery.image", i + 1, entry.Images.Count))); + _shownImage = Images.FirstOrDefault(); + } + + public GalleryEntry Entry { get; } + public string Title => Entry.Title; + public string Byline { get; } + public string Description => Entry.Description; + public IReadOnlyList Tags => Entry.Tags; + public string Stats { get; } + public bool HasStats => Stats.Length > 0; + + /// The CC0 note, with who shared it. + public string License { get; } + + public ObservableCollection Images { get; } = []; + + /// The picture shown large; the others are thumbnails below it. + [ObservableProperty] private PresetGalleryImageViewModel? _shownImage; + + public bool HasSeveralImages => Images.Count > 1; + + /// What each preset in it does. + public ObservableCollection Presets { get; } = []; + + /// Which donut it goes on: the one it brings, or none. + [ObservableProperty] private string? _donut; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(InstallCommand))] + private bool _installable; + + /// Loading what it does, or why it can't be installed here. + [ObservableProperty] private string? _summaryNote; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(InstallCommand))] + [NotifyPropertyChangedFor(nameof(IsInstalling))] + private GalleryInstallState _installState; + + public bool IsInstalling => InstallState == GalleryInstallState.Installing; + + /// What the install did, or why it didn't. + [ObservableProperty] private string? _installMessage; + + public bool HasComments => Entry.Discussion is not null; + + /// Loads the pictures and what the preset does. + public async Task LoadAsync() + { + SummaryNote = _loc["gallery.loading_details"]; + var token = _cancel.Token; + await LoadSummaryAsync(token); + for (var i = 0; i < Entry.Images.Count && !token.IsCancellationRequested; i++) + { + try + { + var data = await _client.GetImageAsync(Entry, Entry.Images[i], token); + var bitmap = await Task.Run(() => GalleryBitmaps.Decode(data, ImageEdge), token); + if (token.IsCancellationRequested) + bitmap?.Dispose(); + else + Images[i].Bitmap = bitmap; + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or ArgumentException) + { + } + } + } + + private async Task LoadSummaryAsync(CancellationToken token) + { + byte[] json; + try + { + json = await _client.GetPresetAsync(Entry, token); + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException) + { + SummaryNote = token.IsCancellationRequested ? null : _loc["gallery.download_failed"]; + return; + } + if (!string.Equals(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(json)), Entry.Sha256, StringComparison.Ordinal)) + { + SummaryNote = _loc["gallery.mismatch"]; + return; + } + var check = SharedBundleCheck.Check(json); + if (check.Bundle is not { } bundle) + { + SummaryNote = _loc.Format("gallery.not_installable", check.Errors.FirstOrDefault()?.ToString() ?? ""); + return; + } + foreach (var preset in bundle.Presets) + Presets.Add(GallerySummaries.Describe(preset, bundle.Presets, _loc)); + Donut = bundle.Profiles.FirstOrDefault() is { } profile + ? _loc.Format("gallery.donut_new", _loc.DisplayName(profile), + profile.Extensions.Count == 0 ? _loc["gallery.donut_mixed"] : string.Join(", ", profile.Extensions.Take(8).Select(e => e.ToUpperInvariant())) + (profile.Extensions.Count > 8 ? " …" : "")) + : _loc["gallery.donut_none"]; + SummaryNote = null; + Installable = true; + } + + private bool CanInstall() => Installable && InstallState is not (GalleryInstallState.Installing or GalleryInstallState.Installed); + + /// Downloads it through the install link and adds it to the library as new presets. + [RelayCommand(CanExecute = nameof(CanInstall))] + private async Task InstallAsync() + { + InstallState = GalleryInstallState.Installing; + InstallMessage = _loc["gallery.installing"]; + byte[] json; + try + { + json = await _client.DownloadPresetAsync(Entry, _cancel.Token); + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException) + { + InstallState = GalleryInstallState.Failed; + InstallMessage = _loc["gallery.download_failed"]; + return; + } + var result = GalleryInstaller.Install(_store, json, Entry.Sha256, _loc.DisplayName, _loc.DisplayName); + if (!result.Ok) + { + InstallState = GalleryInstallState.Failed; + InstallMessage = result.Errors[0].Code == "install.sha256" + ? _loc["gallery.mismatch"] + : _loc.Format("gallery.install_failed", result.Errors[0].ToString()); + return; + } + InstallState = GalleryInstallState.Installed; + InstallMessage = result.Profile is { } donut + ? _loc.Format("gallery.installed_donut", result.Presets.Count, _loc.DisplayName(donut)) + : _loc.Format("gallery.installed", result.Presets.Count); + _installed(result); + } + + /// Opens the preset's discussion (comments and likes) in the browser. + [RelayCommand] + private Task OpenCommentsAsync() => + Entry.Discussion is { } number ? _open(PresetGalleryClient.DiscussionUri(number)) : Task.CompletedTask; + + [RelayCommand] + private void ShowImage(PresetGalleryImageViewModel image) => ShownImage = image; + + public void Dispose() + { + _cancel.Cancel(); + _cancel.Dispose(); + foreach (var image in Images) + { + image.Bitmap?.Dispose(); + image.Bitmap = null; + } + } +} + +/// Turns the gallery's pictures into bitmaps, checking their header before anything decodes them. +internal static class GalleryBitmaps +{ + /// + /// A still PNG, JPEG or WebP of at most pixels, scaled to at most + /// on its long edge; null for anything else. + /// + public static Bitmap? Decode(byte[] data, int edge) + { + if (GalleryImageHeader.Read(data) is not { Animated: false } info + || Math.Max(info.Width, info.Height) > SharedPresetFolderCheck.MaxLongEdge) + return null; + try + { + using var stream = new MemoryStream(data, writable: false); + return info.Width >= info.Height + ? Bitmap.DecodeToWidth(stream, Math.Min(edge, info.Width), BitmapInterpolationMode.HighQuality) + : Bitmap.DecodeToHeight(stream, Math.Min(edge, info.Height), BitmapInterpolationMode.HighQuality); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or IOException or NullReferenceException) + { + return null; + } + } +} diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml b/src/Filee.App/Views/Pages/PresetsPage.axaml index 730257ea2..3fa146a2b 100644 --- a/src/Filee.App/Views/Pages/PresetsPage.axaml +++ b/src/Filee.App/Views/Pages/PresetsPage.axaml @@ -35,6 +35,14 @@ ToolTip.Tip="{DynamicResource presets.delete}" AutomationProperties.Name="{DynamicResource presets.delete}"> + + diff --git a/src/Filee.App/Views/PresetGalleryWindow.axaml b/src/Filee.App/Views/PresetGalleryWindow.axaml new file mode 100644 index 000000000..e2b292edc --- /dev/null +++ b/src/Filee.App/Views/PresetGalleryWindow.axaml @@ -0,0 +1,251 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Filee.App/Views/PresetGalleryWindow.axaml.cs b/src/Filee.App/Views/PresetGalleryWindow.axaml.cs new file mode 100644 index 000000000..8c0faf429 --- /dev/null +++ b/src/Filee.App/Views/PresetGalleryWindow.axaml.cs @@ -0,0 +1,31 @@ +// The preset gallery's window (#1530). Escape closes it; the search box has the keys when it opens, Tab goes on to the +// filters and the list. + +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Threading; +using Filee.App.Services; + +namespace Filee.App.Views; + +public partial class PresetGalleryWindow : Window +{ + public PresetGalleryWindow() + { + InitializeComponent(); + Motion.Track(this); + UiZoom.Track(this); + Opened += (_, _) => Dispatcher.UIThread.Post(() => SearchBox.Focus(), DispatcherPriority.Background); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + if (e.Key == Key.Escape && !e.Handled) + { + Close(); + e.Handled = true; + return; + } + base.OnKeyDown(e); + } +} diff --git a/src/Filee.Cli/Cli.cs b/src/Filee.Cli/Cli.cs index 430653089..b35b77283 100644 --- a/src/Filee.Cli/Cli.cs +++ b/src/Filee.Cli/Cli.cs @@ -1,7 +1,8 @@ -// The "filee" commands: convert, watch, formats, presets, engines. Writes results for people (one line per file) or, with -// --json, one JSON document for other programs; while it runs, convert --json writes events to stderr and watch --json -// to stdout, one JSON object per line. Exit codes: 0 nothing failed (skipped files included), 1 some failed or were -// cancelled, 2 wrong arguments or a missing input, 3 nothing to convert. +// The "filee" commands: convert, watch, formats, presets ('presets check' for the preset gallery), engines. Writes +// results for people (one line per file) or, with --json, one JSON document for other programs; while it runs, +// convert --json writes events to stderr and watch --json to stdout, one JSON object per line. Exit codes: 0 nothing +// failed (skipped files included), 1 some failed or were cancelled, 2 wrong arguments or a missing input, 3 nothing to +// convert. using System.Text.Json; using Filee.Core.Conversion; @@ -40,6 +41,9 @@ public static async Task RunAsync(IReadOnlyList args, TextWriter ou case "version": output.WriteLine($"filee {Help.Version}"); return Success; + // Checks files only: no settings, no engines. + case "presets" when options.Inputs.Count > 0: + return PresetsCheckCommand.Run(options, output, errors); } await using var host = (createHost ?? (() => CliHost.Create()))(); diff --git a/src/Filee.Cli/CliOptions.cs b/src/Filee.Cli/CliOptions.cs index f89efd20d..506eef6db 100644 --- a/src/Filee.Cli/CliOptions.cs +++ b/src/Filee.Cli/CliOptions.cs @@ -209,6 +209,10 @@ public static CliOptions Parse(IReadOnlyList args) "Use either --split-every or --split-parts.", "watch" when options.Inputs.Count != 1 => "Give exactly one folder to watch.", "watch" when options.Sort is not null => "--sort only works with 'filee convert'.", + "presets" when options.Inputs.Count > 0 && options.Inputs[0].ToLowerInvariant() != "check" => + $"Unknown presets command '{options.Inputs[0]}'. Use 'filee presets' or 'filee presets check '.", + "presets" when options.Inputs.Count == 1 => "Give the folder of the shared preset to check, e.g. 'filee presets check presets/my-preset'.", + "presets" when options.Inputs.Count > 2 => "Give one folder at a time.", "engines" when options.Inputs.Count > 0 && options.Inputs[0].ToLowerInvariant() is not ("install" or "remove" or "download") => $"Unknown engines command '{options.Inputs[0]}'. Use 'filee engines', 'filee engines install ', 'filee engines download -o ' or 'filee engines remove '.", "engines" when options.Inputs.Count == 1 => $"Give the engine to {options.Inputs[0].ToLowerInvariant()}, e.g. 'filee engines {options.Inputs[0].ToLowerInvariant()} pandoc'.", diff --git a/src/Filee.Cli/Help.cs b/src/Filee.Cli/Help.cs index 3108aca69..0116da169 100644 --- a/src/Filee.Cli/Help.cs +++ b/src/Filee.Cli/Help.cs @@ -16,8 +16,7 @@ internal static class Help "watch" => Watch, "formats" => "Usage: filee formats [] [--json]\n\nLists every format, or what one format converts to.\n" + "With --json, prints the same as JSON (for scripts and other programs).\n", - "presets" => "Usage: filee presets [--json]\n\nLists the presets saved in Filee (built-in and your own).\n" + - "With --json, prints the same as JSON (for scripts and other programs).\n", + "presets" => Presets, "engines" => Engines, _ => General, }; @@ -31,6 +30,7 @@ filee convert --preset [options] filee watch --to [options] filee formats [] [--json] filee presets [--json] + filee presets check [--json] filee engines [--json] filee engines (install | remove) [--json] filee engines download -o [--json] @@ -50,6 +50,29 @@ filee engines install pandoc """; + private const string Presets = """ + Usage: filee presets [--json] + filee presets check [--json] [--quiet] + + Lists the presets saved in Filee (built-in and your own). With --json, prints the same as JSON (for scripts + and other programs). + + 'check' checks a shared preset for the preset gallery: a folder with preset.json (what Settings → General → + Export writes, with at most 20 presets and one donut), meta.json (optional) and 1 to 4 pictures in images/ + (1.png … 4.webp; PNG, JPEG or WebP, 640 to 2,560 pixels on the long edge, at most 2 MB, not animated). + Only fields on the gallery's list may be in preset.json, and nothing that saves outside the source's folder, + runs a program, or carries a path, a password or a link. It reads nothing else and changes nothing. + Exit codes: 0 the preset may be shared, 1 it has problems, 2 the folder doesn't exist. + + Options: + --json Print the result as JSON: "ok", "errors" (each with "code", "file", "path" and + "message") and "derived" (what the preset is: "kinds", "formats" with "from" and + "to", "minVersion", the number of "presets" and "profiles", and the "sha256" of + preset.json) + --quiet Print nothing when the preset passes + + """; + private const string Engines = """ Usage: filee engines [--json] filee engines install [--from ...] [--json] [--quiet] diff --git a/src/Filee.Cli/PresetsCheckCommand.cs b/src/Filee.Cli/PresetsCheckCommand.cs new file mode 100644 index 000000000..9c7508827 --- /dev/null +++ b/src/Filee.Cli/PresetsCheckCommand.cs @@ -0,0 +1,111 @@ +// "filee presets check ": checks one shared preset's folder for the preset gallery (#1530) with the rules the +// app installs by (SharedPresetFolderCheck), and decodes every picture with SkiaSharp, the library Filee draws and +// converts pictures with. The gallery's CI runs it on each submission and comments what it prints; with --json it +// gets the problems (code, file, path, message) and what the preset is, for meta.json. It reads no settings and +// writes nothing. + +using System.Text.Json; +using Filee.Core.Gallery; +using SkiaSharp; + +namespace Filee.Cli; + +internal static class PresetsCheckCommand +{ + public static int Run(CliOptions options, TextWriter output, TextWriter errors) + { + var folder = options.Inputs[1]; + if (!Directory.Exists(folder)) + { + errors.WriteLine($"filee: not a folder: {folder}"); + return Cli.UsageError; + } + var result = SharedPresetFolderCheck.Check(folder, new SkiaImageDecoder()); + if (options.Json) + WriteJson(result, output); + else if (!options.Quiet || !result.Ok) + WriteText(result, output); + return result.Ok ? Cli.Success : Cli.SomeFailed; + } + + private static void WriteText(PresetCheckResult result, TextWriter output) + { + foreach (var error in result.Errors) + output.WriteLine(error); + if (!result.Ok) + { + output.WriteLine($"Found {result.Errors.Count} problem(s)."); + return; + } + var derived = result.Derived!; + output.WriteLine($"OK: {derived.Presets} preset(s), {derived.Profiles} donut(s). Kinds: {string.Join(", ", derived.Kinds)}. " + + $"Formats: {(derived.From.Count == 0 ? "any" : string.Join(", ", derived.From))} → {(derived.To.Count == 0 ? "-" : string.Join(", ", derived.To))}. " + + $"Needs Filee {derived.MinVersion} or later."); + } + + private static void WriteJson(PresetCheckResult result, TextWriter output) => Cli.WriteJsonDocument(output, json => + { + json.WriteStartObject(); + json.WriteBoolean("ok", result.Ok); + json.WriteStartArray("errors"); + foreach (var error in result.Errors) + { + json.WriteStartObject(); + json.WriteString("code", error.Code); + json.WriteString("file", error.File); + json.WriteString("path", error.Path); + json.WriteString("message", error.Message); + json.WriteEndObject(); + } + json.WriteEndArray(); + if (result.Derived is { } derived) + { + json.WriteStartObject("derived"); + WriteList(json, "kinds", derived.Kinds); + json.WriteStartObject("formats"); + WriteList(json, "from", derived.From); + WriteList(json, "to", derived.To); + json.WriteEndObject(); + json.WriteString("minVersion", derived.MinVersion); + json.WriteNumber("presets", derived.Presets); + json.WriteNumber("profiles", derived.Profiles); + json.WriteString("sha256", derived.Sha256); + json.WriteEndObject(); + } + else + json.WriteNull("derived"); + json.WriteEndObject(); + }); + + private static void WriteList(Utf8JsonWriter json, string name, IEnumerable values) + { + json.WriteStartArray(name); + foreach (var value in values) + json.WriteStringValue(value); + json.WriteEndArray(); + } +} + +/// +/// Decodes a picture with SkiaSharp, every pixel, so a file that is broken past its header fails. Only called for +/// pictures whose header said 2560 pixels or less on the long edge. +/// +internal sealed class SkiaImageDecoder : IGalleryImageDecoder +{ + public GalleryImageDecode Decode(byte[] data) + { + using var stream = new SKMemoryStream(data); + using var codec = SKCodec.Create(stream, out var opened); + if (codec is null) + return new GalleryImageDecode(0, 0, 0, $"not a picture SkiaSharp reads ({opened})"); + var size = codec.Info; + if (Math.Max(size.Width, size.Height) > SharedPresetFolderCheck.MaxLongEdge) + return new GalleryImageDecode(size.Width, size.Height, 1, $"{size.Width} x {size.Height} is larger than its header said"); + var frames = Math.Max(1, codec.FrameCount); + using var bitmap = new SKBitmap(new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul)); + var decoded = codec.GetPixels(bitmap.Info, bitmap.GetPixels()); + return decoded == SKCodecResult.Success + ? new GalleryImageDecode(size.Width, size.Height, frames, null) + : new GalleryImageDecode(size.Width, size.Height, frames, decoded.ToString()); + } +} diff --git a/src/Filee.Core/Gallery/GalleryImageHeader.cs b/src/Filee.Core/Gallery/GalleryImageHeader.cs new file mode 100644 index 000000000..2bf9e4fa4 --- /dev/null +++ b/src/Filee.Core/Gallery/GalleryImageHeader.cs @@ -0,0 +1,151 @@ +// Reads what a picture of a shared preset is from its first bytes: PNG, JPEG or WebP, its size, and whether it moves +// (APNG, animated WebP). Read before anything decodes the picture, so a file claiming 50,000 x 50,000 pixels is refused +// without being decoded. Every offset is checked against the length: the file comes from anyone. + +using System.Buffers.Binary; + +namespace Filee.Core.Gallery; + +/// What found: the format ("png", "jpeg", "webp"), size and motion. +public readonly record struct GalleryImageInfo(string Format, int Width, int Height, bool Animated); + +/// Reads the header of a PNG, JPEG or WebP picture. +public static class GalleryImageHeader +{ + /// The picture's format, size and whether it is animated; null when it is none of the three or broken. + public static GalleryImageInfo? Read(ReadOnlySpan data) + { + if (data.Length >= 24 && data[..8].SequenceEqual((ReadOnlySpan)[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) + return Png(data); + if (data.Length >= 4 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF) + return Jpeg(data); + if (data.Length >= 30 && data[..4].SequenceEqual("RIFF"u8) && data.Slice(8, 4).SequenceEqual("WEBP"u8)) + return WebP(data); + return null; + } + + private static GalleryImageInfo? Png(ReadOnlySpan data) + { + if (!data.Slice(12, 4).SequenceEqual("IHDR"u8)) + return null; + var width = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(16, 4)); + var height = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(20, 4)); + if (width is 0 or > int.MaxValue || height is 0 or > int.MaxValue) + return null; + // An APNG says so with an acTL chunk before its first IDAT. + var animated = false; + var at = 8; + while (at + 8 <= data.Length) + { + var length = BinaryPrimitives.ReadUInt32BigEndian(data.Slice(at, 4)); + var type = data.Slice(at + 4, 4); + if (type.SequenceEqual("acTL"u8)) + { + animated = true; + break; + } + if (type.SequenceEqual("IDAT"u8) || length > int.MaxValue - 12) + break; + at += 12 + (int)length; + } + return new GalleryImageInfo("png", (int)width, (int)height, animated); + } + + private static GalleryImageInfo? Jpeg(ReadOnlySpan data) + { + var at = 2; + while (at + 4 <= data.Length) + { + if (data[at] != 0xFF) + return null; + var marker = data[at + 1]; + if (marker == 0xFF) + { + at++; // fill byte + continue; + } + if (marker is 0xD8 or 0x01 or (>= 0xD0 and <= 0xD7)) + { + at += 2; + continue; + } + var length = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(at + 2, 2)); + if (length < 2) + return null; + // Start of frame: every SOFn but DHT (C4), JPG (C8) and DAC (CC). + if (marker is >= 0xC0 and <= 0xCF and not 0xC4 and not 0xC8 and not 0xCC) + { + if (at + 9 > data.Length) + return null; + var height = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(at + 5, 2)); + var width = BinaryPrimitives.ReadUInt16BigEndian(data.Slice(at + 7, 2)); + return width == 0 || height == 0 ? null : new GalleryImageInfo("jpeg", width, height, false); + } + if (marker is 0xD9 or 0xDA) + return null; // the end, or the image data, before any frame header + at += 2 + length; + } + return null; + } + + private static GalleryImageInfo? WebP(ReadOnlySpan data) + { + int? width = null, height = null; + var animated = false; + var at = 12; + while (at + 8 <= data.Length) + { + var type = data.Slice(at, 4); + var length = BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(at + 4, 4)); + var body = at + 8; + if (length > int.MaxValue - 9) + return null; + var available = Math.Min((int)length, data.Length - body); + var chunk = data.Slice(body, available); + if (type.SequenceEqual("VP8X"u8) && chunk.Length >= 10) + { + animated |= (chunk[0] & 0x02) != 0; + width = 1 + (chunk[4] | chunk[5] << 8 | chunk[6] << 16); + height = 1 + (chunk[7] | chunk[8] << 8 | chunk[9] << 16); + } + else if (type.SequenceEqual("ANIM"u8) || type.SequenceEqual("ANMF"u8)) + { + animated = true; + } + else if (type.SequenceEqual("VP8 "u8) && width is null && chunk.Length >= 10) + { + // Frame tag (3 bytes), start code 9D 01 2A, then 14-bit width and height. + if (chunk[3] != 0x9D || chunk[4] != 0x01 || chunk[5] != 0x2A) + return null; + width = BinaryPrimitives.ReadUInt16LittleEndian(chunk.Slice(6, 2)) & 0x3FFF; + height = BinaryPrimitives.ReadUInt16LittleEndian(chunk.Slice(8, 2)) & 0x3FFF; + } + else if (type.SequenceEqual("VP8L"u8) && width is null && chunk.Length >= 5) + { + if (chunk[0] != 0x2F) + return null; + var bits = BinaryPrimitives.ReadUInt32LittleEndian(chunk.Slice(1, 4)); + width = 1 + (int)(bits & 0x3FFF); + height = 1 + (int)((bits >> 14) & 0x3FFF); + } + // Chunks are padded to an even length. + at = body + (int)length + (int)(length & 1); + } + return width is > 0 && height is > 0 ? new GalleryImageInfo("webp", width.Value, height.Value, animated) : null; + } +} + +/// What decoding a picture fully gave (). +public readonly record struct GalleryImageDecode(int Width, int Height, int Frames, string? Error) +{ + public bool Ok => Error is null; +} + +/// +/// Decodes a picture completely, to tell that it isn't broken past its header. The command line gives one built on +/// the image library Filee converts with; without one the folder check reads the headers only. +/// +public interface IGalleryImageDecoder +{ + GalleryImageDecode Decode(byte[] data); +} diff --git a/src/Filee.Core/Gallery/GalleryIndex.cs b/src/Filee.Core/Gallery/GalleryIndex.cs new file mode 100644 index 000000000..e17d14c05 --- /dev/null +++ b/src/Filee.Core/Gallery/GalleryIndex.cs @@ -0,0 +1,221 @@ +// index.json of the preset gallery (#1530): the list of shared presets the app and filee.sh show. It comes from the +// network, so it is read field by field with limits: an entry that isn't as the contract says is left out, every text +// is cut to a length, and the files it names are paths relative to index.json that end in the preset's own folder +// (filee.sh's index has files/presets//…, the repository's presets//…), never a URL or "..". + +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Filee.Core.Gallery; + +/// Likes, comments and downloads of a shared preset, and its scores for the Hot and Best orders. +public sealed record GalleryStats(int Likes, int Comments, int Downloads, double Hot, IReadOnlyDictionary Best) +{ + public static readonly GalleryStats None = new(0, 0, 0, 0, new Dictionary()); + + /// The periods of the Best order: day, week, month, year and all time. + public static readonly IReadOnlyList Periods = ["day", "week", "month", "year", "all"]; + + public double BestOf(string period) => Best.GetValueOrDefault(period); +} + +/// One shared preset in index.json. +public sealed record GalleryEntry +{ + public required string Id { get; init; } + public required string Title { get; init; } + public string Description { get; init; } = ""; + public string Author { get; init; } = ""; + public IReadOnlyList Tags { get; init; } = []; + public IReadOnlyList Languages { get; init; } = []; + public IReadOnlyList Kinds { get; init; } = []; + public IReadOnlyList FormatsFrom { get; init; } = []; + public IReadOnlyList FormatsTo { get; init; } = []; + + /// The lowest Filee that can install it. + public Version MinVersion { get; init; } = new(0, 0, 0); + + public DateTimeOffset Created { get; init; } + public DateTimeOffset Updated { get; init; } + + /// Its discussion in the gallery's repository (likes and comments), when it has one. + public int? Discussion { get; init; } + + public string License { get; init; } = SharedPresetFolderCheck.License; + + /// Its pictures (1 to 4, the cover first), as paths relative to index.json. + public IReadOnlyList Images { get; init; } = []; + + /// The cover's thumbnail; null without one (the cover is shown instead). + public string? Thumb { get; init; } + + /// Its preset.json, as a path relative to index.json. + public required string Preset { get; init; } + + /// + /// The install link filee.sh counts (https://filee.sh/presets/download/<id>, or relative to index.json), + /// when the index has one; the repository's index has none. + /// + public string? Download { get; init; } + + /// The SHA-256 of its preset.json (lowercase hex): what is installed must be exactly that file. + public required string Sha256 { get; init; } + + public GalleryStats Stats { get; init; } = GalleryStats.None; + + /// True when index.json had stats for it (the site adds them; the repository's own index has none). + public bool HasStats { get; init; } +} + +/// The gallery's list, as read by . +public sealed partial record GalleryIndex(int Version, DateTimeOffset Generated, IReadOnlyList Entries) +{ + /// Largest index.json the app reads, in bytes. + public const int MaxBytes = 8 * 1024 * 1024; + + /// Most entries read; the rest are left out. + public const int MaxEntries = 5000; + + /// Reads index.json. Throws when it isn't an index at all. + public static GalleryIndex Parse(ReadOnlySpan json) + { + if (json.Length > MaxBytes) + throw new JsonException("index.json is too large."); + using var document = JsonDocument.Parse(json.ToArray(), new JsonDocumentOptions { MaxDepth = 16 }); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("presets", out var presets) || presets.ValueKind != JsonValueKind.Array) + throw new JsonException("index.json has no presets list."); + var version = root.TryGetProperty("version", out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var number) ? number : 0; + var entries = new List(); + var ids = new HashSet(StringComparer.Ordinal); + foreach (var item in presets.EnumerateArray()) + { + if (entries.Count >= MaxEntries) + break; + if (Entry(item) is { } entry && ids.Add(entry.Id)) + entries.Add(entry); + } + return new GalleryIndex(version, Date(root, "generated"), entries); + } + + /// One entry, or null when it lacks what an install needs or names a file outside its folder. + private static GalleryEntry? Entry(JsonElement item) + { + if (item.ValueKind != JsonValueKind.Object) + return null; + var id = Text(item, "id", 48); + if (!SharedPresetFolderCheck.IsSlug(id)) + return null; + var preset = Text(item, "preset", 200); + var sha256 = Text(item, "sha256", 64).ToLowerInvariant(); + var title = Text(item, "title", 60).Trim(); + if (InFolder(preset, id) != "preset.json" || !Sha256Pattern().IsMatch(sha256) || title.Length == 0) + return null; + var images = List(item, "images", 4, 200).Where(path => InFolder(path, id) is { } file && ImageName().IsMatch(file)).ToList(); + var thumb = Text(item, "thumb", 200); + var download = Text(item, "download", 200); + var formats = item.TryGetProperty("formats", out var f) && f.ValueKind == JsonValueKind.Object ? f : default; + var stats = item.TryGetProperty("stats", out var s) && s.ValueKind == JsonValueKind.Object ? s : default; + return new GalleryEntry + { + Id = id, + Title = title, + Description = Text(item, "description", 600), + Author = Text(item, "author", 39), + Tags = List(item, "tags", 6, 24), + Languages = List(item, "languages", 10, 16), + Kinds = List(item, "kinds", 3, 16).Where(SharedPresetFolderCheck.Kinds.Contains).ToList(), + FormatsFrom = formats.ValueKind == JsonValueKind.Object ? List(formats, "from", 1000, 32) : [], + FormatsTo = formats.ValueKind == JsonValueKind.Object ? List(formats, "to", 1000, 32) : [], + MinVersion = System.Version.TryParse(Text(item, "minVersion", 20), out var min) ? min : new System.Version(0, 0, 0), + Created = Date(item, "created"), + Updated = Date(item, "updated"), + Discussion = item.TryGetProperty("discussion", out var d) && d.ValueKind == JsonValueKind.Number && d.TryGetInt32(out var n) && n > 0 ? n : null, + License = Text(item, "license", 16) is { Length: > 0 } license ? license : SharedPresetFolderCheck.License, + Images = images, + Thumb = InFolder(thumb, id) is { } thumbFile && ThumbName().IsMatch(thumbFile) ? thumb : null, + Preset = preset, + Download = IsDownload(download, id) ? download : null, + Sha256 = sha256, + HasStats = stats.ValueKind == JsonValueKind.Object, + Stats = stats.ValueKind == JsonValueKind.Object ? Stats(stats) : GalleryStats.None, + }; + } + + private static GalleryStats Stats(JsonElement stats) + { + var best = new Dictionary(StringComparer.Ordinal); + if (stats.TryGetProperty("best", out var b) && b.ValueKind == JsonValueKind.Object) + foreach (var period in GalleryStats.Periods) + best[period] = Number(b, period); + return new GalleryStats((int)Number(stats, "likes"), (int)Number(stats, "comments"), (int)Number(stats, "downloads"), + Number(stats, "hot"), best); + } + + /// + /// The part of inside the preset's folder (preset.json, images/1.webp), when it is + /// a relative path to that folder (files/presets/<id>/…, presets/<id>/…); null otherwise. + /// + private static string? InFolder(string path, string id) + { + var match = RelativePath().Match(path); + return match.Success && match.Groups["id"].Value == id ? match.Groups["file"].Value : null; + } + + // Up to three plain folders before presets// (no "..", no scheme, no leading slash), then a file of the folder. + [GeneratedRegex(@"^(?:[a-z0-9][a-z0-9_\-]*/){0,3}presets/(?[a-z0-9\-]{3,48})/(?preset\.json|images/[1-4](?:-thumb)?\.[a-z]{3,4})$", RegexOptions.CultureInvariant)] + private static partial Regex RelativePath(); + + [GeneratedRegex(@"^images/[1-4]\.(webp|png|jpg|jpeg)$", RegexOptions.CultureInvariant)] + private static partial Regex ImageName(); + + [GeneratedRegex(@"^images/[1-4]-thumb\.webp$", RegexOptions.CultureInvariant)] + private static partial Regex ThumbName(); + + /// + /// An install link of the preset's: https://filee.sh/presets/download/<id> or relative to index.json + /// (download/<id>). The app also checks that it stays on the host index.json came from. + /// + private static bool IsDownload(string link, string id) => + link == "https://filee.sh/presets/download/" + id || DownloadPath().Match(link) is { Success: true } m && m.Groups["id"].Value == id; + + [GeneratedRegex(@"^(?:[a-z0-9][a-z0-9_\-]*/){0,3}download/(?[a-z0-9\-]{3,48})$", RegexOptions.CultureInvariant)] + private static partial Regex DownloadPath(); + + [GeneratedRegex(@"^[0-9a-f]{64}$", RegexOptions.CultureInvariant)] + private static partial Regex Sha256Pattern(); + + private static string Text(JsonElement item, string name, int max) + { + if (!item.TryGetProperty(name, out var value) || value.ValueKind != JsonValueKind.String) + return ""; + var text = value.GetString() ?? ""; + // No control or direction-changing characters in what the window shows. + text = new string([.. text.Where(c => !char.IsControl(c) || c == '\n').Where(c => c is not (>= '‪' and <= '‮') and not (>= '⁦' and <= '⁩'))]); + return text.Length <= max ? text : text[..max]; + } + + private static List List(JsonElement item, string name, int maxCount, int maxLength) + { + if (!item.TryGetProperty(name, out var value) || value.ValueKind != JsonValueKind.Array) + return []; + return [.. value.EnumerateArray() + .Where(e => e.ValueKind == JsonValueKind.String) + .Select(e => e.GetString() ?? "") + .Where(text => text.Length is > 0 && text.Length <= maxLength && !text.Any(char.IsControl)) + .Distinct(StringComparer.Ordinal) + .Take(maxCount)]; + } + + private static double Number(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d) && d >= 0 + ? Math.Min(d, int.MaxValue) + : 0; + + private static DateTimeOffset Date(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + && DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) + ? date + : DateTimeOffset.MinValue; +} diff --git a/src/Filee.Core/Gallery/GalleryInstaller.cs b/src/Filee.Core/Gallery/GalleryInstaller.cs new file mode 100644 index 000000000..eb5f8fe7e --- /dev/null +++ b/src/Filee.Core/Gallery/GalleryInstaller.cs @@ -0,0 +1,113 @@ +// Installs a preset from the preset gallery (#1530). Unlike Settings → General → Import, which replaces presets with +// the same id, an install only adds: every preset and the donut get new ids, and a name the library already has gets +// " (2)". The file is checked again here, with the same rules the gallery's CI used, and must be exactly the file +// index.json lists (its SHA-256): the app trusts neither the server nor the network in between. + +using System.Security.Cryptography; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Gallery; + +/// What an install added, or why nothing was. +public sealed record GalleryInstallResult( + IReadOnlyList Presets, + ToolbarProfile? Profile, + IReadOnlyList Errors) +{ + public bool Ok => Errors.Count == 0; +} + +/// Adds a shared preset.json to the library as new presets (and a new donut). +public static class GalleryInstaller +{ + /// + /// Checks against and the gallery's rules, then adds what it holds + /// to and saves the library. and + /// give the names the user sees (a built-in name in their language), to tell a clash. + /// + public static GalleryInstallResult Install(UserDataStore store, ReadOnlySpan json, string sha256, + Func presetName, Func profileName) + { + var actual = Convert.ToHexStringLower(SHA256.HashData(json)); + if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase)) + return Failed("install.sha256", "is not the file the gallery lists (its SHA-256 differs)"); + + var check = SharedBundleCheck.Check(json); + if (!check.Ok || check.Bundle is not { } bundle) + return new GalleryInstallResult([], null, check.Errors); + + // As Import: no path to a picture of someone else's, and the back faces a bundle from before them lacks. + foreach (var preset in bundle.Presets) + preset.Image.ForgetBackdropPictures(); + SettingsMigrations.AddBackFaces(bundle.Presets, bundle.Profiles); + + var taken = store.Presets.Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + var ids = new Dictionary(StringComparer.Ordinal); + foreach (var preset in bundle.Presets) + { + string id; + do + id = Preset.NewId(); + while (!taken.Add(id)); + ids[preset.Id] = id; + preset.Id = id; + } + string Map(string id) => ids.GetValueOrDefault(id, id); + + var names = store.Presets.Select(presetName).ToHashSet(StringComparer.CurrentCultureIgnoreCase); + foreach (var preset in bundle.Presets) + { + preset.SubPresetIds = [.. preset.SubPresetIds.Select(Map)]; + var name = Unique(presetName(preset), names); + if (name != presetName(preset)) + { + preset.Name = name; + preset.NameKey = null; + } + names.Add(name); + } + + var profile = bundle.Profiles.FirstOrDefault(); + if (profile is not null) + { + var profileIds = store.Profiles.Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + do + profile.Id = Guid.NewGuid().ToString("N")[..12]; + while (profileIds.Contains(profile.Id)); + profile.PresetIds = [.. profile.PresetIds.Select(Map)]; + profile.BackPresetIds = [.. (profile.BackPresetIds ?? []).Select(Map)]; + var name = Unique(profileName(profile), store.Profiles.Select(profileName).ToHashSet(StringComparer.CurrentCultureIgnoreCase)); + if (name != profileName(profile)) + { + profile.Name = name; + profile.NameKey = null; + } + } + + store.Presets.AddRange(bundle.Presets); + // After every donut of the user's: a file type one of theirs takes keeps opening theirs (the first that has + // it), so the new donut changes nothing until the user gives it a file type (Settings → Toolbar). + if (profile is not null) + store.Profiles.Add(profile); + store.SaveLibrary(); + return new GalleryInstallResult(bundle.Presets, profile, []); + } + + /// , or with " (2)", " (3)" … when the library has it already. + internal static string Unique(string name, IReadOnlySet taken) + { + if (!taken.Contains(name)) + return name; + for (var n = 2; ; n++) + { + var candidate = $"{name} ({n})"; + if (!taken.Contains(candidate)) + return candidate; + } + } + + private static GalleryInstallResult Failed(string code, string message) => + new([], null, [new PresetCheckError(code, SharedBundleCheck.FileName, "", message)]); +} diff --git a/src/Filee.Core/Gallery/PresetCheckResult.cs b/src/Filee.Core/Gallery/PresetCheckResult.cs new file mode 100644 index 000000000..8342be31e --- /dev/null +++ b/src/Filee.Core/Gallery/PresetCheckResult.cs @@ -0,0 +1,71 @@ +// What checking a shared preset found (#1530): the problems, each with a stable code for the gallery's CI, and what +// the preset is (its kinds, formats and the lowest Filee that runs it), which the CI writes into meta.json. + +using Filee.Core.Settings; + +namespace Filee.Core.Gallery; + +/// +/// One problem: is stable (scripts match it), the file in the preset's folder +/// (preset.json, images/2.png), where in it (presets[0].output.customFolder, +/// empty for the whole file) and what is wrong, in English, for people. +/// +public sealed record PresetCheckError(string Code, string File, string Path, string Message) +{ + public override string ToString() => + Path.Length == 0 ? $"{File}: {Message} ({Code})" : $"{File}: {Path}: {Message} ({Code})"; +} + +/// +/// What a preset.json is, derived from it: (convert, tool, toolbar), the +/// formats it reads (: its donut's extensions) and writes (), the lowest Filee that +/// can install it, and the SHA-256 of the file (lowercase hex) that index.json lists. +/// +public sealed record PresetCheckDerived( + IReadOnlyList Kinds, + IReadOnlyList From, + IReadOnlyList To, + string MinVersion, + int Presets, + int Profiles, + string Sha256); + +/// The outcome of or . +public sealed class PresetCheckResult +{ + /// Most problems reported; a file with more gets one last "too many problems". + public const int MaxErrors = 200; + + private readonly List _errors = []; + + public IReadOnlyList Errors => _errors; + + /// True when nothing is wrong. + public bool Ok => _errors.Count == 0; + + /// What the preset.json is; null when it couldn't be read as a preset bundle. + public PresetCheckDerived? Derived { get; internal set; } + + /// + /// The bundle as the app reads it, when preset.json passed (what an install adds). Each check reads it anew, so it + /// may be changed. + /// + public PresetBundle? Bundle { get; internal set; } + + /// True once problems were found: further checks stop. + internal bool Full => _errors.Count > MaxErrors; + + internal void Add(string code, string file, string path, string message) + { + if (_errors.Count < MaxErrors) + _errors.Add(new PresetCheckError(code, file, path, message)); + else if (_errors.Count == MaxErrors) + _errors.Add(new PresetCheckError("check.too_many_errors", file, "", $"more than {MaxErrors} problems; the rest aren't listed")); + } + + internal void AddRange(PresetCheckResult other) + { + foreach (var error in other._errors) + Add(error.Code, error.File, error.Path, error.Message); + } +} diff --git a/src/Filee.Core/Gallery/SharedBundleCheck.cs b/src/Filee.Core/Gallery/SharedBundleCheck.cs new file mode 100644 index 000000000..aff8ab44c --- /dev/null +++ b/src/Filee.Core/Gallery/SharedBundleCheck.cs @@ -0,0 +1,310 @@ +// Checks a preset.json shared through the preset gallery (#1530) against the allow-list (SharedPresetRules), first as +// JSON (every field known, every value in range: nothing the app would read is left unchecked) and then as presets +// (kinds, tools, target formats, references between presets and the donut). The gallery's CI runs it through +// 'filee presets check', and the app runs it again before it installs anything, without trusting the server. + +using System.Security.Cryptography; +using System.Text.Json; +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Core.Settings; + +namespace Filee.Core.Gallery; + +/// Checks one preset.json (a ) for the preset gallery. +public static class SharedBundleCheck +{ + /// The file name problems in a bundle are reported against. + public const string FileName = "preset.json"; + + /// + /// The lowest Filee that can install a shared preset: the first with the gallery. A field added to the allow-list + /// later raises it for the presets that use it. + /// + public const string BaselineVersion = "2.5.0"; + + /// Largest preset.json, in bytes. + public const int MaxBytes = SharedPresetRules.MaxBundleBytes; + + /// Checks , the bytes of a preset.json. + public static PresetCheckResult Check(ReadOnlySpan json) => Check(json, SharedPresetRules.MaxPresets); + + internal static PresetCheckResult Check(ReadOnlySpan json, int maxPresets) + { + var result = new PresetCheckResult(); + if (json.Length > SharedPresetRules.MaxBundleBytes) + { + result.Add("bundle.too_large", FileName, "", $"is {json.Length:N0} bytes; a shared preset.json may have at most {SharedPresetRules.MaxBundleBytes:N0}"); + return result; + } + var sha256 = Convert.ToHexStringLower(SHA256.HashData(json)); + // An editor's byte order mark is the only thing tolerated before the JSON. + if (json.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + json = json[3..]; + + JsonDocument document; + try + { + document = JsonDocument.Parse(json.ToArray(), new JsonDocumentOptions + { + MaxDepth = SharedPresetRules.MaxDepth, + CommentHandling = JsonCommentHandling.Disallow, + AllowTrailingCommas = false, + }); + } + catch (JsonException ex) + { + var deep = ex.Message.Contains("maximum configured depth", StringComparison.OrdinalIgnoreCase); + result.Add(deep ? "bundle.too_deep" : "bundle.invalid_json", FileName, "", + deep ? $"nests deeper than {SharedPresetRules.MaxDepth} levels" : "is not valid JSON: " + FirstLine(ex.Message)); + return result; + } + + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + result.Add("bundle.not_object", FileName, "", "must be a JSON object with \"presets\" (as Settings → General → Export writes it)"); + return result; + } + var rules = maxPresets == SharedPresetRules.MaxPresets + ? SharedPresetRules.BundleFields + : SharedPresetRules.BundleFields with + { + Fields = new Dictionary(SharedPresetRules.BundleFields.Fields) + { + ["presets"] = new ListRule(SharedPresetRules.PresetFields, maxPresets), + }, + }; + new Walker(result, FileName).Check(root, rules, ""); + if (!root.TryGetProperty("presets", out var presets) || presets.ValueKind != JsonValueKind.Array || presets.GetArrayLength() == 0) + result.Add("bundle.no_presets", FileName, "presets", "has no presets"); + if (!result.Ok) + return result; + } + + PresetBundle bundle; + try + { + bundle = JsonSerializer.Deserialize(json, FileeJsonContext.Default.PresetBundle) + ?? throw new JsonException("null"); + } + catch (Exception ex) when (ex is JsonException or NotSupportedException or InvalidOperationException) + { + result.Add("bundle.invalid_json", FileName, "", "can't be read as a preset bundle: " + FirstLine(ex.Message)); + return result; + } + + CheckPresets(bundle, result); + if (result.Ok) + result.Bundle = bundle; + result.Derived = Derive(bundle, sha256); + return result; + } + + /// The rules that span fields: kinds, tools, targets and the ids presets and the donut refer to. + private static void CheckPresets(PresetBundle bundle, PresetCheckResult result) + { + var ids = new HashSet(StringComparer.Ordinal); + for (var i = 0; i < bundle.Presets.Count; i++) + { + var preset = bundle.Presets[i]; + var at = $"presets[{i}]"; + if (!ids.Add(preset.Id)) + result.Add("preset.duplicate_id", FileName, at + ".id", $"the id \"{preset.Id}\" is used by another preset in the file"); + if (string.IsNullOrWhiteSpace(preset.Name) && string.IsNullOrEmpty(preset.NameKey)) + result.Add("preset.no_name", FileName, at + ".name", "needs a name"); + + switch (preset.Kind) + { + case PresetKind.Tool when !SharedPresetRules.Tools.Contains(preset.Tool): + result.Add("preset.tool_not_allowed", FileName, at + ".tool", + $"the tool \"{preset.Tool}\" can't be shared (allowed: {string.Join(", ", SharedPresetRules.Tools.Select(t => t ?? Preset.CropTool).Distinct())})"); + break; + case not PresetKind.Tool when preset.Tool is not null: + result.Add("preset.tool_not_allowed", FileName, at + ".tool", "only a preset of the kind Tool has a tool"); + break; + } + + if (preset.IsGroup) + { + if (preset.TargetFormat != Preset.GroupTarget) + result.Add("preset.target_unknown", FileName, at + ".targetFormat", $"a group's target is \"{Preset.GroupTarget}\""); + } + else if (preset.TargetFormat != BuiltInData.SameAsSource + && (FormatRegistry.FindById(preset.TargetFormat) is null || preset.TargetFormat == Preset.CopyTarget)) + { + result.Add("preset.target_unknown", FileName, at + ".targetFormat", $"\"{preset.TargetFormat}\" is not a format Filee writes"); + } + + for (var r = 0; r < preset.Output.Renames.Count; r++) + { + var step = preset.Output.Renames[r]; + if (step.Kind == RenameKind.Regex && OutputPathResolver.RenameError(step.Find) is { } why) + result.Add("output.rename_regex", FileName, $"{at}.output.renames[{r}].find", "is not a valid regular expression: " + FirstLine(why)); + } + } + + var actions = bundle.Presets.Where(p => !p.IsGroup).Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + for (var i = 0; i < bundle.Presets.Count; i++) + { + var preset = bundle.Presets[i]; + if (!preset.IsGroup && preset.SubPresetIds.Count > 0) + result.Add("preset.reference", FileName, $"presets[{i}].subPresetIds", "only a group fans out other presets"); + if (!preset.IsGroup) + continue; + foreach (var id in preset.SubPresetIds.Where(id => !actions.Contains(id))) + result.Add("preset.reference", FileName, $"presets[{i}].subPresetIds", $"\"{id}\" is not a conversion or tool in this file"); + } + + for (var i = 0; i < bundle.Profiles.Count; i++) + { + var profile = bundle.Profiles[i]; + var at = $"profiles[{i}]"; + if (string.IsNullOrWhiteSpace(profile.Name) && string.IsNullOrEmpty(profile.NameKey)) + result.Add("profile.no_name", FileName, at + ".name", "needs a name"); + foreach (var id in profile.PresetIds.Concat(profile.BackPresetIds ?? []).Where(id => !ids.Contains(id)).Distinct()) + result.Add("profile.reference", FileName, at + ".presetIds", $"\"{id}\" is not a preset in this file"); + foreach (var extension in profile.Extensions.Where(e => FormatRegistry.FindByExtension(e) is null)) + result.Add("profile.extension_unknown", FileName, at + ".extensions", $"\"{extension}\" is not an extension Filee knows"); + } + } + + /// What the bundle is, for meta.json (see ). + private static PresetCheckDerived Derive(PresetBundle bundle, string sha256) + { + var kinds = new List(); + if (bundle.Presets.Any(p => p.Kind is PresetKind.Convert or PresetKind.Group)) + kinds.Add("convert"); + if (bundle.Presets.Any(p => p.Kind == PresetKind.Tool)) + kinds.Add("tool"); + if (bundle.Profiles.Count > 0) + kinds.Add("toolbar"); + var from = bundle.Profiles.SelectMany(p => p.Extensions) + .Select(SharedPresetRules.FormatOfExtension).OfType() + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); + var to = bundle.Presets.Where(p => p.Kind == PresetKind.Convert && p.TargetFormat != BuiltInData.SameAsSource) + .Select(p => p.TargetFormat).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); + return new PresetCheckDerived(kinds, from, to, BaselineVersion, bundle.Presets.Count, bundle.Profiles.Count, sha256); + } + + private static string FirstLine(string text) + { + var end = text.IndexOfAny(['\r', '\n']); + return end < 0 ? text : text[..end]; + } + + /// Walks JSON along an , reporting every value the rules don't allow. + internal sealed class Walker(PresetCheckResult result, string file) + { + public void Check(JsonElement value, ValueRule rule, string path) + { + if (result.Full) + return; + if (rule is LeftOutRule leftOut) + { + if (!IsEmpty(value)) + result.Add("field.left_out", file, path, $"must be empty: {leftOut.Why}"); + return; + } + if (value.ValueKind == JsonValueKind.Null) + { + if (!rule.Nullable) + result.Add("field.type", file, path, "may not be null"); + return; + } + switch (rule) + { + case ObjectRule obj: + if (value.ValueKind != JsonValueKind.Object) + { + result.Add("field.type", file, path, "must be an object"); + return; + } + var seen = new HashSet(StringComparer.Ordinal); + foreach (var property in value.EnumerateObject()) + { + var at = path.Length == 0 ? property.Name : $"{path}.{property.Name}"; + if (!seen.Add(property.Name)) + result.Add("field.duplicate", file, at, "appears twice"); + else if (!obj.Fields.TryGetValue(property.Name, out var field)) + result.Add("field.unknown", file, at, "is not a field a shared preset may have"); + else + Check(property.Value, field, at); + } + break; + case BoolRule flag: + if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) + result.Add("field.type", file, path, "must be true or false"); + else if (flag.Only is { } only && value.GetBoolean() != only) + result.Add("field.not_allowed", file, path, $"must be {(only ? "true" : "false")} in a shared preset"); + break; + case IntRule number: + if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt64(out var whole)) + result.Add("field.type", file, path, "must be a whole number"); + else if (whole < number.Min || whole > number.Max || number.Allowed?.Contains(whole) == false) + result.Add("field.range", file, path, number.Allowed is { } allowed + ? $"must be one of {string.Join(", ", allowed)}" + : $"must be from {number.Min} to {number.Max}"); + break; + case NumberRule real: + if (value.ValueKind != JsonValueKind.Number || !value.TryGetDouble(out var d) || !double.IsFinite(d)) + result.Add("field.type", file, path, "must be a number"); + else if (d < real.Min || d > real.Max) + result.Add("field.range", file, path, FormattableString.Invariant($"must be from {real.Min} to {real.Max}")); + break; + case EnumRule choice: + if (value.ValueKind != JsonValueKind.String) + result.Add("field.type", file, path, "must be a name, as a string"); + else if (!choice.Names.Contains(value.GetString(), StringComparer.OrdinalIgnoreCase)) + result.Add("field.value", file, path, $"\"{Shorten(value.GetString())}\" is not allowed (allowed: {string.Join(", ", choice.Names)})"); + break; + case StringRule text: + if (value.ValueKind != JsonValueKind.String) + { + result.Add("field.type", file, path, "must be a string"); + break; + } + var s = value.GetString() ?? ""; + if (s.Length > text.MaxLength) + result.Add("text.length", file, path, $"is {s.Length} characters long; at most {text.MaxLength}"); + else if (SharedText.Common(s) is var (code, message)) + result.Add(code, file, path, message); + else if (text.Check?.Invoke(s) is { } why) + result.Add("field.value", file, path, $"\"{Shorten(s)}\" {why}"); + break; + case ListRule list: + if (value.ValueKind != JsonValueKind.Array) + { + result.Add("field.type", file, path, "must be a list"); + break; + } + var count = value.GetArrayLength(); + if (count > list.MaxCount) + { + result.Add("field.range", file, path, $"has {count} items; at most {list.MaxCount}"); + break; + } + var index = 0; + foreach (var item in value.EnumerateArray()) + Check(item, list.Item, $"{path}[{index++}]"); + break; + } + } + + /// Null, "", false, 0, [] or {}: what an export writes for a field nobody set. + private static bool IsEmpty(JsonElement value) => value.ValueKind switch + { + JsonValueKind.Null or JsonValueKind.False or JsonValueKind.Undefined => true, + JsonValueKind.String => value.GetString()!.Length == 0, + JsonValueKind.Number => value.TryGetDouble(out var d) && d == 0, + JsonValueKind.Array => value.GetArrayLength() == 0, + JsonValueKind.Object => !value.EnumerateObject().Any(), + _ => false, + }; + + private static string Shorten(string? text) => + text is null ? "" : text.Length <= 40 ? text : text[..40] + "…"; + } +} diff --git a/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs b/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs new file mode 100644 index 000000000..268c4288c --- /dev/null +++ b/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs @@ -0,0 +1,281 @@ +// Checks one folder of the preset gallery's repository (#1530): presets// with preset.json, an optional +// meta.json and 1 to 4 pictures in images/ (1 is the cover), the thumbnails the gallery's CI makes next to them. This +// is what 'filee presets check ' runs. Nothing else may be in the folder, and nothing in it may be a link. + +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Filee.Core.Gallery; + +/// Checks a shared preset's folder: its preset.json, meta.json and pictures. +public static partial class SharedPresetFolderCheck +{ + public const string MetaName = "meta.json"; + public const string ImagesFolder = "images"; + + /// Fewest and most pictures a shared preset has. + public const int MinImages = 1, MaxImages = 4; + + /// Largest picture, in bytes. + public const int MaxImageBytes = 2 * 1024 * 1024; + + /// Shortest and longest long edge of a picture, in pixels. + public const int MinLongEdge = 640, MaxLongEdge = 2560; + + /// Longest long edge of a thumbnail the CI made, and its largest size. + public const int MaxThumbEdge = 480, MaxThumbBytes = 512 * 1024; + + /// Largest meta.json, in bytes. + public const int MaxMetaBytes = 16 * 1024; + + /// The licence every shared preset and picture is published under. + public const string License = "CC0-1.0"; + + /// Ids the site's own pages use (filee.sh/presets/files/, …/download/, …/index.json): no preset has them. + public static readonly IReadOnlyList ReservedSlugs = ["files", "download", "index"]; + + /// A preset's id: 3 to 48 of a-z, 0-9 and '-', not starting or ending with '-', and not reserved. + public static bool IsSlug(string text) => Slug().IsMatch(text) && !ReservedSlugs.Contains(text); + + /// The kinds meta.json may list (see ). + public static readonly IReadOnlyList Kinds = ["convert", "tool", "toolbar"]; + + /// + /// Checks . decodes each picture fully; without it only the + /// headers are read. + /// + public static PresetCheckResult Check(string folder, IGalleryImageDecoder? decoder = null) + { + var result = new PresetCheckResult(); + var root = new DirectoryInfo(folder); + if (!root.Exists) + { + result.Add("folder.missing", folder, "", "is not a folder"); + return result; + } + + var hasImages = false; + foreach (var entry in root.EnumerateFileSystemInfos()) + { + if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + result.Add("folder.link", entry.Name, "", "is a link; the folder may only hold real files"); + continue; + } + switch (entry) + { + case FileInfo { Name: SharedBundleCheck.FileName or MetaName }: + break; + case DirectoryInfo { Name: ImagesFolder }: + hasImages = true; + break; + default: + result.Add("folder.unexpected_file", entry.Name, "", $"doesn't belong in a shared preset's folder (only {SharedBundleCheck.FileName}, {MetaName} and {ImagesFolder}/)"); + break; + } + } + + var bundleFile = new FileInfo(Path.Combine(root.FullName, SharedBundleCheck.FileName)); + if (!bundleFile.Exists || bundleFile.Attributes.HasFlag(FileAttributes.ReparsePoint)) + result.Add("folder.no_preset", SharedBundleCheck.FileName, "", "is missing"); + else if (bundleFile.Length > SharedPresetRules.MaxBundleBytes) + result.Add("bundle.too_large", SharedBundleCheck.FileName, "", $"is {bundleFile.Length:N0} bytes; a shared preset.json may have at most {SharedPresetRules.MaxBundleBytes:N0}"); + else + { + var bundle = SharedBundleCheck.Check(File.ReadAllBytes(bundleFile.FullName)); + result.AddRange(bundle); + result.Derived = bundle.Derived; + } + + var metaFile = new FileInfo(Path.Combine(root.FullName, MetaName)); + if (metaFile.Exists && !metaFile.Attributes.HasFlag(FileAttributes.ReparsePoint)) + CheckMeta(metaFile, result.Derived, result); + + if (!hasImages) + result.Add("images.missing", ImagesFolder + "/", "", $"is missing: a shared preset needs {MinImages} to {MaxImages} pictures (1 is the cover)"); + else + CheckImages(new DirectoryInfo(Path.Combine(root.FullName, ImagesFolder)), decoder, result); + return result; + } + + /// The pictures: 1.png … 4.webp (1 to 4, no gaps), each with an optional 1-thumb.webp. + private static void CheckImages(DirectoryInfo folder, IGalleryImageDecoder? decoder, PresetCheckResult result) + { + var numbers = new SortedSet(); + var thumbs = new List<(int Number, FileInfo File)>(); + foreach (var entry in folder.EnumerateFileSystemInfos()) + { + var name = $"{ImagesFolder}/{entry.Name}"; + if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + result.Add("folder.link", name, "", "is a link; the folder may only hold real files"); + continue; + } + if (entry is not FileInfo file) + { + result.Add("images.unexpected_file", name, "", "doesn't belong in images/ (only 1.png … 4.webp)"); + continue; + } + var match = ImageName().Match(file.Name); + if (!match.Success) + { + result.Add("images.name", name, "", "must be named 1 to 4 with .png, .jpg, .jpeg or .webp (1 is the cover)"); + continue; + } + var number = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + if (match.Groups[2].Success) + { + thumbs.Add((number, file)); + continue; + } + if (!numbers.Add(number)) + { + result.Add("images.name", name, "", $"is a second picture {number}"); + continue; + } + CheckImage(file, name, match.Groups[3].Value.ToLowerInvariant(), thumb: false, decoder, result); + } + + if (numbers.Count < MinImages) + result.Add("images.missing", ImagesFolder + "/", "", $"has no pictures: a shared preset needs {MinImages} to {MaxImages} (1 is the cover)"); + else if (numbers.Max != numbers.Count) + result.Add("images.name", ImagesFolder + "/", "", "the pictures must be numbered from 1 without gaps (1 is the cover)"); + foreach (var (number, file) in thumbs) + { + var name = $"{ImagesFolder}/{file.Name}"; + if (!numbers.Contains(number)) + result.Add("images.name", name, "", $"is a thumbnail of picture {number}, which isn't there"); + else + CheckImage(file, name, "webp", thumb: true, decoder, result); + } + } + + [GeneratedRegex(@"^([1-4])(?:(-thumb)\.webp|\.(png|jpg|jpeg|webp))$", RegexOptions.CultureInvariant)] + private static partial Regex ImageName(); + + private static void CheckImage(FileInfo file, string name, string extension, bool thumb, IGalleryImageDecoder? decoder, PresetCheckResult result) + { + var limit = thumb ? MaxThumbBytes : MaxImageBytes; + if (file.Length > limit) + { + result.Add("images.too_large", name, "", $"is {file.Length:N0} bytes; at most {limit:N0}"); + return; + } + var data = File.ReadAllBytes(file.FullName); + if (GalleryImageHeader.Read(data) is not { } info) + { + result.Add("images.format", name, "", "is not a PNG, JPEG or WebP picture"); + return; + } + if (info.Format != (extension is "jpg" or "jpeg" ? "jpeg" : extension)) + { + result.Add("images.format", name, "", $"is a {info.Format.ToUpperInvariant()} picture with the extension .{extension}"); + return; + } + if (info.Animated) + { + result.Add("images.animated", name, "", "is animated; only still pictures are allowed"); + return; + } + var longEdge = Math.Max(info.Width, info.Height); + if (thumb ? longEdge > MaxThumbEdge : longEdge is < MinLongEdge or > MaxLongEdge) + { + result.Add("images.size", name, "", thumb + ? $"is {info.Width} x {info.Height} pixels; a thumbnail's long edge is at most {MaxThumbEdge}" + : $"is {info.Width} x {info.Height} pixels; the long edge must be {MinLongEdge} to {MaxLongEdge}"); + return; + } + if (decoder is null) + return; + var decoded = decoder.Decode(data); + if (!decoded.Ok) + result.Add("images.decode", name, "", "can't be decoded: " + decoded.Error); + else if (decoded.Frames > 1) + result.Add("images.animated", name, "", "is animated; only still pictures are allowed"); + else if (decoded.Width != info.Width || decoded.Height != info.Height) + result.Add("images.decode", name, "", $"decodes as {decoded.Width} x {decoded.Height}, not the {info.Width} x {info.Height} its header says"); + } + + /// The fields of meta.json (see the gallery's SPEC), each optional here: the CI fills some in. + private static readonly ObjectRule MetaFields = new(new Dictionary(StringComparer.Ordinal) + { + ["id"] = new StringRule(48, text => !Slug().IsMatch(text) ? "must be 3 to 48 of a-z, 0-9 and '-'" + : ReservedSlugs.Contains(text) ? "is reserved for the site's own pages" : null), + ["title"] = new StringRule(60, text => text.Trim().Length >= 3 ? null : "must be 3 to 60 characters long"), + ["description"] = new StringRule(600, text => text.Trim().Length >= 10 ? null : "must be 10 to 600 characters long"), + ["author"] = new StringRule(39, text => Login().IsMatch(text) ? null : "is not a GitHub login"), + ["tags"] = new ListRule(new StringRule(24, text => Tag().IsMatch(text) ? null : "must be lowercase a-z, 0-9 and '-'"), 6), + ["languages"] = new ListRule(new StringRule(16, SharedText.LanguageCode), 10), + ["kinds"] = new ListRule(new EnumRule(Kinds), Kinds.Count), + ["formats"] = new ObjectRule(new Dictionary(StringComparer.Ordinal) + { + ["from"] = new ListRule(new StringRule(32, SharedText.Id), 1000), + ["to"] = new ListRule(new StringRule(32, SharedText.Id), 1000), + }), + ["minVersion"] = new StringRule(20, text => Version.TryParse(text, out var v) && v.Build >= 0 && v.Revision < 0 ? null : "must be a version like 2.5.0"), + ["created"] = new StringRule(40, Timestamp), + ["updated"] = new StringRule(40, Timestamp), + ["discussion"] = new IntRule(1, int.MaxValue) { Nullable = true }, + ["license"] = new StringRule(16, text => text == License ? null : $"must be {License}"), + }); + + private static string? Timestamp(string text) => + DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _) ? null : "is not a date and time like 2026-11-15T00:00:00Z"; + + [GeneratedRegex(@"^[a-z0-9][a-z0-9\-]{1,46}[a-z0-9]$", RegexOptions.CultureInvariant)] + private static partial Regex Slug(); + + [GeneratedRegex(@"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$", RegexOptions.CultureInvariant)] + private static partial Regex Login(); + + [GeneratedRegex(@"^[a-z0-9][a-z0-9\-]{0,23}$", RegexOptions.CultureInvariant)] + private static partial Regex Tag(); + + private static void CheckMeta(FileInfo file, PresetCheckDerived? derived, PresetCheckResult result) + { + if (file.Length > MaxMetaBytes) + { + result.Add("meta.too_large", MetaName, "", $"is {file.Length:N0} bytes; at most {MaxMetaBytes:N0}"); + return; + } + JsonDocument document; + try + { + document = JsonDocument.Parse(File.ReadAllBytes(file.FullName), new JsonDocumentOptions { MaxDepth = 8 }); + } + catch (JsonException ex) + { + result.Add("meta.invalid_json", MetaName, "", "is not valid JSON: " + ex.Message.Split('\n')[0]); + return; + } + using (document) + { + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + result.Add("meta.invalid_json", MetaName, "", "must be a JSON object"); + return; + } + var before = result.Errors.Count; + new SharedBundleCheck.Walker(result, MetaName).Check(root, MetaFields, ""); + // What the CI derived from preset.json must still be what preset.json is. + if (derived is null || result.Errors.Count != before) + return; + if (root.TryGetProperty("kinds", out var kinds) && !SameSet(kinds, derived.Kinds)) + result.Add("meta.derived_mismatch", MetaName, "kinds", $"must be [{string.Join(", ", derived.Kinds)}], as preset.json is"); + if (root.TryGetProperty("formats", out var formats)) + { + if (formats.TryGetProperty("from", out var from) && !SameSet(from, derived.From)) + result.Add("meta.derived_mismatch", MetaName, "formats.from", $"must be [{string.Join(", ", derived.From)}], as preset.json is"); + if (formats.TryGetProperty("to", out var to) && !SameSet(to, derived.To)) + result.Add("meta.derived_mismatch", MetaName, "formats.to", $"must be [{string.Join(", ", derived.To)}], as preset.json is"); + } + if (root.TryGetProperty("minVersion", out var min) && Version.Parse(min.GetString()!) < Version.Parse(derived.MinVersion)) + result.Add("meta.derived_mismatch", MetaName, "minVersion", $"must be at least {derived.MinVersion}, the first Filee that can install it"); + } + } + + private static bool SameSet(JsonElement list, IReadOnlyList expected) => + list.EnumerateArray().Select(e => e.GetString()).ToHashSet(StringComparer.Ordinal).SetEquals(expected); +} diff --git a/src/Filee.Core/Gallery/SharedPresetRules.cs b/src/Filee.Core/Gallery/SharedPresetRules.cs new file mode 100644 index 000000000..85101bdcc --- /dev/null +++ b/src/Filee.Core/Gallery/SharedPresetRules.cs @@ -0,0 +1,331 @@ +// The allow-list of what a preset shared in the preset gallery may hold (#1530): every field of a preset and a toolbar +// profile that may appear in a shared preset.json, with the values it may take. A field that isn't listed here fails the +// check, so a field added to Preset later stays out of the gallery until someone decides it is safe and lists it. +// Fields that would carry something of the sharer's (a folder, a password, a picture's path) or run something on the +// installer's computer are listed as "left out": they may be there, as an export writes them, but only empty. + +using Filee.Core.Formats; +using Filee.Core.Presets; +using Filee.Core.Profiles; + +namespace Filee.Core.Gallery; + +/// What one JSON value of a shared preset may be. +internal abstract record ValueRule +{ + /// JSON null is allowed (the field is optional in the model). + public bool Nullable { get; init; } +} + +/// An object with exactly these fields (each optional); any other field fails. +internal sealed record ObjectRule(IReadOnlyDictionary Fields) : ValueRule; + +/// true or false; when just one of them is allowed. +internal sealed record BoolRule(bool? Only = null) : ValueRule; + +/// A whole number from to ; with only those. +internal sealed record IntRule(long Min, long Max, IReadOnlyCollection? Allowed = null) : ValueRule; + +/// A finite number from to . +internal sealed record NumberRule(double Min, double Max) : ValueRule; + +/// One of , as the enum's name (any case, as the app reads it). +internal sealed record EnumRule(IReadOnlyList Names) : ValueRule; + +/// +/// A string of at most characters that passes (null: fine) and +/// the checks every shared text gets (no URL, no personal path, no control characters). +/// +internal sealed record StringRule(int MaxLength, Func? Check = null) : ValueRule; + +/// A list of at most values that each pass . +internal sealed record ListRule(ValueRule Item, int MaxCount) : ValueRule; + +/// +/// A field left out of shared presets: absent, null, "", false, 0, [] or {} only. says why, for the +/// message. +/// +internal sealed record LeftOutRule(string Why) : ValueRule; + +/// The allow-list itself, one per part of a . +internal static class SharedPresetRules +{ + /// Most presets one shared preset.json holds. + public const int MaxPresets = 20; + + /// Most toolbar profiles (donuts) one shared preset.json holds. + public const int MaxProfiles = 1; + + /// Largest preset.json, in bytes. + public const int MaxBundleBytes = 256 * 1024; + + /// How deep the JSON may nest; a preset needs 5 levels. + public const int MaxDepth = 16; + + /// The kinds of preset that may be shared. Copy to folder needs a folder of one's own. + public static readonly IReadOnlyList Kinds = [nameof(PresetKind.Convert), nameof(PresetKind.Group), nameof(PresetKind.Tool)]; + + /// + /// The tools that may be shared (; null is the crop). Metadata is left out: what it + /// changes (author, GPS) is about people. + /// + public static readonly IReadOnlyList Tools = + [ + null, Preset.CropTool, Preset.ClipTool, Preset.ImageEditTool, Preset.HideTool, Preset.AnnotateTool, + Preset.BackgroundTool, Preset.UpscaleTool, + ]; + + /// + /// Where a shared preset may save: the default location, next to the source, or in a folder next to it (named by + /// , which may not hold a separator). Never a folder of its own. + /// + public static readonly IReadOnlyList Locations = + [nameof(OutputLocation.Default), nameof(OutputLocation.SameFolder), nameof(OutputLocation.Subfolder)]; + + /// The placeholders a file name pattern may use (). + public static readonly IReadOnlyList Placeholders = ["name", "ext", "preset", "date", "time", "index"]; + + private static readonly long[] IcoSizes = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; + + private static EnumRule Enum(params T[] except) where T : struct, System.Enum => + new([.. System.Enum.GetNames().Where(n => !except.Select(e => e.ToString()).Contains(n))]); + + private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => + new(fields.ToDictionary(f => f.Name, f => f.Rule, StringComparer.Ordinal)); + + private static readonly BoolRule Flag = new(); + private static readonly StringRule Colour = new(9, SharedText.HexColour); + + /// The fields of one preset. + public static readonly ObjectRule PresetFields = Obj( + ("id", new StringRule(64, SharedText.Id)), + ("name", new StringRule(80)), + ("nameKey", new StringRule(80, SharedText.NameKey) { Nullable = true }), + ("targetFormat", new StringRule(32, SharedText.Id)), + ("kind", new EnumRule(Kinds)), + ("tool", new StringRule(32, SharedText.Id) { Nullable = true }), + ("subPresetIds", new ListRule(new StringRule(64, SharedText.Id), Preset.MaxSubPresets)), + ("icon", new StringRule(48, SharedText.Id) { Nullable = true }), + ("shortName", new StringRule(40) { Nullable = true }), + ("show", Enum() with { Nullable = true }), + ("direction", Enum() with { Nullable = true }), + ("askCompression", Flag), + ("image", Obj( + ("quality", new IntRule(1, 100)), + ("maxSizeMb", new NumberRule(0, 10_000)), + ("maxSizeKeepsPixels", Flag), + ("minSizeMb", new NumberRule(0, 10_000)), + ("resize", Enum()), + ("rotation", Enum()), + ("flip", Enum()), + ("annotations", new LeftOutRule("marks are drawn on one picture, never saved with a preset")), + ("annotationColor", Colour with { Nullable = true }), + ("annotationWidth", Enum()), + ("backdrop", new LeftOutRule("set on one conversion, never saved with a preset")), + ("backdropLook", Obj( + ("kind", Enum()), + ("from", Colour), + ("to", Colour), + ("color", Colour), + ("picture", new LeftOutRule("a picture of one's own is a path on one's computer")), + ("pictureWritten", new LeftOutRule("belongs to a picture of one's own")), + ("pictureLength", new LeftOutRule("belongs to a picture of one's own")), + ("padding", new IntRule(0, BackdropOptions.MaxPadding)), + ("corners", new IntRule(0, BackdropOptions.MaxCorners)), + ("shadow", new IntRule(0, BackdropOptions.MaxShadow)), + ("canvas", Enum())) with + { Nullable = true }), + ("resizePercent", new IntRule(1, 1000)), + ("longEdge", new IntRule(1, CustomImageSize.MaxSide)), + ("width", new IntRule(1, CustomImageSize.MaxSide)), + ("customSize", Obj( + ("width", new IntRule(1, CustomImageSize.MaxSide)), + ("height", new IntRule(1, CustomImageSize.MaxSide)), + ("lockAspect", Flag), + ("shrinkOnly", Flag), + ("unit", Enum()), + ("dpi", new IntRule(CustomImageSize.MinDpi, CustomImageSize.MaxDpi))) with + { Nullable = true }), + ("minShortEdge", new IntRule(1, CustomImageSize.MaxSide) { Nullable = true }), + ("dpi", new IntRule(1, CustomImageSize.MaxDpi) { Nullable = true }), + ("keepMetadata", Flag), + ("keepColorProfile", Flag), + ("maxCompression", Flag), + ("keepSourceQuality", Flag), + ("grayscale", Flag), + ("trimTransparent", Flag), + ("removeBackground", Flag), + ("backgroundTolerance", new IntRule(0, 100)), + ("keepEnclosedBackground", Flag), + ("background", Colour), + ("tiffCompression", Enum()), + ("multiPageTiff", Flag), + ("webpLossless", Flag), + ("joinIntoOne", Flag), + ("joinDirection", Enum()), + ("joinFit", Enum()), + ("joinGap", new IntRule(0, ImageOptions.MaxJoinGap)), + ("joinBackground", new StringRule(16, SharedText.JoinBackground)), + ("fitsTiff", Enum()), + ("fitsDebayer", Flag), + ("icoSizes", new ListRule(new IntRule(16, 256, IcoSizes), IcoSizes.Length)), + ("hideStyle", Enum()), + ("hideStrength", new IntRule(HideTool.MinStrength, HideTool.MaxStrength)), + ("hiddenAreas", new LeftOutRule("the parts of one picture to hide, never saved with a preset")), + ("animationSpeed", new NumberRule(0.1, 10)))), + ("pdf", Obj( + ("mergeIntoSingle", Flag), + ("sourceBookmarks", Flag), + ("normalizeMergePaper", Flag), + ("mergePaper", Enum()), + ("mergeOrientation", Enum()), + ("pageSize", Enum()), + ("marginMm", new NumberRule(0, 200)), + ("renderDpi", new IntRule(1, 2400)), + ("pageRange", new StringRule(200, SharedText.PageRange)), + ("askPageRange", Flag), + ("splitPages", Flag), + ("splitEvery", new IntRule(0, Conversion.PageGroups.MaxSize)), + ("splitParts", new IntRule(0, Conversion.PageGroups.MaxSize)), + ("rotation", Enum()), + ("pagesPerSheet", new IntRule(0, 9, [0, 1, .. PdfOptions.SheetLayouts.Select(n => (long)n)])), + ("sheetPaper", Enum()), + ("sheetOrientation", Enum()), + ("sheetOrder", Enum()), + ("sheetMarginMm", new NumberRule(0, 200)), + ("sheetGapMm", new NumberRule(0, 200)), + ("sheetBorders", Flag), + ("combinePages", Flag), + ("trimPageMargins", Flag), + ("splitTallImage", Flag), + ("compression", Enum()), + ("removeMetadata", Flag), + ("compressWithGhostscript", Flag), + ("watermark", new StringRule(100)), + ("pageNumbers", Flag), + ("password", new LeftOutRule("a password is never shared")), + ("passwordLeftOut", new BoolRule(false)), + ("ocr", Flag), + ("ocrLanguage", new StringRule(64, SharedText.OcrLanguages)))), + ("document", Obj( + ("pdfA", Flag), + ("leaveOutPictures", Flag))), + ("media", Obj( + ("quality", Enum()), + ("maxHeight", new IntRule(0, 8640)), + ("maxSizeMb", new NumberRule(0, 100_000)), + ("maxSizePercent", new IntRule(0, 100)), + ("audioBitrateKbps", new IntRule(0, 1536)), + ("removeAudio", Flag), + ("cropFrame", new StringRule(16, SharedText.CropFrame)), + ("audioChannels", new IntRule(0, 8)), + ("audioSampleRate", new IntRule(0, 384_000)), + ("wavFormat", Enum()), + ("videoCodec", Enum()), + ("audioCodec", Enum()), + ("hardwareEncoding", Flag), + ("saveEveryFrame", Flag), + ("extractMotionPhoto", Flag), + ("caption", Flag), + ("spokenLanguage", new StringRule(16, SharedText.SpokenLanguage)), + ("livePhoto", Enum()), + ("livePhotoStart", new NumberRule(0, 86_400)), + ("livePhotoLength", new NumberRule(0, 60)), + ("livePhotoCover", new NumberRule(0, 60)), + ("frameInterval", new IntRule(1, 86_400)), + ("ringtoneStart", new NumberRule(0, 86_400)), + ("ringtoneLength", new NumberRule(0, 600)), + ("askRingtonePart", Flag), + ("exactCut", Flag), + ("splitEverySeconds", new IntRule(0, 86_400)), + ("splitParts", new IntRule(0, MediaOptions.MaxSplitParts)), + ("clip", new LeftOutRule("a clip is cut from one video, and its music is a file of one's own")), + ("joinIntoOne", Flag), + ("loopMusic", Flag), + ("slideshow", Flag), + ("slideSeconds", new NumberRule(0, 600)), + ("crossfade", Flag), + ("copyAudioWhenPossible", Flag), + ("removeMetadata", Flag))), + ("archive", Obj( + ("combineIntoOne", Flag), + ("level", Enum()))), + ("trace", Obj( + ("mode", Enum()), + ("colors", new IntRule(TracingOptions.MinColors, TracingOptions.MaxColors)), + ("detail", new IntRule(0, 100)))), + ("cad", Obj( + ("version", Enum()), + ("colors", Enum()))), + ("gcode", Obj( + ("view", Enum()))), + ("translate", Obj( + ("enabled", Flag), + ("targetLanguage", new StringRule(16, SharedText.LanguageCode)), + ("sourceLanguage", new StringRule(16, SharedText.LanguageCode)), + ("model", new LeftOutRule("the AI model is the installer's own choice (Settings)")))), + ("upscale", Obj( + ("enabled", Flag), + ("model", new StringRule(80, SharedText.ModelId) { Nullable = true }), + ("scale", new IntRule(1, 8)))), + ("metadata", new LeftOutRule("metadata edits write names, places and dates into files")), + ("output", Obj( + ("location", new EnumRule(Locations)), + ("askEveryTime", Flag), + ("subfolderName", new StringRule(64, SharedText.FileNamePattern)), + ("subfolderOnlyForSeveralFiles", Flag), + ("customFolder", new LeftOutRule("a folder is a path on one's own computer")), + ("keepFoldersFrom", new LeftOutRule("a folder is a path on one's own computer")), + ("fileNamePattern", new StringRule(120, SharedText.FileNamePattern)), + ("renames", new ListRule(Obj( + ("kind", Enum()), + ("find", new StringRule(100)), + ("replace", new StringRule(100, SharedText.RenameReplace)), + // Written by an export, never read back (RenameStep.IsBlank has no setter). + ("isBlank", Flag)), 10)), + ("conflict", new EnumRule([nameof(ConflictPolicy.Rename), nameof(ConflictPolicy.Skip)])), + ("keepDates", Flag), + ("zipResult", Flag), + ("onlyIfSmaller", Flag), + ("replaceOriginal", new BoolRule(false)), + ("moveInsteadOfCopy", new BoolRule(false))))); + + /// The fields of one toolbar profile (a donut). + public static readonly ObjectRule ProfileFields = Obj( + ("id", new StringRule(64, SharedText.Id)), + ("name", new StringRule(80)), + ("nameKey", new StringRule(80, SharedText.NameKey) { Nullable = true }), + ("extensions", new ListRule(new StringRule(16, SharedText.Extension), 400)), + ("isFallback", Flag), + ("presetIds", new ListRule(new StringRule(64, SharedText.Id), ToolbarProfile.MaxSlices)), + ("backPresetIds", new ListRule(new StringRule(64, SharedText.Id), ToolbarProfile.MaxSlices) { Nullable = true }), + ("labelShow", Enum() with { Nullable = true }), + ("labelScale", new NumberRule(ToolbarProfile.MinLabelScale, ToolbarProfile.MaxLabelScale))); + + /// The top of preset.json. + public static readonly ObjectRule BundleFields = Obj( + ("schemaVersion", new IntRule(1, 1)), + ("settingsSchema", new IntRule(1, Settings.AppSettings.CurrentSchemaVersion) { Nullable = true }), + ("presets", new ListRule(PresetFields, MaxPresets)), + ("profiles", new ListRule(ProfileFields, MaxProfiles))); + + /// + /// Every field path the allow-list knows (image.quality, output.renames[].find), with whether it is + /// left out: for the tests that compare it with the model, and for the documentation. + /// + public static IEnumerable<(string Path, bool LeftOut)> Paths(ObjectRule rule, string prefix = "") + { + foreach (var (name, field) in rule.Fields) + { + var path = prefix + name; + yield return (path, field is LeftOutRule); + var inner = field is ListRule list ? list.Item : field; + if (inner is ObjectRule nested) + foreach (var child in Paths(nested, path + (field is ListRule ? "[]." : "."))) + yield return child; + } + } + + /// The format id stands for, for formats.from. + internal static string? FormatOfExtension(string extension) => FormatRegistry.FindByExtension(extension)?.Id; +} diff --git a/src/Filee.Core/Gallery/SharedText.cs b/src/Filee.Core/Gallery/SharedText.cs new file mode 100644 index 000000000..6eacdd1e2 --- /dev/null +++ b/src/Filee.Core/Gallery/SharedText.cs @@ -0,0 +1,149 @@ +// Checks of the texts in a shared preset (#1530): every text is free of links, personal paths and hidden characters, +// and the texts that become file or folder names or are read as codes have the one form the app reads. + +using System.Text.RegularExpressions; +using Filee.Core.Presets; + +namespace Filee.Core.Gallery; + +/// Text checks for shared presets. Each returns why a value is refused, or null when it is fine. +internal static partial class SharedText +{ + /// The only addresses a shared text may contain: Filee's own. + public static readonly IReadOnlyList AllowedUrls = ["https://filee.sh/", "https://github.com/KnifeLemon/"]; + + /// The checks every shared text gets, whatever the field: the problem's code and why, or null. + public static (string Code, string Message)? Common(string text) + { + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + if (char.IsControl(c)) + return ("text.character", "has a control character"); + // Bidirectional overrides and isolates, and zero-width characters, can make a text read as something else. + if (c is '\u200B' or '\u200C' or '\u200D' or '\u200E' or '\u200F' or '\u2060' or '\uFEFF' + || c is >= '\u202A' and <= '\u202E' || c is >= '\u2066' and <= '\u2069') + return ("text.character", "has an invisible or direction-changing character"); + if (char.IsHighSurrogate(c) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1])) + i++; + else if (char.IsSurrogate(c)) + return ("text.character", "is not valid text"); + } + foreach (Match match in Link().Matches(text)) + { + var rest = text[match.Index..]; + if (!AllowedUrls.Any(allowed => rest.StartsWith(allowed, StringComparison.OrdinalIgnoreCase))) + return ("text.url", "has a link (only links to filee.sh are allowed)"); + } + if (PersonalPath().IsMatch(text)) + return ("text.personal_path", "has a path of a computer's folders (C:\\Users\\…, /home/…)"); + return null; + } + + /// A link: a scheme, "www." or a mail address. + [GeneratedRegex(@"(?i)(\b[a-z][a-z0-9+.\-]*://|\bwww\.|\bmailto:|\bfile:|\b[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}\b)", RegexOptions.CultureInvariant)] + private static partial Regex Link(); + + /// + /// A path that tells whose computer it is or where their files are: a drive (C:\, D:/), a network share (\\server), + /// a home folder (/home/, /Users/, ~/), an environment variable (%USERPROFILE%, $HOME). + /// + [GeneratedRegex(@"(?i)(\b[a-z]:[\\/]|\\\\[^\\\s]|(^|[\s""'(=])/(home|users|root|mnt|media|volumes|private|var|tmp|etc)\b|(^|[\s""'(=])~[\\/]|%[a-z_]+%|\$home\b|\$\{?env|\\users\\)", RegexOptions.CultureInvariant)] + private static partial Regex PersonalPath(); + + /// An id: letters, digits, "-", "_" and "." (preset ids, format ids, tool names, icon keys). + public static string? Id(string text) => + IdPattern().IsMatch(text) ? null : "may only have letters, digits, '-', '_' and '.'"; + + [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]*$|^\*$", RegexOptions.CultureInvariant)] + private static partial Regex IdPattern(); + + /// A built-in name's translation key (preset.merge_pdf, profile.images). + public static string? NameKey(string text) => + NameKeyPattern().IsMatch(text) ? null : "is not a name key of Filee's"; + + [GeneratedRegex(@"^(preset|profile|group|tool)\.[a-z0-9_.]+$", RegexOptions.CultureInvariant)] + private static partial Regex NameKeyPattern(); + + /// A file extension without its dot. + public static string? Extension(string text) => + ExtensionPattern().IsMatch(text) ? null : "is not a file extension"; + + [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9_\-~]*$", RegexOptions.CultureInvariant)] + private static partial Regex ExtensionPattern(); + + /// "#RRGGBB" or "#RGB". + public static string? HexColour(string text) => + HexPattern().IsMatch(text) ? null : "is not a colour like #RRGGBB"; + + [GeneratedRegex(@"^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$", RegexOptions.CultureInvariant)] + private static partial Regex HexPattern(); + + /// A colour or "transparent" (). + public static string? JoinBackground(string text) => + text == ImageOptions.TransparentJoin ? null : HexColour(text); + + /// Pages as the editor takes them ("1-3,5"), or empty. + public static string? PageRange(string text) => + Conversion.PageRange.Check(text, null).IsValid ? null : "is not a page range like 1-3,5"; + + /// Tesseract languages, "+" between them ("eng", "chi_sim+eng"). + public static string? OcrLanguages(string text) => + OcrPattern().IsMatch(text) ? null : "is not a list of OCR languages like eng or chi_sim+eng"; + + [GeneratedRegex(@"^[a-z]{3}(_[a-z]{3,4})?(\+[a-z]{3}(_[a-z]{3,4})?){0,5}$", RegexOptions.CultureInvariant)] + private static partial Regex OcrPattern(); + + /// "auto" or a language Whisper knows (). + public static string? SpokenLanguage(string text) => + text == WhisperLanguages.Auto || WhisperLanguages.Find(text) is not null ? null : "is not a spoken language Filee knows"; + + /// "auto" or a language code ("en", "pt-BR", "zh-Hant"). + public static string? LanguageCode(string text) => + LanguagePattern().IsMatch(text) ? null : "is not a language code like en or pt-BR"; + + [GeneratedRegex(@"^(auto|[a-z]{2,3}([_\-][A-Za-z]{2,4})?)$", RegexOptions.CultureInvariant)] + private static partial Regex LanguagePattern(); + + /// An upscaling model's id (the app downloads only the curated ones, by id). + public static string? ModelId(string text) => + ModelPattern().IsMatch(text) ? null : "is not a model id"; + + [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]{0,79}$", RegexOptions.CultureInvariant)] + private static partial Regex ModelPattern(); + + /// "auto", a ratio ("16:9") or empty (). + public static string? CropFrame(string text) => + text.Length == 0 || VideoCrop.Crops(text) ? null : "is not a frame like 16:9 or auto"; + + private static readonly char[] Unsafe = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']; + + /// + /// A file name pattern: text and the placeholders of , never a + /// separator or "..", so the name can't leave the folder it is saved in. + /// + public static string? FileNamePattern(string text) + { + foreach (Match match in Braces().Matches(text)) + { + if (!SharedPresetRules.Placeholders.Contains(match.Groups[1].Value.ToLowerInvariant())) + return $"has an unknown placeholder {match.Value} (use {string.Join(", ", SharedPresetRules.Placeholders.Select(p => "{" + p + "}"))})"; + } + var literal = Braces().Replace(text, ""); + if (literal.Contains('{') || literal.Contains('}')) + return "has an unclosed placeholder"; + if (text.Contains("..")) + return "may not have '..'"; + return text.IndexOfAny(Unsafe) >= 0 ? "may not have \\ / : * ? \" < > |" : null; + } + + [GeneratedRegex(@"\{([^{}]*)\}", RegexOptions.CultureInvariant)] + private static partial Regex Braces(); + + /// + /// What a rename step puts in: no separator, so the name stays one name ("$1" of a regular expression inserts a part + /// of the name, which has none). + /// + public static string? RenameReplace(string text) => + text.IndexOfAny(Unsafe) >= 0 ? "may not have \\ / : * ? \" < > |" : null; +} diff --git a/src/Filee.Core/Settings/FileeJsonContext.cs b/src/Filee.Core/Settings/FileeJsonContext.cs index 990600e6f..ddb90e844 100644 --- a/src/Filee.Core/Settings/FileeJsonContext.cs +++ b/src/Filee.Core/Settings/FileeJsonContext.cs @@ -28,6 +28,13 @@ internal sealed partial class FileeJsonContext : JsonSerializerContext; public sealed class PresetBundle { public int SchemaVersion { get; set; } = 1; + + /// + /// The settings schema () of the Filee that wrote the bundle; null in + /// bundles from before it was written. Tells a later Filee which migrations a bundle's presets still need, and the + /// preset gallery's check that a bundle doesn't come from a newer Filee than the one checking it. + /// + public int? SettingsSchema { get; set; } public List Presets { get; set; } = []; public List Profiles { get; set; } = []; } diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs index cc9fddf77..c8f95302b 100644 --- a/src/Filee.Core/Settings/UserDataStore.cs +++ b/src/Filee.Core/Settings/UserDataStore.cs @@ -268,8 +268,12 @@ private void RestoreBuiltInPresets(IEnumerable ids) /// Exports presets and profiles to a shareable JSON file, without PDF passwords or paths to one's own pictures. /// public void Export(string path) => - Write(path, new PresetBundle { Presets = [.. Presets.Select(p => p.ForSharing())], Profiles = Profiles }, - FileeJsonContext.Default.PresetBundle); + Write(path, new PresetBundle + { + SettingsSchema = AppSettings.CurrentSchemaVersion, + Presets = [.. Presets.Select(p => p.ForSharing())], + Profiles = Profiles, + }, FileeJsonContext.Default.PresetBundle); /// /// Imports presets and profiles from a bundle. Items with an existing id are replaced, new ones added. diff --git a/tests/Filee.App.Tests/PresetGalleryTests.cs b/tests/Filee.App.Tests/PresetGalleryTests.cs new file mode 100644 index 000000000..18f52fe23 --- /dev/null +++ b/tests/Filee.App.Tests/PresetGalleryTests.cs @@ -0,0 +1,529 @@ +// The "Preset gallery" window (#1530) against a stand-in for filee.sh: an HTTP handler that serves an index.json, the +// pictures (drawn with SkiaSharp here) and each preset.json, all made in the test. It checks the sorting and filters, +// that presets for a newer Filee are left out, that installing adds new presets through the counted download link and +// refuses a file that isn't the listed one, the fallback to the repository, the size limits and the picture cache, and +// renders the window in light and dark for the pull request. + +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json.Nodes; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using Avalonia.VisualTree; +using Filee.App.Services; +using Filee.App.ViewModels; +using Filee.App.ViewModels.Pages; +using Filee.App.Views; +using Filee.App.Views.Pages; +using Filee.Core.Gallery; +using Filee.Core.Localization; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; +using SkiaSharp; + +namespace Filee.App.Tests; + +public sealed class PresetGalleryTests : IDisposable +{ + private readonly string _root = Directory.CreateTempSubdirectory("filee-gallery-tests-").FullName; + + public void Dispose() + { + try { Directory.Delete(_root, true); } catch (IOException) { } + } + + /// filee.sh and the gallery's repository, answered from memory; every request is recorded. + private sealed class FakeGallery : HttpMessageHandler + { + public Dictionary Files { get; } = new(StringComparer.Ordinal); + public List Requests { get; } = []; + public bool SiteDown { get; set; } + public bool Offline { get; set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var uri = request.RequestUri!; + lock (Requests) + Requests.Add(uri); + if (Offline || (SiteDown && uri.Host == "filee.sh")) + throw new HttpRequestException("No route to host."); + Assert.True(uri.Scheme == "https" && uri.Host is "filee.sh" or "raw.githubusercontent.com", uri.ToString()); + var key = uri.Host == "filee.sh" ? uri.AbsolutePath : "repo:" + uri.AbsolutePath["/KnifeLemon/Filee-Presets/main".Length..]; + return Task.FromResult(Files.TryGetValue(key, out var data) + ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(data), RequestMessage = request } + : new HttpResponseMessage(HttpStatusCode.NotFound) { RequestMessage = request }); + } + + public int Count(string path) + { + lock (Requests) + return Requests.Count(r => r.AbsolutePath == path); + } + } + + private static byte[] Picture(int width, int height, SKColor sky, SKEncodedImageFormat format = SKEncodedImageFormat.Png) + { + using var bitmap = new SKBitmap(width, height); + using (var canvas = new SKCanvas(bitmap)) + { + canvas.Clear(sky); + using var sun = new SKPaint { Color = SKColors.Gold, IsAntialias = true }; + canvas.DrawCircle(width * 0.7f, height * 0.4f, Math.Min(width, height) / 5f, sun); + using var hill = new SKPaint { Color = new SKColor(60, 140, 90), IsAntialias = true }; + canvas.DrawOval(width * 0.3f, height * 1.05f, width * 0.6f, height * 0.4f, hill); + } + using var image = SKImage.FromBitmap(bitmap); + using var encoded = image.Encode(format, 85); + return encoded.ToArray(); + } + + /// A preset.json as Settings → General → Export writes it, with and a donut. + private byte[] Bundle(IEnumerable presets, ToolbarProfile? profile = null) + { + var data = Path.Combine(_root, "export-" + Guid.NewGuid().ToString("N")[..6]); + var store = new UserDataStore(data); + store.Load(); + store.Presets.Clear(); + store.Presets.AddRange(presets); + store.Profiles.Clear(); + if (profile is not null) + store.Profiles.Add(profile); + var path = Path.Combine(data, "bundle.json"); + store.Export(path); + return File.ReadAllBytes(path); + } + + private static readonly DateTimeOffset Today = new(2026, 11, 15, 0, 0, 0, TimeSpan.Zero); + + /// Adds a shared preset to the gallery: its files, and its entry for index.json. + private JsonObject Share(FakeGallery gallery, string slug, string title, byte[] preset, SKColor sky, string[] kinds, string[] to, + string[] tags, string[] languages, string minVersion = "2.0.0", int days = 0, double hot = 0, int likes = 0, int downloads = 0, + int images = 2, int? discussion = 7) + { + var folder = $"presets/{slug}/"; + gallery.Files["/presets/files/" + folder + "preset.json"] = preset; + gallery.Files["repo:/" + folder + "preset.json"] = preset; + gallery.Files["/presets/download/" + slug] = preset; + var paths = new JsonArray(); + for (var i = 1; i <= images; i++) + { + var picture = Picture(1280, 720, i == 1 ? sky : SKColors.MediumPurple); + gallery.Files[$"/presets/files/{folder}images/{i}.webp"] = picture; + gallery.Files[$"repo:/{folder}images/{i}.webp"] = picture; + paths.Add($"{folder}images/{i}.webp"); + } + var thumb = Picture(480, 270, sky, SKEncodedImageFormat.Webp); + gallery.Files[$"/presets/files/{folder}images/1-thumb.webp"] = thumb; + gallery.Files[$"repo:/{folder}images/1-thumb.webp"] = thumb; + return new JsonObject + { + ["id"] = slug, + ["title"] = title, + ["description"] = $"{title}: made for the gallery tests, with a description long enough to wrap onto a second line in the window.", + ["author"] = "tester-" + slug[..3], + ["tags"] = new JsonArray([.. tags.Select(t => (JsonNode)t)]), + ["languages"] = new JsonArray([.. languages.Select(l => (JsonNode)l)]), + ["kinds"] = new JsonArray([.. kinds.Select(k => (JsonNode)k)]), + ["formats"] = new JsonObject { ["from"] = new JsonArray(), ["to"] = new JsonArray([.. to.Select(t => (JsonNode)t)]) }, + ["minVersion"] = minVersion, + ["created"] = Today.AddDays(-days).ToString("o"), + ["updated"] = Today.AddDays(-days).ToString("o"), + ["discussion"] = discussion, + ["license"] = "CC0-1.0", + ["images"] = paths, + ["thumb"] = $"{folder}images/1-thumb.webp", + ["preset"] = folder + "preset.json", + ["sha256"] = Convert.ToHexStringLower(SHA256.HashData(preset)), + ["stats"] = new JsonObject + { + ["likes"] = likes, + ["comments"] = 1, + ["downloads"] = downloads, + ["hot"] = hot, + ["best"] = new JsonObject { ["day"] = 0, ["week"] = likes, ["month"] = likes, ["year"] = likes + 1, ["all"] = likes + downloads }, + }, + }; + } + + /// + /// Publishes the entries as the repository's index.json (paths presets/<id>/…) and as filee.sh's, whose paths + /// are relative to https://filee.sh/presets/index.json (files/presets/<id>/…) and which has an install link. + /// + private static void Publish(FakeGallery gallery, params JsonObject[] entries) + { + static byte[] Index(IEnumerable list) => Encoding.UTF8.GetBytes(new JsonObject + { + ["version"] = 1, + ["generated"] = Today.ToString("o"), + ["presets"] = new JsonArray([.. list]), + }.ToJsonString()); + gallery.Files["repo:/index.json"] = Index(entries.Select(e => e.DeepClone().AsObject())); + gallery.Files["/presets/index.json"] = Index(entries.Select(e => + { + var site = e.DeepClone().AsObject(); + site["images"] = new JsonArray([.. site["images"]!.AsArray().Select(p => (JsonNode)("files/" + p!.GetValue()))]); + site["thumb"] = "files/" + site["thumb"]!.GetValue(); + site["preset"] = "files/" + site["preset"]!.GetValue(); + site["download"] = "https://filee.sh/presets/download/" + site["id"]!.GetValue(); + return site; + })); + } + + private static Preset Insta() => new() + { + Id = "insta", + Name = "Instagram JPG", + TargetFormat = "jpg", + Image = { Quality = 85, Resize = ResizeMode.LongEdge, LongEdge = 1080, KeepMetadata = false }, + Output = { FileNamePattern = "{name}_insta" }, + }; + + /// A gallery of four shared presets, one of them for a newer Filee. + private FakeGallery Gallery() + { + var gallery = new FakeGallery(); + var scans = new Preset { Id = "scans", Name = "Scans to one PDF", TargetFormat = "pdf", Pdf = { MergeIntoSingle = true, Compression = PdfCompression.Ebook } }; + var left = new Preset { Id = "left", Name = "Turn left", TargetFormat = BuiltInData.SameAsSource, Image = { Rotation = ImageRotation.Left90 } }; + var right = new Preset { Id = "right", Name = "Turn right", TargetFormat = BuiltInData.SameAsSource, Image = { Rotation = ImageRotation.Right90 } }; + var turn = new Preset { Id = "turn", Name = "Turn", Kind = PresetKind.Group, TargetFormat = Preset.GroupTarget, SubPresetIds = ["left", "right"] }; + var donut = new ToolbarProfile { Id = "photos", Name = "Photo desk", Extensions = ["jpg", "png", "heic"], PresetIds = ["turn", "left", "right"], BackPresetIds = [] }; + Publish(gallery, + Share(gallery, "instagram-jpg", "Instagram-ready JPG", Bundle([Insta()]), SKColors.SkyBlue, ["convert"], ["jpg"], ["images", "social"], ["en"], + days: 3, hot: 9, likes: 12, downloads: 340), + Share(gallery, "scan-merge", "Scans to one small PDF", Bundle([scans]), SKColors.LightSalmon, ["convert"], ["pdf"], ["pdf", "office"], ["en", "ko"], + days: 1, hot: 4, likes: 30, downloads: 90), + Share(gallery, "photo-desk", "Photo desk donut", Bundle([turn, left, right], donut), SKColors.MediumAquamarine, ["convert", "toolbar"], [], + ["images"], ["ko"], days: 10, hot: 2, likes: 5, downloads: 20), + Share(gallery, "from-the-future", "Needs a newer Filee", Bundle([Insta()]), SKColors.Gray, ["convert"], ["jpg"], ["images"], ["en"], + minVersion: "99.0.0")); + return gallery; + } + + private UserDataStore Store() + { + var store = new UserDataStore(Path.Combine(_root, "library-" + Guid.NewGuid().ToString("N")[..6])); + store.Load(); + return store; + } + + private (PresetGalleryViewModel Vm, PresetGalleryClient Client, List Opened, List Installed) Open( + FakeGallery gallery, UserDataStore store, string? cache = "") + { + var client = new PresetGalleryClient(gallery, cache); + var opened = new List(); + var installed = new List(); + var vm = new PresetGalleryViewModel(client, store, AppHost.Get(), new Version(2, 5, 0), + uri => { opened.Add(uri); return Task.CompletedTask; }, installed.Add); + _ = vm.LoadAsync(); + ClipWindowTests.WaitFor(() => vm.State != GalleryState.Loading); + return (vm, client, opened, installed); + } + + [AvaloniaFact] + public void The_list_leaves_out_presets_for_a_newer_filee_and_sorts_and_filters() + { + TestServices.EnsureInitialized(); + var (vm, client, _, _) = Open(Gallery(), Store()); + using var _client = client; + using var _vm = vm; + + Assert.Equal(GalleryState.Ready, vm.State); + Assert.Equal(["Instagram-ready JPG", "Scans to one small PDF", "Photo desk donut"], vm.Cards.Select(c => c.Title)); + Assert.Contains("1", vm.NewerText); + + vm.Sort = vm.Sorts.Single(s => s.Value == GallerySort.Best); + Assert.True(vm.ShowPeriods); + vm.Period = vm.Periods.Single(p => p.Value == "all"); + Assert.Equal("Instagram-ready JPG", vm.Cards[0].Title); // 12 + 340 + vm.Period = vm.Periods.Single(p => p.Value == "week"); + Assert.Equal("Scans to one small PDF", vm.Cards[0].Title); // 30 likes this week + vm.Sort = vm.Sorts.Single(s => s.Value == GallerySort.New); + Assert.False(vm.ShowPeriods); + Assert.Equal(["Scans to one small PDF", "Instagram-ready JPG", "Photo desk donut"], vm.Cards.Select(c => c.Title)); + + vm.Kind = vm.Kinds.Single(k => k.Value == "toolbar"); + Assert.Equal(["Photo desk donut"], vm.Cards.Select(c => c.Title)); + vm.Kind = vm.Kinds[0]; + vm.Format = vm.Formats.Single(f => f.Value == "pdf"); + Assert.Equal(["Scans to one small PDF"], vm.Cards.Select(c => c.Title)); + vm.Format = vm.Formats[0]; + vm.Language = vm.Languages.Single(l => l.Value == "ko"); + Assert.Equal(2, vm.Cards.Count); + vm.Tag = vm.Tags.Single(t => t.Value == "images"); + Assert.Equal(["Photo desk donut"], vm.Cards.Select(c => c.Title)); + vm.Tag = vm.Tags[0]; + vm.Language = vm.Languages[0]; + vm.Search = "tester-sca"; + Assert.Equal(["Scans to one small PDF"], vm.Cards.Select(c => c.Title)); + vm.Search = "nothing like this"; + Assert.True(vm.IsEmpty); + Assert.Equal(AppHost.Get()["gallery.empty"], vm.EmptyText); + } + + [AvaloniaFact] + public void Covers_load_into_the_cards() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + var (vm, client, _, _) = Open(gallery, Store()); + using var _client = client; + using var _vm = vm; + + ClipWindowTests.WaitFor(() => vm.Cards.All(c => c.Thumb is not null)); + Assert.Equal(480, vm.Cards[0].Thumb!.PixelSize.Width); + Assert.Equal(1, gallery.Count("/presets/files/presets/instagram-jpg/images/1-thumb.webp")); + Assert.Equal(0, gallery.Count("/presets/files/presets/from-the-future/images/1-thumb.webp")); + Assert.Contains("Instagram-ready JPG", vm.Cards[0].AutomationName); + Assert.Contains("tester-ins", vm.Cards[0].AutomationName); + } + + [AvaloniaFact] + public void The_chosen_preset_shows_what_it_adds_and_installs_as_new_presets_through_the_counted_link() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + var store = Store(); + var ours = store.Presets.Count; + var (vm, client, opened, installed) = Open(gallery, store); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(c => c.Entry.Id == "photo-desk"); + var detail = vm.Detail!; + ClipWindowTests.WaitFor(() => detail.Installable && detail.Images.All(i => i.Bitmap is not null)); + Assert.Equal(["Turn", "Turn left", "Turn right"], detail.Presets.Select(p => p.Name)); + Assert.Contains("Turn left", detail.Presets[0].What); + Assert.Contains("Photo desk", detail.Donut); + Assert.Contains("JPG", detail.Donut); + Assert.Equal(0, gallery.Count("/presets/download/photo-desk")); // looking isn't downloading + + detail.InstallCommand.Execute(null); + ClipWindowTests.WaitFor(() => detail.InstallState != GalleryInstallState.Installing); + + Assert.Equal(GalleryInstallState.Installed, detail.InstallState); + Assert.Equal(1, gallery.Count("/presets/download/photo-desk")); + Assert.Equal(ours + 3, store.Presets.Count); + var result = Assert.Single(installed); + Assert.DoesNotContain(result.Presets, p => p.Id is "turn" or "left" or "right"); + Assert.Same(result.Profile, store.Profiles[^1]); + Assert.False(detail.InstallCommand.CanExecute(null)); // once + + detail.OpenCommentsCommand.Execute(null); + Assert.Equal(new Uri("https://github.com/KnifeLemon/Filee-Presets/discussions/7"), Assert.Single(opened)); + } + + [AvaloniaFact] + public void A_preset_described_in_the_detail_lists_its_target_and_options() + { + TestServices.EnsureInitialized(); + var (vm, client, _, _) = Open(Gallery(), Store()); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(c => c.Entry.Id == "instagram-jpg"); + ClipWindowTests.WaitFor(() => vm.Detail!.Installable); + var summary = Assert.Single(vm.Detail!.Presets); + Assert.Equal("Instagram JPG", summary.Name); + Assert.Contains("JPG", summary.What); + Assert.Contains("85", summary.Options); + Assert.Contains("1080", summary.Options); + Assert.Contains("{name}_insta", summary.Options); + Assert.Equal(AppHost.Get()["gallery.donut_none"], vm.Detail.Donut); + } + + [AvaloniaFact] + public void A_download_that_isnt_the_listed_file_installs_nothing() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + var store = Store(); + var before = store.Presets.Count; + // The counted link answers with another file than the one index.json lists (and the detail view checked). + var other = Insta(); + other.Image.Quality = 5; + gallery.Files["/presets/download/instagram-jpg"] = Bundle([other]); + var (vm, client, _, installed) = Open(gallery, store); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(c => c.Entry.Id == "instagram-jpg"); + ClipWindowTests.WaitFor(() => vm.Detail!.Installable); + vm.Detail!.InstallCommand.Execute(null); + ClipWindowTests.WaitFor(() => vm.Detail.InstallState != GalleryInstallState.Installing); + + Assert.Equal(GalleryInstallState.Failed, vm.Detail.InstallState); + Assert.Equal(AppHost.Get()["gallery.mismatch"], vm.Detail.InstallMessage); + Assert.Equal(before, store.Presets.Count); + Assert.Empty(installed); + } + + [AvaloniaFact] + public void A_listed_preset_the_rules_refuse_cant_be_installed() + { + TestServices.EnsureInitialized(); + var gallery = new FakeGallery(); + var bad = Insta(); + bad.Output.Location = OutputLocation.CustomFolder; + bad.Output.CustomFolder = @"C:\Users\Public"; + Publish(gallery, Share(gallery, "bad-one", "Bad one", Bundle([bad]), SKColors.Red, ["convert"], ["jpg"], [], ["en"])); + var (vm, client, _, _) = Open(gallery, Store()); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(); + ClipWindowTests.WaitFor(() => vm.Detail!.SummaryNote != AppHost.Get()["gallery.loading_details"]); + Assert.False(vm.Detail!.Installable); + Assert.False(vm.Detail.InstallCommand.CanExecute(null)); + Assert.Contains("presets[0].output.", vm.Detail.SummaryNote); + } + + [AvaloniaFact] + public void Without_filee_sh_the_repository_is_read_and_without_a_network_retry_works_later() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + gallery.SiteDown = true; + var store = Store(); + var (vm, client, _, _) = Open(gallery, store); + using var _client = client; + using var _vm = vm; + + Assert.Equal(GalleryState.Ready, vm.State); + Assert.True(client.FromRepository); + ClipWindowTests.WaitFor(() => vm.Cards.All(c => c.Thumb is not null)); + vm.Selected = vm.Cards.Single(c => c.Entry.Id == "instagram-jpg"); + ClipWindowTests.WaitFor(() => vm.Detail!.Installable); + vm.Detail!.InstallCommand.Execute(null); + ClipWindowTests.WaitFor(() => vm.Detail.InstallState == GalleryInstallState.Installed); + // Every file came from the repository, its preset.json in place of the counted link. + Assert.Equal(2, gallery.Requests.Count(r => r.AbsolutePath == "/KnifeLemon/Filee-Presets/main/presets/instagram-jpg/preset.json")); + Assert.DoesNotContain(gallery.Requests, r => r.Host == "filee.sh" && r.AbsolutePath != "/presets/index.json"); + + gallery.Offline = true; + var (offline, offlineClient, _, _) = Open(gallery, store); + using var _offlineClient = offlineClient; + using var _offline = offline; + Assert.Equal(GalleryState.Failed, offline.State); + Assert.True(offline.IsFailed); + gallery.Offline = false; + gallery.SiteDown = false; + offline.LoadCommand.Execute(null); + ClipWindowTests.WaitFor(() => offline.State == GalleryState.Ready); + Assert.Equal(3, offline.Cards.Count); + } + + [AvaloniaFact] + public void Answers_larger_than_their_limit_are_refused() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + gallery.Files["/presets/files/presets/instagram-jpg/images/1-thumb.webp"] = new byte[PresetGalleryClient.MaxThumbBytes + 1]; + var (vm, client, _, _) = Open(gallery, Store()); + using var _client = client; + using var _vm = vm; + ClipWindowTests.WaitFor(() => vm.Cards.Where(c => c.Entry.Id != "instagram-jpg").All(c => c.Thumb is not null)); + Assert.Null(vm.Cards.Single(c => c.Entry.Id == "instagram-jpg").Thumb); + + gallery.Files["/presets/index.json"] = new byte[GalleryIndex.MaxBytes + 1]; + gallery.Files["repo:/index.json"] = new byte[GalleryIndex.MaxBytes + 1]; + var (big, bigClient, _, _) = Open(gallery, Store()); + using var _bigClient = bigClient; + using var _big = big; + Assert.Equal(GalleryState.Failed, big.State); + } + + [AvaloniaFact] + public void Pictures_are_kept_in_the_cache_for_the_next_time() + { + TestServices.EnsureInitialized(); + var gallery = Gallery(); + var cache = Path.Combine(_root, "cache"); + var path = "/presets/files/presets/scan-merge/images/1-thumb.webp"; + var (first, firstClient, _, _) = Open(gallery, Store(), cache); + ClipWindowTests.WaitFor(() => first.Cards.All(c => c.Thumb is not null)); + first.Dispose(); + firstClient.Dispose(); + Assert.Equal(1, gallery.Count(path)); + Assert.NotEmpty(Directory.GetFiles(cache, "*.img")); + + var (second, secondClient, _, _) = Open(gallery, Store(), cache); + using var _secondClient = secondClient; + using var _second = second; + ClipWindowTests.WaitFor(() => second.Cards.All(c => c.Thumb is not null)); + Assert.Equal(1, gallery.Count(path)); + } + + [AvaloniaFact] + public void The_presets_page_opens_the_gallery() + { + TestServices.EnsureInitialized(); + var page = new PresetsPage { DataContext = new PresetsPageViewModel(AppHost.Get(), AppHost.Get(), AppHost.Get()) }; + var window = new Window { Content = page, Width = 1000, Height = 700 }; + window.Show(); + RenderTests.Pump(); + var button = page.GetVisualDescendants().OfType + private void OnUiLanguageChanged(object? sender, EventArgs e) + { + if (State != GalleryState.Ready) + return; + _ = LoadThumbsAsync(); + _ = Detail?.LoadImagesAsync(); } /// This Filee's version, as the update check reads it (a pre-release counts as its release). @@ -280,6 +290,7 @@ private async Task LoadThumbsAsync() public void Dispose() { + _loc.LanguageChanged -= OnUiLanguageChanged; _closing.Cancel(); Detail?.Dispose(); foreach (var card in _all) @@ -294,11 +305,14 @@ public sealed partial class PresetGalleryCardViewModel : ObservableObject, IDisp /// The cover's size in the list, in pixels of its long edge. public const int ThumbEdge = 480; + private readonly ILocalizer _loc; private bool _loading; + private string? _thumbPath; public PresetGalleryCardViewModel(GalleryEntry entry, ILocalizer loc) { Entry = entry; + _loc = loc; Byline = entry.Author.Length == 0 ? "" : loc.Format("gallery.by", entry.Author); Likes = loc.Format("gallery.likes", entry.Stats.Likes.ToString("N0", CultureInfo.CurrentCulture)); Downloads = loc.Format("gallery.downloads", entry.Stats.Downloads.ToString("N0", CultureInfo.CurrentCulture)); @@ -325,20 +339,29 @@ public bool Matches(string query) => || Entry.Author.Contains(query, StringComparison.CurrentCultureIgnoreCase) || Entry.Tags.Any(t => t.Contains(query, StringComparison.CurrentCultureIgnoreCase)); - /// Loads the cover's thumbnail (the cover itself when there is none); a failure leaves the placeholder. + /// + /// Loads the cover's thumbnail in the app's language (; the cover itself when there + /// is none), or again after the language changed; a failure leaves what is shown. + /// public async Task LoadThumbAsync(PresetGalleryClient client, CancellationToken cancellationToken) { - if (Thumb is not null || _loading || (Entry.Thumb ?? Entry.Images.FirstOrDefault()) is not { } path) + var language = _loc.Language; + if (_loading || (Entry.ThumbFor(language) ?? Entry.ImagesFor(language).FirstOrDefault()) is not { } path + || (Thumb is not null && path == _thumbPath)) return; _loading = true; try { var data = await client.GetImageAsync(Entry, path, cancellationToken); var bitmap = await Task.Run(() => GalleryBitmaps.Decode(data, ThumbEdge), cancellationToken); - if (cancellationToken.IsCancellationRequested) + if (cancellationToken.IsCancellationRequested || bitmap is null) bitmap?.Dispose(); else - Thumb = bitmap; + { + var old = Thumb; + (Thumb, _thumbPath) = (bitmap, path); + old?.Dispose(); + } } catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or ArgumentException) { @@ -370,6 +393,9 @@ public sealed record PresetGallerySummary(string Name, string What, string Optio public bool HasOptions => Options.Length > 0; } +/// A setting of the chosen preset that touches the user's files, in their words (). +public sealed record PresetGalleryWarning(string Code, string Text, bool IsHigh); + /// Whether the chosen preset is being installed, was, or couldn't be. public enum GalleryInstallState { @@ -408,9 +434,6 @@ internal PresetGalleryDetailViewModel(GalleryEntry entry, PresetGalleryClient cl ? string.Join(" · ", loc.Format("gallery.likes", entry.Stats.Likes.ToString("N0", CultureInfo.CurrentCulture)), loc.Format("gallery.downloads", entry.Stats.Downloads.ToString("N0", CultureInfo.CurrentCulture))) : ""; - for (var i = 0; i < entry.Images.Count; i++) - Images.Add(new PresetGalleryImageViewModel(loc.Format("gallery.image", i + 1, entry.Images.Count))); - _shownImage = Images.FirstOrDefault(); } public GalleryEntry Entry { get; } @@ -431,6 +454,9 @@ internal PresetGalleryDetailViewModel(GalleryEntry entry, PresetGalleryClient cl public bool HasSeveralImages => Images.Count > 1; + /// The paths shows, for the language they were picked for. + private IReadOnlyList _imagePaths = []; + /// What each preset in it does. public ObservableCollection Presets { get; } = []; @@ -456,22 +482,63 @@ internal PresetGalleryDetailViewModel(GalleryEntry entry, PresetGalleryClient cl public bool HasComments => Entry.Discussion is not null; + /// + /// What the preset does to the user's files, worked out here from the file itself (never from the index), most + /// serious first. + /// + public ObservableCollection Warnings { get; } = []; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasHighWarnings))] + private bool _hasWarnings; + + /// It can replace, move or overwrite files: Install waits for . + public bool HasHighWarnings => Warnings.Any(w => w.IsHigh); + + /// The user ticked "I understand…" for a preset with . + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(InstallCommand))] + private bool _warningsAccepted; + /// Loads the pictures and what the preset does. public async Task LoadAsync() { SummaryNote = _loc["gallery.loading_details"]; + await LoadSummaryAsync(_cancel.Token); + await LoadImagesAsync(); + } + + /// + /// Loads the pictures in the app's language (), or again after the language + /// changed; nothing happens when the language has the same pictures. + /// + public async Task LoadImagesAsync() + { var token = _cancel.Token; - await LoadSummaryAsync(token); - for (var i = 0; i < Entry.Images.Count && !token.IsCancellationRequested; i++) + var paths = Entry.ImagesFor(_loc.Language); + if (paths.SequenceEqual(_imagePaths) || token.IsCancellationRequested) + return; + _imagePaths = paths; + var shown = ShownImage is { } current ? Images.IndexOf(current) : 0; + foreach (var image in Images) + image.Bitmap?.Dispose(); + Images.Clear(); + for (var i = 0; i < paths.Count; i++) + Images.Add(new PresetGalleryImageViewModel(_loc.Format("gallery.image", i + 1, paths.Count))); + ShownImage = Images.Count == 0 ? null : Images[Math.Clamp(shown, 0, Images.Count - 1)]; + OnPropertyChanged(nameof(HasSeveralImages)); + var set = Images.ToList(); + for (var i = 0; i < paths.Count && !token.IsCancellationRequested && _imagePaths == paths; i++) { try { - var data = await _client.GetImageAsync(Entry, Entry.Images[i], token); + var data = await _client.GetImageAsync(Entry, paths[i], token); var bitmap = await Task.Run(() => GalleryBitmaps.Decode(data, ImageEdge), token); - if (token.IsCancellationRequested) + // A language changed meanwhile: these pictures are no longer shown. + if (token.IsCancellationRequested || _imagePaths != paths) bitmap?.Dispose(); else - Images[i].Bitmap = bitmap; + set[i].Bitmap = bitmap; } catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException or InvalidDataException or ArgumentException) { @@ -508,11 +575,17 @@ private async Task LoadSummaryAsync(CancellationToken token) ? _loc.Format("gallery.donut_new", _loc.DisplayName(profile), profile.Extensions.Count == 0 ? _loc["gallery.donut_mixed"] : string.Join(", ", profile.Extensions.Take(8).Select(e => e.ToUpperInvariant())) + (profile.Extensions.Count > 8 ? " …" : "")) : _loc["gallery.donut_none"]; + foreach (var warning in check.Derived?.Warnings ?? []) + Warnings.Add(new PresetGalleryWarning(warning.Code, _loc[$"gallery.warning.{warning.Code}"], warning.Severity == SharedPresetWarnings.High)); + HasWarnings = Warnings.Count > 0; + OnPropertyChanged(nameof(HasHighWarnings)); SummaryNote = null; Installable = true; } - private bool CanInstall() => Installable && InstallState is not (GalleryInstallState.Installing or GalleryInstallState.Installed); + private bool CanInstall() => + Installable && (!HasHighWarnings || WarningsAccepted) + && InstallState is not (GalleryInstallState.Installing or GalleryInstallState.Installed); /// Downloads it through the install link and adds it to the library as new presets. [RelayCommand(CanExecute = nameof(CanInstall))] @@ -531,7 +604,9 @@ private async Task InstallAsync() InstallMessage = _loc["gallery.download_failed"]; return; } - var result = GalleryInstaller.Install(_store, json, Entry.Sha256, _loc.DisplayName, _loc.DisplayName); + // The installer checks the file's SHA-256 against the index's, as the view did: it is the file the warnings + // shown were worked out from. + var result = GalleryInstaller.Install(_store, json, Entry.Sha256, _loc.DisplayName, _loc.DisplayName, Entry.Id); if (!result.Ok) { InstallState = GalleryInstallState.Failed; diff --git a/src/Filee.App/Views/GalleryExportWindow.axaml b/src/Filee.App/Views/GalleryExportWindow.axaml new file mode 100644 index 000000000..8da30744a --- /dev/null +++ b/src/Filee.App/Views/GalleryExportWindow.axaml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Filee.App/Views/GalleryExportWindow.axaml.cs b/src/Filee.App/Views/GalleryExportWindow.axaml.cs new file mode 100644 index 000000000..431c4e6f7 --- /dev/null +++ b/src/Filee.App/Views/GalleryExportWindow.axaml.cs @@ -0,0 +1,28 @@ +// "Export for the gallery" (#1530). Escape closes it. + +using Avalonia.Controls; +using Avalonia.Input; +using Filee.App.Services; + +namespace Filee.App.Views; + +public partial class GalleryExportWindow : Window +{ + public GalleryExportWindow() + { + InitializeComponent(); + Motion.Track(this); + UiZoom.Track(this); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + if (e.Key == Key.Escape && !e.Handled) + { + Close(); + e.Handled = true; + return; + } + base.OnKeyDown(e); + } +} diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml b/src/Filee.App/Views/Pages/PresetsPage.axaml index 3fa146a2b..ac77d3b29 100644 --- a/src/Filee.App/Views/Pages/PresetsPage.axaml +++ b/src/Filee.App/Views/Pages/PresetsPage.axaml @@ -43,6 +43,14 @@ + + diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml index 2e52942ea..d9f72ca7e 100644 --- a/src/Filee.App/Views/PresetEditorView.axaml +++ b/src/Filee.App/Views/PresetEditorView.axaml @@ -37,6 +37,9 @@ + + diff --git a/src/Filee.App/Views/PresetGalleryWindow.axaml b/src/Filee.App/Views/PresetGalleryWindow.axaml index e2b292edc..1bad84370 100644 --- a/src/Filee.App/Views/PresetGalleryWindow.axaml +++ b/src/Filee.App/Views/PresetGalleryWindow.axaml @@ -44,6 +44,17 @@ + + + @@ -150,6 +161,26 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/Filee.Cli/Help.cs b/src/Filee.Cli/Help.cs index 0116da169..965f4787b 100644 --- a/src/Filee.Cli/Help.cs +++ b/src/Filee.Cli/Help.cs @@ -60,15 +60,18 @@ Lists the presets saved in Filee (built-in and your own). With --json, prints th 'check' checks a shared preset for the preset gallery: a folder with preset.json (what Settings → General → Export writes, with at most 20 presets and one donut), meta.json (optional) and 1 to 4 pictures in images/ (1.png … 4.webp; PNG, JPEG or WebP, 640 to 2,560 pixels on the long edge, at most 2 MB, not animated). - Only fields on the gallery's list may be in preset.json, and nothing that saves outside the source's folder, - runs a program, or carries a path, a password or a link. It reads nothing else and changes nothing. + Only fields on the gallery's list may be in preset.json, and nothing that runs a program or carries a folder + of one's own, a password, a path, a link or personal metadata (names, places, copyright owners). Settings that + touch the installer's files (replacing or moving originals, overwriting, metadata) pass with a warning. It reads + nothing else and changes nothing. Exit codes: 0 the preset may be shared, 1 it has problems, 2 the folder doesn't exist. Options: --json Print the result as JSON: "ok", "errors" (each with "code", "file", "path" and "message") and "derived" (what the preset is: "kinds", "formats" with "from" and - "to", "minVersion", the number of "presets" and "profiles", and the "sha256" of - preset.json) + "to", "minVersion", the number of "presets" and "profiles", the "sha256" of + preset.json and "warnings", each with "code", "severity" (high, medium or info), + "message" and the "presets" that have it) --quiet Print nothing when the preset passes """; diff --git a/src/Filee.Cli/PresetsCheckCommand.cs b/src/Filee.Cli/PresetsCheckCommand.cs index 9c7508827..09f430d74 100644 --- a/src/Filee.Cli/PresetsCheckCommand.cs +++ b/src/Filee.Cli/PresetsCheckCommand.cs @@ -38,6 +38,8 @@ private static void WriteText(PresetCheckResult result, TextWriter output) return; } var derived = result.Derived!; + foreach (var warning in derived.Warnings) + output.WriteLine($"warning ({warning.Severity}): {warning.Message} ({warning.Code}: {string.Join(", ", warning.Presets)})"); output.WriteLine($"OK: {derived.Presets} preset(s), {derived.Profiles} donut(s). Kinds: {string.Join(", ", derived.Kinds)}. " + $"Formats: {(derived.From.Count == 0 ? "any" : string.Join(", ", derived.From))} → {(derived.To.Count == 0 ? "-" : string.Join(", ", derived.To))}. " + $"Needs Filee {derived.MinVersion} or later."); @@ -70,6 +72,17 @@ private static void WriteJson(PresetCheckResult result, TextWriter output) => Cl json.WriteNumber("presets", derived.Presets); json.WriteNumber("profiles", derived.Profiles); json.WriteString("sha256", derived.Sha256); + json.WriteStartArray("warnings"); + foreach (var warning in derived.Warnings) + { + json.WriteStartObject(); + json.WriteString("code", warning.Code); + json.WriteString("severity", warning.Severity); + json.WriteString("message", warning.Message); + WriteList(json, "presets", warning.Presets); + json.WriteEndObject(); + } + json.WriteEndArray(); json.WriteEndObject(); } else diff --git a/src/Filee.Core/Gallery/GalleryExport.cs b/src/Filee.Core/Gallery/GalleryExport.cs new file mode 100644 index 000000000..e481177d3 --- /dev/null +++ b/src/Filee.Core/Gallery/GalleryExport.cs @@ -0,0 +1,37 @@ +// "Export for the gallery" (#1530): a preset.json with only the presets one chooses, and one donut if one likes, for a +// submission to the preset gallery. A group brings its members and a donut its slices, so the file is whole. The same +// check the gallery's CI runs is run on it here, so the problems and warnings show before anything is saved. + +using System.Text.Json; +using Filee.Core.Presets; +using Filee.Core.Profiles; +using Filee.Core.Settings; + +namespace Filee.Core.Gallery; + +/// The file "Export for the gallery" writes, and what the gallery's check says about it. +public sealed record GalleryExportFile(byte[] Json, IReadOnlyList Presets, PresetCheckResult Check); + +public static class GalleryExport +{ + /// + /// The bundle of and (with the presets their groups and slices + /// need, in 's order), as an export writes it, and its check. + /// + public static GalleryExportFile Build(IReadOnlyList library, IEnumerable chosen, ToolbarProfile? profile) + { + var ids = chosen.Select(p => p.Id).ToHashSet(StringComparer.Ordinal); + if (profile is not null) + ids.UnionWith(profile.PresetIds.Concat(profile.BackPresetIds ?? [])); + foreach (var group in library.Where(p => p.IsGroup && ids.Contains(p.Id)).ToList()) + ids.UnionWith(group.SubPresetIds); + var presets = library.Where(p => ids.Contains(p.Id)).ToList(); + var json = JsonSerializer.SerializeToUtf8Bytes(new PresetBundle + { + SettingsSchema = AppSettings.CurrentSchemaVersion, + Presets = [.. presets.Select(p => p.ForSharing())], + Profiles = profile is null ? [] : [profile.Clone()], + }, FileeJsonContext.Default.PresetBundle); + return new GalleryExportFile(json, presets, SharedBundleCheck.Check(json)); + } +} diff --git a/src/Filee.Core/Gallery/GalleryIndex.cs b/src/Filee.Core/Gallery/GalleryIndex.cs index e17d14c05..84814023e 100644 --- a/src/Filee.Core/Gallery/GalleryIndex.cs +++ b/src/Filee.Core/Gallery/GalleryIndex.cs @@ -50,6 +50,32 @@ public sealed record GalleryEntry /// The cover's thumbnail; null without one (the cover is shown instead). public string? Thumb { get; init; } + /// + /// Pictures in a language of the app's ("ko" → its list, gaps already filled with the default pictures), for people + /// using Filee in that language; empty when the preset has none. + /// + public IReadOnlyDictionary> ImagesByLang { get; init; } = new Dictionary>(); + + /// The cover's thumbnail per language, as . + public IReadOnlyDictionary ThumbByLang { get; init; } = new Dictionary(); + + /// + /// The pictures for someone using Filee in : its own set, else its base language's + /// ("pt" for "pt-PT"), else the default set. + /// + public IReadOnlyList ImagesFor(string language) => + ByLanguage(ImagesByLang, language) is { Count: > 0 } images ? images : Images; + + /// The cover's thumbnail for , picked as . + public string? ThumbFor(string language) => ByLanguage(ThumbByLang, language) ?? Thumb; + + private static T? ByLanguage(IReadOnlyDictionary sets, string language) where T : class => + sets.GetValueOrDefault(language) ?? sets.GetValueOrDefault(language.Split('-')[0]); + + /// Every picture of the preset, in any language (what the app may download for it). + public bool HasPicture(string path) => + path == Thumb || Images.Contains(path) || ThumbByLang.Values.Contains(path) || ImagesByLang.Values.Any(set => set.Contains(path)); + /// Its preset.json, as a path relative to index.json. public required string Preset { get; init; } @@ -112,8 +138,20 @@ public static GalleryIndex Parse(ReadOnlySpan json) var title = Text(item, "title", 60).Trim(); if (InFolder(preset, id) != "preset.json" || !Sha256Pattern().IsMatch(sha256) || title.Length == 0) return null; - var images = List(item, "images", 4, 200).Where(path => InFolder(path, id) is { } file && ImageName().IsMatch(file)).ToList(); + bool IsPicture(string path) => InFolder(path, id) is { } file && KnownLanguage(ImageName().Match(file)); + bool IsThumb(string path) => InFolder(path, id) is { } file && KnownLanguage(ThumbName().Match(file)); + var images = List(item, "images", 4, 200).Where(IsPicture).ToList(); var thumb = Text(item, "thumb", 200); + var imagesByLang = new Dictionary>(StringComparer.Ordinal); + var thumbByLang = new Dictionary(StringComparer.Ordinal); + if (item.TryGetProperty("imagesByLang", out var byLang) && byLang.ValueKind == JsonValueKind.Object) + foreach (var set in byLang.EnumerateObject().Where(set => IsLanguage(set.Name)).Take(SharedPresetFolderCheck.Languages.Count * 2)) + if (List(byLang, set.Name, 4, 200).Where(IsPicture).ToList() is { Count: > 0 } list) + imagesByLang[set.Name] = list; + if (item.TryGetProperty("thumbByLang", out var thumbs) && thumbs.ValueKind == JsonValueKind.Object) + foreach (var set in thumbs.EnumerateObject().Where(set => IsLanguage(set.Name)).Take(SharedPresetFolderCheck.Languages.Count * 2)) + if (Text(thumbs, set.Name, 200) is { } path && IsThumb(path)) + thumbByLang[set.Name] = path; var download = Text(item, "download", 200); var formats = item.TryGetProperty("formats", out var f) && f.ValueKind == JsonValueKind.Object ? f : default; var stats = item.TryGetProperty("stats", out var s) && s.ValueKind == JsonValueKind.Object ? s : default; @@ -134,7 +172,9 @@ public static GalleryIndex Parse(ReadOnlySpan json) Discussion = item.TryGetProperty("discussion", out var d) && d.ValueKind == JsonValueKind.Number && d.TryGetInt32(out var n) && n > 0 ? n : null, License = Text(item, "license", 16) is { Length: > 0 } license ? license : SharedPresetFolderCheck.License, Images = images, - Thumb = InFolder(thumb, id) is { } thumbFile && ThumbName().IsMatch(thumbFile) ? thumb : null, + Thumb = IsThumb(thumb) ? thumb : null, + ImagesByLang = imagesByLang, + ThumbByLang = thumbByLang, Preset = preset, Download = IsDownload(download, id) ? download : null, Sha256 = sha256, @@ -164,15 +204,24 @@ private static GalleryStats Stats(JsonElement stats) } // Up to three plain folders before presets// (no "..", no scheme, no leading slash), then a file of the folder. - [GeneratedRegex(@"^(?:[a-z0-9][a-z0-9_\-]*/){0,3}presets/(?[a-z0-9\-]{3,48})/(?preset\.json|images/[1-4](?:-thumb)?\.[a-z]{3,4})$", RegexOptions.CultureInvariant)] + [GeneratedRegex(@"^(?:[a-z0-9][a-z0-9_\-]*/){0,3}presets/(?[a-z0-9\-]{3,48})/(?preset\.json|images/(?:[A-Za-z]{2,3}(?:-[A-Za-z]{2,4})?/)?[1-4](?:-thumb)?\.[a-z]{3,4})$", RegexOptions.CultureInvariant)] private static partial Regex RelativePath(); - [GeneratedRegex(@"^images/[1-4]\.(webp|png|jpg|jpeg)$", RegexOptions.CultureInvariant)] + // A picture of the default set (images/1.webp) or of a language's (images/ko/1.webp). + [GeneratedRegex(@"^images/(?:(?[A-Za-z]{2,3}(?:-[A-Za-z]{2,4})?)/)?[1-4]\.(webp|png|jpg|jpeg)$", RegexOptions.CultureInvariant)] private static partial Regex ImageName(); - [GeneratedRegex(@"^images/[1-4]-thumb\.webp$", RegexOptions.CultureInvariant)] + [GeneratedRegex(@"^images/(?:(?[A-Za-z]{2,3}(?:-[A-Za-z]{2,4})?)/)?[1-4]-thumb\.webp$", RegexOptions.CultureInvariant)] private static partial Regex ThumbName(); + /// A match of a picture's name, in the default set or a set of a language of the app's. + private static bool KnownLanguage(Match match) => + match.Success && (!match.Groups["lang"].Success || SharedPresetFolderCheck.Languages.Contains(match.Groups["lang"].Value)); + + /// A language of the app's, or the base of one ("pt", "zh"): the keys of the per-language pictures. + private static bool IsLanguage(string code) => + SharedPresetFolderCheck.Languages.Any(l => l == code || l.Split('-')[0] == code); + /// /// An install link of the preset's: https://filee.sh/presets/download/<id> or relative to index.json /// (download/<id>). The app also checks that it stays on the host index.json came from. diff --git a/src/Filee.Core/Gallery/GalleryInstaller.cs b/src/Filee.Core/Gallery/GalleryInstaller.cs index eb5f8fe7e..398fe68ff 100644 --- a/src/Filee.Core/Gallery/GalleryInstaller.cs +++ b/src/Filee.Core/Gallery/GalleryInstaller.cs @@ -27,8 +27,9 @@ public static class GalleryInstaller /// to and saves the library. and /// give the names the user sees (a built-in name in their language), to tell a clash. /// + /// The gallery entry's id, kept on each preset (). public static GalleryInstallResult Install(UserDataStore store, ReadOnlySpan json, string sha256, - Func presetName, Func profileName) + Func presetName, Func profileName, string? gallery = null) { var actual = Convert.ToHexStringLower(SHA256.HashData(json)); if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase)) @@ -59,6 +60,8 @@ public static GalleryInstallResult Install(UserDataStore store, ReadOnlySpanThe settings that touch the installer's files, most serious first (). + public IReadOnlyList Warnings { get; init; } = []; +} + +/// +/// A setting of a shared preset that touches the installer's files: (stable, see +/// ), ("high", "medium" or "info"), what it does in English, +/// and the ids of the presets in the file that have it. +/// +public sealed record PresetCheckWarning(string Code, string Severity, string Message, IReadOnlyList Presets); /// The outcome of or . public sealed class PresetCheckResult diff --git a/src/Filee.Core/Gallery/SharedBundleCheck.cs b/src/Filee.Core/Gallery/SharedBundleCheck.cs index aff8ab44c..f7c9507fe 100644 --- a/src/Filee.Core/Gallery/SharedBundleCheck.cs +++ b/src/Filee.Core/Gallery/SharedBundleCheck.cs @@ -132,6 +132,11 @@ private static void CheckPresets(PresetBundle bundle, PresetCheckResult result) if (preset.TargetFormat != Preset.GroupTarget) result.Add("preset.target_unknown", FileName, at + ".targetFormat", $"a group's target is \"{Preset.GroupTarget}\""); } + else if (preset.IsCopyToFolder) + { + if (preset.TargetFormat != Preset.CopyTarget) + result.Add("preset.target_unknown", FileName, at + ".targetFormat", $"Copy to folder's target is \"{Preset.CopyTarget}\""); + } else if (preset.TargetFormat != BuiltInData.SameAsSource && (FormatRegistry.FindById(preset.TargetFormat) is null || preset.TargetFormat == Preset.CopyTarget)) { @@ -177,7 +182,7 @@ private static PresetCheckDerived Derive(PresetBundle bundle, string sha256) var kinds = new List(); if (bundle.Presets.Any(p => p.Kind is PresetKind.Convert or PresetKind.Group)) kinds.Add("convert"); - if (bundle.Presets.Any(p => p.Kind == PresetKind.Tool)) + if (bundle.Presets.Any(p => p.IsTool)) kinds.Add("tool"); if (bundle.Profiles.Count > 0) kinds.Add("toolbar"); @@ -186,7 +191,10 @@ private static PresetCheckDerived Derive(PresetBundle bundle, string sha256) .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); var to = bundle.Presets.Where(p => p.Kind == PresetKind.Convert && p.TargetFormat != BuiltInData.SameAsSource) .Select(p => p.TargetFormat).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); - return new PresetCheckDerived(kinds, from, to, BaselineVersion, bundle.Presets.Count, bundle.Profiles.Count, sha256); + return new PresetCheckDerived(kinds, from, to, BaselineVersion, bundle.Presets.Count, bundle.Profiles.Count, sha256) + { + Warnings = SharedPresetWarnings.Of(bundle.Presets), + }; } private static string FirstLine(string text) @@ -274,6 +282,29 @@ public void Check(JsonElement value, ValueRule rule, string path) else if (text.Check?.Invoke(s) is { } why) result.Add("field.value", file, path, $"\"{Shorten(s)}\" {why}"); break; + case MapRule map: + if (value.ValueKind != JsonValueKind.Object) + { + result.Add("field.type", file, path, "must be an object"); + break; + } + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in value.EnumerateObject()) + { + var at = $"{path}.{property.Name}"; + if (!names.Add(property.Name)) + result.Add("field.duplicate", file, at, "appears twice"); + else if (names.Count > map.MaxCount) + { + result.Add("field.range", file, path, $"has more than {map.MaxCount} fields"); + break; + } + else if (map.KeyCheck(property.Name) is { } bad) + result.Add("field.value", file, at, $"\"{Shorten(property.Name)}\" {bad}"); + else + Check(property.Value, map.ValueFor(property.Name), at); + } + break; case ListRule list: if (value.ValueKind != JsonValueKind.Array) { diff --git a/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs b/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs index 268c4288c..971582e48 100644 --- a/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs +++ b/src/Filee.Core/Gallery/SharedPresetFolderCheck.cs @@ -38,6 +38,19 @@ public static partial class SharedPresetFolderCheck /// A preset's id: 3 to 48 of a-z, 0-9 and '-', not starting or ending with '-', and not reserved. public static bool IsSlug(string text) => Slug().IsMatch(text) && !ReservedSlugs.Contains(text); + /// Largest folder of a shared preset, every file in it counted, in bytes. + public const long MaxFolderBytes = 40L * 1024 * 1024; + + /// + /// The app's languages (its i18n files): images/<language>/ may hold pictures in one of them, shown to people + /// using Filee in that language. The app's tests keep this in step with its languages. + /// + public static readonly IReadOnlyList Languages = + [ + "ar", "bn-BD", "de", "en", "es", "fa", "fr", "hi", "id", "it", "ja", "ko", "mn", "ne", "pl", "pt-BR", "pt-PT", "ru", + "th", "tr", "vi", "zh-CN", "zh-TW", + ]; + /// The kinds meta.json may list (see ). public static readonly IReadOnlyList Kinds = ["convert", "tool", "toolbar"]; @@ -96,25 +109,69 @@ public static PresetCheckResult Check(string folder, IGalleryImageDecoder? decod result.Add("images.missing", ImagesFolder + "/", "", $"is missing: a shared preset needs {MinImages} to {MaxImages} pictures (1 is the cover)"); else CheckImages(new DirectoryInfo(Path.Combine(root.FullName, ImagesFolder)), decoder, result); + + var size = root.EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint }) + .Sum(f => f.Length); + if (size > MaxFolderBytes) + result.Add("folder.too_large", "", "", $"holds {size:N0} bytes; a shared preset's folder may hold at most {MaxFolderBytes:N0}"); return result; } - /// The pictures: 1.png … 4.webp (1 to 4, no gaps), each with an optional 1-thumb.webp. + /// + /// The pictures: 1.png … 4.webp (1 to 4, no gaps), each with an optional 1-thumb.webp, and the language sets in + /// images/<language>/ (): the same names, 1 to 4 of the default set's numbers (a number a + /// set leaves out shows the default picture). + /// private static void CheckImages(DirectoryInfo folder, IGalleryImageDecoder? decoder, PresetCheckResult result) + { + var languages = new List(); + var numbers = CheckImageSet(folder, ImagesFolder, decoder, result, languages); + if (numbers.Count < MinImages) + result.Add("images.missing", ImagesFolder + "/", "", $"has no pictures: a shared preset needs {MinImages} to {MaxImages} (1 is the cover)"); + else if (numbers.Max != numbers.Count) + result.Add("images.name", ImagesFolder + "/", "", "the pictures must be numbered from 1 without gaps (1 is the cover)"); + + foreach (var language in languages) + { + var prefix = $"{ImagesFolder}/{language.Name}"; + if (!Languages.Contains(language.Name)) + { + result.Add("images.language", prefix + "/", "", $"is not a language of Filee's ({string.Join(", ", Languages)})"); + continue; + } + var set = CheckImageSet(language, prefix, decoder, result, null); + if (set.Count < MinImages) + result.Add("images.missing", prefix + "/", "", "has no pictures; leave the folder out instead"); + foreach (var number in set.Where(n => !numbers.Contains(n))) + result.Add("images.name", prefix + "/", "", $"has a picture {number}, which the default set (images/) doesn't have"); + } + } + + /// + /// One set of pictures in : checks each, returns their numbers. Folders go to + /// (the default set's language sets), or are refused where there is none. + /// + private static SortedSet CheckImageSet(DirectoryInfo folder, string prefix, IGalleryImageDecoder? decoder, PresetCheckResult result, + List? languages) { var numbers = new SortedSet(); var thumbs = new List<(int Number, FileInfo File)>(); foreach (var entry in folder.EnumerateFileSystemInfos()) { - var name = $"{ImagesFolder}/{entry.Name}"; + var name = $"{prefix}/{entry.Name}"; if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) { result.Add("folder.link", name, "", "is a link; the folder may only hold real files"); continue; } + if (entry is DirectoryInfo directory && languages is not null) + { + languages.Add(directory); + continue; + } if (entry is not FileInfo file) { - result.Add("images.unexpected_file", name, "", "doesn't belong in images/ (only 1.png … 4.webp)"); + result.Add("images.unexpected_file", name, "", "doesn't belong here (only 1.png … 4.webp, and a folder per language in images/)"); continue; } var match = ImageName().Match(file.Name); @@ -136,19 +193,15 @@ private static void CheckImages(DirectoryInfo folder, IGalleryImageDecoder? deco } CheckImage(file, name, match.Groups[3].Value.ToLowerInvariant(), thumb: false, decoder, result); } - - if (numbers.Count < MinImages) - result.Add("images.missing", ImagesFolder + "/", "", $"has no pictures: a shared preset needs {MinImages} to {MaxImages} (1 is the cover)"); - else if (numbers.Max != numbers.Count) - result.Add("images.name", ImagesFolder + "/", "", "the pictures must be numbered from 1 without gaps (1 is the cover)"); foreach (var (number, file) in thumbs) { - var name = $"{ImagesFolder}/{file.Name}"; + var name = $"{prefix}/{file.Name}"; if (!numbers.Contains(number)) result.Add("images.name", name, "", $"is a thumbnail of picture {number}, which isn't there"); else CheckImage(file, name, "webp", thumb: true, decoder, result); } + return numbers; } [GeneratedRegex(@"^([1-4])(?:(-thumb)\.webp|\.(png|jpg|jpeg|webp))$", RegexOptions.CultureInvariant)] @@ -218,6 +271,11 @@ private static void CheckImage(FileInfo file, string name, string extension, boo ["updated"] = new StringRule(40, Timestamp), ["discussion"] = new IntRule(1, int.MaxValue) { Nullable = true }, ["license"] = new StringRule(16, text => text == License ? null : $"must be {License}"), + ["warnings"] = new ListRule(new ObjectRule(new Dictionary(StringComparer.Ordinal) + { + ["code"] = new EnumRule([.. SharedPresetWarnings.All.Select(w => w.Code)]), + ["severity"] = new EnumRule([SharedPresetWarnings.High, SharedPresetWarnings.Medium, SharedPresetWarnings.Info]), + }), SharedPresetWarnings.All.Count), }); private static string? Timestamp(string text) => @@ -271,6 +329,10 @@ private static void CheckMeta(FileInfo file, PresetCheckDerived? derived, Preset if (formats.TryGetProperty("to", out var to) && !SameSet(to, derived.To)) result.Add("meta.derived_mismatch", MetaName, "formats.to", $"must be [{string.Join(", ", derived.To)}], as preset.json is"); } + if (root.TryGetProperty("warnings", out var warnings) + && !warnings.EnumerateArray().Select(w => w.TryGetProperty("code", out var c) ? c.GetString() : null).ToHashSet(StringComparer.Ordinal) + .SetEquals(derived.Warnings.Select(w => w.Code))) + result.Add("meta.derived_mismatch", MetaName, "warnings", $"must be [{string.Join(", ", derived.Warnings.Select(w => w.Code))}], as preset.json is"); if (root.TryGetProperty("minVersion", out var min) && Version.Parse(min.GetString()!) < Version.Parse(derived.MinVersion)) result.Add("meta.derived_mismatch", MetaName, "minVersion", $"must be at least {derived.MinVersion}, the first Filee that can install it"); } diff --git a/src/Filee.Core/Gallery/SharedPresetRules.cs b/src/Filee.Core/Gallery/SharedPresetRules.cs index 85101bdcc..927298166 100644 --- a/src/Filee.Core/Gallery/SharedPresetRules.cs +++ b/src/Filee.Core/Gallery/SharedPresetRules.cs @@ -1,8 +1,11 @@ // The allow-list of what a preset shared in the preset gallery may hold (#1530): every field of a preset and a toolbar // profile that may appear in a shared preset.json, with the values it may take. A field that isn't listed here fails the // check, so a field added to Preset later stays out of the gallery until someone decides it is safe and lists it. -// Fields that would carry something of the sharer's (a folder, a password, a picture's path) or run something on the -// installer's computer are listed as "left out": they may be there, as an export writes them, but only empty. +// Shared presets get as much freedom as the model has; settings that touch the installer's files (replacing or moving +// originals, overwriting, editing metadata) are allowed and reported as warnings (SharedPresetWarnings). Only what +// can't work on another computer or would give something of the sharer's away is "left out": a folder of one's own, a +// password, a picture's or a sound's path, and names, places and copyright owners written into metadata. Those may be +// there, as an export writes them, but only empty. using Filee.Core.Formats; using Filee.Core.Presets; @@ -41,6 +44,12 @@ internal sealed record StringRule(int MaxLength, Func? Check = /// A list of at most values that each pass . internal sealed record ListRule(ValueRule Item, int MaxCount) : ValueRule; +/// +/// An object whose field names are data (metadata fields, "XMP-dc:Title"): at most , each name +/// passing (null: fine), each value checked with the rule gives for it. +/// +internal sealed record MapRule(int MaxCount, Func KeyCheck, Func ValueFor) : ValueRule; + /// /// A field left out of shared presets: absent, null, "", false, 0, [] or {} only. says why, for the /// message. @@ -62,25 +71,28 @@ internal static class SharedPresetRules /// How deep the JSON may nest; a preset needs 5 levels. public const int MaxDepth = 16; - /// The kinds of preset that may be shared. Copy to folder needs a folder of one's own. - public static readonly IReadOnlyList Kinds = [nameof(PresetKind.Convert), nameof(PresetKind.Group), nameof(PresetKind.Tool)]; + /// + /// The kinds of preset that may be shared: every kind there is. Copy to folder comes without its folder (the + /// installer chooses one); a warning says so. + /// + public static readonly IReadOnlyList Kinds = + [nameof(PresetKind.Convert), nameof(PresetKind.Group), nameof(PresetKind.Tool), nameof(PresetKind.CopyToFolder)]; /// - /// The tools that may be shared (; null is the crop). Metadata is left out: what it - /// changes (author, GPS) is about people. + /// The tools that may be shared (; null is the crop): every tool there is. A tool that runs + /// a program or a command (none yet) must never be added here. /// public static readonly IReadOnlyList Tools = [ null, Preset.CropTool, Preset.ClipTool, Preset.ImageEditTool, Preset.HideTool, Preset.AnnotateTool, - Preset.BackgroundTool, Preset.UpscaleTool, + Preset.BackgroundTool, Preset.MetadataTool, Preset.UpscaleTool, ]; /// - /// Where a shared preset may save: the default location, next to the source, or in a folder next to it (named by - /// , which may not hold a separator). Never a folder of its own. + /// Where a shared preset may save: every location. The folder of is left + /// out (a path of one's own), so that one saves next to the source until the installer picks a folder. /// - public static readonly IReadOnlyList Locations = - [nameof(OutputLocation.Default), nameof(OutputLocation.SameFolder), nameof(OutputLocation.Subfolder)]; + public static readonly IReadOnlyList Locations = System.Enum.GetNames(); /// The placeholders a file name pattern may use (). public static readonly IReadOnlyList Placeholders = ["name", "ext", "preset", "date", "time", "index"]; @@ -96,6 +108,27 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => private static readonly BoolRule Flag = new(); private static readonly StringRule Colour = new(9, SharedText.HexColour); + private static readonly ObjectRule Backdrop = Obj( + ("kind", Enum()), + ("from", Colour), + ("to", Colour), + ("color", Colour), + ("picture", new LeftOutRule("a picture of one's own is a path on one's computer")), + ("pictureWritten", new LeftOutRule("belongs to a picture of one's own")), + ("pictureLength", new LeftOutRule("belongs to a picture of one's own")), + ("padding", new IntRule(0, BackdropOptions.MaxPadding)), + ("corners", new IntRule(0, BackdropOptions.MaxCorners)), + ("shadow", new IntRule(0, BackdropOptions.MaxShadow)), + ("canvas", Enum())); + + /// + /// A metadata field given a value: one that names a person, a place or a copyright owner + /// () may only be emptied ([], which removes it), any other may hold text. + /// + private static ValueRule MetadataValue(string field) => SharedText.IsPersonalField(field) + ? new LeftOutRule("names, places and copyright owners are personal data; a shared preset may only remove this field") + : new ListRule(new StringRule(500), 50); + /// The fields of one preset. public static readonly ObjectRule PresetFields = Obj( ("id", new StringRule(64, SharedText.Id)), @@ -110,6 +143,7 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("show", Enum() with { Nullable = true }), ("direction", Enum() with { Nullable = true }), ("askCompression", Flag), + ("gallery", new LeftOutRule("set by the app on a preset installed from the gallery")), ("image", Obj( ("quality", new IntRule(1, 100)), ("maxSizeMb", new NumberRule(0, 10_000)), @@ -118,23 +152,18 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("resize", Enum()), ("rotation", Enum()), ("flip", Enum()), - ("annotations", new LeftOutRule("marks are drawn on one picture, never saved with a preset")), - ("annotationColor", Colour with { Nullable = true }), - ("annotationWidth", Enum()), - ("backdrop", new LeftOutRule("set on one conversion, never saved with a preset")), - ("backdropLook", Obj( - ("kind", Enum()), - ("from", Colour), - ("to", Colour), + ("annotations", new ListRule(Obj( + ("kind", Enum()), ("color", Colour), - ("picture", new LeftOutRule("a picture of one's own is a path on one's computer")), - ("pictureWritten", new LeftOutRule("belongs to a picture of one's own")), - ("pictureLength", new LeftOutRule("belongs to a picture of one's own")), - ("padding", new IntRule(0, BackdropOptions.MaxPadding)), - ("corners", new IntRule(0, BackdropOptions.MaxCorners)), - ("shadow", new IntRule(0, BackdropOptions.MaxShadow)), - ("canvas", Enum())) with + ("width", Enum()), + ("points", new ListRule(Obj(("x", new NumberRule(-1, 2)), ("y", new NumberRule(-1, 2))), 5000)), + ("text", new StringRule(500) { Nullable = true }), + ("number", new IntRule(-9999, 9999))), 500) { Nullable = true }), + ("annotationColor", Colour with { Nullable = true }), + ("annotationWidth", Enum()), + ("backdrop", Backdrop with { Nullable = true }), + ("backdropLook", Backdrop with { Nullable = true }), ("resizePercent", new IntRule(1, 1000)), ("longEdge", new IntRule(1, CustomImageSize.MaxSide)), ("width", new IntRule(1, CustomImageSize.MaxSide)), @@ -171,7 +200,13 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("icoSizes", new ListRule(new IntRule(16, 256, IcoSizes), IcoSizes.Length)), ("hideStyle", Enum()), ("hideStrength", new IntRule(HideTool.MinStrength, HideTool.MaxStrength)), - ("hiddenAreas", new LeftOutRule("the parts of one picture to hide, never saved with a preset")), + ("hiddenAreas", new ListRule(Obj( + ("x", new NumberRule(0, 1)), + ("y", new NumberRule(0, 1)), + ("width", new NumberRule(0, 1)), + ("height", new NumberRule(0, 1)), + ("style", Enum() with { Nullable = true })), 500) + { Nullable = true }), ("animationSpeed", new NumberRule(0.1, 10)))), ("pdf", Obj( ("mergeIntoSingle", Flag), @@ -204,7 +239,7 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("watermark", new StringRule(100)), ("pageNumbers", Flag), ("password", new LeftOutRule("a password is never shared")), - ("passwordLeftOut", new BoolRule(false)), + ("passwordLeftOut", Flag), ("ocr", Flag), ("ocrLanguage", new StringRule(64, SharedText.OcrLanguages)))), ("document", Obj( @@ -239,7 +274,25 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("exactCut", Flag), ("splitEverySeconds", new IntRule(0, 86_400)), ("splitParts", new IntRule(0, MediaOptions.MaxSplitParts)), - ("clip", new LeftOutRule("a clip is cut from one video, and its music is a file of one's own")), + ("clip", Obj( + ("parts", new ListRule(Obj( + ("start", new NumberRule(0, 1_000_000)), + ("end", new NumberRule(0, 1_000_000)), + ("blank", Flag), + ("volume", new NumberRule(0, ClipPart.MaxVolume)), + ("muted", Flag), + ("speed", new NumberRule(ClipPart.MinSpeed, ClipPart.MaxSpeed))), 1000)), + ("fadeIn", new NumberRule(0, ClipEdit.MaxFade)), + ("fadeOut", new NumberRule(0, ClipEdit.MaxFade)), + ("music", Obj( + ("path", new LeftOutRule("a sound of one's own is a path on one's computer")), + ("offset", new NumberRule(0, 1_000_000)), + ("from", new NumberRule(0, 1_000_000)), + ("length", new NumberRule(0, 1_000_000)), + ("volume", new NumberRule(0, ClipPart.MaxVolume)), + ("fade", Flag)) with + { Nullable = true })) with + { Nullable = true }), ("joinIntoOne", Flag), ("loopMusic", Flag), ("slideshow", Flag), @@ -263,12 +316,17 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("enabled", Flag), ("targetLanguage", new StringRule(16, SharedText.LanguageCode)), ("sourceLanguage", new StringRule(16, SharedText.LanguageCode)), - ("model", new LeftOutRule("the AI model is the installer's own choice (Settings)")))), + ("model", new StringRule(100, SharedText.OllamaModel) { Nullable = true }))), ("upscale", Obj( ("enabled", Flag), ("model", new StringRule(80, SharedText.ModelId) { Nullable = true }), ("scale", new IntRule(1, 8)))), - ("metadata", new LeftOutRule("metadata edits write names, places and dates into files")), + ("metadata", Obj( + ("set", new MapRule(200, SharedText.MetadataField, MetadataValue)), + ("remove", new ListRule(new StringRule(100, SharedText.MetadataField), 500)), + ("removeLocation", Flag), + ("removeAll", Flag)) with + { Nullable = true }), ("output", Obj( ("location", new EnumRule(Locations)), ("askEveryTime", Flag), @@ -283,12 +341,12 @@ private static ObjectRule Obj(params (string Name, ValueRule Rule)[] fields) => ("replace", new StringRule(100, SharedText.RenameReplace)), // Written by an export, never read back (RenameStep.IsBlank has no setter). ("isBlank", Flag)), 10)), - ("conflict", new EnumRule([nameof(ConflictPolicy.Rename), nameof(ConflictPolicy.Skip)])), + ("conflict", Enum()), ("keepDates", Flag), ("zipResult", Flag), ("onlyIfSmaller", Flag), - ("replaceOriginal", new BoolRule(false)), - ("moveInsteadOfCopy", new BoolRule(false))))); + ("replaceOriginal", Flag), + ("moveInsteadOfCopy", Flag)))); /// The fields of one toolbar profile (a donut). public static readonly ObjectRule ProfileFields = Obj( diff --git a/src/Filee.Core/Gallery/SharedPresetWarnings.cs b/src/Filee.Core/Gallery/SharedPresetWarnings.cs new file mode 100644 index 000000000..135d78838 --- /dev/null +++ b/src/Filee.Core/Gallery/SharedPresetWarnings.cs @@ -0,0 +1,69 @@ +// The warnings of a shared preset (#1530): settings the gallery allows that touch the installer's files (replacing or +// moving originals, overwriting files, writing or removing metadata, a fixed AI model, edits drawn into every file). The +// check derives them from preset.json; the gallery's CI copies the codes into meta.json and index.json for the site, +// and the app derives them again from the file it installs, never trusting the index. The codes are a contract with +// the site and the gallery's repository: add new ones, never rename one. + +using Filee.Core.Presets; + +namespace Filee.Core.Gallery; + +public static class SharedPresetWarnings +{ + public const string High = "high", Medium = "medium", Info = "info"; + + /// Every warning code, with its severity and what it means, most serious first. + public static readonly IReadOnlyList<(string Code, string Severity, string Message)> All = + [ + ("replaces_original", High, "Replaces the original files: the result takes their place and the originals go to the Recycle Bin / Trash."), + ("moves_original", High, "Moves the original files into a folder instead of copying them."), + ("overwrites_existing", Medium, "Overwrites a file that already has the result's name instead of adding a number."), + ("copies_to_folder", Medium, "Copies files into a folder; you choose the folder after installing."), + ("edits_metadata", Medium, "Writes metadata fields into the files it converts."), + ("fixed_edits", Medium, "Draws the same marks, hidden areas, background or clip into every file it converts."), + ("strips_metadata", Info, "Removes metadata (such as camera details, dates or location) from the files it converts."), + ("uses_translate_model", Info, "Translates with a particular AI model, which you may need to download in Ollama."), + ]; + + /// The severity of ; null for a code this version doesn't know. + public static string? SeverityOf(string code) => All.FirstOrDefault(w => w.Code == code).Severity; + + /// The warnings give, each with the ids of the presets that have it. + public static IReadOnlyList Of(IEnumerable presets) + { + var found = new Dictionary>(StringComparer.Ordinal); + foreach (var preset in presets) + foreach (var code in Codes(preset)) + { + if (!found.TryGetValue(code, out var ids)) + found[code] = ids = []; + ids.Add(preset.Id); + } + return [.. All.Where(w => found.ContainsKey(w.Code)).Select(w => new PresetCheckWarning(w.Code, w.Severity, w.Message, found[w.Code]))]; + } + + /// The warning codes of one preset. + public static IEnumerable Codes(Preset preset) + { + if (preset.IsGroup) + yield break; + var output = preset.Output; + if (output.ReplaceOriginal) + yield return "replaces_original"; + if (preset.IsCopyToFolder && output.MoveInsteadOfCopy) + yield return "moves_original"; + if (output.Conflict == ConflictPolicy.Overwrite) + yield return "overwrites_existing"; + if (preset.IsCopyToFolder) + yield return "copies_to_folder"; + if (preset.Metadata is { Set.Count: > 0 }) + yield return "edits_metadata"; + if (preset.Image.HasAnnotations || preset.Image.HidesAreas || preset.Image.AddsBackdrop || preset.Media.Clip is { Parts.Count: > 0 }) + yield return "fixed_edits"; + if (!preset.Image.KeepMetadata || preset.Pdf.RemoveMetadata || preset.Media.RemoveMetadata + || preset.Metadata is { Remove.Count: > 0 } or { RemoveLocation: true } or { RemoveAll: true }) + yield return "strips_metadata"; + if (preset.Translate.Enabled && !string.IsNullOrWhiteSpace(preset.Translate.Model)) + yield return "uses_translate_model"; + } +} diff --git a/src/Filee.Core/Gallery/SharedText.cs b/src/Filee.Core/Gallery/SharedText.cs index 6eacdd1e2..cb89a2104 100644 --- a/src/Filee.Core/Gallery/SharedText.cs +++ b/src/Filee.Core/Gallery/SharedText.cs @@ -112,6 +112,26 @@ public static (string Code, string Message)? Common(string text) [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._\-]{0,79}$", RegexOptions.CultureInvariant)] private static partial Regex ModelPattern(); + /// An Ollama model name ("llama3.1:8b", "library/qwen2.5"): never an address. + public static string? OllamaModel(string text) => + OllamaPattern().IsMatch(text) && !text.Contains("//", StringComparison.Ordinal) ? null : "is not a model name like llama3.1:8b"; + + [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._:/\-]{0,99}$", RegexOptions.CultureInvariant)] + private static partial Regex OllamaPattern(); + + /// One metadata field, "Group:Tag" (). + public static string? MetadataField(string text) => + MetadataEdits.IsFieldKey(text) ? null : "is not a metadata field like XMP-dc:Title"; + + /// + /// True for a metadata field that names a person, a place or a copyright owner (author, artist, creator, copyright, + /// owner, credit, GPS and place fields, contact details): a shared preset may only remove it, never give it a value. + /// + public static bool IsPersonalField(string field) => PersonalField().IsMatch(field); + + [GeneratedRegex(@"(?i)(author|artist|creator|copyright|owner|by-?line|credit|rights|contact|e-?mail|phone|address|city|country|state|province|location|gps|latitude|longitude|altitude|position|lastmodifiedby|company|manager|name|person|serial|keywords?)", RegexOptions.CultureInvariant)] + private static partial Regex PersonalField(); + /// "auto", a ratio ("16:9") or empty (). public static string? CropFrame(string text) => text.Length == 0 || VideoCrop.Crops(text) ? null : "is not a frame like 16:9 or auto"; diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs index 90dad9577..d1e0e7fe1 100644 --- a/src/Filee.Core/Presets/Preset.cs +++ b/src/Filee.Core/Presets/Preset.cs @@ -183,6 +183,12 @@ public sealed class Preset [JsonConverter(typeof(LabelDirectionJsonConverter))] public LabelDirection? Direction { get; set; } + /// + /// The preset gallery entry (its id on filee.sh) this preset was installed from, so the editor can say so; null for + /// every other preset. Never shared (). + /// + public string? Gallery { get; set; } + /// A conversion or a group. A kind this version doesn't know (from a newer Filee) is read as a group. [JsonConverter(typeof(PresetKindJsonConverter))] public PresetKind Kind { get; set; } = PresetKind.Convert; @@ -428,6 +434,11 @@ public Preset WithoutPassword(bool mark) public Preset ForSharing() { var copy = WithoutPassword(mark: false); + if (copy.Gallery is not null) + { + copy = ReferenceEquals(copy, this) ? Clone() : copy; + copy.Gallery = null; + } if (copy.Image.Backdrop?.Picture is null && copy.Image.BackdropLook?.Picture is null) return copy; copy = ReferenceEquals(copy, this) ? Clone() : copy; @@ -459,6 +470,7 @@ public Preset ForSharing() Direction = Direction, AskCompression = AskCompression, Kind = Kind, + Gallery = Gallery, Tool = Tool, SubPresetIds = [.. SubPresetIds], }; diff --git a/tests/Filee.App.Tests/PresetGalleryTests.cs b/tests/Filee.App.Tests/PresetGalleryTests.cs index 18f52fe23..9d252aa9a 100644 --- a/tests/Filee.App.Tests/PresetGalleryTests.cs +++ b/tests/Filee.App.Tests/PresetGalleryTests.cs @@ -168,6 +168,12 @@ static byte[] Index(IEnumerable list) => Encoding.UTF8.GetBytes(new site["thumb"] = "files/" + site["thumb"]!.GetValue(); site["preset"] = "files/" + site["preset"]!.GetValue(); site["download"] = "https://filee.sh/presets/download/" + site["id"]!.GetValue(); + if (site["imagesByLang"] is JsonObject byLang) + foreach (var (language, list) in byLang.ToList()) + byLang[language] = new JsonArray([.. list!.AsArray().Select(p => (JsonNode)("files/" + p!.GetValue()))]); + if (site["thumbByLang"] is JsonObject thumbs) + foreach (var (language, path) in thumbs.ToList()) + thumbs[language] = "files/" + path!.GetValue(); return site; })); } @@ -456,6 +462,196 @@ public void Pictures_are_kept_in_the_cache_for_the_next_time() Assert.Equal(1, gallery.Count(path)); } + /// A gallery of one preset that replaces the originals (a high warning) and strips metadata. + private FakeGallery RiskyGallery() + { + var gallery = new FakeGallery(); + var risky = Insta(); + risky.Output.ReplaceOriginal = true; + Publish(gallery, Share(gallery, "in-place-jpg", "JPG in place", Bundle([risky]), SKColors.Tomato, ["convert"], ["jpg"], ["images"], ["en"])); + return gallery; + } + + [AvaloniaFact] + public void A_preset_that_can_replace_originals_warns_and_installs_only_once_the_user_agrees() + { + TestServices.EnsureInitialized(); + var store = Store(); + var (vm, client, _, installed) = Open(RiskyGallery(), store); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(); + var detail = vm.Detail!; + ClipWindowTests.WaitFor(() => detail.Installable); + var loc = AppHost.Get(); + Assert.Equal([loc["gallery.warning.replaces_original"], loc["gallery.warning.strips_metadata"]], detail.Warnings.Select(w => w.Text)); + Assert.True(detail.HasHighWarnings); + Assert.False(detail.InstallCommand.CanExecute(null)); + + detail.WarningsAccepted = true; + Assert.True(detail.InstallCommand.CanExecute(null)); + detail.InstallCommand.Execute(null); + ClipWindowTests.WaitFor(() => detail.InstallState == GalleryInstallState.Installed); + + // Kept as shared, and marked as from the gallery. + var preset = Assert.Single(Assert.Single(installed).Presets); + Assert.True(preset.Output.ReplaceOriginal); + Assert.Equal("in-place-jpg", preset.Gallery); + var editor = new PresetEditorViewModel(preset, loc); + Assert.Contains("in-place-jpg", editor.GalleryNote); + Assert.Null(new PresetEditorViewModel(Insta(), loc).GalleryNote); + } + + [AvaloniaFact] + public void A_preset_with_only_milder_warnings_installs_without_the_tick() + { + TestServices.EnsureInitialized(); + var (vm, client, _, _) = Open(Gallery(), Store()); + using var _client = client; + using var _vm = vm; + + vm.Selected = vm.Cards.Single(c => c.Entry.Id == "instagram-jpg"); + ClipWindowTests.WaitFor(() => vm.Detail!.Installable); + Assert.True(vm.Detail!.HasWarnings); // it removes metadata + Assert.False(vm.Detail.HasHighWarnings); + Assert.True(vm.Detail.InstallCommand.CanExecute(null)); + } + + [AvaloniaFact] + public void Pictures_follow_the_apps_language_and_change_with_it() + { + TestServices.EnsureInitialized("en"); + var gallery = Gallery(); + var entry = Share(gallery, "korean-shots", "Korean screenshots", Bundle([Insta()]), SKColors.SkyBlue, ["convert"], ["jpg"], [], ["ko"]); + var korean = Picture(1280, 720, SKColors.HotPink); + var koreanThumb = Picture(480, 270, SKColors.HotPink, SKEncodedImageFormat.Webp); + gallery.Files["/presets/files/presets/korean-shots/images/ko/1.webp"] = korean; + gallery.Files["/presets/files/presets/korean-shots/images/ko/1-thumb.webp"] = koreanThumb; + entry["imagesByLang"] = new JsonObject { ["ko"] = new JsonArray("presets/korean-shots/images/ko/1.webp", "presets/korean-shots/images/2.webp") }; + entry["thumbByLang"] = new JsonObject { ["ko"] = "presets/korean-shots/images/ko/1-thumb.webp" }; + Publish(gallery, entry); + var localization = AppHost.Get(); + var (vm, client, _, _) = Open(gallery, Store()); + using var _client = client; + try + { + var card = vm.Cards.Single(); + ClipWindowTests.WaitFor(() => card.Thumb is not null); + Assert.Equal(0, gallery.Count("/presets/files/presets/korean-shots/images/ko/1-thumb.webp")); + vm.Selected = card; + ClipWindowTests.WaitFor(() => vm.Detail!.Images.All(i => i.Bitmap is not null)); + var english = card.Thumb; + + localization.SetLanguage("ko"); + ClipWindowTests.WaitFor(() => card.Thumb != english && vm.Detail!.Images.All(i => i.Bitmap is not null)); + Assert.Equal(1, gallery.Count("/presets/files/presets/korean-shots/images/ko/1-thumb.webp")); + Assert.Equal(1, gallery.Count("/presets/files/presets/korean-shots/images/ko/1.webp")); + Assert.Equal(2, vm.Detail!.Images.Count); + Assert.Equal(AppHost.Get().Format("gallery.image", 1, 2), vm.Detail.Images[0].Name); + } + finally + { + vm.Dispose(); + TestServices.EnsureInitialized("en"); + } + } + + [AvaloniaFact] + public void The_validator_knows_every_language_of_the_app() + { + Assert.Equal(LocalizationService.Languages.Select(l => l.Code).Order(StringComparer.Ordinal), + SharedPresetFolderCheck.Languages.Order(StringComparer.Ordinal)); + } + + [AvaloniaFact] + public void Export_for_the_gallery_checks_the_choice_and_saves_preset_json() + { + TestServices.EnsureInitialized(); + var store = Store(); + var own = store.FindPreset("to-png")!; + var opened = new List(); + var path = Path.Combine(_root, "shared", "preset.json"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var vm = new GalleryExportViewModel(store, AppHost.Get(), own, uri => { opened.Add(uri); return Task.CompletedTask; }, + () => Task.FromResult(path)); + + Assert.True(vm.CanSave); + Assert.Single(vm.Presets, p => p.IsChosen); + vm.SaveCommand.Execute(null); + ClipWindowTests.WaitFor(() => vm.Status == AppHost.Get()["gallery.export_saved"]); + Assert.True(SharedBundleCheck.Check(File.ReadAllBytes(path)).Ok); + Assert.Equal(AppHost.Get()["gallery.export_saved"], vm.Status); + + // A folder of one's own can't be shared: listed, and Save waits. + own.Output.Location = OutputLocation.CustomFolder; + own.Output.CustomFolder = Path.Combine(_root, "out"); + own.Output.ReplaceOriginal = true; + vm.Presets.Single(p => p.Preset == own).IsChosen = false; + vm.Presets.Single(p => p.Preset == own).IsChosen = true; + Assert.False(vm.CanSave); + Assert.Contains(vm.Problems, p => p.StartsWith("presets[0].output.customFolder", StringComparison.Ordinal)); + // Without the folder it can be shared, with the warning the gallery will show. + own.Output.CustomFolder = ""; + vm.Presets.Single(p => p.Preset == own).IsChosen = false; + vm.Presets.Single(p => p.Preset == own).IsChosen = true; + Assert.True(vm.CanSave); + Assert.Contains(vm.Warnings, w => w.Code == "replaces_original" && w.IsHigh); + + vm.Presets.Single(p => p.Preset == own).IsChosen = false; + Assert.False(vm.CanSave); + Assert.Equal(AppHost.Get()["gallery.export_none"], vm.Status); + + vm.OpenFormCommand.Execute(null); + Assert.Equal(GalleryExportViewModel.SubmitUri, Assert.Single(opened)); + } + + [AvaloniaTheory] + [InlineData("en", false)] + [InlineData("ko", true)] + [InlineData("ar", false)] + public void The_export_and_the_warnings_render(string language, bool dark) + { + TestServices.EnsureInitialized(language); + var theme = AppHost.Get(); + if (dark) + theme.Apply(new ThemeSettings { Mode = ThemeMode.Dark }, language); + try + { + var (vm, client, _, _) = Open(RiskyGallery(), Store()); + using var _client = client; + using var _vm = vm; + vm.Selected = vm.Cards.Single(); + ClipWindowTests.WaitFor(() => vm.Detail!.Installable && vm.Detail.Images.All(i => i.Bitmap is not null)); + var window = new PresetGalleryWindow { DataContext = vm }; + window.Show(); + RenderTests.Pump(); + Assert.True(window.GetVisualDescendants().OfType().Single(b => b.Name == "WarningPanel").IsEffectivelyVisible); + Assert.True(window.GetVisualDescendants().OfType().Single(b => b.Name == "AcceptRisk").IsEffectivelyVisible); + RenderTests.Save(window, $"preset-gallery-warning-{language}-{(dark ? "dark" : "light")}.png"); + window.Close(); + + var store = Store(); + var own = store.FindPreset("to-png")!; + own.Output.Location = OutputLocation.CustomFolder; + own.Output.CustomFolder = @"C:\Users\Public\Out"; + own.Output.Conflict = Filee.Core.Presets.ConflictPolicy.Overwrite; + var export = new GalleryExportWindow + { + DataContext = new GalleryExportViewModel(store, AppHost.Get(), own, _ => Task.CompletedTask, () => Task.FromResult(null)), + }; + export.Show(); + RenderTests.Pump(); + RenderTests.Save(export, $"gallery-export-{language}-{(dark ? "dark" : "light")}.png"); + export.Close(); + } + finally + { + if (dark) + theme.Apply(new ThemeSettings(), language); + } + } + [AvaloniaFact] public void The_presets_page_opens_the_gallery() { @@ -467,6 +663,8 @@ public void The_presets_page_opens_the_gallery() var button = page.GetVisualDescendants().OfType + - + diff --git a/src/Filee.App/Views/Pages/PresetsPage.axaml.cs b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs index 37d497887..88542325b 100644 --- a/src/Filee.App/Views/Pages/PresetsPage.axaml.cs +++ b/src/Filee.App/Views/Pages/PresetsPage.axaml.cs @@ -1,4 +1,6 @@ using Avalonia.Controls; +using Avalonia.Threading; +using Avalonia.VisualTree; using Filee.App.ViewModels.Pages; namespace Filee.App.Views.Pages; @@ -6,11 +8,48 @@ namespace Filee.App.Views.Pages; public partial class PresetsPage : UserControl { private const int FixedMenuItems = 3; // "Empty preset", the separator and the heading + private PresetsPageViewModel? _viewModel; public PresetsPage() { InitializeComponent(); - DataContextChanged += (_, _) => FillAddMenu(); + DataContextChanged += (_, _) => + { + Unsubscribe(); + FillAddMenu(); + if (TopLevel.GetTopLevel(this) is not null) + Subscribe(); + }; + AttachedToVisualTree += (_, _) => Subscribe(); + DetachedFromVisualTree += (_, _) => Unsubscribe(); + } + + private void Subscribe() + { + if (_viewModel is not null || DataContext is not PresetsPageViewModel vm) + return; + _viewModel = vm; + vm.ValidationFailed += RevealInvalidField; + } + + private void Unsubscribe() + { + if (_viewModel is not null) + _viewModel.ValidationFailed -= RevealInvalidField; + _viewModel = null; + } + + private void RevealInvalidField(object? sender, EventArgs e) + { + // Binding updates and the editor's conditional cards must be laid out before scrolling to their error. + Dispatcher.UIThread.Post(() => + { + if (TopLevel.GetTopLevel(this) is null) + return; + var error = PresetEditor.GetVisualDescendants().OfType() + .FirstOrDefault(t => t.IsEffectivelyVisible && t.Classes.Contains("danger") && !string.IsNullOrEmpty(t.Text)); + error?.BringIntoView(); + }, DispatcherPriority.Loaded); } /// One "New" menu item per ready-made preset, so the menu follows the list (#553). diff --git a/tests/Filee.App.Tests/PresetSaveFeedbackTests.cs b/tests/Filee.App.Tests/PresetSaveFeedbackTests.cs new file mode 100644 index 000000000..f6c69d97c --- /dev/null +++ b/tests/Filee.App.Tests/PresetSaveFeedbackTests.cs @@ -0,0 +1,237 @@ +// The Presets page reports real write results and keeps failed edits available without changing the saved library. + +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using Avalonia.VisualTree; +using Filee.App.Controls; +using Filee.App.Services; +using Filee.App.ViewModels.Pages; +using Filee.App.Views.Pages; +using Filee.Core.Localization; +using Filee.Core.Presets; +using Filee.Core.Settings; + +namespace Filee.App.Tests; + +[Collection("Motion")] +public sealed class PresetSaveFeedbackTests +{ + public static TheoryData Languages => new(LocalizationService.Languages.Select(l => l.Code)); + + private sealed class Fixture : IDisposable + { + internal readonly string Folder = Directory.CreateTempSubdirectory("filee-save-feedback-").FullName; + internal readonly UserDataStore Store; + internal readonly PresetsPageViewModel ViewModel; + + internal Fixture() + { + TestServices.EnsureInitialized("en"); + Store = new UserDataStore(Folder); + Store.Presets.Clear(); + Store.Presets.Add(new Preset { Id = "feedback", Name = "Original", TargetFormat = "png" }); + Store.SaveLibrary(); + ViewModel = new PresetsPageViewModel(Store, AppHost.Get(), AppHost.Get()); + } + + public void Dispose() => Directory.Delete(Folder, true); + } + + [AvaloniaFact] + public void Success_is_reported_after_the_library_is_written_and_can_be_repeated() + { + using var f = new Fixture(); + var results = new List(); + f.Store.LibraryChanged += (_, _) => results.Add(f.ViewModel.SaveResult); + f.ViewModel.Editor!.Name = "Changed"; + f.ViewModel.SaveCommand.Execute(null); + Assert.Equal([SaveResult.None], results); + Assert.Equal(SaveResult.Succeeded, f.ViewModel.SaveResult); + Assert.Equal("Saved", f.ViewModel.SaveStatus); + Assert.Null(f.ViewModel.SaveError); + var reloaded = new UserDataStore(f.Folder); + reloaded.Load(); + Assert.Equal("Changed", reloaded.FindPreset("feedback")!.Name); + + var transitions = new List(); + f.ViewModel.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(f.ViewModel.SaveResult)) transitions.Add(f.ViewModel.SaveResult); }; + f.ViewModel.SaveCommand.Execute(null); + Assert.Equal([SaveResult.None, SaveResult.Succeeded], transitions); + f.ViewModel.Editor!.Name = "Unsaved"; + f.ViewModel.RevertCommand.Execute(null); + Assert.Equal("Changed", f.ViewModel.Editor!.Name); + Assert.Equal(SaveResult.None, f.ViewModel.SaveResult); + } + + [AvaloniaTheory] + [InlineData("name")] + [InlineData("range")] + [InlineData("size")] + public void Validation_explains_the_field_and_does_not_write(string invalid) + { + using var f = new Fixture(); + var editor = f.ViewModel.Editor!; + switch (invalid) + { + case "name": editor.Name = " "; break; + case "range": + editor.Target = editor.Targets.Single(c => c.Value == "jpg"); + editor.ImageMinSize = 5; + editor.ImageMaxSize = 1; + break; + case "size": + editor.Resize = editor.ResizeModes.Single(c => c.Value == ResizeMode.Custom); + editor.CustomWidth = null; + editor.CustomHeight = null; + break; + } + var before = File.ReadAllText(Path.Combine(f.Folder, "presets.json")); + var revealed = false; + f.ViewModel.ValidationFailed += (_, _) => revealed = true; + f.ViewModel.SaveCommand.Execute(null); + Assert.True(revealed); + Assert.Equal(SaveResult.Failed, f.ViewModel.SaveResult); + Assert.Equal(editor.NameError ?? editor.SizeRangeError ?? editor.DestinationError ?? editor.CustomSizeError, f.ViewModel.SaveError); + Assert.False(string.IsNullOrWhiteSpace(f.ViewModel.SaveError)); + Assert.Equal(before, File.ReadAllText(Path.Combine(f.Folder, "presets.json"))); + Assert.Equal("Original", f.Store.FindPreset("feedback")!.Name); + } + + [AvaloniaFact] + public void Write_failure_is_readable_edits_can_be_retried_and_revert_keeps_the_saved_values() + { + using var f = new Fixture(); + var blocked = Path.Combine(f.Folder, "presets.json.tmp"); + Directory.CreateDirectory(blocked); // A deterministic access failure on Windows and Unix, even as root. + var before = File.ReadAllText(Path.Combine(f.Folder, "presets.json")); + f.ViewModel.Editor!.Name = "Retry this"; + f.ViewModel.SaveCommand.Execute(null); + Assert.Equal(SaveResult.Failed, f.ViewModel.SaveResult); + Assert.StartsWith("Could not save presets: ", f.ViewModel.SaveError); + Assert.Contains("presets.json.tmp", f.ViewModel.SaveError); + Assert.Equal("Retry this", f.ViewModel.Editor!.Name); + Assert.Equal("Original", f.Store.FindPreset("feedback")!.Name); + Assert.Equal(before, File.ReadAllText(Path.Combine(f.Folder, "presets.json"))); + f.ViewModel.RevertCommand.Execute(null); + Assert.Equal("Original", f.ViewModel.Editor!.Name); + Assert.Null(f.ViewModel.SaveError); + Directory.Delete(blocked); + f.ViewModel.Editor.Name = "Retry succeeded"; + f.ViewModel.SaveCommand.Execute(null); + Assert.Equal(SaveResult.Succeeded, f.ViewModel.SaveResult); + Assert.Null(f.ViewModel.SaveError); + Assert.Equal("Retry succeeded", f.Store.FindPreset("feedback")!.Name); + } + + [AvaloniaFact] + public void Switching_presets_clears_the_previous_failure() + { + using var f = new Fixture(); + f.ViewModel.Editor!.Name = ""; + f.ViewModel.SaveCommand.Execute(null); + f.ViewModel.SelectedPreset = null; + Assert.Null(f.ViewModel.SaveStatus); + Assert.Equal(SaveResult.None, f.ViewModel.SaveResult); + Assert.Null(f.ViewModel.Editor); + } + + [AvaloniaTheory] + [MemberData(nameof(Languages))] + public void Save_feedback_is_translated_in_every_catalog(string language) + { + TestServices.EnsureInitialized(language); + var loc = AppHost.Get(); + Assert.NotEqual("presets.saved", loc["presets.saved"]); + Assert.False(string.IsNullOrWhiteSpace(loc["presets.saved"])); + var failure = loc.Format("presets.save_failed", "write-error-detail"); + Assert.Contains("write-error-detail", failure); + Assert.DoesNotContain("{0}", failure); + if (language != "en") + Assert.DoesNotContain("Could not save presets", failure); + } + + [AvaloniaFact] + public void Invalid_field_is_brought_into_view_even_when_the_editor_is_scrolled_away() + { + using var f = new Fixture(); + var page = new PresetsPage { DataContext = f.ViewModel }; + var window = new Window { Content = page, Width = 980, Height = 420 }; + try + { + window.Show(); + RenderTests.Pump(); + var scroll = page.GetVisualDescendants().OfType().Single(s => s.Content is StackPanel panel && panel.Children.OfType().Any()); + scroll.Offset = new Avalonia.Vector(0, scroll.Extent.Height); + RenderTests.Pump(); + f.ViewModel.Editor!.Name = ""; + f.ViewModel.SaveCommand.Execute(null); + RenderTests.Pump(); + var error = page.FindControl("PresetEditor")!.GetVisualDescendants().OfType() + .First(t => t.Text == "Enter a name"); + var point = error.TranslatePoint(default, scroll)!.Value; + Assert.InRange(point.Y, 0, scroll.Viewport.Height - error.Bounds.Height); + } + finally + { + window.Close(); + } + } + + [AvaloniaTheory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task Button_keeps_its_size_restores_its_label_and_respects_reduced_motion(bool reducedMotion, bool failure) + { + using var f = new Fixture(); + AppHost.Get().Apply(new ThemeSettings { Mode = reducedMotion ? ThemeMode.Dark : ThemeMode.Light }, "en"); + Motion.Set(!reducedMotion); + var page = new PresetsPage { DataContext = f.ViewModel }; + var window = new Window { Content = page, Width = 980, Height = 760 }; + try + { + window.Show(); + RenderTests.Pump(); + var button = page.FindControl